diff --git a/README.md b/README.md index 38b18b9..2bb45b6 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ A Cacti 1.2 plugin that brings resources and metrics from public cloud providers into Cacti as ordinary devices, data sources, and graphs. Cloud workloads then sit next to the network that carries them, under Cacti's permissions, and Thold and Maint can alert on and suppress them. One plugin covers every provider, with a driver per provider: DigitalOcean, AWS, Google Cloud, and Azure first. -> **Status: in development, no release yet.** Milestone 2 (foundation) is merged on `main`. The plugin installs, stores accounts and credentials, and runs its collector, but no provider driver is merged, so it collects nothing. Milestone 3 (DigitalOcean and Cacti objects) is in progress and not yet on `main`. Do not run it in production. +> **Status: milestone 3 (DigitalOcean and Cacti objects), in review.** The milestone adds the DigitalOcean driver, Cacti templates, a scope device per account with a data query per resource type, the script server input, and a request estimate on New Graphs and the health page. Initial checks against a live DigitalOcean account are recorded in [provider facts](docs/research/provider-facts.md). Do not run it in production. ## Why @@ -26,7 +26,7 @@ The plugin reads each provider's monitoring API on a Cacti poller, caches the la | Phase | Scope | Milestones | Status | |---|---|---|---| | 0, research | Provider fact confirmation, metric catalogs, cost and rate model, signing test vectors, transport spike | [M1](https://github.com/somethingwithproof/plugin_cloud/milestone/1) | Done, except the checks that need a live provider account | -| 1, core and DigitalOcean | Accounts, credential vault, transport, collector, observation cache, Cacti objects, health page, DigitalOcean Droplets and load balancers | [M2](https://github.com/somethingwithproof/plugin_cloud/milestone/2), [M3](https://github.com/somethingwithproof/plugin_cloud/milestone/3), [M4](https://github.com/somethingwithproof/plugin_cloud/milestone/4) | M2 merged ([#81](https://github.com/somethingwithproof/plugin_cloud/pull/81)); M3 in progress, not on `main`; M4 not started | +| 1, core and DigitalOcean | Accounts, credential vault, transport, collector, observation cache, Cacti objects, health page, DigitalOcean Droplets and load balancers | [M2](https://github.com/somethingwithproof/plugin_cloud/milestone/2), [M3](https://github.com/somethingwithproof/plugin_cloud/milestone/3), [M4](https://github.com/somethingwithproof/plugin_cloud/milestone/4) | M2 done ([#81](https://github.com/somethingwithproof/plugin_cloud/pull/81)); M3 driver, templates, and scope devices merged; request estimates, permissions, and performance checks in review; M4 not started | | 2, AWS | Signature Version 4, `AssumeRole`, instance roles, CloudWatch `GetMetricData`, regional inventory | [M5](https://github.com/somethingwithproof/plugin_cloud/milestone/5) | Not started | | 3, Google Cloud | Service account JWT, metadata server, Cloud Monitoring `timeSeries.list` | [M6](https://github.com/somethingwithproof/plugin_cloud/milestone/6) | Not started | | 4, Azure | Entra client credentials, managed identity, Resource Graph, `metrics:getBatch` | [M7](https://github.com/somethingwithproof/plugin_cloud/milestone/7) | Not started | diff --git a/cloud_health.php b/cloud_health.php index c333f70..8163a8b 100644 --- a/cloud_health.php +++ b/cloud_health.php @@ -47,4 +47,5 @@ api_user_realm_auth('cloud_accounts.php'), (int) read_config_option('poller_interval') ); +cloud_estimate_view()->render(cloud_accounts()->all()); bottom_footer(); diff --git a/docs/PLAN.md b/docs/PLAN.md index 8b652a3..24d7702 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -174,7 +174,7 @@ flowchart TB | Component | Responsibility | Interfaces | Failure behavior | |---|---|---|---| -| Plugin pages | Accounts, credentials, inventory, graph selection with cost estimate, health | Cacti page framework, csrf-magic, realms | Show cached data with its age; never call a provider during a page request except Verify | +| Plugin pages | Accounts, credentials, inventory, health with the request estimate, an estimate link and summary on New Graphs for scope devices | Cacti page framework, csrf-magic, realms | Show cached data with its age; never call a provider during a page request except Verify | | Collector (`poller_cloud.php`) | For each due account: refresh credentials, run discovery when due, read metrics for enabled data sources, update the cache and health | `poller_bottom`, `exec_background()`, `register_process_start()`, filtered by `poller_id` | One instance per poller; time budget per run; per-account lease; resumes next cycle | | Provider driver | Authentication, endpoints, discovery, metric reads, cost and request estimates for one provider | `ProviderDriver` interface | Returns typed errors (`auth`, `permission`, `throttled`, `transient`, `malformed`, `config`); never throws provider text into pages | | Transport | One HTTPS request at a time with timeouts, size cap, no redirects, outbound allowlist | `HttpTransport` interface | A refused URL never resolves a name or opens a socket | diff --git a/lib/CostPreview.php b/lib/CostPreview.php new file mode 100644 index 0000000..4e3ecd0 --- /dev/null +++ b/lib/CostPreview.php @@ -0,0 +1,140 @@ + + * 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; + +/** + * Usage estimates for what an account could graph and what it collects + * (REQ-COST-001, REQ-COST-002, ADR 0005). Every figure comes from the + * provider driver's own estimate, from cached inventory only; nothing here + * calls a provider. + */ +final class CostPreview { + private const SECONDS_PER_HOUR = 3600; + + public function __construct( + private readonly ResourceRepository $resources, + private readonly SeriesRepository $series, + ) { + } + + /** + * One row per graph the account's resources can have: the cost of that + * graph on one resource, and on every resource of its type. + * + * @return list + */ + public function graphs(Account $account, ProviderDriver $driver): array { + if ($account->provider !== Provider::DigitalOcean) { + return []; + } + + $rows = []; + $served = []; + + foreach (DigitalOceanCatalog::GRAPHS as $graph => [$type, $title, , , $fields]) { + $served[$type] ??= $this->resources->served($account->id, $type); + $metrics = self::metrics($fields); + $example = [['id' => 0, 'providerId' => '0']]; + + $rows[] = [ + 'graph' => $graph, + 'type' => $type, + 'title' => $title, + 'resources' => count($served[$type]), + 'perResource' => $driver->estimate(self::requests($example, $type, $metrics), $account->collectInterval), + 'all' => $driver->estimate(self::requests($served[$type], $type, $metrics), $account->collectInterval), + ]; + } + + return $rows; + } + + /** + * Every graph on every resource the account has. + */ + public function everything(Account $account, ProviderDriver $driver): UsageEstimate { + $requests = []; + + if ($account->provider === Provider::DigitalOcean) { + $metrics = []; + + foreach (DigitalOceanCatalog::GRAPHS as [$type, , , , $fields]) { + $metrics[$type] = array_merge($metrics[$type] ?? [], self::metrics($fields)); + } + + foreach ($metrics as $type => $names) { + $requests = array_merge( + $requests, + self::requests($this->resources->served($account->id, $type), $type, $names) + ); + } + } + + return $driver->estimate($requests, $account->collectInterval); + } + + /** + * The metric series that fit the collector budget. Discovery requests + * already spent by a run reduce the allowance in exactly the same way. + */ + public function collected(Account $account, ProviderDriver $driver, int $discoveryRequests = 0): UsageEstimate { + [$fit] = RequestBudget::split($account, $driver, $this->series->enabledFor($account->id), $discoveryRequests); + + return $driver->estimate($fit, $account->collectInterval); + } + + public function requested(Account $account, ProviderDriver $driver): UsageEstimate { + return $driver->estimate($this->series->enabledFor($account->id), $account->collectInterval); + } + + public static function perHour(UsageEstimate $estimate, int $collectInterval): int { + return (int) ceil($estimate->requestsPerCollection * self::SECONDS_PER_HOUR / max(1, $collectInterval)); + } + + /** + * The fields of a graph that read a metric; age reads nothing. + * + * @param list $fields + * @return list + */ + private static function metrics(array $fields): array { + return array_values(array_filter( + $fields, + static fn (string $field): bool => DigitalOceanCatalog::metric($field) !== null + )); + } + + /** + * @param list $resources + * @param list $metrics + * @return list + */ + private static function requests(array $resources, string $type, array $metrics): array { + $requests = []; + + foreach ($resources as $resource) { + foreach ($metrics as $metric) { + $requests[] = new MetricRequest($resource['id'], $type, $resource['providerId'], $metric); + } + } + + return $requests; + } +} diff --git a/lib/DigitalOceanDriver.php b/lib/DigitalOceanDriver.php index 4593a34..64ca70f 100644 --- a/lib/DigitalOceanDriver.php +++ b/lib/DigitalOceanDriver.php @@ -43,6 +43,10 @@ final class DigitalOceanDriver implements ProviderDriver { private const MONTH = 2592000; + /** Where the rate limit is documented and no API charge is (provider facts DO10). */ + private const PRICE_SOURCE = 'https://docs.digitalocean.com/reference/api/reference/openapi.json'; + private const PRICE_CHECKED = '2026-11-14'; + /** The longest wait a provider may impose through Retry-After or ratelimit-reset. */ private const MAX_WAIT = 3600; @@ -248,7 +252,13 @@ public function collect(Account $account, Secret $credential, array $requests): public function estimate(array $requests, int $intervalSeconds): UsageEstimate { $perCollection = count($requests); - return new UsageEstimate($perCollection, (int) ceil($perCollection * self::MONTH / max(1, $intervalSeconds)), 0.0); + return new UsageEstimate( + $perCollection, + (int) ceil($perCollection * self::MONTH / max(1, $intervalSeconds)), + 0.0, + self::PRICE_SOURCE, + self::PRICE_CHECKED + ); } /** diff --git a/lib/EstimateView.php b/lib/EstimateView.php new file mode 100644 index 0000000..a7c1609 --- /dev/null +++ b/lib/EstimateView.php @@ -0,0 +1,205 @@ + + * 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 Cloud Request Estimate box on the health page: what each account + * collects now (REQ-COST-002) and what each graph would add before it is + * created (REQ-COST-001). Every figure comes from cached inventory. + */ +final class EstimateView { + public const ANCHOR = 'cloud-estimate-'; + + public function __construct( + private readonly CostPreview $cost, + private readonly Drivers $drivers, + ) { + } + + /** + * @param list $accounts + */ + public function render(array $accounts): void { + html_start_box(__('Cloud Request Estimate', 'cloud'), '100%', '', '3', 'center', ''); + + $headers = [ + __('Account', 'cloud'), + __('Selection', 'cloud'), + __('Resources', 'cloud'), + __('Requests per Hour, One Resource', 'cloud'), + __('Requests per Month, One Resource', 'cloud'), + __('Requests per Hour', 'cloud'), + __('Requests per Month', 'cloud'), + __('Cost per Month', 'cloud'), + ]; + + print '' . implode('', array_map('html_escape', $headers)) . ''; + + $sources = []; + + foreach ($accounts as $account) { + $driver = $this->drivers->for($account); + + if ($driver === null) { + continue; + } + + $first = true; + + foreach ($this->rows($account, $driver) as $row) { + $attributes = $first ? ' id="' . self::ANCHOR . $account->id . '"' : ''; + $first = false; + + print '' + . implode('', array_map('html_escape', $row['cells'])) . ''; + + if ($row['source'] !== '') { + $sources[$account->provider->label()] = [$row['source'], $row['checked']]; + } + } + + $note = $this->budgetNote($account, $driver); + + if ($note !== null) { + print '' + . html_escape($note[0]) . ''; + } + } + + if ($sources === []) { + print '' + . html_escape(__('No accounts to estimate.', 'cloud')) . ''; + } + + print '' . html_escape(__( + 'Estimates use list prices and exclude discounts and shared free tiers.', + 'cloud' + )); + + foreach ($sources as $provider => [$source, $checked]) { + print '
' . html_escape(__('%s prices from', $provider, 'cloud')) . ' ' . html_escape($source) . '' + . html_escape(', ' . __('checked %s.', $checked, 'cloud')); + } + + print ''; + + html_end_box(); + } + + /** + * The account's rows as plain text: what it collects now, every graph + * on every resource, then each graph. + * + * @return list, source: string, checked: string}> + */ + public function rows(Account $account, ProviderDriver $driver): array { + $interval = $account->collectInterval; + $collected = $this->cost->collected($account, $driver); + $all = $this->cost->everything($account, $driver); + $rows = [ + self::row($account->name, __('Collected now', 'cloud'), '-', '-', '-', $collected, $interval), + self::row('', __('Every graph on every resource', 'cloud'), '-', '-', '-', $all, $interval), + ]; + + foreach ($this->cost->graphs($account, $driver) as $graph) { + $rows[] = self::row( + '', + self::typeLabel($graph['type']) . ': ' . $graph['title'], + (string) $graph['resources'], + number_format(CostPreview::perHour($graph['perResource'], $interval)), + number_format($graph['perResource']->requestsPerMonth), + $graph['all'], + $interval + ); + } + + return $rows; + } + + /** + * Whether graphing everything fits the account's share of its token's + * hourly limit, and whether what it collects now does. + * + * @return array{0: string, 1: bool}|null the note, and whether it warns + */ + public function budgetNote(Account $account, ProviderDriver $driver): ?array { + $share = RequestBudget::hourlyShare($account); + + if ($share === null) { + return null; + } + + $wanted = CostPreview::perHour($this->cost->requested($account, $driver), $account->collectInterval); + $now = CostPreview::perHour($this->cost->collected($account, $driver), $account->collectInterval); + $all = CostPreview::perHour($this->cost->everything($account, $driver), $account->collectInterval); + + return [ + __( + // Cacti's __() formats its own way and has no %%, so every value is a string. + 'Request share: %s requests per hour, %s percent of the token limit. Collected now: %s. Every graph: %s.', + number_format($share), + (string) $account->requestShare, + number_format($now), + number_format($all), + 'cloud' + ) . ($wanted > $now ? ' ' . __('Collection is capped; the remaining series read U.', 'cloud') : '') + . ' ' . __('Metric estimate between discovery runs; discovery requests reduce the collection allowance.', 'cloud'), + $wanted > $now, + ]; + } + + /** + * @return array{cells: list, source: string, checked: string} + */ + private static function row( + string $account, + string $selection, + string $resources, + string $oneResource, + string $oneResourceMonth, + UsageEstimate $estimate, + int $interval + ): array { + return [ + 'cells' => [ + $account, + $selection, + $resources, + $oneResource, + $oneResourceMonth, + number_format(CostPreview::perHour($estimate, $interval)), + number_format($estimate->requestsPerMonth), + $estimate->monthlyCost > 0 + ? '$' . number_format($estimate->monthlyCost, 2) + : __('No charge documented', 'cloud'), + ], + 'source' => $estimate->priceSource, + 'checked' => $estimate->priceChecked, + ]; + } + + private static function typeLabel(string $type): string { + return match ($type) { + DigitalOceanCatalog::DROPLET => __('Droplet', 'cloud'), + DigitalOceanCatalog::LOAD_BALANCER => __('Load Balancer', 'cloud'), + default => $type, + }; + } +} diff --git a/lib/RequestBudget.php b/lib/RequestBudget.php index 9c4d3ed..d112d2a 100644 --- a/lib/RequestBudget.php +++ b/lib/RequestBudget.php @@ -41,6 +41,16 @@ final class RequestBudget { 'digitalocean' => [5000, 250], ]; + /** + * The account's share of its token's hourly limit, or null for a + * provider without one. + */ + public static function hourlyShare(Account $account): ?int { + $limits = self::LIMITS[$account->provider->value] ?? null; + + return $limits === null ? null : intdiv($limits[0] * $account->requestShare, 100); + } + public static function perRun(Account $account): ?int { $limits = self::LIMITS[$account->provider->value] ?? null; diff --git a/lib/Schema.php b/lib/Schema.php index 4b7d926..4a8badd 100644 --- a/lib/Schema.php +++ b/lib/Schema.php @@ -43,6 +43,7 @@ final class Schema { 'config_settings' => 'cloud_config_settings', 'device_remove' => 'cloud_device_remove', 'draw_navigation_text' => 'cloud_draw_navigation_text', + 'graphs_new_top_links' => 'cloud_graphs_new_top_links', 'poller_bottom' => 'cloud_poller_bottom', ]; diff --git a/lib/UsageEstimate.php b/lib/UsageEstimate.php index 776c815..673e135 100644 --- a/lib/UsageEstimate.php +++ b/lib/UsageEstimate.php @@ -19,11 +19,18 @@ namespace Somethingwithproof\Cloud; +/** + * What collecting a set of series costs (REQ-COST-001). The cost is at list + * price, before discounts and shared free tiers (REQ-COST-003), and names + * the page the price came from and the date it was checked. + */ final readonly class UsageEstimate { public function __construct( public int $requestsPerCollection, public int $requestsPerMonth, public float $monthlyCost, + public string $priceSource = '', + public string $priceChecked = '', ) { } } diff --git a/locales/po/cacti.pot b/locales/po/cacti.pot index 8bbdaa4..bb13d8c 100644 --- a/locales/po/cacti.pot +++ b/locales/po/cacti.pot @@ -234,6 +234,93 @@ msgstr "" msgid "Instance identity of the poller" msgstr "" +#: lib/EstimateView.php setup.php +msgid "Cloud Request Estimate" +msgstr "" + +#: lib/EstimateView.php lib/HealthPage.php +msgid "Account" +msgstr "" + +#: lib/EstimateView.php +msgid "Selection" +msgstr "" + +#: lib/EstimateView.php lib/HealthPage.php +msgid "Resources" +msgstr "" + +#: lib/EstimateView.php +msgid "Requests per Hour, One Resource" +msgstr "" + +#: lib/EstimateView.php +msgid "Requests per Month, One Resource" +msgstr "" + +#: lib/EstimateView.php +msgid "Requests per Hour" +msgstr "" + +#: lib/EstimateView.php +msgid "Requests per Month" +msgstr "" + +#: lib/EstimateView.php +msgid "Cost per Month" +msgstr "" + +#: lib/EstimateView.php +msgid "No accounts to estimate." +msgstr "" + +#: lib/EstimateView.php +msgid "Estimates use list prices and exclude discounts and shared free tiers." +msgstr "" + +#: lib/EstimateView.php +#, php-format +msgid "%s prices from" +msgstr "" + +#: lib/EstimateView.php +#, php-format +msgid "checked %s." +msgstr "" + +#: lib/EstimateView.php +msgid "Collected now" +msgstr "" + +#: lib/EstimateView.php +msgid "Every graph on every resource" +msgstr "" + +#: lib/EstimateView.php +#, php-format +msgid "Request share: %s requests per hour, %s percent of the token limit. Collected now: %s. Every graph: %s." +msgstr "" + +#: lib/EstimateView.php +msgid "Collection is capped; the remaining series read U." +msgstr "" + +#: lib/EstimateView.php +msgid "Metric estimate between discovery runs; discovery requests reduce the collection allowance." +msgstr "" + +#: lib/EstimateView.php +msgid "No charge documented" +msgstr "" + +#: lib/EstimateView.php +msgid "Droplet" +msgstr "" + +#: lib/EstimateView.php +msgid "Load Balancer" +msgstr "" + #: lib/HealthPage.php msgid "Cloud Warnings" msgstr "" @@ -246,10 +333,6 @@ msgstr "" msgid "Cloud Collection" msgstr "" -#: lib/HealthPage.php -msgid "Account" -msgstr "" - #: lib/HealthPage.php msgid "Collection" msgstr "" @@ -270,10 +353,6 @@ msgstr "" msgid "Discovery" msgstr "" -#: lib/HealthPage.php -msgid "Resources" -msgstr "" - #: lib/HealthPage.php msgid "Data" msgstr "" diff --git a/setup.php b/setup.php index 170fee4..00a6d0f 100644 --- a/setup.php +++ b/setup.php @@ -477,6 +477,53 @@ function (int $host, int $query, int $method): void { return $keeper; } +function cloud_estimate_view(): \Somethingwithproof\Cloud\EstimateView { + return new \Somethingwithproof\Cloud\EstimateView( + new \Somethingwithproof\Cloud\CostPreview( + new \Somethingwithproof\Cloud\ResourceRepository(false, new \Somethingwithproof\Cloud\SystemClock()), + new \Somethingwithproof\Cloud\SeriesRepository(false) + ), + \Somethingwithproof\Cloud\Drivers::production() + ); +} + +/** + * New Graphs, for a scope device: what graphing everything would cost, and + * a link to the per-graph estimate (REQ-COST-001). Cached data only. + */ +function cloud_graphs_new_top_links(): void { + global $config; + + $host = get_request_var('host_id'); + + if (!is_numeric($host) || !cloud_boot() || !api_user_realm_auth('cloud_health.php')) { + return; + } + + $clock = new \Somethingwithproof\Cloud\SystemClock(); + $id = (new \Somethingwithproof\Cloud\DeviceRepository(false, $clock))->accountFor((int) $host); + $account = $id === null ? null : cloud_accounts()->find($id); + $driver = $account === null ? null : \Somethingwithproof\Cloud\Drivers::production()->for($account); + + if ($account === null || $driver === null) { + return; + } + + $view = cloud_estimate_view(); + $note = $view->budgetNote($account, $driver); + + print "*id + ) + . "'>" . __esc('Cloud Request Estimate', 'cloud') . '
'; + + if ($note !== null) { + print '' . html_escape($note[0]) . '
'; + } +} + function cloud_poller_bottom(): void { global $config; diff --git a/tests/Integration/LifecycleTest.php b/tests/Integration/LifecycleTest.php index a78a1b6..8d75e07 100644 --- a/tests/Integration/LifecycleTest.php +++ b/tests/Integration/LifecycleTest.php @@ -42,6 +42,7 @@ 'config_settings', 'device_remove', 'draw_navigation_text', + 'graphs_new_top_links', 'poller_bottom', ]; diff --git a/tests/Integration/ScopeDeviceTest.php b/tests/Integration/ScopeDeviceTest.php index 2d25bbb..89c0e30 100644 --- a/tests/Integration/ScopeDeviceTest.php +++ b/tests/Integration/ScopeDeviceTest.php @@ -212,3 +212,13 @@ // Verify all fields (3), as chosen on the device page. expect(lifecycle('edit_device', '3')['result']['reindex'])->toBe([3, 3]); }); + +it('shows the request estimate on New Graphs for a scope device only, to users who may view it', function () { + $host = (string) lifecycle('scope_device')['result']; + $links = lifecycle('top_links', '1 ' . $host)['result']; + + expect($links)->toContain('plugins/cloud/cloud_health.php#cloud-estimate-') + ->and($links)->toContain('Request share: 2,500 requests per hour, 50 percent of the token limit. Collected now: 0.') + ->and(lifecycle('top_links', '1 1')['result'])->toBe('') + ->and(lifecycle('top_links', '0 ' . $host)['result'])->toBe(''); +}); diff --git a/tests/Unit/CostPreviewTest.php b/tests/Unit/CostPreviewTest.php new file mode 100644 index 0000000..6018c94 --- /dev/null +++ b/tests/Unit/CostPreviewTest.php @@ -0,0 +1,165 @@ + + * 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\CostPreview; +use Somethingwithproof\Cloud\DigitalOceanDriver; +use Somethingwithproof\Cloud\Drivers; +use Somethingwithproof\Cloud\EstimateView; +use Somethingwithproof\Cloud\FixedClock; +use Somethingwithproof\Cloud\RefusingTransport; +use Somethingwithproof\Cloud\ResourceRepository; +use Somethingwithproof\Cloud\SeriesRepository; + +/* + * #41's acceptance: estimates for a fixture selection match hand-computed + * values. Three Droplets and one load balancer, collected every 300 s, so a + * series costs 12 requests an hour and 8,640 a month (30 days). + */ + +function cloud_cost_account(array $row = []): Account { + return Account::fromRow($row + [ + 'id' => 4, + 'provider' => 'digitalocean', + 'name' => 'Ops', + 'credential_source' => 'vault', + 'collect_interval' => 300, + 'request_share' => 50, + 'admin_state' => 'enabled', + ]); +} + +/** + * @param list $collected Droplet metrics the collector reads, one series each on d1 + */ +function cloud_cost_world(array $collected = ['do_cpu_pct', 'do_load_1']): void { + $GLOBALS['__cloud_db_rows'] = [ + 'FROM plugin_cloud_resource' => fn (string $sql, array $params): array => match ($params[1]) { + 'droplet' => [ + ['id' => 1, 'provider_id' => '101', 'name' => 'a', 'first_seen' => 0], + ['id' => 2, 'provider_id' => '102', 'name' => 'b', 'first_seen' => 0], + ['id' => 3, 'provider_id' => '103', 'name' => 'c', 'first_seen' => 0], + ], + 'load_balancer' => [ + ['id' => 9, 'provider_id' => '4de7ac8b-495b-4884-9a69-1050c6793cd6', 'name' => 'lb', 'first_seen' => 0], + ], + default => [], + }, + 'FROM plugin_cloud_series' => array_map(fn (string $metric): array => [ + 'resource_id' => 1, + 'type' => 'droplet', + 'provider_id' => '101', + 'metric' => $metric, + ], $collected), + ]; +} + +function cloud_cost_view(): EstimateView { + $clock = new FixedClock(1_800_000_000); + + return new EstimateView( + new CostPreview(new ResourceRepository(false, $clock), new SeriesRepository(false)), + Drivers::production() + ); +} + +function cloud_cost_driver(): DigitalOceanDriver { + return new DigitalOceanDriver(new RefusingTransport(), new FixedClock(1_800_000_000)); +} + +it('estimates each graph, everything, and what is collected now from the driver\'s request count', function () { + cloud_cost_world(); + + $rows = array_column(cloud_cost_view()->rows(cloud_cost_account(), cloud_cost_driver()), 'cells'); + $by = array_column($rows, null, 1); + $none = 'No charge documented'; + + // Account, selection, resources, per hour on one resource, per hour, per month, cost. + expect($rows[0])->toBe(['Ops', 'Collected now', '-', '-', '-', '24', '17,280', $none]) + ->and($rows[1])->toBe(['', 'Every graph on every resource', '-', '-', '-', '624', '449,280', $none]) + ->and($by['Droplet: CPU'])->toBe(['', 'Droplet: CPU', '3', '12', '8,640', '36', '25,920', $none]) + ->and($by['Droplet: Bandwidth'])->toBe(['', 'Droplet: Bandwidth', '3', '48', '34,560', '144', '103,680', $none]) + ->and($by['Droplet: Load Average'])->toBe(['', 'Droplet: Load Average', '3', '36', '25,920', '108', '77,760', $none]) + ->and($by['Droplet: Memory'])->toBe(['', 'Droplet: Memory', '3', '48', '34,560', '144', '103,680', $none]) + ->and($by['Droplet: Collection Age'])->toBe(['', 'Droplet: Collection Age', '3', '0', '0', '0', '0', $none]) + ->and($by['Load Balancer: Throughput'])->toBe(['', 'Load Balancer: Throughput', '1', '60', '43,200', '60', '43,200', $none]) + ->and($rows)->toHaveCount(2 + 15); +}); + +it('agrees with the graphs: every graph on every resource is the sum of the graph rows', function () { + cloud_cost_world(); + + $rows = array_column(cloud_cost_view()->rows(cloud_cost_account(), cloud_cost_driver()), 'cells'); + $total = array_sum(array_map(fn (array $row): int => (int) str_replace(',', '', $row[5]), array_slice($rows, 2))); + + expect($total)->toBe(624); +}); + +it('names the price source and check date, and that estimates use list prices', function () { + cloud_cost_world(); + $rows = cloud_cost_view()->rows(cloud_cost_account(), cloud_cost_driver()); + + expect($rows[0]['source'])->toBe('https://docs.digitalocean.com/reference/api/reference/openapi.json') + ->and($rows[0]['checked'])->toBe('2026-11-14'); + + ob_start(); + cloud_cost_view()->render([cloud_cost_account()]); + $html = (string) ob_get_clean(); + + expect($html)->toContain('Estimates use list prices and exclude discounts and shared free tiers.') + ->and($html)->toContain('href="https://docs.digitalocean.com/reference/api/reference/openapi.json"') + ->and($html)->toContain('checked 2026-11-14.') + ->and($html)->toContain('id="cloud-estimate-4"'); +}); + +it('compares collection and everything with the account\'s request share', function () { + cloud_cost_world(); + expect(cloud_cost_view()->budgetNote(cloud_cost_account(), cloud_cost_driver()))->toBe([ + 'Request share: 2,500 requests per hour, 50 percent of the token limit. Collected now: 24. Every graph: 624. Metric estimate between discovery runs; discovery requests reduce the collection allowance.', + false, + ]); + + // 1% of 5,000 is 50 an hour; five series are 60. + cloud_cost_world(['do_cpu_pct', 'do_load_1', 'do_load_5', 'do_load_15', 'do_mem_free']); + expect(cloud_cost_view()->budgetNote(cloud_cost_account(['request_share' => 1]), cloud_cost_driver()))->toBe([ + 'Request share: 50 requests per hour, 1 percent of the token limit. Collected now: 24. Every graph: 624. ' + . 'Collection is capped; the remaining series read U. Metric estimate between discovery runs; discovery requests reduce the collection allowance.', + true, + ]); +}); + +it('scales with the interval: every 60 s costs five times every 300 s', function () { + cloud_cost_world(); + $view = cloud_cost_view(); + $rows = array_column($view->rows(cloud_cost_account(['collect_interval' => 60]), cloud_cost_driver()), 'cells'); + + expect($rows[1])->toBe(['', 'Every graph on every resource', '-', '-', '-', '3,120', '2,246,400', 'No charge documented']); +}); + + +it('uses the collector split after discovery spends part of the per-run cap', function () { + cloud_cost_world(['do_cpu_pct', 'do_load_1', 'do_load_5']); + $cost = new CostPreview(new ResourceRepository(false, new FixedClock(1_800_000_000)), new SeriesRepository(false)); + $account = cloud_cost_account(['request_share' => 1]); + $driver = cloud_cost_driver(); + expect(CostPreview::perHour($cost->collected($account, $driver), 300))->toBe(24) + ->and(CostPreview::perHour($cost->collected($account, $driver, 1), 300))->toBe(12) + ->and(CostPreview::perHour($cost->collected($account, $driver, 2), 300))->toBe(0); +}); diff --git a/tests/bin/lifecycle.php b/tests/bin/lifecycle.php index 0059d92..6a1ab84 100644 --- a/tests/bin/lifecycle.php +++ b/tests/bin/lifecycle.php @@ -342,6 +342,17 @@ $result = (new \Somethingwithproof\Cloud\SeriesRepository(false))->sync($account, $leases, 'lifecycle'); $leases->release($account, $holder); + break; + case 'top_links': + // What New Graphs prints for a device, as user " ". + include_once($config['base_path'] . '/plugins/cloud/setup.php'); + list($user, $host) = explode(' ', $argument, 2); + $_SESSION['sess_user_id'] = (int) $user; + set_request_var('host_id', $host); + ob_start(); + api_plugin_hook('graphs_new_top_links'); + $result = (string) ob_get_clean(); + break; case 'drop_table': db_execute('DROP TABLE IF EXISTS `' . preg_replace('/[^a-z_]/', '', $argument) . '`'); diff --git a/tests/bootstrap-unit.php b/tests/bootstrap-unit.php index f8cefe3..319ec21 100644 --- a/tests/bootstrap-unit.php +++ b/tests/bootstrap-unit.php @@ -80,10 +80,16 @@ function read_config_option($config_name, $force = false) { $GLOBALS['__cloud_db_rows'] = []; $GLOBALS['__cloud_db_fail'] = []; -function cloud_test_rows(string $sql): mixed { +/** + * The stub rows for the first needle the SQL contains. A Closure entry + * answers from the bound parameters. + * + * @param list $params + */ +function cloud_test_rows(string $sql, array $params = []): mixed { foreach ($GLOBALS['__cloud_db_rows'] as $needle => $rows) { if (str_contains($sql, $needle)) { - return $rows instanceof Closure ? $rows($sql) : $rows; + return $rows instanceof Closure ? $rows($sql, $params) : $rows; } } @@ -106,7 +112,7 @@ function db_execute_prepared($sql, $params = [], $log = true, $db_conn = false, if (!function_exists('db_fetch_assoc_prepared')) { function db_fetch_assoc_prepared($sql, $params = [], $log = true, $db_conn = false, $log_function = null) { - return cloud_test_rows($sql); + return cloud_test_rows($sql, $params); } } @@ -177,3 +183,22 @@ function db_fetch_insert_id($db_conn = false) { require_once dirname(__DIR__) . '/setup.php'; require_once dirname(__DIR__) . '/include/autoload.php'; + +// Cacti's page helpers, enough to render a box into a string. +if (!function_exists('html_escape')) { + function html_escape($string) { + return htmlspecialchars((string) $string, ENT_QUOTES, 'UTF-8'); + } +} + +if (!function_exists('html_start_box')) { + function html_start_box($title, $width, $div, $cell_padding, $align, $add_text) { + print ''; + } +} + +if (!function_exists('html_end_box')) { + function html_end_box($trailing_br = true) { + print '
' . html_escape($title) . '
'; + } +}