Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
febe226
feat: create scope devices and serve their resources through the scri…
somethingwithproof Nov 15, 2026
2e9dec8
fix: trust a scope device link only while its host still carries the …
somethingwithproof Nov 15, 2026
53f7545
fix: collect the metrics graphed on each account's scope device
somethingwithproof Nov 15, 2026
7c1b7a3
fix: serve U for resources in the missing lifecycle
somethingwithproof Nov 15, 2026
bf46108
fix: age a series skipped for budget from the datapoint it kept
somethingwithproof Nov 15, 2026
9697255
fix: remove a new scope device whose account link was not recorded
somethingwithproof Nov 15, 2026
17cebda
fix: leave an account's series unchanged when its data sources cannot…
somethingwithproof Nov 15, 2026
c949b70
fix: fence series sync with the collector's lease
somethingwithproof Nov 15, 2026
06a2877
fix: serialize scope device creation per account
somethingwithproof Nov 15, 2026
fdc478e
fix: keep query reindexing on scope devices across edits
somethingwithproof Nov 15, 2026
831e0af
test: bind the lock name in the scope device lock scenario
somethingwithproof Nov 15, 2026
182da17
fix: reconcile series by data source, resource and account
somethingwithproof Nov 15, 2026
750cf9f
fix: keep core's deadlock retry out of the series sync transaction
somethingwithproof Nov 15, 2026
7b44210
fix: tell an unreadable reindex snapshot apart from an empty one
somethingwithproof Nov 15, 2026
1412a0f
fix: reindex scope devices after discovery changes their resources
somethingwithproof Nov 15, 2026
c82a966
fix: empty a scope device query's index when its last resource retires
somethingwithproof Nov 15, 2026
328d5bb
fix: retry a scope device reindex that failed after a partial cache u…
somethingwithproof Nov 16, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 23 additions & 2 deletions cloud_accounts.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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':
Expand Down
6 changes: 3 additions & 3 deletions docs/PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<path_cacti>/resource/script_server/`, because Cacti 1.2 refuses a data query file outside `<path_cacti>/resource`; uninstall leaves the templates and those files, because devices and graphs may still use them.

Expand Down Expand Up @@ -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.

Expand Down
2 changes: 2 additions & 0 deletions lib/AccountRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 = ?',
Expand Down
19 changes: 18 additions & 1 deletion lib/AccountsPage.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ final class AccountsPage {
public function __construct(
private readonly AccountRepository $accounts,
private readonly CredentialStore $credentials,
private readonly DeviceRepository $devices,
) {
}

Expand All @@ -43,13 +44,14 @@ public function renderList(): void {
__('Credential', 'cloud'),
__('State', 'cloud'),
__('Verify', 'cloud'),
__('Device', 'cloud'),
__('Actions', 'cloud'),
])) . '</th></tr>';

$accounts = $this->accounts->all();

if ($accounts === []) {
print '<tr><td colspan="6"><em>' . html_escape(__('No cloud accounts yet.', 'cloud')) . '</em></td></tr>';
print '<tr><td colspan="7"><em>' . html_escape(__('No cloud accounts yet.', 'cloud')) . '</em></td></tr>';
}

foreach ($accounts as $account) {
Expand All @@ -61,6 +63,7 @@ public function renderList(): void {
. '<td>' . html_escape($account->enabled() ? __('Enabled', 'cloud') : __('Disabled', 'cloud')) . '</td>'
. '<td title="' . html_escape($account->verifyStatus->message()) . '">'
. html_escape($account->verifyStatus->message()) . '</td>'
. '<td>' . $this->deviceCell($account) . '</td>'
. '<td>' . $this->actionForm($account->id, 'verify', __('Verify', 'cloud')) . ' '
. $this->actionForm($account->id, 'delete', __('Delete', 'cloud')) . '</td>'
. '</tr>';
Expand Down Expand Up @@ -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 '<a class="linkEditMain" href="' . html_escape('../../host.php?action=edit&id=' . $host) . '">'
. html_escape(__('Device %d', $host, 'cloud')) . '</a>';
}

return $this->actionForm($account->id, 'create_device', __('Create Cacti Device', 'cloud'));
}

private function actionForm(int $id, string $action, string $label): string {
return '<form method="post" action="' . html_escape(self::FILE) . '" style="display:inline">'
. '<input type="hidden" name="action" value="' . html_escape($action) . '">'
Expand Down
15 changes: 12 additions & 3 deletions lib/Collector.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ public function __construct(
private readonly Redactor $redactor,
private readonly Clock $clock,
private readonly string $holder,
private readonly ?ScopeDevices $scopeDevices = null,
) {
}

Expand Down Expand Up @@ -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())));
Expand All @@ -190,6 +198,7 @@ private function runAccount(Account $account): void {
}
}

$this->series->sync($account->id, $this->leases, $this->holder);
$wanted = $this->series->enabledFor($account->id);
[$fit, $left] = RequestBudget::split($account, $driver, $wanted, $requests);

Expand Down
187 changes: 187 additions & 0 deletions lib/DeviceRepository.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
<?php
/*
* SPDX-FileCopyrightText: 2026 Thomas Vincent <thomasvincent@gmail.com>
* 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).
*
* 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:';

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 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 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 (?, ?, ?)',
[$hostId, $accountId, $this->clock->now()],
true,
$this->connection
) !== false;
}

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

return $id > 0 ? $id : null;
}

/**
* 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<string, string|null>|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_name, field_value FROM host_snmp_cache
WHERE host_id = ? AND field_name IN ('resourceId', 'resourceName')",
[$hostId],
true,
$this->connection
);

if (!is_array($rows)) {
return null;
}

$fields = [];

foreach (Row::rows($rows) as $row) {
$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;
}

/**
* The reindex method of each data query on a live scope device; empty
* for any other device.
*
* @return array<int, int>|null data query id => reindex method; null
* when they could not be read
*/
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)
WHERE q.host_id = ?',
[self::EXTERNAL_PREFIX, $hostId],
true,
$this->connection
);

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');
}

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
WHERE d.account_id = ? AND h.external_id = CONCAT(?, d.account_id)',
[$accountId, self::EXTERNAL_PREFIX],
'',
true,
$this->connection
);

return $id > 0 ? $id : null;
}
}
16 changes: 16 additions & 0 deletions lib/FreshnessEvaluator.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
12 changes: 1 addition & 11 deletions lib/HealthPage.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
Loading
Loading