From febe226d570fd265a48987379d71c3aa6f60712f Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 03:53:18 -0800 Subject: [PATCH 01/17] feat: create scope devices and serve their resources through the script server ss_cloud() answers Cacti's index, num_indexes, query and get calls from the plugin cache and never calls a provider. A value is served while it is current or delayed, by the same rule the health page counts, and as U otherwise; age is always numeric, since the newest value or since discovery. A device sees only the resources of the account it is the scope device of, so any other device, type, field or index reads U. Schema version 3 adds plugin_cloud_device. The accounts page creates an account's scope device on request through api_device_save(), with the provider's device template, availability None and the account's poller, then reindexes its data queries once linked. The device_remove hook and account deletion drop the link; the Cacti device keeps its history. The freshness rule moves into FreshnessEvaluator::state() so the health page and the script server share it. Closes #43 Closes #44 Signed-off-by: Thomas Vincent --- cloud_accounts.php | 25 +++- lib/AccountRepository.php | 2 + lib/AccountsPage.php | 19 ++- lib/DeviceRepository.php | 69 +++++++++ lib/FreshnessEvaluator.php | 16 +++ lib/HealthPage.php | 12 +- lib/ObservationRepository.php | 22 +++ lib/ResourceRepository.php | 27 ++++ lib/Schema.php | 16 ++- lib/ScopeDevices.php | 121 ++++++++++++++++ lib/ScriptServer.php | 194 ++++++++++++++++++++++++++ lib/TemplateRepository.php | 24 +++- locales/po/cacti.pot | 22 +++ setup.php | 64 +++++++++ ss_cloud.php | 73 ++++++++++ tests/Integration/LifecycleTest.php | 28 +++- tests/Integration/ScopeDeviceTest.php | 80 +++++++++++ tests/Unit/AccountTest.php | 2 + tests/Unit/ScriptServerTest.php | 177 +++++++++++++++++++++++ tests/bin/lifecycle.php | 90 ++++++++++++ tests/bin/php-guard-check.php | 2 +- 21 files changed, 1060 insertions(+), 25 deletions(-) create mode 100644 lib/DeviceRepository.php create mode 100644 lib/ScopeDevices.php create mode 100644 lib/ScriptServer.php create mode 100644 ss_cloud.php create mode 100644 tests/Integration/ScopeDeviceTest.php create mode 100644 tests/Unit/ScriptServerTest.php diff --git a/cloud_accounts.php b/cloud_accounts.php index a68d464..a5accf4 100644 --- a/cloud_accounts.php +++ b/cloud_accounts.php @@ -31,11 +31,15 @@ exit; } -cloud_require_post('cloud_accounts.php', array('save', 'delete', 'verify')); +cloud_require_post('cloud_accounts.php', array('save', 'delete', 'verify', 'create_device')); $cloud_accounts = cloud_accounts(); $cloud_credentials = cloud_credentials(); -$cloud_page = new \Somethingwithproof\Cloud\AccountsPage($cloud_accounts, $cloud_credentials); +$cloud_page = new \Somethingwithproof\Cloud\AccountsPage( + $cloud_accounts, + $cloud_credentials, + new \Somethingwithproof\Cloud\DeviceRepository(false, new \Somethingwithproof\Cloud\SystemClock()) +); $cloud_user = isset($_SESSION['sess_user_id']) && is_numeric($_SESSION['sess_user_id']) ? (int) $_SESSION['sess_user_id'] : 0; @@ -150,6 +154,23 @@ ); } + header('Location: cloud_accounts.php'); + exit; + case 'create_device': + $cloud_account = $cloud_accounts->find((int) get_filter_request_var('id')); + + if ($cloud_account !== null) { + $cloud_host = cloud_scope_devices()->create($cloud_account); + + raise_message( + 'cloud_device', + $cloud_host > 0 + ? __('The Cacti device for %s is ready.', $cloud_account->name, 'cloud') + : __('The Cacti device was not created; see the Cacti log.', 'cloud'), + $cloud_host > 0 ? MESSAGE_LEVEL_INFO : MESSAGE_LEVEL_ERROR + ); + } + header('Location: cloud_accounts.php'); exit; case 'edit': diff --git a/lib/AccountRepository.php b/lib/AccountRepository.php index 548f679..b7b35fa 100644 --- a/lib/AccountRepository.php +++ b/lib/AccountRepository.php @@ -137,6 +137,8 @@ public function delete(int $id, int $userId): bool { ['DELETE FROM plugin_cloud_series WHERE account_id = ?', [$id]], ['DELETE FROM plugin_cloud_lease WHERE account_id = ?', [$id]], ['DELETE FROM plugin_cloud_health WHERE account_id = ?', [$id]], + // The Cacti device stays, with its history; it just serves nothing now. + ['DELETE FROM plugin_cloud_device WHERE account_id = ?', [$id]], [ 'DELETE o FROM plugin_cloud_observation o INNER JOIN plugin_cloud_resource r ON r.id = o.resource_id WHERE r.account_id = ?', diff --git a/lib/AccountsPage.php b/lib/AccountsPage.php index 5d2aede..f91ee32 100644 --- a/lib/AccountsPage.php +++ b/lib/AccountsPage.php @@ -31,6 +31,7 @@ final class AccountsPage { public function __construct( private readonly AccountRepository $accounts, private readonly CredentialStore $credentials, + private readonly DeviceRepository $devices, ) { } @@ -43,13 +44,14 @@ public function renderList(): void { __('Credential', 'cloud'), __('State', 'cloud'), __('Verify', 'cloud'), + __('Device', 'cloud'), __('Actions', 'cloud'), ])) . ''; $accounts = $this->accounts->all(); if ($accounts === []) { - print '' . html_escape(__('No cloud accounts yet.', 'cloud')) . ''; + print '' . html_escape(__('No cloud accounts yet.', 'cloud')) . ''; } foreach ($accounts as $account) { @@ -61,6 +63,7 @@ public function renderList(): void { . '' . html_escape($account->enabled() ? __('Enabled', 'cloud') : __('Disabled', 'cloud')) . '' . '' . html_escape($account->verifyStatus->message()) . '' + . '' . $this->deviceCell($account) . '' . '' . $this->actionForm($account->id, 'verify', __('Verify', 'cloud')) . ' ' . $this->actionForm($account->id, 'delete', __('Delete', 'cloud')) . '' . ''; @@ -190,6 +193,20 @@ private function credentialSummary(Account $account): string { }; } + /** + * A link to the account's scope device, or the button that creates it. + */ + private function deviceCell(Account $account): string { + $host = $this->devices->hostFor($account->id); + + if ($host !== null) { + return '' + . html_escape(__('Device %d', $host, 'cloud')) . ''; + } + + return $this->actionForm($account->id, 'create_device', __('Create Cacti Device', 'cloud')); + } + private function actionForm(int $id, string $action, string $label): string { return '
' . '' diff --git a/lib/DeviceRepository.php b/lib/DeviceRepository.php new file mode 100644 index 0000000..51f0060 --- /dev/null +++ b/lib/DeviceRepository.php @@ -0,0 +1,69 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * 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. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ +namespace Somethingwithproof\Cloud; + +/** + * Which Cacti device is each account's scope device (ADR 0010). One device + * per account: the script server serves an account's resources only to its + * own device (REQ-SS-004). + */ +final class DeviceRepository { + public function __construct(private readonly \PDO|false $connection, private readonly Clock $clock) { + } + + public function link(int $hostId, int $accountId): void { + db_execute_prepared( + 'INSERT INTO plugin_cloud_device (host_id, account_id, created_at) VALUES (?, ?, ?)', + [$hostId, $accountId, $this->clock->now()], + true, + $this->connection + ); + } + + /** + * Forget a device Cacti deleted. Its graphs and data sources go with it. + */ + public function unlink(int $hostId): void { + db_execute_prepared('DELETE FROM plugin_cloud_device WHERE host_id = ?', [$hostId], true, $this->connection); + } + + public function accountFor(int $hostId): ?int { + $id = (int) db_fetch_cell_prepared( + 'SELECT account_id FROM plugin_cloud_device WHERE host_id = ?', + [$hostId], + '', + true, + $this->connection + ); + + return $id > 0 ? $id : null; + } + + public function hostFor(int $accountId): ?int { + $id = (int) db_fetch_cell_prepared( + 'SELECT host_id FROM plugin_cloud_device WHERE account_id = ?', + [$accountId], + '', + true, + $this->connection + ); + + return $id > 0 ? $id : null; + } +} diff --git a/lib/FreshnessEvaluator.php b/lib/FreshnessEvaluator.php index 7434e03..2d0eaef 100644 --- a/lib/FreshnessEvaluator.php +++ b/lib/FreshnessEvaluator.php @@ -35,6 +35,22 @@ final class FreshnessEvaluator { public function __construct(private readonly Clock $clock) { } + /** + * The state of a cached datapoint as the health page counts it and the + * script server serves it. No catalog metric documents a period yet + * (#16), so the account's collection interval stands in for it. + * + * @return string a Freshness value, 'unknown', or the cache status + */ + public function state(Observation $observation, string $status, int $collectInterval): string { + return match (true) { + // A recent datapoint without a value is still no measurement. + $observation->value === null => 'unknown', + $status === 'ok' => $this->evaluate($observation, $collectInterval, 0, $collectInterval)->value, + default => $status, + }; + } + public function evaluate(?Observation $observation, int $period, int $delay, int $collectInterval): Freshness { if ($observation === null || $observation->observedAt <= 0) { return Freshness::Never; diff --git a/lib/HealthPage.php b/lib/HealthPage.php index 16363f9..a34125c 100644 --- a/lib/HealthPage.php +++ b/lib/HealthPage.php @@ -118,17 +118,7 @@ public function row(Account $account): array { $freshness = []; foreach ($this->observations->forAccount($account->id) as $entry) { - $state = match (true) { - // A recent datapoint without a value is still no measurement. - $entry['observation']->value === null => 'unknown', - $entry['status'] === 'ok' => $this->freshness->evaluate( - $entry['observation'], - $account->collectInterval, - 0, - $account->collectInterval - )->value, - default => $entry['status'], - }; + $state = $this->freshness->state($entry['observation'], $entry['status'], $account->collectInterval); $freshness[$state] = ($freshness[$state] ?? 0) + 1; } diff --git a/lib/ObservationRepository.php b/lib/ObservationRepository.php index 221d365..2c556d2 100644 --- a/lib/ObservationRepository.php +++ b/lib/ObservationRepository.php @@ -74,6 +74,28 @@ public function find(int $resourceId, string $metric): ?Observation { return is_array($row) ? Observation::fromRow($row) : null; } + /** + * @return array metric => entry + */ + public function forResource(int $resourceId): array { + $out = []; + + foreach (Row::rows(db_fetch_assoc_prepared( + 'SELECT * FROM plugin_cloud_observation WHERE resource_id = ?', + [$resourceId], + true, + $this->connection + )) as $row) { + $observation = Observation::fromRow($row); + + if ($observation !== null) { + $out[$observation->metric] = ['observation' => $observation, 'status' => Row::string($row, 'status')]; + } + } + + return $out; + } + /** * @return list */ diff --git a/lib/ResourceRepository.php b/lib/ResourceRepository.php index 119e9c3..90a3508 100644 --- a/lib/ResourceRepository.php +++ b/lib/ResourceRepository.php @@ -82,6 +82,33 @@ public function sync(int $accountId, Inventory $inventory, LeaseRepository $leas return true; } + /** + * Resources a scope device serves: every one discovery has not retired, + * so a missing resource keeps its index and reads as unknown. + * + * @return list + */ + public function served(int $accountId, string $type): array { + $out = []; + + foreach (Row::rows(db_fetch_assoc_prepared( + 'SELECT id, provider_id, name, first_seen FROM plugin_cloud_resource + WHERE account_id = ? AND type = ? AND lifecycle != ? ORDER BY provider_id', + [$accountId, $type, Lifecycle::Deleted->value], + true, + $this->connection + )) as $row) { + $out[] = [ + 'id' => Row::int($row, 'id'), + 'providerId' => Row::string($row, 'provider_id'), + 'name' => Row::string($row, 'name'), + 'firstSeen' => Row::int($row, 'first_seen'), + ]; + } + + return $out; + } + /** * @return array lifecycle => count */ diff --git a/lib/Schema.php b/lib/Schema.php index 1b0b146..73d2186 100644 --- a/lib/Schema.php +++ b/lib/Schema.php @@ -34,11 +34,12 @@ * the next run (REQ-LIFE-003). No migration calls a provider (REQ-LIFE-006). */ final class Schema { - public const VERSION = 2; + public const VERSION = 3; public const HOOKS = [ 'config_arrays' => 'cloud_config_arrays', 'config_settings' => 'cloud_config_settings', + 'device_remove' => 'cloud_device_remove', 'draw_navigation_text' => 'cloud_draw_navigation_text', 'poller_bottom' => 'cloud_poller_bottom', ]; @@ -170,6 +171,8 @@ private function migrations(): array { 1 => fn (): bool => $this->createTables(self::tables()), // A fresh install already has the column from tables(). 2 => fn (): bool => $this->addColumn('plugin_cloud_health', self::retryAtColumn()), + // A fresh install already has the table; the create skips it. + 3 => fn (): bool => $this->createTables(['plugin_cloud_device' => self::tables()['plugin_cloud_device']]), ]; } @@ -375,6 +378,17 @@ public static function tables(): array { ], 'primary' => 'resource_id`,`metric', ], + // The Cacti scope device of each account (ADR 0010). + 'plugin_cloud_device' => $innodb + [ + 'comment' => 'Cacti scope device per account', + 'columns' => [ + $id('host_id'), + $id('account_id'), + $time('created_at'), + ], + 'primary' => 'host_id', + 'unique_keys' => [['name' => 'account', 'columns' => ['account_id']]], + ], 'plugin_cloud_lease' => $innodb + [ 'comment' => 'Per-account collector leases', 'columns' => [ diff --git a/lib/ScopeDevices.php b/lib/ScopeDevices.php new file mode 100644 index 0000000..85786ce --- /dev/null +++ b/lib/ScopeDevices.php @@ -0,0 +1,121 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * 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. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ +namespace Somethingwithproof\Cloud; + +/** + * Creates each account's Cacti scope device (REQ-OBJ-010, ADR 0010) through + * Cacti's own device API, never by writing Cacti tables (REQ-OBJ-012). The + * device polls nothing itself: availability None, on the account's poller, + * with the provider's device template, whose data queries list the + * account's resources through ss_cloud(). + * + * The accounts page calls this only when an administrator asks for it. + */ +final class ScopeDevices { + /** api_device_save()'s availability method None (AVAIL_NONE). */ + private const AVAILABILITY_NONE = 0; + + /** The device template of each provider, as TemplateRepository keys. */ + private const TEMPLATES = [Provider::DigitalOcean->value => 'host_template/digitalocean']; + + /** + * @param \Closure(Account, int): int $save api_device_save() for this account + * and device template, returning the new device id or 0 + * @param \Closure(int, int): void $reindex run_data_query() for a device and data query + */ + public function __construct( + private readonly DeviceRepository $devices, + private readonly TemplateRepository $templates, + private readonly \Closure $save, + private readonly \Closure $reindex, + ) { + } + + /** + * @return int the account's device id, created now or earlier; 0 when it + * could not be created + */ + public function create(Account $account): int { + $existing = $this->devices->hostFor($account->id); + + if ($existing !== null) { + return $existing; + } + + $key = self::TEMPLATES[$account->provider->value] ?? null; + $template = $key === null ? null : $this->templates->id('host_template', $key); + + if ($template === null) { + Log::error(sprintf('Account %d: no Cacti device template; import the plugin templates first', $account->id)); + + return 0; + } + + $host = ($this->save)($account, $template); + + if ($host <= 0) { + Log::error(sprintf('Account %d: Cacti refused the scope device', $account->id)); + + return 0; + } + + $this->devices->link($host, $account->id); + + // Saving applied the template's data queries and indexed them before + // the link existed, so they found nothing; index them again now. + foreach (TemplateRepository::objects()['snmp_query'] as $query) { + $id = $this->templates->id('snmp_query', $query); + + if ($id !== null) { + ($this->reindex)($host, $id); + } + } + + Log::info(sprintf('Account %d: created scope device %d', $account->id, $host)); + + return $host; + } + + /** + * The fields api_device_save() takes, in order, for an account's device. + * + * @return list + */ + public static function deviceFields(Account $account, int $template): array { + return [ + 0, // id: a new device + $template, + $account->name, // description + 'cloud-account-' . $account->id, // hostname; nothing connects to it + '', // snmp_community + 0, // snmp_version: none + '', '', 161, 500, // snmp username, password, port, timeout + '', // disabled: no + self::AVAILABILITY_NONE, + 1, 23, 400, 1, // ping method, port, timeout, retries: unused + 'Cloud scope device for account ' . $account->id . '; created by the Cloud plugin.', + '', '', '', '', '', // SNMPv3 fields + 5, 1, // max_oids, device_threads + $account->pollerId, + 0, // site: none + 'cloud:' . $account->id, // external_id + '', // location + ]; + } +} diff --git a/lib/ScriptServer.php b/lib/ScriptServer.php new file mode 100644 index 0000000..87bc410 --- /dev/null +++ b/lib/ScriptServer.php @@ -0,0 +1,194 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * 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. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ +namespace Somethingwithproof\Cloud; + +/** + * The script server side of the resource data queries (#44). Cacti's poller + * and reindex call ss_cloud(), which hands its arguments here. Everything is + * read from the plugin's cache; nothing here calls a provider (REQ-SS-002). + * + * A device sees only the resources of the account it is the scope device + * of (REQ-SS-004). An unknown device, type, field or resource gets no + * indexes and reads as U, so a stale poller item cannot read another + * account's data. + */ +final class ScriptServer { + public const UNKNOWN = 'U'; + + private const COMMANDS = ['index', 'num_indexes', 'query', 'get']; + + public function __construct( + private readonly DeviceRepository $devices, + private readonly AccountRepository $accounts, + private readonly ResourceRepository $resources, + private readonly ObservationRepository $observations, + private readonly FreshnessEvaluator $freshness, + private readonly Clock $clock, + ) { + } + + /** + * @return string the lines to print for index, num_indexes and query; + * the value to return for get + */ + public function run(int $hostId, string $type, string $command, string $field = '', string $index = ''): string { + if (!in_array($command, self::COMMANDS, true)) { + return ''; + } + + $fields = self::fields($type); + $account = $hostId > 0 && $fields !== [] ? $this->account($hostId) : null; + $known = in_array($field, $fields, true); + + if ($command === 'get') { + return $account !== null && $known ? $this->get($account, $type, $field, $index) : self::UNKNOWN; + } + + $resources = $account !== null ? $this->resources->served($account->id, $type) : []; + + if ($command === 'num_indexes') { + return (string) count($resources); + } + + if ($command === 'query' && (!$known || $account === null)) { + return ''; + } + + $lines = ''; + + foreach ($resources as $resource) { + $lines .= $command === 'index' + ? $resource['providerId'] . "\n" + : $resource['providerId'] . '!' . $this->value($account, $resource, $field) . "\n"; + } + + return $lines; + } + + /** + * The data query fields of a resource type: its index and name, then + * every data source its graphs use. Empty for an unknown type. + * + * @return list + */ + public static function fields(string $type): array { + $fields = []; + + foreach (DigitalOceanCatalog::GRAPHS as $graph) { + if ($graph[0] === $type) { + $fields = array_merge($fields, $graph[4]); + } + } + + return $fields === [] ? [] : array_merge(['resourceId', 'resourceName'], $fields); + } + + private function account(int $hostId): ?Account { + $id = $this->devices->accountFor($hostId); + + return $id === null ? null : $this->accounts->find($id); + } + + private function get(Account $account, string $type, string $field, string $index): string { + foreach ($this->resources->served($account->id, $type) as $resource) { + if ($resource['providerId'] === $index) { + return $this->value($account, $resource, $field); + } + } + + return self::UNKNOWN; + } + + /** + * @param array{id: int, providerId: string, name: string, firstSeen: int} $resource + */ + private function value(Account $account, array $resource, string $field): string { + if ($field === 'resourceId') { + return $resource['providerId']; + } + + if ($field === 'resourceName') { + return self::label($resource['name']); + } + + $entries = $this->observations->forResource($resource['id']); + + if (in_array($field, DigitalOceanCatalog::AGE, true)) { + return (string) $this->age($resource, $entries); + } + + $entry = $entries[$field] ?? null; + + if (!$account->enabled() || $entry === null) { + return self::UNKNOWN; + } + + $state = $this->freshness->state($entry['observation'], $entry['status'], $account->collectInterval); + + if (!in_array($state, [Freshness::Current->value, Freshness::Delayed->value], true)) { + return self::UNKNOWN; + } + + return self::number((float) $entry['observation']->value); + } + + /** + * Seconds since the newest datapoint with a value, or since discovery + * when there is none; never negative, always numeric (REQ-SS-003). + * + * @param array{id: int, providerId: string, name: string, firstSeen: int} $resource + * @param array $entries + */ + private function age(array $resource, array $entries): int { + $newest = 0; + + foreach ($entries as $entry) { + if ($entry['observation']->value !== null && $entry['status'] === 'ok') { + $newest = max($newest, $entry['observation']->observedAt); + } + } + + $since = $newest > 0 ? $newest : $resource['firstSeen']; + + return max(0, $this->clock->now() - $since); + } + + /** + * A name as one output field: the delimiter, line breaks and other + * control characters would split or corrupt the line. + */ + public static function label(string $name): string { + $clean = trim((string) preg_replace('/[!\x00-\x1F\x7F]+/', ' ', $name)); + + return $clean === '' ? self::UNKNOWN : $clean; + } + + /** + * A plain decimal, never exponent notation. + */ + public static function number(float $value): string { + if (!is_finite($value)) { + return self::UNKNOWN; + } + + $text = rtrim(rtrim(sprintf('%.6F', $value), '0'), '.'); + + return $text === '-0' ? '0' : $text; + } +} diff --git a/lib/TemplateRepository.php b/lib/TemplateRepository.php index 68292df..d84a413 100644 --- a/lib/TemplateRepository.php +++ b/lib/TemplateRepository.php @@ -45,15 +45,13 @@ public function unlock(): void { } public function recordedChecksum(): string { - $value = db_fetch_cell_prepared( + return (string) db_fetch_cell_prepared( 'SELECT value FROM settings WHERE name = ?', [self::SETTING], '', true, $this->connection ); - - return is_string($value) ? $value : ''; } public function recordChecksum(string $sha256): void { @@ -113,6 +111,26 @@ public static function hash(string $key): string { return substr(hash('sha256', 'plugin_cloud/' . $key), 0, 32); } + /** + * The id of one package object, or null when it is not imported. + */ + public function id(string $table, string $key): ?int { + if (!in_array($key, self::objects()[$table] ?? [], true)) { + return null; + } + + // $table is a key of objects(), so never input. + $id = (int) db_fetch_cell_prepared( + 'SELECT id FROM `' . $table . '` WHERE hash = ?', + [self::hash($key)], + '', + true, + $this->connection + ); + + return $id > 0 ? $id : null; + } + /** * @return list the keys of package objects not in the database */ diff --git a/locales/po/cacti.pot b/locales/po/cacti.pot index 406952f..8bbdaa4 100644 --- a/locales/po/cacti.pot +++ b/locales/po/cacti.pot @@ -37,6 +37,15 @@ msgstr "" msgid "The account and its collected data were deleted. Its Cacti devices and graphs were left in place." msgstr "" +#: cloud_accounts.php +#, php-format +msgid "The Cacti device for %s is ready." +msgstr "" + +#: cloud_accounts.php +msgid "The Cacti device was not created; see the Cacti log." +msgstr "" + #: lib/AccountInput.php msgid "Provider: choose one of the listed providers." msgstr "" @@ -127,6 +136,10 @@ msgstr "" msgid "Verify" msgstr "" +#: lib/AccountsPage.php +msgid "Device" +msgstr "" + #: lib/AccountsPage.php msgid "Actions" msgstr "" @@ -200,6 +213,15 @@ msgstr "" msgid "Instance identity" msgstr "" +#: lib/AccountsPage.php +#, php-format +msgid "Device %d" +msgstr "" + +#: lib/AccountsPage.php +msgid "Create Cacti Device" +msgstr "" + #: lib/CredentialSource.php msgid "Stored in the plugin vault" msgstr "" diff --git a/setup.php b/setup.php index 5160ed4..b30a357 100644 --- a/setup.php +++ b/setup.php @@ -399,6 +399,29 @@ function cloud_draw_navigation_text($nav) { * poller_bottom hook: start this poller's collector in the background * (REQ-COLL-001). The collector itself skips accounts of other pollers. */ +/** + * Cacti is deleting devices: forget any that were scope devices. Runs + * before the rows go, and receives the ids as an array. + * + * @param mixed $ids + * @return mixed the ids, unchanged, for the next plugin + */ +function cloud_device_remove($ids) { + if (!cloud_boot() || !is_array($ids)) { + return $ids; + } + + $devices = new \Somethingwithproof\Cloud\DeviceRepository(false, new \Somethingwithproof\Cloud\SystemClock()); + + foreach ($ids as $id) { + if (is_numeric($id)) { + $devices->unlink((int) $id); + } + } + + return $ids; +} + function cloud_poller_bottom(): void { global $config; @@ -431,6 +454,47 @@ function cloud_poller_bottom(): void { exec_background($php, array('-q', __DIR__ . '/poller_cloud.php', '--poller=' . (int) $config['poller_id'])); } +function cloud_scope_devices(): \Somethingwithproof\Cloud\ScopeDevices { + global $config; + + // The libraries host.php loads to save a device and run its data queries. + foreach (array( + 'api_data_source.php', 'api_device.php', 'api_graph.php', 'data_query.php', + 'ping.php', 'poller.php', 'snmp.php', 'template.php', 'utility.php' + ) as $file) { + include_once($config['library_path'] . '/' . $file); + } + + return new \Somethingwithproof\Cloud\ScopeDevices( + new \Somethingwithproof\Cloud\DeviceRepository(false, new \Somethingwithproof\Cloud\SystemClock()), + new \Somethingwithproof\Cloud\TemplateRepository(false), + function (\Somethingwithproof\Cloud\Account $account, int $template): int { + $id = call_user_func_array( + 'api_device_save', + \Somethingwithproof\Cloud\ScopeDevices::deviceFields($account, $template) + ); + + return is_numeric($id) ? (int) $id : 0; + }, + function (int $host, int $query): void { + run_data_query($host, $query); + } + ); +} + +function cloud_script_server(): \Somethingwithproof\Cloud\ScriptServer { + $clock = new \Somethingwithproof\Cloud\SystemClock(); + + return new \Somethingwithproof\Cloud\ScriptServer( + new \Somethingwithproof\Cloud\DeviceRepository(false, $clock), + cloud_accounts(), + new \Somethingwithproof\Cloud\ResourceRepository(false, $clock), + new \Somethingwithproof\Cloud\ObservationRepository(false), + new \Somethingwithproof\Cloud\FreshnessEvaluator($clock), + $clock + ); +} + function cloud_collector(int $pollerId): \Somethingwithproof\Cloud\Collector { $clock = new \Somethingwithproof\Cloud\SystemClock(); diff --git a/ss_cloud.php b/ss_cloud.php new file mode 100644 index 0000000..f35a3d4 --- /dev/null +++ b/ss_cloud.php @@ -0,0 +1,73 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * 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. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + + +/* + * Script server entry point for the resource data queries (#44). Cacti runs + * this file two ways: the script server includes it once per process and + * calls ss_cloud() for each poller item, and a data query reindex runs it as + * a CLI script. Kept parseable by PHP 8.0, like the other entry points. + */ + +if (!isset($called_by_script_server)) { + include_once(__DIR__ . '/../../include/cli_check.php'); + + array_shift($_SERVER['argv']); + + print call_user_func_array('ss_cloud', $_SERVER['argv']); +} + +/** + * The script server calls only a function defined in the file the poller + * item names, after checking that file resolves under Cacti's base path. + * Parameters stay untyped, like Cacti's own ss_ functions: every argument + * arrives as a string. + * + * @param mixed $host_id the calling device, from the |host_id| argument + * @param mixed $type the resource type the data query names + * @param mixed $cmd index, num_indexes, query, or get + * @param mixed $arg1 the field, for query and get + * @param mixed $arg2 the index, for get + */ +function ss_cloud($host_id = 0, $type = '', $cmd = 'index', $arg1 = '', $arg2 = '') { + include_once(__DIR__ . '/setup.php'); + + $get = $cmd === 'get'; + + // An unsupported runtime or a disabled plugin serves nothing. + if (!cloud_php_supported() || !api_plugin_is_enabled('cloud') || !cloud_boot()) { + return $get ? 'U' : ''; + } + + $output = cloud_script_server()->run( + is_numeric($host_id) ? (int) $host_id : 0, + is_string($type) ? $type : '', + is_string($cmd) ? $cmd : '', + is_scalar($arg1) ? (string) $arg1 : '', + is_scalar($arg2) ? (string) $arg2 : '' + ); + + if ($get) { + return $output; + } + + print $output; + + return ''; +} diff --git a/tests/Integration/LifecycleTest.php b/tests/Integration/LifecycleTest.php index 6bd53a1..a922a87 100644 --- a/tests/Integration/LifecycleTest.php +++ b/tests/Integration/LifecycleTest.php @@ -20,9 +20,13 @@ // The version INFO declares, which Cacti records as the installed version. define('CLOUD_VERSION', (string) (parse_ini_file(dirname(__DIR__, 2) . '/INFO', true)['info']['version'] ?? '')); +// Schema::VERSION; the integration process does not load the plugin classes. +const CLOUD_SCHEMA = '3'; + const CLOUD_TABLES = [ 'plugin_cloud_account', 'plugin_cloud_audit', + 'plugin_cloud_device', 'plugin_cloud_health', 'plugin_cloud_lease', 'plugin_cloud_observation', @@ -31,7 +35,7 @@ 'plugin_cloud_series', ]; -const CLOUD_HOOKS = ['config_arrays', 'config_settings', 'draw_navigation_text', 'poller_bottom']; +const CLOUD_HOOKS = ['config_arrays', 'config_settings', 'device_remove', 'draw_navigation_text', 'poller_bottom']; beforeEach(function () { lifecycle('reset'); @@ -46,7 +50,7 @@ expect($state['plugin']['status'])->toEqual('4') ->and($state['plugin']['version'])->toEqual(CLOUD_VERSION) - ->and($state['schema'])->toEqual('2') + ->and($state['schema'])->toEqual(CLOUD_SCHEMA) ->and(array_keys($state['tables']))->toBe(CLOUD_TABLES) ->and($state['tracked'])->toBe(CLOUD_TABLES) ->and(array_keys($state['hooks']))->toBe(CLOUD_HOOKS) @@ -116,7 +120,7 @@ expect($state['result'])->toBeTrue() ->and(array_keys($state['tables']))->toBe(CLOUD_TABLES) ->and($state['tables']['plugin_cloud_account'])->toBe(1) - ->and($state['schema'])->toEqual('2') + ->and($state['schema'])->toEqual(CLOUD_SCHEMA) ->and($state['plugin']['version'])->toEqual(CLOUD_VERSION); }); @@ -129,7 +133,7 @@ ->and($stopped['schema'])->toEqual('0'); $finished = lifecycle('upgrade'); - expect($finished['schema'])->toEqual('2'); + expect($finished['schema'])->toEqual(CLOUD_SCHEMA); }); it('adds the retry column to a version 1 database, and a kept uninstall keeps it', function () { @@ -140,7 +144,7 @@ $upgraded = lifecycle('upgrade'); expect($upgraded['result'])->toBeTrue() - ->and($upgraded['schema'])->toEqual('2') + ->and($upgraded['schema'])->toEqual(CLOUD_SCHEMA) ->and($upgraded['health_columns'])->toContain('retry_at') ->and($upgraded['tracked_columns'])->toBe(['plugin_cloud_health.retry_at']) ->and($upgraded['tables']['plugin_cloud_account'])->toBe(1); @@ -151,10 +155,22 @@ ->and($kept['tracked_columns'])->toBe([]); $reinstalled = lifecycle('install'); - expect($reinstalled['schema'])->toEqual('2') + expect($reinstalled['schema'])->toEqual(CLOUD_SCHEMA) ->and($reinstalled['health_columns'])->toContain('retry_at'); }); +it('creates the device table on a version 2 database and tracks it for uninstall', function () { + lifecycle('install'); + lifecycle('drop_table', 'plugin_cloud_device'); + lifecycle('set_schema', '2'); + + $upgraded = lifecycle('upgrade'); + expect($upgraded['result'])->toBeTrue() + ->and($upgraded['schema'])->toEqual(CLOUD_SCHEMA) + ->and(array_keys($upgraded['tables']))->toContain('plugin_cloud_device') + ->and($upgraded['tracked'])->toContain('plugin_cloud_device'); +}); + it('refuses a schema newer than the code and leaves the recorded version alone', function () { lifecycle('install'); lifecycle('set_schema', '99'); diff --git a/tests/Integration/ScopeDeviceTest.php b/tests/Integration/ScopeDeviceTest.php new file mode 100644 index 0000000..3ae77bd --- /dev/null +++ b/tests/Integration/ScopeDeviceTest.php @@ -0,0 +1,80 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * 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. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + + +/* + * Scope devices against a real Cacti (#43, #44): created through Cacti's + * device API, indexed through ss_cloud(), and kept in step with discovery. + */ + +beforeEach(function () { + lifecycle('reset'); + lifecycle('install'); + lifecycle('enable'); + lifecycle('seed'); +}); + +afterAll(function () { + lifecycle('reset'); +}); + +it('creates a scope device with its template, no availability check, and the account\'s poller', function () { + $created = lifecycle('scope_device'); + $host = $created['result']; + + expect($host)->toBeGreaterThan(0) + ->and($created['devices'])->toBe([[ + 'host_id' => $host, + 'account_id' => $created['devices'][0]['account_id'], + 'description' => 'Seed', + 'availability_method' => 0, + 'poller_id' => 1, + 'template' => 'Cloud: DigitalOcean Scope', + ]]) + ->and($created['device_queries'])->toBe(['Cloud: DigitalOcean Droplets', 'Cloud: DigitalOcean Load Balancers']) + ->and($created['device_index'])->toBe(['101' => 'web-1', '102' => 'web-2']); +}); + +it('reindexes resources added, renamed, and retired upstream', function () { + lifecycle('scope_device'); + lifecycle('resource', '103=web-3'); + lifecycle('resource', '101=web-1-renamed'); + lifecycle('resource', '102=deleted'); + + expect(lifecycle('reindex')['device_index'])->toBe(['101' => 'web-1-renamed', '103' => 'web-3']); +}); + +it('serves the device\'s own resources through the script server, and nothing to another device', function () { + $host = (string) lifecycle('scope_device')['result']; + + expect(lifecycle('ss', $host . ' droplet get resourceName 101')['result'])->toBe('web-1') + ->and(lifecycle('ss', $host . ' droplet get do_cpu_pct 101')['result'])->toBe('U') + ->and(lifecycle('ss', '1 droplet get resourceName 101')['result'])->toBe('U') + ->and(lifecycle('ss', $host . ' droplet num_indexes')['output'])->toBe('2'); +}); + +it('forgets the device when Cacti deletes it, and creates a new one on request', function () { + $first = lifecycle('scope_device')['result']; + + expect(lifecycle('remove_device')['devices'])->toBe([]); + + $second = lifecycle('scope_device'); + expect($second['result'])->toBeGreaterThan($first) + ->and($second['devices'])->toHaveCount(1); +}); diff --git a/tests/Unit/AccountTest.php b/tests/Unit/AccountTest.php index d297edc..5d1bdad 100644 --- a/tests/Unit/AccountTest.php +++ b/tests/Unit/AccountTest.php @@ -244,6 +244,7 @@ function cloud_delete_with(array $inTransaction): array { 'plugin_cloud_series', 'plugin_cloud_lease', 'plugin_cloud_health', + 'plugin_cloud_device', 'plugin_cloud_observation', 'plugin_cloud_resource', 'plugin_cloud_account', @@ -264,6 +265,7 @@ function cloud_delete_with(array $inTransaction): array { 'plugin_cloud_series', 'plugin_cloud_lease', 'plugin_cloud_health', + 'plugin_cloud_device', 'plugin_cloud_observation', 'plugin_cloud_resource', 'plugin_cloud_account', diff --git a/tests/Unit/ScriptServerTest.php b/tests/Unit/ScriptServerTest.php new file mode 100644 index 0000000..6a66202 --- /dev/null +++ b/tests/Unit/ScriptServerTest.php @@ -0,0 +1,177 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * 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. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + + +use Somethingwithproof\Cloud\AccountRepository; +use Somethingwithproof\Cloud\DeviceRepository; +use Somethingwithproof\Cloud\FixedClock; +use Somethingwithproof\Cloud\FreshnessEvaluator; +use Somethingwithproof\Cloud\ObservationRepository; +use Somethingwithproof\Cloud\ResourceRepository; +use Somethingwithproof\Cloud\ScriptServer; + +/* + * ss_cloud()'s answers (#44) against the database stubs: one account whose + * scope device is host 7, one Droplet, and its cached datapoints. + */ + +const CLOUD_SS_NOW = 1_800_000_000; + +function cloud_ss(): ScriptServer { + $clock = new FixedClock(CLOUD_SS_NOW); + + return new ScriptServer( + new DeviceRepository(false, $clock), + new AccountRepository(false, $clock), + new ResourceRepository(false, $clock), + new ObservationRepository(false), + new FreshnessEvaluator($clock), + $clock + ); +} + +/** + * @param list> $observations + */ +function cloud_ss_world(array $observations = [], array $account = [], ?int $owner = 4): void { + $GLOBALS['__cloud_db_rows'] = [ + 'FROM plugin_cloud_device' => $owner === null ? [] : [['account_id' => $owner]], + 'FROM plugin_cloud_account' => [$account + [ + 'id' => 4, + 'provider' => 'digitalocean', + 'name' => 'Ops', + 'credential_source' => 'vault', + 'collect_interval' => 300, + 'admin_state' => 'enabled', + ]], + 'FROM plugin_cloud_resource' => [[ + 'id' => 11, + 'provider_id' => '3164444', + 'name' => "web!01\nprod", + 'first_seen' => CLOUD_SS_NOW - 5000, + ]], + 'FROM plugin_cloud_observation' => $observations, + ]; +} + +function cloud_ss_obs(string $metric, ?float $value, int $age, string $status = 'ok'): array { + return [ + 'resource_id' => 11, + 'metric' => $metric, + 'value' => $value, + 'observed_at' => $value === null && $status !== 'ok' ? 0 : CLOUD_SS_NOW - $age, + 'fetched_at' => CLOUD_SS_NOW - 10, + 'status' => $status, + ]; +} + +it('lists the account\'s resources as indexes, with ids and names for reindex', function () { + cloud_ss_world(); + + expect(cloud_ss()->run(7, 'droplet', 'index'))->toBe("3164444\n") + ->and(cloud_ss()->run(7, 'droplet', 'num_indexes'))->toBe('1') + ->and(cloud_ss()->run(7, 'droplet', 'query', 'resourceId'))->toBe("3164444!3164444\n") + ->and(cloud_ss()->run(7, 'droplet', 'query', 'resourceName'))->toBe("3164444!web 01 prod\n"); +}); + +dataset('freshness', [ + // The account interval is 300 s, so current is within 600 s and delayed within 1200 s. + 'current' => [cloud_ss_obs('do_cpu_pct', 12.5, 60), '12.5'], + 'delayed' => [cloud_ss_obs('do_cpu_pct', 12.5, 900), '12.5'], + 'stale' => [cloud_ss_obs('do_cpu_pct', 12.5, 1300), 'U'], + 'skewed' => [cloud_ss_obs('do_cpu_pct', 12.5, -600), 'U'], + 'no value' => [cloud_ss_obs('do_cpu_pct', null, 60), 'U'], + 'budget' => [cloud_ss_obs('do_cpu_pct', 12.5, 60, 'budget'), 'U'], + 'failed' => [cloud_ss_obs('do_cpu_pct', null, 60, 'failed'), 'U'], + 'never' => [cloud_ss_obs('do_cpu_pct', null, 0, 'never'), 'U'], +]); + +it('serves a value only while it is current or delayed, and U otherwise', function ( + array $observation, + string $expected +) { + cloud_ss_world([$observation]); + + expect(cloud_ss()->run(7, 'droplet', 'get', 'do_cpu_pct', '3164444'))->toBe($expected) + ->and(cloud_ss()->run(7, 'droplet', 'query', 'do_cpu_pct'))->toBe('3164444!' . $expected . "\n"); +})->with('freshness'); + +it('serves U for a metric never collected and for a disabled account', function () { + cloud_ss_world([cloud_ss_obs('do_cpu_pct', 12.5, 60)]); + expect(cloud_ss()->run(7, 'droplet', 'get', 'do_bw_pub_in', '3164444'))->toBe('U'); + + cloud_ss_world([cloud_ss_obs('do_cpu_pct', 12.5, 60)], ['admin_state' => 'disabled']); + expect(cloud_ss()->run(7, 'droplet', 'get', 'do_cpu_pct', '3164444'))->toBe('U'); +}); + +it('keeps age numeric: since the newest value, or since discovery without one', function () { + cloud_ss_world([cloud_ss_obs('do_cpu_pct', 1.0, 90), cloud_ss_obs('do_bw_pub_in', 2.0, 40)]); + expect(cloud_ss()->run(7, 'droplet', 'get', 'do_age', '3164444'))->toBe('40'); + + cloud_ss_world([cloud_ss_obs('do_cpu_pct', null, 0, 'never')]); + expect(cloud_ss()->run(7, 'droplet', 'get', 'do_age', '3164444'))->toBe('5000'); + + cloud_ss_world([], ['admin_state' => 'disabled']); + expect(cloud_ss()->run(7, 'droplet', 'get', 'do_age', '3164444'))->toBe('5000'); +}); + +it('refuses a device that is no account\'s scope device', function () { + cloud_ss_world([cloud_ss_obs('do_cpu_pct', 12.5, 60)], [], null); + + expect(cloud_ss()->run(8, 'droplet', 'index'))->toBe('') + ->and(cloud_ss()->run(8, 'droplet', 'num_indexes'))->toBe('0') + ->and(cloud_ss()->run(8, 'droplet', 'query', 'do_cpu_pct'))->toBe('') + ->and(cloud_ss()->run(8, 'droplet', 'get', 'do_cpu_pct', '3164444'))->toBe('U'); +}); + +it('refuses an index that is not one of the device\'s resources', function () { + cloud_ss_world([cloud_ss_obs('do_cpu_pct', 12.5, 60)]); + + expect(cloud_ss()->run(7, 'droplet', 'get', 'do_cpu_pct', '9999'))->toBe('U') + ->and(cloud_ss()->run(7, 'droplet', 'get', 'do_cpu_pct', ''))->toBe('U'); +}); + +it('validates the type, command and field', function () { + cloud_ss_world([cloud_ss_obs('do_cpu_pct', 12.5, 60)]); + + expect(cloud_ss()->run(7, 'volume', 'index'))->toBe('') + ->and(cloud_ss()->run(7, 'volume', 'get', 'do_cpu_pct', '3164444'))->toBe('U') + ->and(cloud_ss()->run(7, 'droplet', 'get', 'dolb_cpu_pct', '3164444'))->toBe('U') + ->and(cloud_ss()->run(7, 'droplet', 'get', 'no_such_field', '3164444'))->toBe('U') + ->and(cloud_ss()->run(7, 'droplet', 'query', 'no_such_field'))->toBe('') + ->and(cloud_ss()->run(7, 'droplet', 'drop'))->toBe('') + ->and(cloud_ss()->run(0, 'droplet', 'get', 'do_cpu_pct', '3164444'))->toBe('U'); +}); + +it('prints plain decimals and names that cannot break the output line', function () { + expect(ScriptServer::number(1234567890123.0))->toBe('1234567890123') + ->and(ScriptServer::number(0.000001))->toBe('0.000001') + ->and(ScriptServer::number(-0.0))->toBe('0') + ->and(ScriptServer::number(INF))->toBe('U') + ->and(ScriptServer::label("a!b\r\nc\x00d"))->toBe('a b c d') + ->and(ScriptServer::label("!\n"))->toBe('U'); +}); + +it('offers the index, the name, and every data source its graphs use as fields', function () { + expect(ScriptServer::fields('droplet'))->toBe([ + 'resourceId', 'resourceName', 'do_cpu_pct', 'do_bw_pub_in', 'do_bw_pub_out', 'do_bw_prv_in', 'do_bw_prv_out', + 'do_load_1', 'do_load_5', 'do_load_15', 'do_mem_total', 'do_mem_avail', 'do_mem_free', 'do_mem_cached', 'do_age', + ]) + ->and(ScriptServer::fields('volume'))->toBe([]); +}); diff --git a/tests/bin/lifecycle.php b/tests/bin/lifecycle.php index 401343b..cc5eb08 100644 --- a/tests/bin/lifecycle.php +++ b/tests/bin/lifecycle.php @@ -160,6 +160,64 @@ array($id) ); + break; + case 'scope_device': + // The account a seed made, with two Droplets, gets its scope device. + include_once($config['base_path'] . '/plugins/cloud/setup.php'); + cloud_boot(); + $account = (int) db_fetch_cell("SELECT id FROM plugin_cloud_account WHERE name = 'Seed'"); + + foreach (array('101' => 'web-1', '102' => 'web-2') as $provider_id => $name) { + db_execute_prepared( + "INSERT IGNORE INTO plugin_cloud_resource (account_id, type, provider_id, name, lifecycle, first_seen, last_seen) + VALUES (?, 'droplet', ?, ?, 'active', UNIX_TIMESTAMP(), UNIX_TIMESTAMP())", + array($account, $provider_id, $name) + ); + } + + $result = cloud_scope_devices()->create(cloud_accounts()->find($account)); + + break; + case 'resource': + // Change one Droplet as discovery would: add, rename or retire it. + list($provider_id, $change) = explode('=', $argument, 2); + $account = (int) db_fetch_cell("SELECT id FROM plugin_cloud_account WHERE name = 'Seed'"); + + if ($change === 'deleted') { + db_execute_prepared( + "UPDATE plugin_cloud_resource SET lifecycle = 'deleted' WHERE account_id = ? AND provider_id = ?", + array($account, $provider_id) + ); + } else { + db_execute_prepared( + "INSERT INTO plugin_cloud_resource (account_id, type, provider_id, name, lifecycle, first_seen, last_seen) + VALUES (?, 'droplet', ?, ?, 'active', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()) + ON DUPLICATE KEY UPDATE name = VALUES(name)", + array($account, $provider_id, $change) + ); + } + + break; + case 'reindex': + include_once($config['base_path'] . '/lib/data_query.php'); + include_once($config['base_path'] . '/lib/snmp.php'); + + foreach (db_fetch_assoc('SELECT host_id, snmp_query_id FROM host_snmp_query') as $row) { + run_data_query($row['host_id'], $row['snmp_query_id']); + } + + break; + case 'remove_device': + include_once($config['base_path'] . '/lib/api_device.php'); + api_device_remove((int) db_fetch_cell('SELECT host_id FROM plugin_cloud_device')); + + break; + case 'ss': + // Call ss_cloud() as the script server does: " [field] [index]". + $called_by_script_server = true; + include_once($config['base_path'] . '/plugins/cloud/ss_cloud.php'); + $result = (string) call_user_func_array('ss_cloud', explode(' ', $argument)); + break; case 'drop_table': db_execute('DROP TABLE IF EXISTS `' . preg_replace('/[^a-z_]/', '', $argument) . '`'); @@ -307,6 +365,34 @@ $tables[$row['t']] = (int) db_fetch_cell('SELECT COUNT(*) FROM `' . $row['t'] . '`'); } +// The device state, only while the plugin's device table exists. +$device_state = array('devices' => array(), 'device_queries' => array(), 'device_index' => array()); + +if (isset($tables['plugin_cloud_device'])) { + $device_state = array( + 'devices' => db_fetch_assoc( + 'SELECT d.host_id, d.account_id, h.description, h.availability_method, h.poller_id, ht.name AS template + FROM plugin_cloud_device d INNER JOIN host h ON h.id = d.host_id + LEFT JOIN host_template ht ON ht.id = h.host_template_id' + ), + 'device_queries' => array_column( + db_fetch_assoc( + 'SELECT sq.name FROM host_snmp_query hsq INNER JOIN snmp_query sq ON sq.id = hsq.snmp_query_id + INNER JOIN plugin_cloud_device d ON d.host_id = hsq.host_id ORDER BY sq.name' + ), + 'name' + ), + 'device_index' => array_column( + db_fetch_assoc( + "SELECT c.snmp_index, c.field_value FROM host_snmp_cache c INNER JOIN plugin_cloud_device d ON d.host_id = c.host_id + WHERE c.field_name = 'resourceName' ORDER BY c.snmp_index" + ), + 'field_value', + 'snmp_index' + ), + ); +} + print json_encode(array( 'result' => $result, 'output' => $output, @@ -362,6 +448,10 @@ db_fetch_assoc("SELECT name FROM graph_templates WHERE name LIKE 'Cloud: %' ORDER BY name"), 'name' ), + 'devices' => $device_state['devices'], + 'device_queries' => $device_state['device_queries'], + 'device_index' => $device_state['device_index'], + 'hosts' => (int) db_fetch_cell('SELECT COUNT(*) FROM host'), 'templates_sha' => db_fetch_cell("SELECT value FROM settings WHERE name = 'cloud_templates_sha256'"), 'resource_files' => array_map( 'basename', diff --git a/tests/bin/php-guard-check.php b/tests/bin/php-guard-check.php index ffd2c59..bcabaab 100644 --- a/tests/bin/php-guard-check.php +++ b/tests/bin/php-guard-check.php @@ -117,7 +117,7 @@ function guard_call_shims() { if ($supported) { guard_expect($state['status'] == 1, 'install and enable succeed (status ' . $state['status'] . ')'); - guard_expect($state['tables'] === 8, 'all eight plugin tables exist (' . $state['tables'] . ')'); + guard_expect($state['tables'] === 9, 'all nine plugin tables exist (' . $state['tables'] . ')'); guard_expect($state['hooks'] >= 3 && $state['realms'] === 2, 'hooks and realms are registered'); } else { guard_expect( From 2e9dec8d04ac79b7d660906c65ac8b264624cc8d Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 03:57:46 -0800 Subject: [PATCH 02/17] fix: trust a scope device link only while its host still carries the account's external_id Cacti skips a disabled plugin's hooks, so a device deleted then left its link behind: creating a device again returned the dead id, and a reused host id could have been served the account. accountFor() and hostFor() now require the host row with external_id cloud:, and link() replaces any stale link before inserting. Signed-off-by: Thomas Vincent --- lib/DeviceRepository.php | 25 +++++++++++++++++++++---- lib/ScopeDevices.php | 2 +- tests/Integration/ScopeDeviceTest.php | 12 ++++++++++++ tests/bin/lifecycle.php | 5 +++++ 4 files changed, 39 insertions(+), 5 deletions(-) diff --git a/lib/DeviceRepository.php b/lib/DeviceRepository.php index 51f0060..287b23a 100644 --- a/lib/DeviceRepository.php +++ b/lib/DeviceRepository.php @@ -22,12 +22,27 @@ * Which Cacti device is each account's scope device (ADR 0010). One device * per account: the script server serves an account's resources only to its * own device (REQ-SS-004). + * + * A link counts only while its host exists and still carries the + * external_id the plugin gave it. Cacti skips a disabled plugin's hooks, so + * a device deleted then leaves its link behind, and a reused host id must + * not inherit the account. */ final class DeviceRepository { public function __construct(private readonly \PDO|false $connection, private readonly Clock $clock) { } + public const EXTERNAL_PREFIX = 'cloud:'; + + /** + * Replaces any earlier link of the account, which can only be stale when + * the caller found no live one. + */ public function link(int $hostId, int $accountId): void { + db_execute_prepared('DELETE FROM plugin_cloud_device WHERE account_id = ? OR host_id = ?', [ + $accountId, + $hostId, + ], true, $this->connection); db_execute_prepared( 'INSERT INTO plugin_cloud_device (host_id, account_id, created_at) VALUES (?, ?, ?)', [$hostId, $accountId, $this->clock->now()], @@ -45,8 +60,9 @@ public function unlink(int $hostId): void { public function accountFor(int $hostId): ?int { $id = (int) db_fetch_cell_prepared( - 'SELECT account_id FROM plugin_cloud_device WHERE host_id = ?', - [$hostId], + 'SELECT d.account_id FROM plugin_cloud_device d INNER JOIN host h ON h.id = d.host_id + WHERE d.host_id = ? AND h.external_id = CONCAT(?, d.account_id)', + [$hostId, self::EXTERNAL_PREFIX], '', true, $this->connection @@ -57,8 +73,9 @@ public function accountFor(int $hostId): ?int { public function hostFor(int $accountId): ?int { $id = (int) db_fetch_cell_prepared( - 'SELECT host_id FROM plugin_cloud_device WHERE account_id = ?', - [$accountId], + 'SELECT d.host_id FROM plugin_cloud_device d INNER JOIN host h ON h.id = d.host_id + WHERE d.account_id = ? AND h.external_id = CONCAT(?, d.account_id)', + [$accountId, self::EXTERNAL_PREFIX], '', true, $this->connection diff --git a/lib/ScopeDevices.php b/lib/ScopeDevices.php index 85786ce..641f1fe 100644 --- a/lib/ScopeDevices.php +++ b/lib/ScopeDevices.php @@ -114,7 +114,7 @@ public static function deviceFields(Account $account, int $template): array { 5, 1, // max_oids, device_threads $account->pollerId, 0, // site: none - 'cloud:' . $account->id, // external_id + DeviceRepository::EXTERNAL_PREFIX . $account->id, // external_id; the link checks it '', // location ]; } diff --git a/tests/Integration/ScopeDeviceTest.php b/tests/Integration/ScopeDeviceTest.php index 3ae77bd..eafcd1b 100644 --- a/tests/Integration/ScopeDeviceTest.php +++ b/tests/Integration/ScopeDeviceTest.php @@ -78,3 +78,15 @@ expect($second['result'])->toBeGreaterThan($first) ->and($second['devices'])->toHaveCount(1); }); + +it('ignores a link whose device went while the plugin was disabled, and replaces it', function () { + $first = (string) lifecycle('scope_device')['result']; + lifecycle('drop_host'); + + expect(lifecycle('ss', $first . ' droplet get resourceName 101')['result'])->toBe('U'); + + $second = lifecycle('scope_device'); + expect($second['result'])->toBeGreaterThan((int) $first) + ->and($second['devices'])->toHaveCount(1) + ->and($second['device_index'])->toBe(['101' => 'web-1', '102' => 'web-2']); +}); diff --git a/tests/bin/lifecycle.php b/tests/bin/lifecycle.php index cc5eb08..86adf6a 100644 --- a/tests/bin/lifecycle.php +++ b/tests/bin/lifecycle.php @@ -206,6 +206,11 @@ run_data_query($row['host_id'], $row['snmp_query_id']); } + break; + case 'drop_host': + // Delete the device row without Cacti's hooks, as when the plugin is disabled. + db_execute('DELETE h FROM host h INNER JOIN plugin_cloud_device d ON d.host_id = h.id'); + break; case 'remove_device': include_once($config['base_path'] . '/lib/api_device.php'); From 53f7545d00717f77cb3c4dac17277aa40c5dd9e8 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 04:16:42 -0800 Subject: [PATCH 03/17] fix: collect the metrics graphed on each account's scope device Nothing wrote plugin_cloud_series, so graphs created on a scope device were never collected. Each collector run now rebuilds the account's series from the Cacti data sources on its live scope device: one row per data source and catalog metric whose data query index is one of the account's resources. Age fields read nothing and get no row. Cacti's tables are only read. Provider ids are compared as binary, since the plugin's tables take the server's default collation and Cacti's use utf8mb4_unicode_ci. Signed-off-by: Thomas Vincent --- lib/Collector.php | 1 + lib/SeriesRepository.php | 90 +++++++++++++++++++++++++++ tests/Integration/ScopeDeviceTest.php | 14 +++++ tests/bin/lifecycle.php | 70 ++++++++++++++++++++- 4 files changed, 174 insertions(+), 1 deletion(-) diff --git a/lib/Collector.php b/lib/Collector.php index a74be8e..df45f1b 100644 --- a/lib/Collector.php +++ b/lib/Collector.php @@ -190,6 +190,7 @@ private function runAccount(Account $account): void { } } + $this->series->sync($account->id); $wanted = $this->series->enabledFor($account->id); [$fit, $left] = RequestBudget::split($account, $driver, $wanted, $requests); diff --git a/lib/SeriesRepository.php b/lib/SeriesRepository.php index 056926c..3ffa15f 100644 --- a/lib/SeriesRepository.php +++ b/lib/SeriesRepository.php @@ -28,6 +28,96 @@ final class SeriesRepository { public function __construct(private readonly \PDO|false $connection) { } + /** + * Rebuild an account's series from the Cacti data sources on its scope + * device (ADR 0010): one row per data source and catalog metric whose + * data query index is one of the account's resources. Age fields have + * no row, since they read nothing. Cacti's tables are only read. + * + * An account without a live scope device keeps its rows. + * + * @return bool whether the account has a scope device to sync from + */ + public function sync(int $accountId): bool { + $host = (int) db_fetch_cell_prepared( + 'SELECT d.host_id FROM plugin_cloud_device d INNER JOIN host h ON h.id = d.host_id + WHERE d.account_id = ? AND h.external_id = CONCAT(?, d.account_id)', + [$accountId, DeviceRepository::EXTERNAL_PREFIX], + '', + true, + $this->connection + ); + + if ($host <= 0) { + return false; + } + + $wanted = []; + + foreach ([DigitalOceanCatalog::DROPLET, DigitalOceanCatalog::LOAD_BALANCER] as $type) { + // Cacti's tables and the plugin's can differ in collation; ids match exactly. + $rows = db_fetch_assoc_prepared( + 'SELECT dl.id AS local_data_id, dtr.data_source_name AS metric, r.id AS resource_id + FROM data_local dl + INNER JOIN snmp_query q ON q.id = dl.snmp_query_id AND q.hash = ? + INNER JOIN data_template_rrd dtr ON dtr.local_data_id = dl.id + INNER JOIN plugin_cloud_resource r ON r.account_id = ? AND r.type = ? + AND BINARY r.provider_id = BINARY dl.snmp_index + WHERE dl.host_id = ?', + [TemplateRepository::hash('data_query/' . $type), $accountId, $type, $host], + true, + $this->connection + ); + + foreach (Row::rows($rows) as $row) { + $metric = Row::string($row, 'metric'); + + if ((DigitalOceanCatalog::metric($metric)['type'] ?? null) === $type) { + $wanted[Row::int($row, 'local_data_id') . '/' . $metric] = [ + Row::int($row, 'local_data_id'), + $metric, + Row::int($row, 'resource_id'), + ]; + } + } + } + + $existing = []; + + foreach (Row::rows(db_fetch_assoc_prepared( + 'SELECT local_data_id, metric FROM plugin_cloud_series WHERE account_id = ?', + [$accountId], + true, + $this->connection + )) as $row) { + $existing[Row::int($row, 'local_data_id') . '/' . Row::string($row, 'metric')] = [ + Row::int($row, 'local_data_id'), + Row::string($row, 'metric'), + ]; + } + + foreach (array_diff_key($existing, $wanted) as [$local, $metric]) { + db_execute_prepared( + 'DELETE FROM plugin_cloud_series WHERE account_id = ? AND local_data_id = ? AND metric = ?', + [$accountId, $local, $metric], + true, + $this->connection + ); + } + + foreach (array_diff_key($wanted, $existing) as [$local, $metric, $resource]) { + db_execute_prepared( + 'INSERT IGNORE INTO plugin_cloud_series (local_data_id, account_id, resource_id, metric, created_at) + VALUES (?, ?, ?, ?, UNIX_TIMESTAMP())', + [$local, $accountId, $resource, $metric], + true, + $this->connection + ); + } + + return true; + } + /** * @return list */ diff --git a/tests/Integration/ScopeDeviceTest.php b/tests/Integration/ScopeDeviceTest.php index eafcd1b..a060222 100644 --- a/tests/Integration/ScopeDeviceTest.php +++ b/tests/Integration/ScopeDeviceTest.php @@ -90,3 +90,17 @@ ->and($second['devices'])->toHaveCount(1) ->and($second['device_index'])->toBe(['101' => 'web-1', '102' => 'web-2']); }); + +it('collects exactly the metrics graphed on the scope device, and stops when a graph goes', function () { + lifecycle('scope_device'); + $cpu = lifecycle('graph', 'do_cpu 101')['result']; + lifecycle('graph', 'do_load 102'); + lifecycle('graph', 'do_age 102'); + + expect($cpu)->toBeGreaterThan(0) + ->and(lifecycle('sync')['series'])->toBe(['101 do_cpu_pct', '102 do_load_1', '102 do_load_15', '102 do_load_5']); + + lifecycle('remove_graph', (string) $cpu); + + expect(lifecycle('sync')['series'])->toBe(['102 do_load_1', '102 do_load_15', '102 do_load_5']); +}); diff --git a/tests/bin/lifecycle.php b/tests/bin/lifecycle.php index 86adf6a..86651ef 100644 --- a/tests/bin/lifecycle.php +++ b/tests/bin/lifecycle.php @@ -223,6 +223,59 @@ include_once($config['base_path'] . '/plugins/cloud/ss_cloud.php'); $result = (string) call_user_func_array('ss_cloud', explode(' ', $argument)); + break; + case 'graph': + // Create one plugin graph on the scope device, as New Graphs does: " ". + include_once($config['base_path'] . '/plugins/cloud/setup.php'); + include_once($config['base_path'] . '/lib/api_data_source.php'); + include_once($config['base_path'] . '/lib/api_graph.php'); + include_once($config['base_path'] . '/lib/data_query.php'); + include_once($config['base_path'] . '/lib/template.php'); + include_once($config['base_path'] . '/lib/utility.php'); + cloud_boot(); + list($key, $provider_id) = explode(' ', $argument, 2); + $type = \Somethingwithproof\Cloud\DigitalOceanCatalog::GRAPHS[$key][0]; + $templates = new \Somethingwithproof\Cloud\TemplateRepository(false); + $query = $templates->id('snmp_query', 'data_query/' . $type); + $host = (int) db_fetch_cell('SELECT host_id FROM plugin_cloud_device'); + $suggested = array(); + $created = create_complete_graph_from_template( + $templates->id('graph_templates', 'graph_template/' . $key), + $host, + array( + 'snmp_query_id' => $query, + 'snmp_index_on' => get_best_data_query_index_type($host, $query), + 'snmp_query_graph_id' => $templates->id('snmp_query_graph', 'data_query_graph/' . $key), + 'snmp_index' => $provider_id, + ), + $suggested + ); + $result = (int) $created['local_graph_id']; + + break; + case 'remove_graph': + // Delete a graph and its data sources, as the Graphs page does. + include_once($config['base_path'] . '/lib/api_data_source.php'); + include_once($config['base_path'] . '/lib/api_graph.php'); + $sources = array_column( + db_fetch_assoc_prepared( + 'SELECT DISTINCT dtr.local_data_id FROM graph_templates_item gti + INNER JOIN data_template_rrd dtr ON dtr.id = gti.task_item_id WHERE gti.local_graph_id = ?', + array((int) $argument) + ), + 'local_data_id' + ); + api_data_source_remove_multi($sources); + api_graph_remove((int) $argument); + + break; + case 'sync': + include_once($config['base_path'] . '/plugins/cloud/setup.php'); + cloud_boot(); + $result = (new \Somethingwithproof\Cloud\SeriesRepository(false))->sync( + (int) db_fetch_cell("SELECT id FROM plugin_cloud_account WHERE name = 'Seed'") + ); + break; case 'drop_table': db_execute('DROP TABLE IF EXISTS `' . preg_replace('/[^a-z_]/', '', $argument) . '`'); @@ -371,7 +424,12 @@ } // The device state, only while the plugin's device table exists. -$device_state = array('devices' => array(), 'device_queries' => array(), 'device_index' => array()); +$device_state = array( + 'devices' => array(), + 'device_queries' => array(), + 'device_index' => array(), + 'series' => array(), +); if (isset($tables['plugin_cloud_device'])) { $device_state = array( @@ -387,6 +445,15 @@ ), 'name' ), + 'series' => array_map( + function ($row) { + return $row['provider_id'] . ' ' . $row['metric']; + }, + db_fetch_assoc( + 'SELECT r.provider_id, s.metric FROM plugin_cloud_series s + INNER JOIN plugin_cloud_resource r ON r.id = s.resource_id ORDER BY r.provider_id, s.metric' + ) + ), 'device_index' => array_column( db_fetch_assoc( "SELECT c.snmp_index, c.field_value FROM host_snmp_cache c INNER JOIN plugin_cloud_device d ON d.host_id = c.host_id @@ -456,6 +523,7 @@ 'devices' => $device_state['devices'], 'device_queries' => $device_state['device_queries'], 'device_index' => $device_state['device_index'], + 'series' => $device_state['series'], 'hosts' => (int) db_fetch_cell('SELECT COUNT(*) FROM host'), 'templates_sha' => db_fetch_cell("SELECT value FROM settings WHERE name = 'cloud_templates_sha256'"), 'resource_files' => array_map( From 7c1b7a38be99171df94acd2c8a9c99e703733f42 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 09:19:01 -0800 Subject: [PATCH 04/17] fix: serve U for resources in the missing lifecycle A resource that the last discovery did not list keeps its index on the scope device, but collection stops for it. Its last value still read as current or delayed until the observation aged out. served() now returns each resource's lifecycle, and the script server answers U for any data field of a missing resource. Its id, name and age stay as they were. Signed-off-by: Thomas Vincent --- lib/ResourceRepository.php | 5 +++-- lib/ScriptServer.php | 10 ++++++++-- tests/Unit/ScriptServerTest.php | 12 ++++++++++++ 3 files changed, 23 insertions(+), 4 deletions(-) diff --git a/lib/ResourceRepository.php b/lib/ResourceRepository.php index 90a3508..e587b7a 100644 --- a/lib/ResourceRepository.php +++ b/lib/ResourceRepository.php @@ -86,13 +86,13 @@ public function sync(int $accountId, Inventory $inventory, LeaseRepository $leas * Resources a scope device serves: every one discovery has not retired, * so a missing resource keeps its index and reads as unknown. * - * @return list + * @return list */ public function served(int $accountId, string $type): array { $out = []; foreach (Row::rows(db_fetch_assoc_prepared( - 'SELECT id, provider_id, name, first_seen FROM plugin_cloud_resource + 'SELECT id, provider_id, name, first_seen, lifecycle FROM plugin_cloud_resource WHERE account_id = ? AND type = ? AND lifecycle != ? ORDER BY provider_id', [$accountId, $type, Lifecycle::Deleted->value], true, @@ -103,6 +103,7 @@ public function served(int $accountId, string $type): array { 'providerId' => Row::string($row, 'provider_id'), 'name' => Row::string($row, 'name'), 'firstSeen' => Row::int($row, 'first_seen'), + 'lifecycle' => Row::string($row, 'lifecycle'), ]; } diff --git a/lib/ScriptServer.php b/lib/ScriptServer.php index 87bc410..e0b4973 100644 --- a/lib/ScriptServer.php +++ b/lib/ScriptServer.php @@ -116,7 +116,7 @@ private function get(Account $account, string $type, string $field, string $inde } /** - * @param array{id: int, providerId: string, name: string, firstSeen: int} $resource + * @param array{id: int, providerId: string, name: string, firstSeen: int, lifecycle: string} $resource */ private function value(Account $account, array $resource, string $field): string { if ($field === 'resourceId') { @@ -133,6 +133,12 @@ private function value(Account $account, array $resource, string $field): string return (string) $this->age($resource, $entries); } + // Collection has stopped for a resource discovery no longer lists, so + // its last value would read as current until it aged out. + if ($resource['lifecycle'] === Lifecycle::Missing->value) { + return self::UNKNOWN; + } + $entry = $entries[$field] ?? null; if (!$account->enabled() || $entry === null) { @@ -152,7 +158,7 @@ private function value(Account $account, array $resource, string $field): string * Seconds since the newest datapoint with a value, or since discovery * when there is none; never negative, always numeric (REQ-SS-003). * - * @param array{id: int, providerId: string, name: string, firstSeen: int} $resource + * @param array{id: int, providerId: string, name: string, firstSeen: int, lifecycle: string} $resource * @param array $entries */ private function age(array $resource, array $entries): int { diff --git a/tests/Unit/ScriptServerTest.php b/tests/Unit/ScriptServerTest.php index 6a66202..375d0aa 100644 --- a/tests/Unit/ScriptServerTest.php +++ b/tests/Unit/ScriptServerTest.php @@ -65,6 +65,7 @@ function cloud_ss_world(array $observations = [], array $account = [], ?int $own 'provider_id' => '3164444', 'name' => "web!01\nprod", 'first_seen' => CLOUD_SS_NOW - 5000, + 'lifecycle' => 'active', ]], 'FROM plugin_cloud_observation' => $observations, ]; @@ -120,6 +121,17 @@ function cloud_ss_obs(string $metric, ?float $value, int $age, string $status = expect(cloud_ss()->run(7, 'droplet', 'get', 'do_cpu_pct', '3164444'))->toBe('U'); }); +it('serves U for a resource discovery no longer lists, but keeps its index, name and age', function () { + cloud_ss_world([cloud_ss_obs('do_cpu_pct', 12.5, 60)]); + $GLOBALS['__cloud_db_rows']['FROM plugin_cloud_resource'][0]['lifecycle'] = 'missing'; + + expect(cloud_ss()->run(7, 'droplet', 'get', 'do_cpu_pct', '3164444'))->toBe('U') + ->and(cloud_ss()->run(7, 'droplet', 'query', 'do_cpu_pct'))->toBe("3164444!U\n") + ->and(cloud_ss()->run(7, 'droplet', 'index'))->toBe("3164444\n") + ->and(cloud_ss()->run(7, 'droplet', 'get', 'resourceName', '3164444'))->toBe('web 01 prod') + ->and(cloud_ss()->run(7, 'droplet', 'get', 'do_age', '3164444'))->toBe('60'); +}); + it('keeps age numeric: since the newest value, or since discovery without one', function () { cloud_ss_world([cloud_ss_obs('do_cpu_pct', 1.0, 90), cloud_ss_obs('do_bw_pub_in', 2.0, 40)]); expect(cloud_ss()->run(7, 'droplet', 'get', 'do_age', '3164444'))->toBe('40'); From bf4610882f444df11af8296ea9b8d5c38659c7c8 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 09:20:04 -0800 Subject: [PATCH 05/17] fix: age a series skipped for budget from the datapoint it kept markUnread() records the budget status but keeps the series' last value and timestamp. The age field counted only datapoints with status ok, so one budget skip moved the age back to the resource's discovery time and could raise a false stale-collection alert. Age now comes from the newest datapoint with a value, whatever its status. Signed-off-by: Thomas Vincent --- lib/ScriptServer.php | 6 ++++-- tests/Unit/ScriptServerTest.php | 7 +++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/lib/ScriptServer.php b/lib/ScriptServer.php index e0b4973..817873b 100644 --- a/lib/ScriptServer.php +++ b/lib/ScriptServer.php @@ -156,7 +156,9 @@ private function value(Account $account, array $resource, string $field): string /** * Seconds since the newest datapoint with a value, or since discovery - * when there is none; never negative, always numeric (REQ-SS-003). + * when there is none; never negative, always numeric (REQ-SS-003). A + * series skipped for budget keeps its last datapoint, and with it its + * age, whatever status the skip recorded. * * @param array{id: int, providerId: string, name: string, firstSeen: int, lifecycle: string} $resource * @param array $entries @@ -165,7 +167,7 @@ private function age(array $resource, array $entries): int { $newest = 0; foreach ($entries as $entry) { - if ($entry['observation']->value !== null && $entry['status'] === 'ok') { + if ($entry['observation']->value !== null) { $newest = max($newest, $entry['observation']->observedAt); } } diff --git a/tests/Unit/ScriptServerTest.php b/tests/Unit/ScriptServerTest.php index 375d0aa..c060e32 100644 --- a/tests/Unit/ScriptServerTest.php +++ b/tests/Unit/ScriptServerTest.php @@ -143,6 +143,13 @@ function cloud_ss_obs(string $metric, ?float $value, int $age, string $status = expect(cloud_ss()->run(7, 'droplet', 'get', 'do_age', '3164444'))->toBe('5000'); }); +it('ages a series skipped for budget from the datapoint it kept, not from discovery', function () { + cloud_ss_world([cloud_ss_obs('do_cpu_pct', 12.5, 60, 'budget')]); + + expect(cloud_ss()->run(7, 'droplet', 'get', 'do_age', '3164444'))->toBe('60') + ->and(cloud_ss()->run(7, 'droplet', 'get', 'do_cpu_pct', '3164444'))->toBe('U'); +}); + it('refuses a device that is no account\'s scope device', function () { cloud_ss_world([cloud_ss_obs('do_cpu_pct', 12.5, 60)], [], null); From 9697255c999688f12e327f9dae0e494aad5c4a36 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 09:21:09 -0800 Subject: [PATCH 06/17] fix: remove a new scope device whose account link was not recorded link() ignored the results of its DELETE and INSERT. When the mapping write failed after Cacti saved the host, create() indexed an unlinked device and the page reported it ready, although the script server served it nothing. link() now reports whether both writes succeeded. On failure, create() removes the new host through api_device_remove(), logs an error and returns 0, so a retry starts from a clean state. The unit database stub can now fail chosen statements the way core's wrapper reports an SQL error. Signed-off-by: Thomas Vincent --- lib/DeviceRepository.php | 21 ++++---- lib/ScopeDevices.php | 11 +++- setup.php | 3 ++ tests/Unit/ScopeDevicesTest.php | 95 +++++++++++++++++++++++++++++++++ tests/bootstrap-unit.php | 11 +++- 5 files changed, 130 insertions(+), 11 deletions(-) create mode 100644 tests/Unit/ScopeDevicesTest.php diff --git a/lib/DeviceRepository.php b/lib/DeviceRepository.php index 287b23a..a36b431 100644 --- a/lib/DeviceRepository.php +++ b/lib/DeviceRepository.php @@ -37,18 +37,21 @@ public function __construct(private readonly \PDO|false $connection, private rea /** * Replaces any earlier link of the account, which can only be stale when * the caller found no live one. + * + * @return bool whether the link was recorded; without it the device + * serves nothing */ - public function link(int $hostId, int $accountId): void { - db_execute_prepared('DELETE FROM plugin_cloud_device WHERE account_id = ? OR host_id = ?', [ + public function link(int $hostId, int $accountId): bool { + return db_execute_prepared('DELETE FROM plugin_cloud_device WHERE account_id = ? OR host_id = ?', [ $accountId, $hostId, - ], true, $this->connection); - db_execute_prepared( - 'INSERT INTO plugin_cloud_device (host_id, account_id, created_at) VALUES (?, ?, ?)', - [$hostId, $accountId, $this->clock->now()], - true, - $this->connection - ); + ], true, $this->connection) !== false + && db_execute_prepared( + 'INSERT INTO plugin_cloud_device (host_id, account_id, created_at) VALUES (?, ?, ?)', + [$hostId, $accountId, $this->clock->now()], + true, + $this->connection + ) !== false; } /** diff --git a/lib/ScopeDevices.php b/lib/ScopeDevices.php index 641f1fe..a0b6ecd 100644 --- a/lib/ScopeDevices.php +++ b/lib/ScopeDevices.php @@ -38,12 +38,14 @@ final class ScopeDevices { * @param \Closure(Account, int): int $save api_device_save() for this account * and device template, returning the new device id or 0 * @param \Closure(int, int): void $reindex run_data_query() for a device and data query + * @param \Closure(int): void $remove api_device_remove() for a device */ public function __construct( private readonly DeviceRepository $devices, private readonly TemplateRepository $templates, private readonly \Closure $save, private readonly \Closure $reindex, + private readonly \Closure $remove, ) { } @@ -75,7 +77,14 @@ public function create(Account $account): int { return 0; } - $this->devices->link($host, $account->id); + // An unlinked device would look ready but serve nothing, and a retry + // would make another; remove it so the retry starts clean. + if (!$this->devices->link($host, $account->id)) { + ($this->remove)($host); + Log::error(sprintf('Account %d: the scope device link was not recorded; removed device %d', $account->id, $host)); + + return 0; + } // Saving applied the template's data queries and indexed them before // the link existed, so they found nothing; index them again now. diff --git a/setup.php b/setup.php index b30a357..c843f13 100644 --- a/setup.php +++ b/setup.php @@ -478,6 +478,9 @@ function (\Somethingwithproof\Cloud\Account $account, int $template): int { }, function (int $host, int $query): void { run_data_query($host, $query); + }, + function (int $host): void { + api_device_remove($host); } ); } diff --git a/tests/Unit/ScopeDevicesTest.php b/tests/Unit/ScopeDevicesTest.php new file mode 100644 index 0000000..9598671 --- /dev/null +++ b/tests/Unit/ScopeDevicesTest.php @@ -0,0 +1,95 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * 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. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +use Somethingwithproof\Cloud\Account; +use Somethingwithproof\Cloud\DeviceRepository; +use Somethingwithproof\Cloud\FixedClock; +use Somethingwithproof\Cloud\ScopeDevices; +use Somethingwithproof\Cloud\TemplateRepository; + +/* + * Scope device creation against the database stubs, with Cacti's device + * API replaced by closures that record their calls. Account 4 has no live + * scope device; Cacti saves its new one as host 42. + */ + +function cloud_scope_world(): void { + $GLOBALS['__cloud_db_exec'] = []; + $GLOBALS['__cloud_db_fail'] = []; + $GLOBALS['__cloud_log'] = []; + $GLOBALS['__cloud_db_rows'] = [ + 'FROM plugin_cloud_device' => [], + 'FROM `host_template`' => [['id' => 3]], + 'FROM `snmp_query`' => [['id' => 9]], + ]; + $GLOBALS['__cloud_scope'] = ['saved' => [], 'reindexed' => [], 'removed' => []]; +} + +function cloud_scope_devices_under_test(): ScopeDevices { + return new ScopeDevices( + new DeviceRepository(false, new FixedClock(1_800_000_000)), + new TemplateRepository(false), + static function (Account $account, int $template): int { + $GLOBALS['__cloud_scope']['saved'][] = $template; + + return 42; + }, + static function (int $host, int $query): void { + $GLOBALS['__cloud_scope']['reindexed'][] = [$host, $query]; + }, + static function (int $host): void { + $GLOBALS['__cloud_scope']['removed'][] = $host; + } + ); +} + +function cloud_scope_account(): Account { + $account = Account::fromRow([ + 'id' => 4, + 'provider' => 'digitalocean', + 'name' => 'Ops', + 'credential_source' => 'vault', + 'admin_state' => 'enabled', + ]); + + expect($account)->not->toBeNull(); + + return $account; +} + +it('links the device it saved and indexes its data queries', function () { + cloud_scope_world(); + + expect(cloud_scope_devices_under_test()->create(cloud_scope_account()))->toBe(42) + ->and($GLOBALS['__cloud_scope']['saved'])->toBe([3]) + ->and($GLOBALS['__cloud_scope']['reindexed'])->toBe([[42, 9], [42, 9]]) + ->and($GLOBALS['__cloud_scope']['removed'])->toBe([]); +}); + +it('removes the device it saved when the link is not recorded, and reports failure', function () { + cloud_scope_world(); + $GLOBALS['__cloud_db_fail'] = ['INSERT INTO plugin_cloud_device']; + + expect(cloud_scope_devices_under_test()->create(cloud_scope_account()))->toBe(0) + ->and($GLOBALS['__cloud_scope']['removed'])->toBe([42]) + ->and($GLOBALS['__cloud_scope']['reindexed'])->toBe([]) + ->and(implode("\n", array_column($GLOBALS['__cloud_log'], 'message')))->toContain('ERROR: Account 4'); + + $GLOBALS['__cloud_db_fail'] = []; +}); diff --git a/tests/bootstrap-unit.php b/tests/bootstrap-unit.php index a8b7950..6707eb9 100644 --- a/tests/bootstrap-unit.php +++ b/tests/bootstrap-unit.php @@ -72,9 +72,12 @@ function read_config_option($config_name, $force = false) { // Repositories in unit tests talk to these stubs. A test reads the // statements from $GLOBALS['__cloud_db_exec'] and queues query results in -// $GLOBALS['__cloud_db_rows'] (keyed by a substring of the SQL). +// $GLOBALS['__cloud_db_rows'] (keyed by a substring of the SQL). A statement +// containing a substring listed in $GLOBALS['__cloud_db_fail'] fails, as +// core's wrapper reports an SQL error, by returning false. $GLOBALS['__cloud_db_exec'] = []; $GLOBALS['__cloud_db_rows'] = []; +$GLOBALS['__cloud_db_fail'] = []; function cloud_test_rows(string $sql): mixed { foreach ($GLOBALS['__cloud_db_rows'] as $needle => $rows) { @@ -90,6 +93,12 @@ function cloud_test_rows(string $sql): mixed { function db_execute_prepared($sql, $params = [], $log = true, $db_conn = false, $log_function = null) { $GLOBALS['__cloud_db_exec'][] = ['sql' => $sql, 'params' => $params]; + foreach ($GLOBALS['__cloud_db_fail'] as $needle) { + if (str_contains($sql, $needle)) { + return false; + } + } + return true; } } From 17cebdacc2598aacdeb14a2454157af2fa9e28c4 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 09:25:11 -0800 Subject: [PATCH 07/17] fix: leave an account's series unchanged when its data sources cannot be read db_fetch_assoc_prepared() returns false on an SQL error, and Row::rows() reads that as no rows. A failed query for one resource type therefore looked like a device without data sources of that type, and sync() deleted every series of that type until a later sync restored them. sync() now stops and changes nothing when either the scope device's data sources or the existing series cannot be read, and logs a warning for the first. Signed-off-by: Thomas Vincent --- lib/SeriesRepository.php | 23 ++++++++--- tests/Unit/SeriesRepositoryTest.php | 61 +++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+), 5 deletions(-) create mode 100644 tests/Unit/SeriesRepositoryTest.php diff --git a/lib/SeriesRepository.php b/lib/SeriesRepository.php index 3ffa15f..4165f53 100644 --- a/lib/SeriesRepository.php +++ b/lib/SeriesRepository.php @@ -34,9 +34,11 @@ public function __construct(private readonly \PDO|false $connection) { * data query index is one of the account's resources. Age fields have * no row, since they read nothing. Cacti's tables are only read. * - * An account without a live scope device keeps its rows. + * An account without a live scope device keeps its rows, and so does one + * whose data sources could not be read: a failed query is not an empty + * device. * - * @return bool whether the account has a scope device to sync from + * @return bool whether the series were rebuilt */ public function sync(int $accountId): bool { $host = (int) db_fetch_cell_prepared( @@ -69,6 +71,12 @@ public function sync(int $accountId): bool { $this->connection ); + if (!is_array($rows)) { + Log::warning(sprintf('Account %d: scope device data sources unreadable; series left unchanged', $accountId)); + + return false; + } + foreach (Row::rows($rows) as $row) { $metric = Row::string($row, 'metric'); @@ -83,13 +91,18 @@ public function sync(int $accountId): bool { } $existing = []; - - foreach (Row::rows(db_fetch_assoc_prepared( + $rows = db_fetch_assoc_prepared( 'SELECT local_data_id, metric FROM plugin_cloud_series WHERE account_id = ?', [$accountId], true, $this->connection - )) as $row) { + ); + + if (!is_array($rows)) { + return false; + } + + foreach (Row::rows($rows) as $row) { $existing[Row::int($row, 'local_data_id') . '/' . Row::string($row, 'metric')] = [ Row::int($row, 'local_data_id'), Row::string($row, 'metric'), diff --git a/tests/Unit/SeriesRepositoryTest.php b/tests/Unit/SeriesRepositoryTest.php new file mode 100644 index 0000000..f2eee41 --- /dev/null +++ b/tests/Unit/SeriesRepositoryTest.php @@ -0,0 +1,61 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * 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. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +use Somethingwithproof\Cloud\SeriesRepository; + +/* + * Series sync against the database stubs: account 4's scope device is host + * 7, and its one recorded series reads do_cpu_pct from data source 5. + */ + +/** + * @param list>|false $sources the scope device's data sources + */ +function cloud_series_world(array|false $sources): void { + $GLOBALS['__cloud_db_exec'] = []; + $GLOBALS['__cloud_db_rows'] = [ + 'FROM plugin_cloud_device' => [['host_id' => 7]], + 'FROM data_local' => $sources, + 'FROM plugin_cloud_series' => [['local_data_id' => 5, 'metric' => 'do_cpu_pct']], + ]; +} + +/** + * @return list the mutating statements the sync ran + */ +function cloud_series_writes(): array { + return array_values(array_filter( + array_map(static fn (array $exec): string => strtok(trim($exec['sql']), ' '), $GLOBALS['__cloud_db_exec']), + static fn (string $verb): bool => in_array($verb, ['DELETE', 'INSERT'], true) + )); +} + +it('replaces the series whose data sources changed', function () { + cloud_series_world([['local_data_id' => 6, 'metric' => 'do_load_1', 'resource_id' => 11]]); + + expect((new SeriesRepository(false))->sync(4))->toBeTrue() + ->and(cloud_series_writes())->toBe(['DELETE', 'INSERT']); +}); + +it('deletes nothing when the scope device\'s data sources cannot be read', function () { + cloud_series_world(false); + + expect((new SeriesRepository(false))->sync(4))->toBeFalse() + ->and(cloud_series_writes())->toBe([]); +}); From c949b7014dfa5729f61ce28eac990e1e91078fb9 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 09:28:53 -0800 Subject: [PATCH 08/17] fix: fence series sync with the collector's lease sync() could read the account's series after its run's lease expired, then delete rows a newer lease holder had just inserted, working from an older snapshot of the scope device. The series changes now run in one transaction that starts with a locking read of the lease row and checks that the caller still holds the lease. If it does not, or if a write fails or leaves the transaction, sync() rolls back and changes nothing. The lease row stays locked until commit, so no other run can take the lease over between the check and the writes. The collector passes its lease holder to sync(). Signed-off-by: Thomas Vincent --- lib/Collector.php | 2 +- lib/LeaseRepository.php | 16 ++++++++ lib/SeriesRepository.php | 54 ++++++++++++++++++++++----- tests/Integration/ScopeDeviceTest.php | 15 ++++++++ tests/Unit/SeriesRepositoryTest.php | 40 ++++++++++++++++---- tests/bin/lifecycle.php | 11 ++++-- 6 files changed, 117 insertions(+), 21 deletions(-) diff --git a/lib/Collector.php b/lib/Collector.php index df45f1b..176e483 100644 --- a/lib/Collector.php +++ b/lib/Collector.php @@ -190,7 +190,7 @@ private function runAccount(Account $account): void { } } - $this->series->sync($account->id); + $this->series->sync($account->id, $this->leases, $this->holder); $wanted = $this->series->enabledFor($account->id); [$fit, $left] = RequestBudget::split($account, $driver, $wanted, $requests); diff --git a/lib/LeaseRepository.php b/lib/LeaseRepository.php index 27a9b54..b0ae5a5 100644 --- a/lib/LeaseRepository.php +++ b/lib/LeaseRepository.php @@ -58,6 +58,22 @@ public function holds(int $accountId, string $holder): bool { ) === 1; } + /** + * holds(), as a locking read for use inside a transaction: the lease row + * stays locked until the transaction ends, so no other run can take the + * lease over between this check and the caller's writes. The row is + * selected by its key alone, so it is locked whoever holds it. + */ + public function holdsForUpdate(int $accountId, string $holder): bool { + return (int) db_fetch_cell_prepared( + 'SELECT holder = ? AND expires_at >= ? FROM plugin_cloud_lease WHERE account_id = ? FOR UPDATE', + [$holder, $this->clock->now(), $accountId], + '', + true, + $this->connection + ) === 1; + } + /** * When a run last took this account's lease, or 0. Written as an attempt * starts and kept after release, so it records attempts whose results diff --git a/lib/SeriesRepository.php b/lib/SeriesRepository.php index 4165f53..834e7d9 100644 --- a/lib/SeriesRepository.php +++ b/lib/SeriesRepository.php @@ -38,9 +38,13 @@ public function __construct(private readonly \PDO|false $connection) { * whose data sources could not be read: a failed query is not an empty * device. * + * The rows change in one transaction that first locks the caller's lease + * and checks it is still held, so a run that lost its lease while it read + * cannot replace a newer holder's rows from its older snapshot. + * * @return bool whether the series were rebuilt */ - public function sync(int $accountId): bool { + public function sync(int $accountId, LeaseRepository $leases, string $holder): bool { $host = (int) db_fetch_cell_prepared( 'SELECT d.host_id FROM plugin_cloud_device d INNER JOIN host h ON h.id = d.host_id WHERE d.account_id = ? AND h.external_id = CONCAT(?, d.account_id)', @@ -90,6 +94,16 @@ public function sync(int $accountId): bool { } } + if (!db_begin_transaction($this->connection)) { + return false; + } + + if (!$leases->holdsForUpdate($accountId, $holder)) { + $this->rollback(); + + return false; + } + $existing = []; $rows = db_fetch_assoc_prepared( 'SELECT local_data_id, metric FROM plugin_cloud_series WHERE account_id = ?', @@ -99,6 +113,8 @@ public function sync(int $accountId): bool { ); if (!is_array($rows)) { + $this->rollback(); + return false; } @@ -109,26 +125,44 @@ public function sync(int $accountId): bool { ]; } + $writes = []; + foreach (array_diff_key($existing, $wanted) as [$local, $metric]) { - db_execute_prepared( + $writes[] = [ 'DELETE FROM plugin_cloud_series WHERE account_id = ? AND local_data_id = ? AND metric = ?', [$accountId, $local, $metric], - true, - $this->connection - ); + ]; } foreach (array_diff_key($wanted, $existing) as [$local, $metric, $resource]) { - db_execute_prepared( + $writes[] = [ 'INSERT IGNORE INTO plugin_cloud_series (local_data_id, account_id, resource_id, metric, created_at) VALUES (?, ?, ?, ?, UNIX_TIMESTAMP())', [$local, $accountId, $resource, $metric], - true, - $this->connection - ); + ]; + } + + foreach ($writes as [$sql, $params]) { + // InnoDB ends the transaction on a deadlock and core retries the + // statement on its own, outside the lease's lock. + if (db_execute_prepared($sql, $params, true, $this->connection) === false || !$this->inTransaction()) { + $this->rollback(); + + return false; + } } - return true; + return db_commit_transaction($this->connection) === true; + } + + private function inTransaction(): bool { + return (int) db_fetch_cell_prepared('SELECT @@in_transaction', [], '', true, $this->connection) === 1; + } + + private function rollback(): void { + if ($this->inTransaction()) { + db_rollback_transaction($this->connection); + } } /** diff --git a/tests/Integration/ScopeDeviceTest.php b/tests/Integration/ScopeDeviceTest.php index a060222..e1465e7 100644 --- a/tests/Integration/ScopeDeviceTest.php +++ b/tests/Integration/ScopeDeviceTest.php @@ -104,3 +104,18 @@ expect(lifecycle('sync')['series'])->toBe(['102 do_load_1', '102 do_load_15', '102 do_load_5']); }); + +it('leaves the series alone when the collector syncing them no longer holds the lease', function () { + lifecycle('scope_device'); + $cpu = lifecycle('graph', 'do_cpu 101')['result']; + + $stolen = lifecycle('sync', 'stolen'); + expect($stolen['result'])->toBeFalse() + ->and($stolen['series'])->toBe([]) + ->and(lifecycle('sync')['series'])->toBe(['101 do_cpu_pct']); + + lifecycle('remove_graph', (string) $cpu); + + expect(lifecycle('sync', 'stolen')['series'])->toBe(['101 do_cpu_pct']) + ->and(lifecycle('sync')['series'])->toBe([]); +}); diff --git a/tests/Unit/SeriesRepositoryTest.php b/tests/Unit/SeriesRepositoryTest.php index f2eee41..23a0722 100644 --- a/tests/Unit/SeriesRepositoryTest.php +++ b/tests/Unit/SeriesRepositoryTest.php @@ -17,45 +17,71 @@ * more details. */ +use Somethingwithproof\Cloud\FixedClock; +use Somethingwithproof\Cloud\LeaseRepository; use Somethingwithproof\Cloud\SeriesRepository; /* * Series sync against the database stubs: account 4's scope device is host - * 7, and its one recorded series reads do_cpu_pct from data source 5. + * 7, its one recorded series reads do_cpu_pct from data source 5, and run-1 + * holds its lease unless a test says otherwise. */ /** * @param list>|false $sources the scope device's data sources */ -function cloud_series_world(array|false $sources): void { +function cloud_series_world(array|false $sources, bool $held = true): void { $GLOBALS['__cloud_db_exec'] = []; $GLOBALS['__cloud_db_rows'] = [ 'FROM plugin_cloud_device' => [['host_id' => 7]], 'FROM data_local' => $sources, + 'FROM plugin_cloud_lease' => [['held' => $held ? 1 : 0]], 'FROM plugin_cloud_series' => [['local_data_id' => 5, 'metric' => 'do_cpu_pct']], ]; } +function cloud_series_sync(): bool { + return (new SeriesRepository(false))->sync(4, new LeaseRepository(false, new FixedClock(1_800_000_000)), 'run-1'); +} + /** - * @return list the mutating statements the sync ran + * @return list the transaction and mutating statements the sync ran */ function cloud_series_writes(): array { return array_values(array_filter( array_map(static fn (array $exec): string => strtok(trim($exec['sql']), ' '), $GLOBALS['__cloud_db_exec']), - static fn (string $verb): bool => in_array($verb, ['DELETE', 'INSERT'], true) + static fn (string $verb): bool => in_array($verb, ['BEGIN', 'DELETE', 'INSERT', 'COMMIT', 'ROLLBACK'], true) )); } it('replaces the series whose data sources changed', function () { cloud_series_world([['local_data_id' => 6, 'metric' => 'do_load_1', 'resource_id' => 11]]); - expect((new SeriesRepository(false))->sync(4))->toBeTrue() - ->and(cloud_series_writes())->toBe(['DELETE', 'INSERT']); + expect(cloud_series_sync())->toBeTrue() + ->and(cloud_series_writes())->toBe(['BEGIN', 'DELETE', 'INSERT', 'COMMIT']); }); it('deletes nothing when the scope device\'s data sources cannot be read', function () { cloud_series_world(false); - expect((new SeriesRepository(false))->sync(4))->toBeFalse() + expect(cloud_series_sync())->toBeFalse() ->and(cloud_series_writes())->toBe([]); }); + +it('changes nothing once another run holds the lease', function () { + cloud_series_world([['local_data_id' => 6, 'metric' => 'do_load_1', 'resource_id' => 11]], false); + + expect(cloud_series_sync())->toBeFalse() + ->and(cloud_series_writes())->toBe(['BEGIN', 'ROLLBACK']); +}); + +it('rolls back when a write leaves the transaction, as a deadlock retry does', function () { + cloud_series_world([['local_data_id' => 6, 'metric' => 'do_load_1', 'resource_id' => 11]]); + // The delete runs, but InnoDB has ended the transaction by then. + $GLOBALS['__cloud_in_tx'] = [0, 0]; + + expect(cloud_series_sync())->toBeFalse() + ->and(cloud_series_writes())->toBe(['BEGIN', 'DELETE']); + + $GLOBALS['__cloud_in_tx'] = []; +}); diff --git a/tests/bin/lifecycle.php b/tests/bin/lifecycle.php index 86651ef..715ee50 100644 --- a/tests/bin/lifecycle.php +++ b/tests/bin/lifecycle.php @@ -270,11 +270,16 @@ break; case 'sync': + // Sync the series as a collector holding the lease, or, with + // "stolen", as one whose lease another run has taken over. include_once($config['base_path'] . '/plugins/cloud/setup.php'); cloud_boot(); - $result = (new \Somethingwithproof\Cloud\SeriesRepository(false))->sync( - (int) db_fetch_cell("SELECT id FROM plugin_cloud_account WHERE name = 'Seed'") - ); + $account = (int) db_fetch_cell("SELECT id FROM plugin_cloud_account WHERE name = 'Seed'"); + $leases = new \Somethingwithproof\Cloud\LeaseRepository(false, new \Somethingwithproof\Cloud\SystemClock()); + $holder = $argument === 'stolen' ? 'lifecycle-newer' : 'lifecycle'; + $leases->acquire($account, $holder, 60); + $result = (new \Somethingwithproof\Cloud\SeriesRepository(false))->sync($account, $leases, 'lifecycle'); + $leases->release($account, $holder); break; case 'drop_table': From 06a2877944ce725d53006881f552ab2e34988624 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 09:29:56 -0800 Subject: [PATCH 09/17] fix: serialize scope device creation per account Two requests could both find no device for an account, and each saved a host. The second link() then deleted the first request's live link, so both reported success while only one device served the account. create() now takes a named lock for the account before it checks again for a device, saves and links it, and releases the lock afterwards. A request that cannot get the lock within its timeout creates nothing and reports an error. link() now deletes only stale links, those whose host is gone or no longer carries the account's external_id, so the unique account key refuses a second live link and the failed create removes its own host. Integration tests cover a create while another connection holds the lock, and a create whose link write fails. Signed-off-by: Thomas Vincent --- lib/DeviceRepository.php | 32 ++++++++++++++++++++++++--- lib/ScopeDevices.php | 24 ++++++++++++++++++++ setup.php | 5 +++-- tests/Integration/ScopeDeviceTest.php | 19 ++++++++++++++++ tests/Unit/ScopeDevicesTest.php | 23 +++++++++++++++++++ tests/bin/lifecycle.php | 12 +++++++++- tests/bootstrap-unit.php | 9 ++++---- 7 files changed, 114 insertions(+), 10 deletions(-) diff --git a/lib/DeviceRepository.php b/lib/DeviceRepository.php index a36b431..da4afad 100644 --- a/lib/DeviceRepository.php +++ b/lib/DeviceRepository.php @@ -34,17 +34,43 @@ public function __construct(private readonly \PDO|false $connection, private rea public const EXTERNAL_PREFIX = 'cloud:'; + private const LOCK = 'plugin_cloud_device_'; + + /** + * Serializes creating one account's device. The lock is per connection, + * so it ends with the request at the latest. + */ + public function lock(int $accountId, int $timeout): bool { + $locked = db_fetch_cell_prepared( + 'SELECT GET_LOCK(?, ?)', + [self::LOCK . $accountId, $timeout], + '', + true, + $this->connection + ); + + return (string) $locked === '1'; + } + + public function unlock(int $accountId): void { + db_execute_prepared('DO RELEASE_LOCK(?)', [self::LOCK . $accountId], true, $this->connection); + } + /** - * Replaces any earlier link of the account, which can only be stale when - * the caller found no live one. + * Replaces the account's stale links, those whose host is gone or no + * longer carries the account's external_id. A live link stays, so the + * account key refuses a second device for the account. * * @return bool whether the link was recorded; without it the device * serves nothing */ public function link(int $hostId, int $accountId): bool { - return db_execute_prepared('DELETE FROM plugin_cloud_device WHERE account_id = ? OR host_id = ?', [ + return db_execute_prepared('DELETE d FROM plugin_cloud_device d LEFT JOIN host h ON h.id = d.host_id + WHERE (d.account_id = ? OR d.host_id = ?) + AND (h.id IS NULL OR NOT (h.external_id <=> CONCAT(?, d.account_id)))', [ $accountId, $hostId, + self::EXTERNAL_PREFIX, ], true, $this->connection) !== false && db_execute_prepared( 'INSERT INTO plugin_cloud_device (host_id, account_id, created_at) VALUES (?, ?, ?)', diff --git a/lib/ScopeDevices.php b/lib/ScopeDevices.php index a0b6ecd..db80ffb 100644 --- a/lib/ScopeDevices.php +++ b/lib/ScopeDevices.php @@ -39,6 +39,8 @@ final class ScopeDevices { * and device template, returning the new device id or 0 * @param \Closure(int, int): void $reindex run_data_query() for a device and data query * @param \Closure(int): void $remove api_device_remove() for a device + * @param int $lockTimeout seconds to wait for another + * request creating the same account's device */ public function __construct( private readonly DeviceRepository $devices, @@ -46,6 +48,7 @@ public function __construct( private readonly \Closure $save, private readonly \Closure $reindex, private readonly \Closure $remove, + private readonly int $lockTimeout = 10, ) { } @@ -69,6 +72,27 @@ public function create(Account $account): int { return 0; } + // Two requests that both found no device would each save one. + if (!$this->devices->lock($account->id, $this->lockTimeout)) { + Log::error(sprintf('Account %d: another request is creating its scope device', $account->id)); + + return 0; + } + + try { + return $this->createLocked($account, $template); + } finally { + $this->devices->unlock($account->id); + } + } + + private function createLocked(Account $account, int $template): int { + $existing = $this->devices->hostFor($account->id); + + if ($existing !== null) { + return $existing; + } + $host = ($this->save)($account, $template); if ($host <= 0) { diff --git a/setup.php b/setup.php index c843f13..054d023 100644 --- a/setup.php +++ b/setup.php @@ -454,7 +454,7 @@ function cloud_poller_bottom(): void { exec_background($php, array('-q', __DIR__ . '/poller_cloud.php', '--poller=' . (int) $config['poller_id'])); } -function cloud_scope_devices(): \Somethingwithproof\Cloud\ScopeDevices { +function cloud_scope_devices(int $lockTimeout = 10): \Somethingwithproof\Cloud\ScopeDevices { global $config; // The libraries host.php loads to save a device and run its data queries. @@ -481,7 +481,8 @@ function (int $host, int $query): void { }, function (int $host): void { api_device_remove($host); - } + }, + $lockTimeout ); } diff --git a/tests/Integration/ScopeDeviceTest.php b/tests/Integration/ScopeDeviceTest.php index e1465e7..9a6ad52 100644 --- a/tests/Integration/ScopeDeviceTest.php +++ b/tests/Integration/ScopeDeviceTest.php @@ -51,6 +51,25 @@ ->and($created['device_index'])->toBe(['101' => 'web-1', '102' => 'web-2']); }); +it('creates no device while another request is creating the account\'s', function () { + $hosts = lifecycle('state')['hosts']; + $locked = lifecycle('scope_device', 'locked'); + + expect($locked['result'])->toBe(0) + ->and($locked['devices'])->toBe([]) + ->and($locked['hosts'])->toBe($hosts) + ->and(lifecycle('scope_device')['result'])->toBeGreaterThan(0); +}); + +it('removes the device it saved when the account link cannot be written', function () { + $hosts = lifecycle('state')['hosts']; + lifecycle('drop_table', 'plugin_cloud_device'); + + $failed = lifecycle('scope_device'); + expect($failed['result'])->toBe(0) + ->and($failed['hosts'])->toBe($hosts); +}); + it('reindexes resources added, renamed, and retired upstream', function () { lifecycle('scope_device'); lifecycle('resource', '103=web-3'); diff --git a/tests/Unit/ScopeDevicesTest.php b/tests/Unit/ScopeDevicesTest.php index 9598671..02f55d5 100644 --- a/tests/Unit/ScopeDevicesTest.php +++ b/tests/Unit/ScopeDevicesTest.php @@ -37,6 +37,7 @@ function cloud_scope_world(): void { 'FROM plugin_cloud_device' => [], 'FROM `host_template`' => [['id' => 3]], 'FROM `snmp_query`' => [['id' => 9]], + 'GET_LOCK' => [['locked' => 1]], ]; $GLOBALS['__cloud_scope'] = ['saved' => [], 'reindexed' => [], 'removed' => []]; } @@ -93,3 +94,25 @@ function cloud_scope_account(): Account { $GLOBALS['__cloud_db_fail'] = []; }); + +it('creates nothing while another request holds the account\'s creation lock', function () { + cloud_scope_world(); + $GLOBALS['__cloud_db_rows']['GET_LOCK'] = [['locked' => 0]]; + + expect(cloud_scope_devices_under_test()->create(cloud_scope_account()))->toBe(0) + ->and($GLOBALS['__cloud_scope']['saved'])->toBe([]) + ->and(array_column($GLOBALS['__cloud_db_exec'], 'sql'))->not->toContain('DO RELEASE_LOCK(?)'); +}); + +it('returns the device another request created while it waited for the lock', function () { + cloud_scope_world(); + $lookups = 0; + + $GLOBALS['__cloud_db_rows']['FROM plugin_cloud_device'] = static function () use (&$lookups): array { + return ++$lookups === 1 ? [] : [['host_id' => 77]]; + }; + + expect(cloud_scope_devices_under_test()->create(cloud_scope_account()))->toBe(77) + ->and($GLOBALS['__cloud_scope']['saved'])->toBe([]) + ->and(array_column($GLOBALS['__cloud_db_exec'], 'sql'))->toContain('DO RELEASE_LOCK(?)'); +}); diff --git a/tests/bin/lifecycle.php b/tests/bin/lifecycle.php index 715ee50..eb804ff 100644 --- a/tests/bin/lifecycle.php +++ b/tests/bin/lifecycle.php @@ -175,7 +175,17 @@ ); } - $result = cloud_scope_devices()->create(cloud_accounts()->find($account)); + // "locked": another request holds the account's creation lock. + if ($argument === 'locked') { + $other = new PDO( + 'mysql:host=' . $database_hostname . ';port=' . $database_port . ';dbname=' . $database_default, + $database_username, + $database_password + ); + $other->query("SELECT GET_LOCK('plugin_cloud_device_" . $account . "', 0)"); + } + + $result = cloud_scope_devices(1)->create(cloud_accounts()->find($account)); break; case 'resource': diff --git a/tests/bootstrap-unit.php b/tests/bootstrap-unit.php index 6707eb9..5238d4b 100644 --- a/tests/bootstrap-unit.php +++ b/tests/bootstrap-unit.php @@ -72,9 +72,10 @@ function read_config_option($config_name, $force = false) { // Repositories in unit tests talk to these stubs. A test reads the // statements from $GLOBALS['__cloud_db_exec'] and queues query results in -// $GLOBALS['__cloud_db_rows'] (keyed by a substring of the SQL). A statement -// containing a substring listed in $GLOBALS['__cloud_db_fail'] fails, as -// core's wrapper reports an SQL error, by returning false. +// $GLOBALS['__cloud_db_rows'] (keyed by a substring of the SQL; a closure +// there answers each query, so answers can change between calls). A +// statement containing a substring listed in $GLOBALS['__cloud_db_fail'] +// fails, as core's wrapper reports an SQL error, by returning false. $GLOBALS['__cloud_db_exec'] = []; $GLOBALS['__cloud_db_rows'] = []; $GLOBALS['__cloud_db_fail'] = []; @@ -82,7 +83,7 @@ function read_config_option($config_name, $force = false) { function cloud_test_rows(string $sql): mixed { foreach ($GLOBALS['__cloud_db_rows'] as $needle => $rows) { if (str_contains($sql, $needle)) { - return $rows; + return $rows instanceof Closure ? $rows($sql) : $rows; } } From fdc478e018de578a0b3ac7dccffdf555bdf522b4 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 13:09:41 -0800 Subject: [PATCH 10/17] fix: keep query reindexing on scope devices across edits For a device whose SNMP version is none, api_device_save() sets every data query's reindex method to None and deletes its poller_reindex rows, in Cacti 1.2.31 and on 1.2.x. Scope devices use that SNMP version, so editing only a scope device's description stopped Cacti from reindexing the resources discovery adds or retires. The plugin now registers api_device_save and api_device_new hooks. Before a scope device is saved, the first records the reindex method of each of its data queries. After the save, the second restores any method the save changed through api_device_dq_change(), which also handles remote pollers and rebuilds the reindex checks. api_device_new runs after every successful save, new or edited, in both releases. New scope devices now reindex on an index count change. The site default, uptime going backwards, needs SNMP, so a scope device created with it never reindexed; the index count method compares ss_cloud()'s num_indexes with the cached count and needs no SNMP. Integration tests cover a new device's reindex method, an ordinary edit followed by a resource added upstream, and a method chosen on the device page surviving an edit. Signed-off-by: Thomas Vincent --- docs/PLAN.md | 2 +- lib/DeviceRepository.php | 24 ++++++++ lib/Schema.php | 2 + lib/ScopeDevices.php | 18 ++++-- lib/ScopeReindex.php | 66 ++++++++++++++++++++ setup.php | 59 +++++++++++++++++- tests/Integration/LifecycleTest.php | 10 +++- tests/Integration/ScopeDeviceTest.php | 27 ++++++++- tests/Unit/ScopeDevicesTest.php | 8 +-- tests/Unit/ScopeReindexTest.php | 86 +++++++++++++++++++++++++++ tests/bin/lifecycle.php | 49 +++++++++++++++ tests/bin/php-guard-check.php | 9 +++ 12 files changed, 347 insertions(+), 13 deletions(-) create mode 100644 lib/ScopeReindex.php create mode 100644 tests/Unit/ScopeReindexTest.php diff --git a/docs/PLAN.md b/docs/PLAN.md index 317b761..a42652e 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -292,7 +292,7 @@ Plugin code is object-oriented wherever Cacti's plugin contract allows it, follo **Where procedural code remains.** Cacti calls plugins by function name, so these entry points stay procedural. Each is a thin shim, parseable on PHP 8.0, that checks the PHP version, validates input, and hands off to a class: - `setup.php` lifecycle functions: `plugin_cloud_install()`, `plugin_cloud_uninstall()`, `plugin_cloud_version()`, `plugin_cloud_check_config()`, `plugin_cloud_upgrade()`. -- Hook callbacks: `config_arrays`, `config_settings`, `draw_navigation_text`, `poller_bottom`, `api_device_save`, `device_remove`, `graph_buttons`; `replicate_out` and `remote_agent` in phase 5. +- Hook callbacks: `config_arrays`, `config_settings`, `draw_navigation_text`, `poller_bottom`, `api_device_save`, `api_device_new`, `device_remove`, `graph_buttons`; `replicate_out` and `remote_agent` in phase 5. - Page scripts such as `cloud_accounts.php` and `cloud.php`, which include `include/auth.php`, read request variables with `get_filter_request_var()`, and call a page class. - The script server input function and the `poller_cloud.php` CLI entry point. diff --git a/lib/DeviceRepository.php b/lib/DeviceRepository.php index da4afad..80314f2 100644 --- a/lib/DeviceRepository.php +++ b/lib/DeviceRepository.php @@ -100,6 +100,30 @@ public function accountFor(int $hostId): ?int { return $id > 0 ? $id : null; } + /** + * The reindex method of each data query on a live scope device; empty + * for any other device. + * + * @return array data query id => reindex method + */ + public function reindexMethods(int $hostId): array { + $methods = []; + + foreach (Row::rows(db_fetch_assoc_prepared( + 'SELECT q.snmp_query_id, q.reindex_method FROM host_snmp_query q + INNER JOIN plugin_cloud_device d ON d.host_id = q.host_id + INNER JOIN host h ON h.id = d.host_id AND h.external_id = CONCAT(?, d.account_id) + WHERE q.host_id = ?', + [self::EXTERNAL_PREFIX, $hostId], + true, + $this->connection + )) as $row) { + $methods[Row::int($row, 'snmp_query_id')] = Row::int($row, 'reindex_method'); + } + + return $methods; + } + public function hostFor(int $accountId): ?int { $id = (int) db_fetch_cell_prepared( 'SELECT d.host_id FROM plugin_cloud_device d INNER JOIN host h ON h.id = d.host_id diff --git a/lib/Schema.php b/lib/Schema.php index 73d2186..4b7d926 100644 --- a/lib/Schema.php +++ b/lib/Schema.php @@ -37,6 +37,8 @@ final class Schema { public const VERSION = 3; public const HOOKS = [ + 'api_device_new' => 'cloud_device_saved', + 'api_device_save' => 'cloud_device_save', 'config_arrays' => 'cloud_config_arrays', 'config_settings' => 'cloud_config_settings', 'device_remove' => 'cloud_device_remove', diff --git a/lib/ScopeDevices.php b/lib/ScopeDevices.php index db80ffb..d075114 100644 --- a/lib/ScopeDevices.php +++ b/lib/ScopeDevices.php @@ -31,13 +31,22 @@ final class ScopeDevices { /** api_device_save()'s availability method None (AVAIL_NONE). */ private const AVAILABILITY_NONE = 0; + /** + * Reindex on an index count change (DATA_QUERY_AUTOINDEX_INDEX_NUM_CHANGE): + * the poller compares ss_cloud()'s num_indexes with the cached count. The + * site default, uptime going backwards, needs SNMP, which a scope device + * does not have, so it would never reindex. + */ + public const REINDEX_METHOD = 2; + /** The device template of each provider, as TemplateRepository keys. */ private const TEMPLATES = [Provider::DigitalOcean->value => 'host_template/digitalocean']; /** * @param \Closure(Account, int): int $save api_device_save() for this account * and device template, returning the new device id or 0 - * @param \Closure(int, int): void $reindex run_data_query() for a device and data query + * @param \Closure(int, int, int): void $reindex api_device_dq_change() for a device, + * data query and reindex method, which also runs the data query * @param \Closure(int): void $remove api_device_remove() for a device * @param int $lockTimeout seconds to wait for another * request creating the same account's device @@ -110,13 +119,14 @@ private function createLocked(Account $account, int $template): int { return 0; } - // Saving applied the template's data queries and indexed them before - // the link existed, so they found nothing; index them again now. + // Saving applied the template's data queries with the site's reindex + // method and indexed them before the link existed, so they found + // nothing; set the method and index them again now. foreach (TemplateRepository::objects()['snmp_query'] as $query) { $id = $this->templates->id('snmp_query', $query); if ($id !== null) { - ($this->reindex)($host, $id); + ($this->reindex)($host, $id, self::REINDEX_METHOD); } } diff --git a/lib/ScopeReindex.php b/lib/ScopeReindex.php new file mode 100644 index 0000000..5241b95 --- /dev/null +++ b/lib/ScopeReindex.php @@ -0,0 +1,66 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * 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. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ +namespace Somethingwithproof\Cloud; + +/** + * Keeps a scope device's data query reindex methods across an edit. Its + * SNMP version is none, and for such a device api_device_save() sets every + * data query's reindex method to None and drops its reindex checks, so a + * description change alone would stop Cacti from following resources + * coming and going (ADR 0010). The api_device_save hook remembers the + * methods before the save; the api_device_new hook, which runs after + * every successful save, puts back any the save changed through + * api_device_dq_change(), which also rebuilds the reindex checks. + */ +final class ScopeReindex { + /** @var array> host => data query => reindex method */ + private array $saved = []; + + /** + * @param \Closure(int, int, int): void $change api_device_dq_change() for a + * device, data query and reindex method + */ + public function __construct(private readonly DeviceRepository $devices, private readonly \Closure $change) { + } + + public function remember(int $hostId): void { + $methods = $this->devices->reindexMethods($hostId); + + if ($methods !== []) { + $this->saved[$hostId] = $methods; + } + } + + public function restore(int $hostId): void { + $saved = $this->saved[$hostId] ?? []; + unset($this->saved[$hostId]); + + if ($saved === []) { + return; + } + + $current = $this->devices->reindexMethods($hostId); + + foreach ($saved as $query => $method) { + if (isset($current[$query]) && $current[$query] !== $method) { + ($this->change)($hostId, $query, $method); + } + } + } +} diff --git a/setup.php b/setup.php index 054d023..568a465 100644 --- a/setup.php +++ b/setup.php @@ -422,6 +422,61 @@ function cloud_device_remove($ids) { return $ids; } +/** + * Cacti is about to save a device: remember a scope device's reindex + * methods, which the save resets (see ScopeReindex). + * + * @param mixed $save + * @return mixed the device fields, unchanged, for the save + */ +function cloud_device_save($save) { + if (cloud_boot() && is_array($save) && isset($save['id']) && is_numeric($save['id']) && $save['id'] > 0) { + cloud_scope_reindex()->remember((int) $save['id']); + } + + return $save; +} + +/** + * Cacti saved a device, new or edited: put back the reindex methods of a + * scope device that the save reset. + * + * @param mixed $save + * @return mixed the device fields, unchanged + */ +function cloud_device_saved($save) { + if (cloud_boot() && is_array($save) && isset($save['id']) && is_numeric($save['id']) && $save['id'] > 0) { + cloud_scope_reindex()->restore((int) $save['id']); + } + + return $save; +} + +/** + * One instance per request, so the save hook's memory reaches the hook + * that runs after the save. + */ +function cloud_scope_reindex(): \Somethingwithproof\Cloud\ScopeReindex { + global $config; + + static $keeper = null; + + if ($keeper === null) { + foreach (array('api_device.php', 'data_query.php', 'poller.php', 'snmp.php') as $file) { + include_once($config['library_path'] . '/' . $file); + } + + $keeper = new \Somethingwithproof\Cloud\ScopeReindex( + new \Somethingwithproof\Cloud\DeviceRepository(false, new \Somethingwithproof\Cloud\SystemClock()), + function (int $host, int $query, int $method): void { + api_device_dq_change($host, $query, $method); + } + ); + } + + return $keeper; +} + function cloud_poller_bottom(): void { global $config; @@ -476,8 +531,8 @@ function (\Somethingwithproof\Cloud\Account $account, int $template): int { return is_numeric($id) ? (int) $id : 0; }, - function (int $host, int $query): void { - run_data_query($host, $query); + function (int $host, int $query, int $method): void { + api_device_dq_change($host, $query, $method); }, function (int $host): void { api_device_remove($host); diff --git a/tests/Integration/LifecycleTest.php b/tests/Integration/LifecycleTest.php index a922a87..a78a1b6 100644 --- a/tests/Integration/LifecycleTest.php +++ b/tests/Integration/LifecycleTest.php @@ -35,7 +35,15 @@ 'plugin_cloud_series', ]; -const CLOUD_HOOKS = ['config_arrays', 'config_settings', 'device_remove', 'draw_navigation_text', 'poller_bottom']; +const CLOUD_HOOKS = [ + 'api_device_new', + 'api_device_save', + 'config_arrays', + 'config_settings', + 'device_remove', + 'draw_navigation_text', + 'poller_bottom', +]; beforeEach(function () { lifecycle('reset'); diff --git a/tests/Integration/ScopeDeviceTest.php b/tests/Integration/ScopeDeviceTest.php index 9a6ad52..51381f8 100644 --- a/tests/Integration/ScopeDeviceTest.php +++ b/tests/Integration/ScopeDeviceTest.php @@ -48,7 +48,8 @@ 'template' => 'Cloud: DigitalOcean Scope', ]]) ->and($created['device_queries'])->toBe(['Cloud: DigitalOcean Droplets', 'Cloud: DigitalOcean Load Balancers']) - ->and($created['device_index'])->toBe(['101' => 'web-1', '102' => 'web-2']); + ->and($created['device_index'])->toBe(['101' => 'web-1', '102' => 'web-2']) + ->and($created['device_reindex'])->toBe([2, 2]); }); it('creates no device while another request is creating the account\'s', function () { @@ -138,3 +139,27 @@ expect(lifecycle('sync', 'stolen')['series'])->toBe(['101 do_cpu_pct']) ->and(lifecycle('sync')['series'])->toBe([]); }); + +it('keeps reindexing a scope device after an ordinary edit, so a resource added upstream is found', function () { + $host = (string) lifecycle('scope_device')['result']; + $edit = lifecycle('edit_device')['result']; + + // Index count changed (2), as created, on both data queries. The + // Droplets query's reindex check expects its two cached indexes; Cacti + // writes no check for the load balancer query, which has none cached. + expect($edit['description'])->toBe('Seed edited') + ->and($edit['reindex'])->toBe([2, 2]) + ->and($edit['checks'])->toBe(['2']); + + // The poller's check now sees three Droplets against two and reindexes. + lifecycle('resource', '103=web-3'); + expect(lifecycle('ss', $host . ' droplet num_indexes')['output'])->toBe('3') + ->and(lifecycle('reindex')['device_index'])->toBe(['101' => 'web-1', '102' => 'web-2', '103' => 'web-3']); +}); + +it('keeps a reindex method an administrator chose for the scope device across an edit', function () { + lifecycle('scope_device'); + + // Verify all fields (3), as chosen on the device page. + expect(lifecycle('edit_device', '3')['result']['reindex'])->toBe([3, 3]); +}); diff --git a/tests/Unit/ScopeDevicesTest.php b/tests/Unit/ScopeDevicesTest.php index 02f55d5..4fb0f75 100644 --- a/tests/Unit/ScopeDevicesTest.php +++ b/tests/Unit/ScopeDevicesTest.php @@ -51,8 +51,8 @@ static function (Account $account, int $template): int { return 42; }, - static function (int $host, int $query): void { - $GLOBALS['__cloud_scope']['reindexed'][] = [$host, $query]; + static function (int $host, int $query, int $method): void { + $GLOBALS['__cloud_scope']['reindexed'][] = [$host, $query, $method]; }, static function (int $host): void { $GLOBALS['__cloud_scope']['removed'][] = $host; @@ -74,12 +74,12 @@ function cloud_scope_account(): Account { return $account; } -it('links the device it saved and indexes its data queries', function () { +it('links the device it saved and indexes its data queries, reindexing on an index count change', function () { cloud_scope_world(); expect(cloud_scope_devices_under_test()->create(cloud_scope_account()))->toBe(42) ->and($GLOBALS['__cloud_scope']['saved'])->toBe([3]) - ->and($GLOBALS['__cloud_scope']['reindexed'])->toBe([[42, 9], [42, 9]]) + ->and($GLOBALS['__cloud_scope']['reindexed'])->toBe([[42, 9, 2], [42, 9, 2]]) ->and($GLOBALS['__cloud_scope']['removed'])->toBe([]); }); diff --git a/tests/Unit/ScopeReindexTest.php b/tests/Unit/ScopeReindexTest.php new file mode 100644 index 0000000..470251b --- /dev/null +++ b/tests/Unit/ScopeReindexTest.php @@ -0,0 +1,86 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * 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. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +use Somethingwithproof\Cloud\DeviceRepository; +use Somethingwithproof\Cloud\FixedClock; +use Somethingwithproof\Cloud\ScopeReindex; + +/* + * Reindex methods across a scope device edit, against the database stubs: + * host 7 is a scope device whose two data queries, 9 and 10, use index + * count (2) and verify all fields (3). + */ + +/** + * @param list> $queries host_snmp_query rows of host 7 + */ +function cloud_reindex_queries(array $queries): void { + $GLOBALS['__cloud_db_rows'] = ['FROM host_snmp_query' => $queries]; +} + +/** + * @return array{0: ScopeReindex, 1: \ArrayObject>} + */ +function cloud_reindex_keeper(): array { + $changes = new ArrayObject(); + + return [ + new ScopeReindex( + new DeviceRepository(false, new FixedClock(1_800_000_000)), + static function (int $host, int $query, int $method) use ($changes): void { + $changes[] = [$host, $query, $method]; + } + ), + $changes, + ]; +} + +it('puts back the reindex methods a scope device save reset, and only those', function () { + [$keeper, $changes] = cloud_reindex_keeper(); + + cloud_reindex_queries([ + ['snmp_query_id' => 9, 'reindex_method' => 2], + ['snmp_query_id' => 10, 'reindex_method' => 3], + ]); + $keeper->remember(7); + + cloud_reindex_queries([ + ['snmp_query_id' => 9, 'reindex_method' => 0], + ['snmp_query_id' => 10, 'reindex_method' => 3], + ]); + $keeper->restore(7); + + expect($changes->getArrayCopy())->toBe([[7, 9, 2]]); + + // Each save is restored once. + $keeper->restore(7); + expect($changes->getArrayCopy())->toBe([[7, 9, 2]]); +}); + +it('leaves a device alone that is no scope device, or that was just created', function () { + [$keeper, $changes] = cloud_reindex_keeper(); + + cloud_reindex_queries([]); + $keeper->remember(8); + cloud_reindex_queries([['snmp_query_id' => 9, 'reindex_method' => 0]]); + $keeper->restore(8); + $keeper->restore(9); + + expect($changes->getArrayCopy())->toBe([]); +}); diff --git a/tests/bin/lifecycle.php b/tests/bin/lifecycle.php index eb804ff..d2d7a08 100644 --- a/tests/bin/lifecycle.php +++ b/tests/bin/lifecycle.php @@ -216,6 +216,46 @@ run_data_query($row['host_id'], $row['snmp_query_id']); } + break; + case 'edit_device': + // Save the scope device with a new description, as host.php does, + // optionally after setting its data queries' reindex method as on the + // device page. Prints each query's reindex method and reindex checks + // after the save. + include_once($config['base_path'] . '/plugins/cloud/setup.php'); + cloud_scope_devices(); + $host = (int) db_fetch_cell('SELECT host_id FROM plugin_cloud_device'); + $account = cloud_accounts()->find((int) db_fetch_cell('SELECT account_id FROM plugin_cloud_device')); + + if ($argument !== '') { + foreach (db_fetch_assoc_prepared('SELECT snmp_query_id FROM host_snmp_query WHERE host_id = ?', array($host)) as $row) { + api_device_dq_change($host, $row['snmp_query_id'], (int) $argument); + } + } + + $fields = \Somethingwithproof\Cloud\ScopeDevices::deviceFields( + $account, + (int) db_fetch_cell_prepared('SELECT host_template_id FROM host WHERE id = ?', array($host)) + ); + $fields[0] = $host; + $fields[2] = 'Seed edited'; + call_user_func_array('api_device_save', $fields); + + $result = array( + 'description' => db_fetch_cell_prepared('SELECT description FROM host WHERE id = ?', array($host)), + 'reindex' => array_map('intval', array_column( + db_fetch_assoc_prepared('SELECT reindex_method FROM host_snmp_query WHERE host_id = ? ORDER BY snmp_query_id', array($host)), + 'reindex_method' + )), + 'checks' => array_column( + db_fetch_assoc_prepared( + 'SELECT assert_value FROM poller_reindex WHERE host_id = ? ORDER BY data_query_id', + array($host) + ), + 'assert_value' + ), + ); + break; case 'drop_host': // Delete the device row without Cacti's hooks, as when the plugin is disabled. @@ -440,6 +480,7 @@ // The device state, only while the plugin's device table exists. $device_state = array( + 'device_reindex' => array(), 'devices' => array(), 'device_queries' => array(), 'device_index' => array(), @@ -448,6 +489,13 @@ if (isset($tables['plugin_cloud_device'])) { $device_state = array( + 'device_reindex' => array_map('intval', array_column( + db_fetch_assoc( + 'SELECT q.reindex_method FROM host_snmp_query q INNER JOIN plugin_cloud_device d ON d.host_id = q.host_id + ORDER BY q.snmp_query_id' + ), + 'reindex_method' + )), 'devices' => db_fetch_assoc( 'SELECT d.host_id, d.account_id, h.description, h.availability_method, h.poller_id, ht.name AS template FROM plugin_cloud_device d INNER JOIN host h ON h.id = d.host_id @@ -538,6 +586,7 @@ function ($row) { 'devices' => $device_state['devices'], 'device_queries' => $device_state['device_queries'], 'device_index' => $device_state['device_index'], + 'device_reindex' => $device_state['device_reindex'], 'series' => $device_state['series'], 'hosts' => (int) db_fetch_cell('SELECT COUNT(*) FROM host'), 'templates_sha' => db_fetch_cell("SELECT value FROM settings WHERE name = 'cloud_templates_sha256'"), diff --git a/tests/bin/php-guard-check.php b/tests/bin/php-guard-check.php index bcabaab..df62c3f 100644 --- a/tests/bin/php-guard-check.php +++ b/tests/bin/php-guard-check.php @@ -78,6 +78,15 @@ function guard_call_shims() { guard_expect(cloud_draw_navigation_text($nav) === $nav, 'draw_navigation_text returns the navigation unchanged'); } + // Every device save passes its fields through these two. + $save = array('id' => 0, 'description' => 'guard'); + + foreach (array('cloud_device_save', 'cloud_device_saved') as $function) { + if (function_exists($function)) { + guard_expect($function($save) === $save, $function . ' returns the device fields unchanged'); + } + } + // Core's own dispatch, as every page load does. api_plugin_hook('config_arrays'); api_plugin_hook('config_settings'); From 831e0af8c70a2f9345f767a877587a913b262f9e Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 13:23:28 -0800 Subject: [PATCH 11/17] test: bind the lock name in the scope device lock scenario The lifecycle script built the GET_LOCK statement by concatenating the account id. It now passes the lock name as a bound parameter, which SonarCloud's S2077 rule asks for. Signed-off-by: Thomas Vincent --- tests/bin/lifecycle.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/bin/lifecycle.php b/tests/bin/lifecycle.php index d2d7a08..540f7c5 100644 --- a/tests/bin/lifecycle.php +++ b/tests/bin/lifecycle.php @@ -182,7 +182,7 @@ $database_username, $database_password ); - $other->query("SELECT GET_LOCK('plugin_cloud_device_" . $account . "', 0)"); + $other->prepare('SELECT GET_LOCK(?, 0)')->execute(array('plugin_cloud_device_' . $account)); } $result = cloud_scope_devices(1)->create(cloud_accounts()->find($account)); From 182da17e14f9ed3570f4fc7417ed7b436604cfc3 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 13:26:02 -0800 Subject: [PATCH 12/17] fix: reconcile series by data source, resource and account sync() compared series by data source and metric alone. When an operator pointed a data source at another resource index, the key stayed the same and the row kept collecting the old resource. When a data source moved to this account's device from another account's, the other account's row held the primary key, INSERT IGNORE skipped the new row, and the account never collected that series. Series are now compared by data source, metric, resource and account. The existing rows are this account's and any whose data source is on this account's device, so a stale row of another account goes even if that account's collector never runs again. Deletes run before inserts, and an insert that still conflicts fails and rolls the sync back instead of being ignored. Signed-off-by: Thomas Vincent --- lib/SeriesRepository.php | 38 +++++++++++------ tests/Integration/ScopeDeviceTest.php | 11 +++++ tests/Unit/SeriesRepositoryTest.php | 60 ++++++++++++++++++++++++--- tests/bin/lifecycle.php | 11 +++++ 4 files changed, 103 insertions(+), 17 deletions(-) diff --git a/lib/SeriesRepository.php b/lib/SeriesRepository.php index 834e7d9..23d3f2b 100644 --- a/lib/SeriesRepository.php +++ b/lib/SeriesRepository.php @@ -38,6 +38,13 @@ public function __construct(private readonly \PDO|false $connection) { * whose data sources could not be read: a failed query is not an empty * device. * + * A row is the data source, metric, resource and account together, so + * a data source an operator moved to another resource index, or to this + * account's device from another account's, replaces its old row rather + * than keeping it. Rows of other accounts whose data source is now on + * this device are stale and go too; their own collector may never run + * again to remove them. + * * The rows change in one transaction that first locks the caller's lease * and checks it is still held, so a run that lost its lease while it read * cannot replace a newer holder's rows from its older snapshot. @@ -85,11 +92,9 @@ public function sync(int $accountId, LeaseRepository $leases, string $holder): b $metric = Row::string($row, 'metric'); if ((DigitalOceanCatalog::metric($metric)['type'] ?? null) === $type) { - $wanted[Row::int($row, 'local_data_id') . '/' . $metric] = [ - Row::int($row, 'local_data_id'), - $metric, - Row::int($row, 'resource_id'), - ]; + $series = [Row::int($row, 'local_data_id'), $metric, Row::int($row, 'resource_id'), $accountId]; + + $wanted[implode('/', $series)] = $series; } } } @@ -106,8 +111,10 @@ public function sync(int $accountId, LeaseRepository $leases, string $holder): b $existing = []; $rows = db_fetch_assoc_prepared( - 'SELECT local_data_id, metric FROM plugin_cloud_series WHERE account_id = ?', - [$accountId], + 'SELECT s.local_data_id, s.metric, s.resource_id, s.account_id FROM plugin_cloud_series s + LEFT JOIN data_local dl ON dl.id = s.local_data_id + WHERE s.account_id = ? OR dl.host_id = ?', + [$accountId, $host], true, $this->connection ); @@ -119,24 +126,31 @@ public function sync(int $accountId, LeaseRepository $leases, string $holder): b } foreach (Row::rows($rows) as $row) { - $existing[Row::int($row, 'local_data_id') . '/' . Row::string($row, 'metric')] = [ + $series = [ Row::int($row, 'local_data_id'), Row::string($row, 'metric'), + Row::int($row, 'resource_id'), + Row::int($row, 'account_id'), ]; + + $existing[implode('/', $series)] = $series; } $writes = []; - foreach (array_diff_key($existing, $wanted) as [$local, $metric]) { + // Deletes first: a replaced row holds the data source and metric key + // its replacement needs. + foreach (array_diff_key($existing, $wanted) as [$local, $metric, $resource, $account]) { $writes[] = [ - 'DELETE FROM plugin_cloud_series WHERE account_id = ? AND local_data_id = ? AND metric = ?', - [$accountId, $local, $metric], + 'DELETE FROM plugin_cloud_series + WHERE local_data_id = ? AND metric = ? AND resource_id = ? AND account_id = ?', + [$local, $metric, $resource, $account], ]; } foreach (array_diff_key($wanted, $existing) as [$local, $metric, $resource]) { $writes[] = [ - 'INSERT IGNORE INTO plugin_cloud_series (local_data_id, account_id, resource_id, metric, created_at) + 'INSERT INTO plugin_cloud_series (local_data_id, account_id, resource_id, metric, created_at) VALUES (?, ?, ?, ?, UNIX_TIMESTAMP())', [$local, $accountId, $resource, $metric], ]; diff --git a/tests/Integration/ScopeDeviceTest.php b/tests/Integration/ScopeDeviceTest.php index 51381f8..452d3ea 100644 --- a/tests/Integration/ScopeDeviceTest.php +++ b/tests/Integration/ScopeDeviceTest.php @@ -125,6 +125,17 @@ expect(lifecycle('sync')['series'])->toBe(['102 do_load_1', '102 do_load_15', '102 do_load_5']); }); +it('moves a series to the resource its data source now reads', function () { + lifecycle('scope_device'); + lifecycle('graph', 'do_cpu 101'); + + expect(lifecycle('sync')['series'])->toBe(['101 do_cpu_pct']); + + lifecycle('move_index', '101=102'); + + expect(lifecycle('sync')['series'])->toBe(['102 do_cpu_pct']); +}); + it('leaves the series alone when the collector syncing them no longer holds the lease', function () { lifecycle('scope_device'); $cpu = lifecycle('graph', 'do_cpu 101')['result']; diff --git a/tests/Unit/SeriesRepositoryTest.php b/tests/Unit/SeriesRepositoryTest.php index 23a0722..3e1833d 100644 --- a/tests/Unit/SeriesRepositoryTest.php +++ b/tests/Unit/SeriesRepositoryTest.php @@ -23,23 +23,42 @@ /* * Series sync against the database stubs: account 4's scope device is host - * 7, its one recorded series reads do_cpu_pct from data source 5, and run-1 - * holds its lease unless a test says otherwise. + * 7, its one recorded series reads do_cpu_pct of resource 11 from data + * source 5, and run-1 holds its lease unless a test says otherwise. */ /** - * @param list>|false $sources the scope device's data sources + * @param list>|false $sources the scope device's data sources + * @param list>|null $recorded series rows of the account or its device */ -function cloud_series_world(array|false $sources, bool $held = true): void { +function cloud_series_world(array|false $sources, bool $held = true, ?array $recorded = null): void { $GLOBALS['__cloud_db_exec'] = []; $GLOBALS['__cloud_db_rows'] = [ 'FROM plugin_cloud_device' => [['host_id' => 7]], 'FROM data_local' => $sources, 'FROM plugin_cloud_lease' => [['held' => $held ? 1 : 0]], - 'FROM plugin_cloud_series' => [['local_data_id' => 5, 'metric' => 'do_cpu_pct']], + 'FROM plugin_cloud_series' => $recorded + ?? [['local_data_id' => 5, 'metric' => 'do_cpu_pct', 'resource_id' => 11, 'account_id' => 4]], ]; } +/** + * @return list}> each mutating statement's verb and parameters + */ +function cloud_series_mutations(): array { + $out = []; + + foreach ($GLOBALS['__cloud_db_exec'] as $exec) { + $verb = strtok(trim($exec['sql']), ' '); + + if (in_array($verb, ['DELETE', 'INSERT'], true)) { + $out[] = [$verb, $exec['params']]; + } + } + + return $out; +} + function cloud_series_sync(): bool { return (new SeriesRepository(false))->sync(4, new LeaseRepository(false, new FixedClock(1_800_000_000)), 'run-1'); } @@ -85,3 +104,34 @@ function cloud_series_writes(): array { $GLOBALS['__cloud_in_tx'] = []; }); + +it('keeps a series whose data source, resource and account are unchanged', function () { + cloud_series_world([['local_data_id' => 5, 'metric' => 'do_cpu_pct', 'resource_id' => 11]]); + + expect(cloud_series_sync())->toBeTrue() + ->and(cloud_series_writes())->toBe(['BEGIN', 'COMMIT']); +}); + +it('replaces a series whose data source an operator moved to another resource', function () { + cloud_series_world([['local_data_id' => 5, 'metric' => 'do_cpu_pct', 'resource_id' => 12]]); + + expect(cloud_series_sync())->toBeTrue() + ->and(cloud_series_mutations())->toBe([ + ['DELETE', [5, 'do_cpu_pct', 11, 4]], + ['INSERT', [5, 4, 12, 'do_cpu_pct']], + ]); +}); + +it('replaces another account\'s series whose data source is now on this account\'s device', function () { + cloud_series_world( + [['local_data_id' => 5, 'metric' => 'do_cpu_pct', 'resource_id' => 11]], + true, + [['local_data_id' => 5, 'metric' => 'do_cpu_pct', 'resource_id' => 30, 'account_id' => 3]] + ); + + expect(cloud_series_sync())->toBeTrue() + ->and(cloud_series_mutations())->toBe([ + ['DELETE', [5, 'do_cpu_pct', 30, 3]], + ['INSERT', [5, 4, 11, 'do_cpu_pct']], + ]); +}); diff --git a/tests/bin/lifecycle.php b/tests/bin/lifecycle.php index 540f7c5..cf210d2 100644 --- a/tests/bin/lifecycle.php +++ b/tests/bin/lifecycle.php @@ -302,6 +302,17 @@ ); $result = (int) $created['local_graph_id']; + break; + case 'move_index': + // Point the scope device's data sources at another resource index, + // as editing a data source's index does: "=". + list($from, $to) = explode('=', $argument, 2); + db_execute_prepared( + 'UPDATE data_local dl INNER JOIN plugin_cloud_device d ON d.host_id = dl.host_id + SET dl.snmp_index = ? WHERE dl.snmp_index = ?', + array($to, $from) + ); + break; case 'remove_graph': // Delete a graph and its data sources, as the Graphs page does. From 750cf9ff0f9f72a1f29532480432903aa6404545 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 13:27:28 -0800 Subject: [PATCH 13/17] fix: keep core's deadlock retry out of the series sync transaction Core's database wrapper retries a statement that hit a deadlock or a lock wait timeout. InnoDB has rolled the transaction back by then, so the retried statement ran on its own, outside the lease's lock, and a later rollback could not undo it. Core retries only statements it logs. The lease check, the read of the existing series and every write in the transaction now run unlogged, so a deadlock fails the statement instead of retrying it. sync() also checks that the transaction is still open before each statement and before the commit. Any failure rolls back, logs a warning and stops; the next collector run syncs again. Signed-off-by: Thomas Vincent --- lib/LeaseRepository.php | 6 +++-- lib/SeriesRepository.php | 40 +++++++++++++++++++---------- tests/Unit/SeriesRepositoryTest.php | 24 ++++++++++++++--- tests/bootstrap-unit.php | 2 +- 4 files changed, 53 insertions(+), 19 deletions(-) diff --git a/lib/LeaseRepository.php b/lib/LeaseRepository.php index b0ae5a5..9716538 100644 --- a/lib/LeaseRepository.php +++ b/lib/LeaseRepository.php @@ -62,14 +62,16 @@ public function holds(int $accountId, string $holder): bool { * holds(), as a locking read for use inside a transaction: the lease row * stays locked until the transaction ends, so no other run can take the * lease over between this check and the caller's writes. The row is - * selected by its key alone, so it is locked whoever holds it. + * selected by its key alone, so it is locked whoever holds it. Unlogged, + * so core does not retry it after a deadlock outside the transaction; + * a failed read counts as not held. */ public function holdsForUpdate(int $accountId, string $holder): bool { return (int) db_fetch_cell_prepared( 'SELECT holder = ? AND expires_at >= ? FROM plugin_cloud_lease WHERE account_id = ? FOR UPDATE', [$holder, $this->clock->now(), $accountId], '', - true, + false, $this->connection ) === 1; } diff --git a/lib/SeriesRepository.php b/lib/SeriesRepository.php index 23d3f2b..afbca7f 100644 --- a/lib/SeriesRepository.php +++ b/lib/SeriesRepository.php @@ -49,6 +49,14 @@ public function __construct(private readonly \PDO|false $connection) { * and checks it is still held, so a run that lost its lease while it read * cannot replace a newer holder's rows from its older snapshot. * + * Core's database wrapper retries a statement that hit a deadlock or a + * lock wait timeout, but InnoDB has by then rolled the transaction back, + * so the retry would run on its own, outside the lease's lock. Core + * retries only statements it logs, so every statement in the transaction + * runs unlogged and fails instead, and the transaction is checked to be + * still open before each one. Any failure rolls back and stops; the next + * collector run syncs again. + * * @return bool whether the series were rebuilt */ public function sync(int $accountId, LeaseRepository $leases, string $holder): bool { @@ -103,7 +111,7 @@ public function sync(int $accountId, LeaseRepository $leases, string $holder): b return false; } - if (!$leases->holdsForUpdate($accountId, $holder)) { + if (!$leases->holdsForUpdate($accountId, $holder) || !$this->inTransaction()) { $this->rollback(); return false; @@ -115,14 +123,12 @@ public function sync(int $accountId, LeaseRepository $leases, string $holder): b LEFT JOIN data_local dl ON dl.id = s.local_data_id WHERE s.account_id = ? OR dl.host_id = ?', [$accountId, $host], - true, + false, $this->connection ); - if (!is_array($rows)) { - $this->rollback(); - - return false; + if (!is_array($rows) || !$this->inTransaction()) { + return $this->abandon($accountId); } foreach (Row::rows($rows) as $row) { @@ -157,18 +163,26 @@ public function sync(int $accountId, LeaseRepository $leases, string $holder): b } foreach ($writes as [$sql, $params]) { - // InnoDB ends the transaction on a deadlock and core retries the - // statement on its own, outside the lease's lock. - if (db_execute_prepared($sql, $params, true, $this->connection) === false || !$this->inTransaction()) { - $this->rollback(); - - return false; + if (!$this->inTransaction() || db_execute_prepared($sql, $params, false, $this->connection) === false) { + return $this->abandon($accountId); } } - return db_commit_transaction($this->connection) === true; + return $this->inTransaction() && db_commit_transaction($this->connection) === true; } + private function abandon(int $accountId): bool { + $this->rollback(); + Log::warning(sprintf('Account %d: series sync rolled back; the next run retries it', $accountId)); + + return false; + } + + /** + * InnoDB can end the transaction under any statement. + * + * @phpstan-impure + */ private function inTransaction(): bool { return (int) db_fetch_cell_prepared('SELECT @@in_transaction', [], '', true, $this->connection) === 1; } diff --git a/tests/Unit/SeriesRepositoryTest.php b/tests/Unit/SeriesRepositoryTest.php index 3e1833d..444d4a1 100644 --- a/tests/Unit/SeriesRepositoryTest.php +++ b/tests/Unit/SeriesRepositoryTest.php @@ -94,10 +94,11 @@ function cloud_series_writes(): array { ->and(cloud_series_writes())->toBe(['BEGIN', 'ROLLBACK']); }); -it('rolls back when a write leaves the transaction, as a deadlock retry does', function () { +it('runs no statement once the transaction has ended', function () { cloud_series_world([['local_data_id' => 6, 'metric' => 'do_load_1', 'resource_id' => 11]]); - // The delete runs, but InnoDB has ended the transaction by then. - $GLOBALS['__cloud_in_tx'] = [0, 0]; + // Open after the lease check, the read and before the delete; InnoDB + // ends it during the delete, so the insert must not run on its own. + $GLOBALS['__cloud_in_tx'] = [1, 1, 1, 0, 0]; expect(cloud_series_sync())->toBeFalse() ->and(cloud_series_writes())->toBe(['BEGIN', 'DELETE']); @@ -105,6 +106,23 @@ function cloud_series_writes(): array { $GLOBALS['__cloud_in_tx'] = []; }); +it('writes unlogged, so core cannot retry a deadlocked write outside the transaction, and stops on a failure', function () { + cloud_series_world([['local_data_id' => 6, 'metric' => 'do_load_1', 'resource_id' => 11]]); + $GLOBALS['__cloud_db_fail'] = ['DELETE FROM plugin_cloud_series']; + + $synced = cloud_series_sync(); + $logged = array_column(array_filter( + $GLOBALS['__cloud_db_exec'], + static fn (array $exec): bool => str_contains($exec['sql'], 'plugin_cloud_series') + ), 'log'); + + expect($synced)->toBeFalse() + ->and(cloud_series_writes())->toBe(['BEGIN', 'DELETE', 'ROLLBACK']) + ->and($logged)->toBe([false]); + + $GLOBALS['__cloud_db_fail'] = []; +}); + it('keeps a series whose data source, resource and account are unchanged', function () { cloud_series_world([['local_data_id' => 5, 'metric' => 'do_cpu_pct', 'resource_id' => 11]]); diff --git a/tests/bootstrap-unit.php b/tests/bootstrap-unit.php index 5238d4b..f8cefe3 100644 --- a/tests/bootstrap-unit.php +++ b/tests/bootstrap-unit.php @@ -92,7 +92,7 @@ function cloud_test_rows(string $sql): mixed { if (!function_exists('db_execute_prepared')) { function db_execute_prepared($sql, $params = [], $log = true, $db_conn = false, $log_function = null) { - $GLOBALS['__cloud_db_exec'][] = ['sql' => $sql, 'params' => $params]; + $GLOBALS['__cloud_db_exec'][] = ['sql' => $sql, 'params' => $params, 'log' => $log]; foreach ($GLOBALS['__cloud_db_fail'] as $needle) { if (str_contains($sql, $needle)) { From 7b44210ec4009ac6f105975e4a8f0df3b376aa48 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 13:28:31 -0800 Subject: [PATCH 14/17] fix: tell an unreadable reindex snapshot apart from an empty one reindexMethods() read a failed query as no data queries. remember() then recorded nothing, the save reset every method to None, and restore() had nothing to put back, so the scope device silently stopped reindexing. reindexMethods() now returns null when the query fails. A plugin hook cannot stop Cacti's save, so after a save whose snapshot failed, restore() gives every data query the save left at None the method scope devices are created with, and logs a warning that a different method an administrator chose may be lost. If the methods cannot be read after the save either, it logs an error. Signed-off-by: Thomas Vincent --- lib/DeviceRepository.php | 19 +++++++++++++------ lib/ScopeReindex.php | 30 ++++++++++++++++++++++++++---- tests/Unit/ScopeReindexTest.php | 22 ++++++++++++++++++++-- 3 files changed, 59 insertions(+), 12 deletions(-) diff --git a/lib/DeviceRepository.php b/lib/DeviceRepository.php index 80314f2..71d2d82 100644 --- a/lib/DeviceRepository.php +++ b/lib/DeviceRepository.php @@ -104,12 +104,11 @@ public function accountFor(int $hostId): ?int { * The reindex method of each data query on a live scope device; empty * for any other device. * - * @return array data query id => reindex method + * @return array|null data query id => reindex method; null + * when they could not be read */ - public function reindexMethods(int $hostId): array { - $methods = []; - - foreach (Row::rows(db_fetch_assoc_prepared( + public function reindexMethods(int $hostId): ?array { + $rows = db_fetch_assoc_prepared( 'SELECT q.snmp_query_id, q.reindex_method FROM host_snmp_query q INNER JOIN plugin_cloud_device d ON d.host_id = q.host_id INNER JOIN host h ON h.id = d.host_id AND h.external_id = CONCAT(?, d.account_id) @@ -117,7 +116,15 @@ public function reindexMethods(int $hostId): array { [self::EXTERNAL_PREFIX, $hostId], true, $this->connection - )) as $row) { + ); + + if (!is_array($rows)) { + return null; + } + + $methods = []; + + foreach (Row::rows($rows) as $row) { $methods[Row::int($row, 'snmp_query_id')] = Row::int($row, 'reindex_method'); } diff --git a/lib/ScopeReindex.php b/lib/ScopeReindex.php index 5241b95..ed679c0 100644 --- a/lib/ScopeReindex.php +++ b/lib/ScopeReindex.php @@ -27,9 +27,14 @@ * methods before the save; the api_device_new hook, which runs after * every successful save, puts back any the save changed through * api_device_dq_change(), which also rebuilds the reindex checks. + * + * A hook cannot stop the save, so when the methods could not be read + * before it, each data query the save left at None gets the method scope + * devices are created with, and a warning says so: the device keeps + * reindexing, though a different method an administrator chose is lost. */ final class ScopeReindex { - /** @var array> host => data query => reindex method */ + /** @var array|null> host => data query => reindex method, or null when unread */ private array $saved = []; /** @@ -48,14 +53,31 @@ public function remember(int $hostId): void { } public function restore(int $hostId): void { - $saved = $this->saved[$hostId] ?? []; + if (!array_key_exists($hostId, $this->saved)) { + return; + } + + $saved = $this->saved[$hostId]; unset($this->saved[$hostId]); - if ($saved === []) { + $current = $this->devices->reindexMethods($hostId); + + if ($current === null) { + Log::error(sprintf('Device %d: reindex methods unreadable after the save; check its data queries', $hostId)); + return; } - $current = $this->devices->reindexMethods($hostId); + if ($saved === null) { + if ($current !== []) { + Log::warning(sprintf('Device %d: reindex methods were unreadable before the save; reset ones get the default', $hostId)); + } + + $saved = array_map( + static fn (int $method): int => $method === 0 ? ScopeDevices::REINDEX_METHOD : $method, + $current + ); + } foreach ($saved as $query => $method) { if (isset($current[$query]) && $current[$query] !== $method) { diff --git a/tests/Unit/ScopeReindexTest.php b/tests/Unit/ScopeReindexTest.php index 470251b..fdb0029 100644 --- a/tests/Unit/ScopeReindexTest.php +++ b/tests/Unit/ScopeReindexTest.php @@ -28,9 +28,10 @@ */ /** - * @param list> $queries host_snmp_query rows of host 7 + * @param list>|false $queries host_snmp_query rows of + * host 7, or false for a failed query */ -function cloud_reindex_queries(array $queries): void { +function cloud_reindex_queries(array|false $queries): void { $GLOBALS['__cloud_db_rows'] = ['FROM host_snmp_query' => $queries]; } @@ -84,3 +85,20 @@ static function (int $host, int $query, int $method) use ($changes): void { expect($changes->getArrayCopy())->toBe([]); }); + +it('gives a scope device the default reindex method when its methods were unreadable before the save', function () { + [$keeper, $changes] = cloud_reindex_keeper(); + $GLOBALS['__cloud_log'] = []; + + cloud_reindex_queries(false); + $keeper->remember(7); + + cloud_reindex_queries([ + ['snmp_query_id' => 9, 'reindex_method' => 0], + ['snmp_query_id' => 10, 'reindex_method' => 3], + ]); + $keeper->restore(7); + + expect($changes->getArrayCopy())->toBe([[7, 9, 2]]) + ->and(implode("\n", array_column($GLOBALS['__cloud_log'], 'message')))->toContain('WARNING: Device 7'); +}); From 1412a0fe5b86d0eeb326c723710b06bedd336778 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 14:27:15 -0800 Subject: [PATCH 15/17] fix: reindex scope devices after discovery changes their resources Index count changed, the reindex method new scope devices use, misses a resource replaced by another at the same count, a renamed resource, and a data query that had no resources, since Cacti caches no count for it. Verify all fields builds no checks for script server queries in 1.2.31 or 1.2.x, so it cannot cover these either. After each successful discovery the collector now compares the resources the account's scope device should list with what Cacti last cached for it. When they differ, it runs run_data_query() for each of the device's data queries under the account's creation lock. Comparing with Cacti's cache means a reindex that could not run, for example while the device was being created, is retried after the next discovery. Index count changed stays as a backstop. Signed-off-by: Thomas Vincent --- docs/PLAN.md | 4 +- lib/Collector.php | 14 ++- lib/DeviceRepository.php | 26 ++++++ lib/ResourceRepository.php | 28 ++++++ lib/ScopeDevices.php | 73 ++++++++++++++- setup.php | 7 +- tests/Integration/ScopeDeviceTest.php | 28 ++++++ tests/Unit/ScopeDevicesTest.php | 39 +++++++- tests/bin/discover.php | 127 ++++++++++++++++++++++++++ tests/bin/lifecycle.php | 4 + 10 files changed, 341 insertions(+), 9 deletions(-) create mode 100644 tests/bin/discover.php diff --git a/docs/PLAN.md b/docs/PLAN.md index a42652e..e13649c 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -221,10 +221,10 @@ The mapping, decided in [ADR 0010](decisions/0010-scope-devices-with-resource-da | Object | Created from | Notes | |---|---|---| | Scope device | A device template per provider, for example "Cloud: DigitalOcean Scope", carrying that provider's data queries; each device created with availability method None (`AVAIL_NONE`, 0) and the account's poller, because a Cacti 1.2 device template has no availability field | One per account and scope: a DigitalOcean team, an AWS account and region, a Google Cloud project, an Azure subscription and region | -| Resource data query | Script server data query per resource type, for example "Cloud: DigitalOcean Droplets" | Indexes are provider resource IDs; descriptions are resource names; reindexing follows Cacti's normal behavior | +| Resource data query | Script server data query per resource type, for example "Cloud: DigitalOcean Droplets" | Indexes are provider resource IDs; descriptions are resource names. After each discovery, when the resources the scope device should list differ from what Cacti last indexed (one added, renamed, or retired), the collector runs the device's data queries itself, as Cacti's reindex does. The device's reindex method, index count changed, is a backstop: Cacti's checks miss a replaced or renamed resource and a query that had none, and verify all fields builds no checks for script server queries | | Data sources and graphs | A data template and a graph template per catalog graph, generated from the metric catalog | A graph's data source holds only that graph's metrics, so creating a graph collects nothing else ([ADR 0005](decisions/0005-collect-only-what-is-graphed.md)); polled through the script server; reach Thold through `poller_output` | -This follows plugin_cloudflare's pattern of one account device with resources as data query indexes. It keeps device counts proportional to accounts, not to resources, and Cacti's reindexing handles resources that come and go. The cost is that Maint suppresses a whole scope, not one resource, and a virtual machine's cloud graphs do not sit on the Cacti device that polls the same machine over SNMP. Mapping resources onto existing devices is a research issue. +This follows plugin_cloudflare's pattern of one account device with resources as data query indexes. It keeps device counts proportional to accounts, not to resources, and reindexing after discovery handles resources that come and go. The cost is that Maint suppresses a whole scope, not one resource, and a virtual machine's cloud graphs do not sit on the Cacti device that polls the same machine over SNMP. Mapping resources onto existing devices is a research issue. Templates ship as Cacti template XML in `templates/`, generated from the catalog by `php tests/bin/generate-templates.php templates`; a unit test fails when the shipped files and the catalog disagree. Install and upgrade import them with `import_xml_data()` when the package changed or an object is missing, matched by fixed hashes so re-imports update rather than duplicate. Each data query definition is copied into `/resource/script_server/`, because Cacti 1.2 refuses a data query file outside `/resource`; uninstall leaves the templates and those files, because devices and graphs may still use them. diff --git a/lib/Collector.php b/lib/Collector.php index 176e483..5abdd9e 100644 --- a/lib/Collector.php +++ b/lib/Collector.php @@ -52,6 +52,7 @@ public function __construct( private readonly Redactor $redactor, private readonly Clock $clock, private readonly string $holder, + private readonly ?ScopeDevices $scopeDevices = null, ) { } @@ -175,10 +176,17 @@ private function runAccount(Account $account): void { try { $inventory = $driver->discover($account, $credential); $requests += $inventory->requests; - $discovery = $this->resources->sync($account->id, $inventory, $this->leases, $this->holder) - ? CollectionState::Ok - : CollectionState::Partial; + $synced = $this->resources->sync($account->id, $inventory, $this->leases, $this->holder); + $discovery = $synced ? CollectionState::Ok : CollectionState::Partial; $discoveredAt = $now; + + // Cacti's own reindex checks miss a replaced or renamed + // resource and a data query that had none. + $served = $synced && $this->scopeDevices !== null ? $this->resources->servedIndex($account->id) : null; + + if ($served !== null) { + $this->scopeDevices?->refresh($account->id, $served); + } } catch (DriverError|TransportError $e) { $discovery = CollectionState::Failed; Log::warning(sprintf('Account %d: discovery failed: %s', $account->id, $this->redactor->clean($e->getMessage()))); diff --git a/lib/DeviceRepository.php b/lib/DeviceRepository.php index 71d2d82..d268e4f 100644 --- a/lib/DeviceRepository.php +++ b/lib/DeviceRepository.php @@ -100,6 +100,32 @@ public function accountFor(int $hostId): ?int { return $id > 0 ? $id : null; } + /** + * What Cacti last indexed on a device: each index and its resource name. + * + * @return array|null index => name; null when unreadable + */ + public function cachedIndex(int $hostId): ?array { + $rows = db_fetch_assoc_prepared( + "SELECT snmp_index, field_value FROM host_snmp_cache WHERE host_id = ? AND field_name = 'resourceName'", + [$hostId], + true, + $this->connection + ); + + if (!is_array($rows)) { + return null; + } + + $index = []; + + foreach (Row::rows($rows) as $row) { + $index[Row::string($row, 'snmp_index')] = Row::string($row, 'field_value'); + } + + return $index; + } + /** * The reindex method of each data query on a live scope device; empty * for any other device. diff --git a/lib/ResourceRepository.php b/lib/ResourceRepository.php index e587b7a..273f69d 100644 --- a/lib/ResourceRepository.php +++ b/lib/ResourceRepository.php @@ -110,6 +110,34 @@ public function served(int $accountId, string $type): array { return $out; } + /** + * What the account's scope device should list: each served resource's + * id and name as ss_cloud() reports them. + * + * @return array|null provider id => name; null when the + * resources could not be read + */ + public function servedIndex(int $accountId): ?array { + $rows = db_fetch_assoc_prepared( + 'SELECT provider_id, name FROM plugin_cloud_resource WHERE account_id = ? AND lifecycle != ?', + [$accountId, Lifecycle::Deleted->value], + true, + $this->connection + ); + + if (!is_array($rows)) { + return null; + } + + $index = []; + + foreach (Row::rows($rows) as $row) { + $index[Row::string($row, 'provider_id')] = ScriptServer::label(Row::string($row, 'name')); + } + + return $index; + } + /** * @return array lifecycle => count */ diff --git a/lib/ScopeDevices.php b/lib/ScopeDevices.php index d075114..d63df91 100644 --- a/lib/ScopeDevices.php +++ b/lib/ScopeDevices.php @@ -25,7 +25,9 @@ * with the provider's device template, whose data queries list the * account's resources through ss_cloud(). * - * The accounts page calls this only when an administrator asks for it. + * The accounts page creates a device only when an administrator asks for + * it. The collector indexes it again after a discovery when the resources + * it serves differ from what Cacti last indexed. */ final class ScopeDevices { /** api_device_save()'s availability method None (AVAIL_NONE). */ @@ -35,7 +37,11 @@ final class ScopeDevices { * Reindex on an index count change (DATA_QUERY_AUTOINDEX_INDEX_NUM_CHANGE): * the poller compares ss_cloud()'s num_indexes with the cached count. The * site default, uptime going backwards, needs SNMP, which a scope device - * does not have, so it would never reindex. + * does not have, so it would never reindex. Verify all fields builds no + * checks for script server queries in 1.2.31 or 1.2.x. An index count + * misses a replaced or renamed resource and a query that had none, so + * this is only a backstop for refresh(), which the collector calls after + * each discovery. */ public const REINDEX_METHOD = 2; @@ -47,6 +53,7 @@ final class ScopeDevices { * and device template, returning the new device id or 0 * @param \Closure(int, int, int): void $reindex api_device_dq_change() for a device, * data query and reindex method, which also runs the data query + * @param \Closure(int, int): void $index run_data_query() for a device and data query * @param \Closure(int): void $remove api_device_remove() for a device * @param int $lockTimeout seconds to wait for another * request creating the same account's device @@ -56,6 +63,7 @@ public function __construct( private readonly TemplateRepository $templates, private readonly \Closure $save, private readonly \Closure $reindex, + private readonly \Closure $index, private readonly \Closure $remove, private readonly int $lockTimeout = 10, ) { @@ -135,6 +143,67 @@ private function createLocked(Account $account, int $template): int { return $host; } + /** + * Index the account's scope device again, as Cacti's reindex does, when + * what Cacti last indexed differs from what it should list. Comparing + * with Cacti's cache rather than with the previous discovery means a + * refresh that could not run is retried after the next discovery. Runs + * under the account's creation lock so a device being created is not + * indexed half linked. + * + * @param array $served provider id => name, as + * ResourceRepository::servedIndex() returns + * + * @return bool whether the device, if there is one, is up to date + */ + public function refresh(int $accountId, array $served): bool { + $host = $this->devices->hostFor($accountId); + + if ($host === null || $this->indexed($host, $served)) { + return true; + } + + if (!$this->devices->lock($accountId, $this->lockTimeout)) { + Log::warning(sprintf('Account %d: scope device busy; reindexed after the next discovery', $accountId)); + + return false; + } + + try { + $queries = $this->devices->reindexMethods($host); + + if ($queries === null) { + Log::warning(sprintf('Account %d: scope device data queries unreadable; not reindexed', $accountId)); + + return false; + } + + foreach (array_keys($queries) as $query) { + ($this->index)($host, $query); + } + + return true; + } finally { + $this->devices->unlock($accountId); + } + } + + /** + * @param array $served + */ + private function indexed(int $host, array $served): bool { + $cached = $this->devices->cachedIndex($host); + + if ($cached === null) { + return false; + } + + ksort($cached); + ksort($served); + + return $cached === $served; + } + /** * The fields api_device_save() takes, in order, for an account's device. * diff --git a/setup.php b/setup.php index 568a465..2b2d923 100644 --- a/setup.php +++ b/setup.php @@ -534,6 +534,9 @@ function (\Somethingwithproof\Cloud\Account $account, int $template): int { function (int $host, int $query, int $method): void { api_device_dq_change($host, $query, $method); }, + function (int $host, int $query): void { + run_data_query($host, $query); + }, function (int $host): void { api_device_remove($host); }, @@ -568,6 +571,8 @@ function cloud_collector(int $pollerId): \Somethingwithproof\Cloud\Collector { new \Somethingwithproof\Cloud\HealthRepository(false), new \Somethingwithproof\Cloud\Redactor(), $clock, - 'poller' . $pollerId . '-' . getmypid() . '-' . bin2hex(random_bytes(4)) + 'poller' . $pollerId . '-' . getmypid() . '-' . bin2hex(random_bytes(4)), + // Wait briefly for a device being created; the next discovery retries. + cloud_scope_devices(1) ); } diff --git a/tests/Integration/ScopeDeviceTest.php b/tests/Integration/ScopeDeviceTest.php index 452d3ea..c6bdf43 100644 --- a/tests/Integration/ScopeDeviceTest.php +++ b/tests/Integration/ScopeDeviceTest.php @@ -71,6 +71,34 @@ ->and($failed['hosts'])->toBe($hosts); }); +it('indexes its scope device after a discovery that replaces a resource, until the old one is retired', function () { + lifecycle('scope_device'); + + // The count stays two while 103 replaces 102, which Cacti's index + // count check cannot see; 102 is served while missing. + expect(lifecycle('discover', 'droplet:101=web-1,droplet:103=web-3')['device_index']) + ->toBe(['101' => 'web-1', '102' => 'web-2', '103' => 'web-3']); + + lifecycle('discover', 'droplet:101=web-1,droplet:103=web-3'); + + expect(lifecycle('discover', 'droplet:101=web-1,droplet:103=web-3')['device_index']) + ->toBe(['101' => 'web-1', '103' => 'web-3']); +}); + +it('indexes its scope device after a discovery that only renames a resource', function () { + lifecycle('scope_device'); + + expect(lifecycle('discover', 'droplet:101=web-1-renamed,droplet:102=web-2')['device_index']) + ->toBe(['101' => 'web-1-renamed', '102' => 'web-2']); +}); + +it('indexes a data query that had no resources when discovery finds its first', function () { + lifecycle('scope_device'); + + expect(lifecycle('discover', 'droplet:101=web-1,droplet:102=web-2,load_balancer:lb-1=front')['device_index']) + ->toBe(['101' => 'web-1', '102' => 'web-2', 'lb-1' => 'front']); +}); + it('reindexes resources added, renamed, and retired upstream', function () { lifecycle('scope_device'); lifecycle('resource', '103=web-3'); diff --git a/tests/Unit/ScopeDevicesTest.php b/tests/Unit/ScopeDevicesTest.php index 4fb0f75..495270c 100644 --- a/tests/Unit/ScopeDevicesTest.php +++ b/tests/Unit/ScopeDevicesTest.php @@ -39,7 +39,7 @@ function cloud_scope_world(): void { 'FROM `snmp_query`' => [['id' => 9]], 'GET_LOCK' => [['locked' => 1]], ]; - $GLOBALS['__cloud_scope'] = ['saved' => [], 'reindexed' => [], 'removed' => []]; + $GLOBALS['__cloud_scope'] = ['saved' => [], 'reindexed' => [], 'indexed' => [], 'removed' => []]; } function cloud_scope_devices_under_test(): ScopeDevices { @@ -54,6 +54,9 @@ static function (Account $account, int $template): int { static function (int $host, int $query, int $method): void { $GLOBALS['__cloud_scope']['reindexed'][] = [$host, $query, $method]; }, + static function (int $host, int $query): void { + $GLOBALS['__cloud_scope']['indexed'][] = [$host, $query]; + }, static function (int $host): void { $GLOBALS['__cloud_scope']['removed'][] = $host; } @@ -116,3 +119,37 @@ function cloud_scope_account(): Account { ->and($GLOBALS['__cloud_scope']['saved'])->toBe([]) ->and(array_column($GLOBALS['__cloud_db_exec'], 'sql'))->toContain('DO RELEASE_LOCK(?)'); }); + +it('indexes each data query of the account\'s device again when Cacti\'s index is stale, under the account\'s lock', function () { + cloud_scope_world(); + $GLOBALS['__cloud_db_rows']['FROM host_snmp_cache'] = [ + ['snmp_index' => '101', 'field_value' => 'web-1'], + ['snmp_index' => '102', 'field_value' => 'web-2'], + ]; + $GLOBALS['__cloud_db_rows']['FROM host_snmp_query'] = [ + ['snmp_query_id' => 9, 'reindex_method' => 2], + ['snmp_query_id' => 10, 'reindex_method' => 2], + ]; + $GLOBALS['__cloud_db_rows']['FROM plugin_cloud_device'] = [['host_id' => 42]]; + + expect(cloud_scope_devices_under_test()->refresh(4, ['102' => 'web-2', '101' => 'web-1']))->toBeTrue() + ->and($GLOBALS['__cloud_scope']['indexed'])->toBe([]); + + expect(cloud_scope_devices_under_test()->refresh(4, ['101' => 'web-1', '103' => 'web-3']))->toBeTrue() + ->and($GLOBALS['__cloud_scope']['indexed'])->toBe([[42, 9], [42, 10]]) + ->and(array_column($GLOBALS['__cloud_db_exec'], 'sql'))->toContain('DO RELEASE_LOCK(?)'); +}); + +it('indexes nothing while the account\'s device is being created, or when it has none', function () { + cloud_scope_world(); + $GLOBALS['__cloud_db_rows']['FROM host_snmp_cache'] = []; + + expect(cloud_scope_devices_under_test()->refresh(4, ['101' => 'web-1']))->toBeTrue() + ->and($GLOBALS['__cloud_scope']['indexed'])->toBe([]); + + $GLOBALS['__cloud_db_rows']['FROM plugin_cloud_device'] = [['host_id' => 42]]; + $GLOBALS['__cloud_db_rows']['GET_LOCK'] = [['locked' => 0]]; + + expect(cloud_scope_devices_under_test()->refresh(4, ['101' => 'web-1']))->toBeFalse() + ->and($GLOBALS['__cloud_scope']['indexed'])->toBe([]); +}); diff --git a/tests/bin/discover.php b/tests/bin/discover.php new file mode 100644 index 0000000..b97d6fa --- /dev/null +++ b/tests/bin/discover.php @@ -0,0 +1,127 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * 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. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * One discovery of the Seed account, included by tests/bin/lifecycle.php + * discover, through the production collector with a fake driver. The + * argument lists the resources discovery returns, comma separated, each + * ":=". The collector itself must index the scope device + * when the resources it serves change; nothing here runs a data query. + */ + +use Somethingwithproof\Cloud\Account; +use Somethingwithproof\Cloud\CloudResource; +use Somethingwithproof\Cloud\CollectResult; +use Somethingwithproof\Cloud\Collector; +use Somethingwithproof\Cloud\CredentialStore; +use Somethingwithproof\Cloud\Drivers; +use Somethingwithproof\Cloud\HttpTransport; +use Somethingwithproof\Cloud\Inventory; +use Somethingwithproof\Cloud\OutboundPolicy; +use Somethingwithproof\Cloud\Provider; +use Somethingwithproof\Cloud\ProviderDriver; +use Somethingwithproof\Cloud\Secret; +use Somethingwithproof\Cloud\UsageEstimate; +use Somethingwithproof\Cloud\VerifyStatus; + +include_once($config['base_path'] . '/plugins/cloud/setup.php'); +cloud_boot(); + +final class DiscoverDriver implements ProviderDriver { + /** @var list */ + public static array $resources = []; + + public function __construct(HttpTransport $http) { + } + + public function provider(): Provider { + return Provider::DigitalOcean; + } + + public function endpoints(Account $account): OutboundPolicy { + return new OutboundPolicy(['api.example.com']); + } + + public function operations(): array { + return []; + } + + public function verify(Account $account, Secret $credential): VerifyStatus { + return VerifyStatus::Ok; + } + + public function discover(Account $account, Secret $credential): Inventory { + return new Inventory(self::$resources, 1); + } + + public function collect(Account $account, Secret $credential, array $requests): CollectResult { + return new CollectResult([], 0); + } + + public function estimate(array $requests, int $intervalSeconds): UsageEstimate { + return new UsageEstimate(count($requests), 0, 0.0); + } +} + +foreach (array_filter(explode(',', $argument)) as $entry) { + list($type_id, $name) = explode('=', $entry, 2); + list($type, $id) = explode(':', $type_id, 2); + + DiscoverDriver::$resources[] = new CloudResource($type, $id, $name, 'nyc3'); +} + +$discover_dir = sys_get_temp_dir() . '/cloud-discover-' . getmypid(); +@mkdir($discover_dir, 0700); +file_put_contents($discover_dir . '/token', 'dop_v1_' . str_repeat('c', 64)); +chmod($discover_dir . '/token', 0600); + +$account = (int) db_fetch_cell("SELECT id FROM plugin_cloud_account WHERE name = 'Seed'"); +db_execute_prepared( + "UPDATE plugin_cloud_account SET credential_source = 'file', credential_file = ? WHERE id = ?", + array($discover_dir . '/token', $account) +); +// Discovery is due on every call. +db_execute_prepared('DELETE FROM plugin_cloud_health WHERE account_id = ?', array($account)); + +$discover_clock = new \Somethingwithproof\Cloud\SystemClock(); +$discover_drivers = new Drivers( + static fn (OutboundPolicy $p): HttpTransport => new \Somethingwithproof\Cloud\RefusingTransport() +); +$discover_drivers->register( + Provider::DigitalOcean, + static fn (HttpTransport $http): ProviderDriver => new DiscoverDriver($http) +); + +$result = (new Collector( + new \Somethingwithproof\Cloud\AccountRepository(false, $discover_clock), + $discover_drivers, + new CredentialStore(new \Somethingwithproof\Cloud\SecretRepository(false, $discover_clock), '/nonexistent'), + new \Somethingwithproof\Cloud\LeaseRepository(false, $discover_clock), + new \Somethingwithproof\Cloud\ResourceRepository(false, $discover_clock), + new \Somethingwithproof\Cloud\SeriesRepository(false), + new \Somethingwithproof\Cloud\ObservationRepository(false), + new \Somethingwithproof\Cloud\HealthRepository(false), + new \Somethingwithproof\Cloud\Redactor(), + $discover_clock, + 'lifecycle-discover', + cloud_scope_devices(1) +))->run(1, 240); + +unlink($discover_dir . '/token'); +rmdir($discover_dir); diff --git a/tests/bin/lifecycle.php b/tests/bin/lifecycle.php index cf210d2..0059d92 100644 --- a/tests/bin/lifecycle.php +++ b/tests/bin/lifecycle.php @@ -428,6 +428,10 @@ 'account_gone' => $accounts->find($id) === null ); + break; + case 'discover': + include($config['base_path'] . '/plugins/cloud/tests/bin/discover.php'); + break; case 'collector_flow': include($config['base_path'] . '/plugins/cloud/tests/bin/collector-flow.php'); From c82a966c1e941a2caa6a01e130d7df9dd9026011 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 15:31:05 -0800 Subject: [PATCH 16/17] fix: empty a scope device query's index when its last resource retires When every resource of a data query was retired, refresh() ran run_data_query() on an empty index list. In 1.2.31 and 1.2.x the script query gives up on an empty list before it updates host_snmp_cache, so the retired resource stayed listed and every discovery retried the same failing reindex. The resources served are now grouped by type, with every type present, so an empty list is a confirmed empty inventory rather than a failed read. For such a query, refresh() calls Cacti's own data_query_update_host_cache_from_buffer() with nothing present, which marks the query's cached rows stale and deletes them. A failed read still skips the refresh, and a data query that fails to run is now logged and retried after the next discovery. Signed-off-by: Thomas Vincent --- lib/ResourceRepository.php | 13 +++---- lib/ScopeDevices.php | 35 ++++++++++++++---- setup.php | 8 ++++- tests/Integration/ScopeDeviceTest.php | 10 ++++++ tests/Unit/ScopeDevicesTest.php | 51 +++++++++++++++++++++++---- 5 files changed, 96 insertions(+), 21 deletions(-) diff --git a/lib/ResourceRepository.php b/lib/ResourceRepository.php index 273f69d..a3242fd 100644 --- a/lib/ResourceRepository.php +++ b/lib/ResourceRepository.php @@ -112,14 +112,15 @@ public function served(int $accountId, string $type): array { /** * What the account's scope device should list: each served resource's - * id and name as ss_cloud() reports them. + * id and name as ss_cloud() reports them, by type. Every catalog type is + * present, so an empty list means confirmed empty, not unread. * - * @return array|null provider id => name; null when the - * resources could not be read + * @return array>|null type => provider id + * => name; null when the resources could not be read */ public function servedIndex(int $accountId): ?array { $rows = db_fetch_assoc_prepared( - 'SELECT provider_id, name FROM plugin_cloud_resource WHERE account_id = ? AND lifecycle != ?', + 'SELECT type, provider_id, name FROM plugin_cloud_resource WHERE account_id = ? AND lifecycle != ?', [$accountId, Lifecycle::Deleted->value], true, $this->connection @@ -129,10 +130,10 @@ public function servedIndex(int $accountId): ?array { return null; } - $index = []; + $index = [DigitalOceanCatalog::DROPLET => [], DigitalOceanCatalog::LOAD_BALANCER => []]; foreach (Row::rows($rows) as $row) { - $index[Row::string($row, 'provider_id')] = ScriptServer::label(Row::string($row, 'name')); + $index[Row::string($row, 'type')][Row::string($row, 'provider_id')] = ScriptServer::label(Row::string($row, 'name')); } return $index; diff --git a/lib/ScopeDevices.php b/lib/ScopeDevices.php index d63df91..bb60644 100644 --- a/lib/ScopeDevices.php +++ b/lib/ScopeDevices.php @@ -53,7 +53,9 @@ final class ScopeDevices { * and device template, returning the new device id or 0 * @param \Closure(int, int, int): void $reindex api_device_dq_change() for a device, * data query and reindex method, which also runs the data query - * @param \Closure(int, int): void $index run_data_query() for a device and data query + * @param \Closure(int, int): bool $index run_data_query() for a device and data query + * @param \Closure(int, int): void $clear empties Cacti's index cache of a device's + * data query, for one whose resources are all gone * @param \Closure(int): void $remove api_device_remove() for a device * @param int $lockTimeout seconds to wait for another * request creating the same account's device @@ -64,6 +66,7 @@ public function __construct( private readonly \Closure $save, private readonly \Closure $reindex, private readonly \Closure $index, + private readonly \Closure $clear, private readonly \Closure $remove, private readonly int $lockTimeout = 10, ) { @@ -151,15 +154,20 @@ private function createLocked(Account $account, int $template): int { * under the account's creation lock so a device being created is not * indexed half linked. * - * @param array $served provider id => name, as - * ResourceRepository::servedIndex() returns + * A data query whose resources are all gone cannot be run: Cacti's + * script query gives up on an empty index list before it updates the + * cache, in 1.2.31 and 1.2.x, so the last resource would stay listed. + * Its cache is emptied instead. + * + * @param array> $served type => provider + * id => name, as ResourceRepository::servedIndex() returns * * @return bool whether the device, if there is one, is up to date */ public function refresh(int $accountId, array $served): bool { $host = $this->devices->hostFor($accountId); - if ($host === null || $this->indexed($host, $served)) { + if ($host === null || $this->indexed($host, array_replace([], ...array_values($served)))) { return true; } @@ -178,11 +186,24 @@ public function refresh(int $accountId, array $served): bool { return false; } - foreach (array_keys($queries) as $query) { - ($this->index)($host, $query); + $indexed = true; + + foreach ($served as $type => $resources) { + $query = $this->templates->id('snmp_query', 'data_query/' . $type); + + if ($query === null || !isset($queries[$query])) { + continue; + } + + if ($resources === []) { + ($this->clear)($host, $query); + } elseif (!($this->index)($host, $query)) { + Log::warning(sprintf('Account %d: scope device data query %d failed; reindexed after the next discovery', $accountId, $query)); + $indexed = false; + } } - return true; + return $indexed; } finally { $this->devices->unlock($accountId); } diff --git a/setup.php b/setup.php index 2b2d923..170fee4 100644 --- a/setup.php +++ b/setup.php @@ -534,8 +534,14 @@ function (\Somethingwithproof\Cloud\Account $account, int $template): int { function (int $host, int $query, int $method): void { api_device_dq_change($host, $query, $method); }, + function (int $host, int $query): bool { + return (bool) run_data_query($host, $query); + }, function (int $host, int $query): void { - run_data_query($host, $query); + // Cacti's own cache update, with nothing present: it marks the + // query's rows stale and deletes them. + $none = array(); + data_query_update_host_cache_from_buffer($host, $query, $none, $none); }, function (int $host): void { api_device_remove($host); diff --git a/tests/Integration/ScopeDeviceTest.php b/tests/Integration/ScopeDeviceTest.php index c6bdf43..2d25bbb 100644 --- a/tests/Integration/ScopeDeviceTest.php +++ b/tests/Integration/ScopeDeviceTest.php @@ -92,6 +92,16 @@ ->toBe(['101' => 'web-1-renamed', '102' => 'web-2']); }); +it('empties a data query\'s index once its last resource is retired', function () { + lifecycle('scope_device'); + lifecycle('discover', 'droplet:101=web-1,droplet:102=web-2,load_balancer:lb-1=front'); + lifecycle('discover', 'droplet:101=web-1,droplet:102=web-2'); + lifecycle('discover', 'droplet:101=web-1,droplet:102=web-2'); + + expect(lifecycle('discover', 'droplet:101=web-1,droplet:102=web-2')['device_index']) + ->toBe(['101' => 'web-1', '102' => 'web-2']); +}); + it('indexes a data query that had no resources when discovery finds its first', function () { lifecycle('scope_device'); diff --git a/tests/Unit/ScopeDevicesTest.php b/tests/Unit/ScopeDevicesTest.php index 495270c..ba983cc 100644 --- a/tests/Unit/ScopeDevicesTest.php +++ b/tests/Unit/ScopeDevicesTest.php @@ -39,7 +39,7 @@ function cloud_scope_world(): void { 'FROM `snmp_query`' => [['id' => 9]], 'GET_LOCK' => [['locked' => 1]], ]; - $GLOBALS['__cloud_scope'] = ['saved' => [], 'reindexed' => [], 'indexed' => [], 'removed' => []]; + $GLOBALS['__cloud_scope'] = ['saved' => [], 'reindexed' => [], 'indexed' => [], 'cleared' => [], 'removed' => []]; } function cloud_scope_devices_under_test(): ScopeDevices { @@ -54,8 +54,13 @@ static function (Account $account, int $template): int { static function (int $host, int $query, int $method): void { $GLOBALS['__cloud_scope']['reindexed'][] = [$host, $query, $method]; }, - static function (int $host, int $query): void { + static function (int $host, int $query): bool { $GLOBALS['__cloud_scope']['indexed'][] = [$host, $query]; + + return $GLOBALS['__cloud_scope']['index_ok'] ?? true; + }, + static function (int $host, int $query): void { + $GLOBALS['__cloud_scope']['cleared'][] = [$host, $query]; }, static function (int $host): void { $GLOBALS['__cloud_scope']['removed'][] = $host; @@ -120,8 +125,19 @@ function cloud_scope_account(): Account { ->and(array_column($GLOBALS['__cloud_db_exec'], 'sql'))->toContain('DO RELEASE_LOCK(?)'); }); -it('indexes each data query of the account\'s device again when Cacti\'s index is stale, under the account\'s lock', function () { +/** + * Host 42 is account 4's device, with the Droplet query 9 and the load + * balancer query 10, and Cacti has indexed Droplets 101 and 102. + */ +function cloud_scope_indexed_world(): void { cloud_scope_world(); + $ids = [9, 10]; + $GLOBALS['__cloud_db_rows']['FROM `snmp_query`'] = static function () use (&$ids): array { + $id = array_shift($ids) ?? 0; + $ids[] = $id; + + return [['id' => $id]]; + }; $GLOBALS['__cloud_db_rows']['FROM host_snmp_cache'] = [ ['snmp_index' => '101', 'field_value' => 'web-1'], ['snmp_index' => '102', 'field_value' => 'web-2'], @@ -131,25 +147,46 @@ function cloud_scope_account(): Account { ['snmp_query_id' => 10, 'reindex_method' => 2], ]; $GLOBALS['__cloud_db_rows']['FROM plugin_cloud_device'] = [['host_id' => 42]]; +} - expect(cloud_scope_devices_under_test()->refresh(4, ['102' => 'web-2', '101' => 'web-1']))->toBeTrue() +it('indexes the account\'s device again when Cacti\'s index is stale, under the account\'s lock', function () { + cloud_scope_indexed_world(); + + expect(cloud_scope_devices_under_test()->refresh(4, ['droplet' => ['102' => 'web-2', '101' => 'web-1'], 'load_balancer' => []]))->toBeTrue() ->and($GLOBALS['__cloud_scope']['indexed'])->toBe([]); - expect(cloud_scope_devices_under_test()->refresh(4, ['101' => 'web-1', '103' => 'web-3']))->toBeTrue() + expect(cloud_scope_devices_under_test()->refresh(4, ['droplet' => ['101' => 'web-1'], 'load_balancer' => ['lb-1' => 'front']]))->toBeTrue() ->and($GLOBALS['__cloud_scope']['indexed'])->toBe([[42, 9], [42, 10]]) + ->and($GLOBALS['__cloud_scope']['cleared'])->toBe([]) ->and(array_column($GLOBALS['__cloud_db_exec'], 'sql'))->toContain('DO RELEASE_LOCK(?)'); }); +it('empties Cacti\'s index of a data query whose resources are all gone, rather than running it', function () { + cloud_scope_indexed_world(); + + expect(cloud_scope_devices_under_test()->refresh(4, ['droplet' => [], 'load_balancer' => ['lb-1' => 'front']]))->toBeTrue() + ->and($GLOBALS['__cloud_scope']['cleared'])->toBe([[42, 9]]) + ->and($GLOBALS['__cloud_scope']['indexed'])->toBe([[42, 10]]); +}); + +it('reports a data query that failed to run, so the next discovery retries it', function () { + cloud_scope_indexed_world(); + $GLOBALS['__cloud_scope']['index_ok'] = false; + + expect(cloud_scope_devices_under_test()->refresh(4, ['droplet' => ['103' => 'web-3'], 'load_balancer' => []]))->toBeFalse() + ->and(implode("\n", array_column($GLOBALS['__cloud_log'], 'message')))->toContain('data query 9 failed'); +}); + it('indexes nothing while the account\'s device is being created, or when it has none', function () { cloud_scope_world(); $GLOBALS['__cloud_db_rows']['FROM host_snmp_cache'] = []; - expect(cloud_scope_devices_under_test()->refresh(4, ['101' => 'web-1']))->toBeTrue() + expect(cloud_scope_devices_under_test()->refresh(4, ['droplet' => ['101' => 'web-1'], 'load_balancer' => []]))->toBeTrue() ->and($GLOBALS['__cloud_scope']['indexed'])->toBe([]); $GLOBALS['__cloud_db_rows']['FROM plugin_cloud_device'] = [['host_id' => 42]]; $GLOBALS['__cloud_db_rows']['GET_LOCK'] = [['locked' => 0]]; - expect(cloud_scope_devices_under_test()->refresh(4, ['101' => 'web-1']))->toBeFalse() + expect(cloud_scope_devices_under_test()->refresh(4, ['droplet' => ['101' => 'web-1'], 'load_balancer' => []]))->toBeFalse() ->and($GLOBALS['__cloud_scope']['indexed'])->toBe([]); }); From 328d5bb4e279ff5216e187b2d7274f3ef89f196c Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 19:07:29 -0800 Subject: [PATCH 17/17] fix: retry a scope device reindex that failed after a partial cache update refresh() decided whether Cacti's index was current from the cached resource names alone. A data query that cached the new names and then failed, for example on the resource id field, left a cache the next discovery read as current, so the failed reindex was never retried. An index now counts as cached only when Cacti holds both fields the data queries read, the resource id and name, with the id matching the index. An incomplete index matches no served resource, so the next discovery reindexes until the whole query succeeds. Signed-off-by: Thomas Vincent --- lib/DeviceRepository.php | 23 +++++++++++--- lib/ScopeDevices.php | 3 ++ tests/Unit/ScopeDevicesTest.php | 53 ++++++++++++++++++++++++++++++--- 3 files changed, 71 insertions(+), 8 deletions(-) diff --git a/lib/DeviceRepository.php b/lib/DeviceRepository.php index d268e4f..bc3db55 100644 --- a/lib/DeviceRepository.php +++ b/lib/DeviceRepository.php @@ -102,12 +102,18 @@ public function accountFor(int $hostId): ?int { /** * What Cacti last indexed on a device: each index and its resource name. + * An index is complete only when Cacti cached both fields the data + * queries read, with the id matching the index; an incomplete one maps + * to null, which matches no served resource, so a reindex that failed + * partway is retried. * - * @return array|null index => name; null when unreadable + * @return array|null index => name, or null when + * incomplete; null when unreadable */ public function cachedIndex(int $hostId): ?array { $rows = db_fetch_assoc_prepared( - "SELECT snmp_index, field_value FROM host_snmp_cache WHERE host_id = ? AND field_name = 'resourceName'", + "SELECT snmp_index, field_name, field_value FROM host_snmp_cache + WHERE host_id = ? AND field_name IN ('resourceId', 'resourceName')", [$hostId], true, $this->connection @@ -117,10 +123,19 @@ public function cachedIndex(int $hostId): ?array { return null; } - $index = []; + $fields = []; foreach (Row::rows($rows) as $row) { - $index[Row::string($row, 'snmp_index')] = Row::string($row, 'field_value'); + $fields[Row::string($row, 'snmp_index')][Row::string($row, 'field_name')] = Row::string($row, 'field_value'); + } + + $index = []; + + foreach ($fields as $snmpIndex => $values) { + $complete = isset($values['resourceId'], $values['resourceName']) + && $values['resourceId'] === (string) $snmpIndex; + + $index[$snmpIndex] = $complete ? $values['resourceName'] : null; } return $index; diff --git a/lib/ScopeDevices.php b/lib/ScopeDevices.php index bb60644..b127652 100644 --- a/lib/ScopeDevices.php +++ b/lib/ScopeDevices.php @@ -210,6 +210,9 @@ public function refresh(int $accountId, array $served): bool { } /** + * Whether Cacti's cache lists exactly the served resources, each with + * every field the data queries read. + * * @param array $served */ private function indexed(int $host, array $served): bool { diff --git a/tests/Unit/ScopeDevicesTest.php b/tests/Unit/ScopeDevicesTest.php index ba983cc..bf05058 100644 --- a/tests/Unit/ScopeDevicesTest.php +++ b/tests/Unit/ScopeDevicesTest.php @@ -57,6 +57,10 @@ static function (int $host, int $query, int $method): void { static function (int $host, int $query): bool { $GLOBALS['__cloud_scope']['indexed'][] = [$host, $query]; + if (isset($GLOBALS['__cloud_scope']['on_index'])) { + ($GLOBALS['__cloud_scope']['on_index'])(); + } + return $GLOBALS['__cloud_scope']['index_ok'] ?? true; }, static function (int $host, int $query): void { @@ -125,6 +129,24 @@ function cloud_scope_account(): Account { ->and(array_column($GLOBALS['__cloud_db_exec'], 'sql'))->toContain('DO RELEASE_LOCK(?)'); }); +/** + * host_snmp_cache rows for complete indexes. + * + * @param array $names index => resource name + * + * @return list> + */ +function cloud_scope_cache(array $names): array { + $rows = []; + + foreach ($names as $index => $name) { + $rows[] = ['snmp_index' => (string) $index, 'field_name' => 'resourceId', 'field_value' => (string) $index]; + $rows[] = ['snmp_index' => (string) $index, 'field_name' => 'resourceName', 'field_value' => $name]; + } + + return $rows; +} + /** * Host 42 is account 4's device, with the Droplet query 9 and the load * balancer query 10, and Cacti has indexed Droplets 101 and 102. @@ -138,10 +160,7 @@ function cloud_scope_indexed_world(): void { return [['id' => $id]]; }; - $GLOBALS['__cloud_db_rows']['FROM host_snmp_cache'] = [ - ['snmp_index' => '101', 'field_value' => 'web-1'], - ['snmp_index' => '102', 'field_value' => 'web-2'], - ]; + $GLOBALS['__cloud_db_rows']['FROM host_snmp_cache'] = cloud_scope_cache(['101' => 'web-1', '102' => 'web-2']); $GLOBALS['__cloud_db_rows']['FROM host_snmp_query'] = [ ['snmp_query_id' => 9, 'reindex_method' => 2], ['snmp_query_id' => 10, 'reindex_method' => 2], @@ -177,6 +196,32 @@ function cloud_scope_indexed_world(): void { ->and(implode("\n", array_column($GLOBALS['__cloud_log'], 'message')))->toContain('data query 9 failed'); }); +it('retries a data query that updated the cached names but then failed', function () { + cloud_scope_indexed_world(); + $served = ['droplet' => ['101' => 'web-1', '103' => 'web-3'], 'load_balancer' => []]; + // Cacti caches the new names but not every id before the query fails. + $GLOBALS['__cloud_scope']['index_ok'] = false; + $GLOBALS['__cloud_scope']['on_index'] = static function (): void { + $GLOBALS['__cloud_db_rows']['FROM host_snmp_cache'] = array_values(array_filter( + cloud_scope_cache(['101' => 'web-1', '103' => 'web-3']), + static fn (array $row): bool => !($row['snmp_index'] === '103' && $row['field_name'] === 'resourceId') + )); + }; + + expect(cloud_scope_devices_under_test()->refresh(4, $served))->toBeFalse(); + + $GLOBALS['__cloud_scope']['index_ok'] = true; + $GLOBALS['__cloud_scope']['on_index'] = static function (): void { + $GLOBALS['__cloud_db_rows']['FROM host_snmp_cache'] = cloud_scope_cache(['101' => 'web-1', '103' => 'web-3']); + }; + + expect(cloud_scope_devices_under_test()->refresh(4, $served))->toBeTrue() + ->and($GLOBALS['__cloud_scope']['indexed'])->toBe([[42, 9], [42, 9]]); + + expect(cloud_scope_devices_under_test()->refresh(4, $served))->toBeTrue() + ->and($GLOBALS['__cloud_scope']['indexed'])->toBe([[42, 9], [42, 9]]); +}); + it('indexes nothing while the account\'s device is being created, or when it has none', function () { cloud_scope_world(); $GLOBALS['__cloud_db_rows']['FROM host_snmp_cache'] = [];