diff --git a/.github/workflows/plugin-ci-workflow.yml b/.github/workflows/plugin-ci-workflow.yml index 422042c..e58c666 100644 --- a/.github/workflows/plugin-ci-workflow.yml +++ b/.github/workflows/plugin-ci-workflow.yml @@ -70,6 +70,9 @@ jobs: integration-test: name: PHP ${{ matrix.php }} on Cacti ${{ matrix.cacti }} runs-on: ubuntu-latest + # The real pages and collector run below; no provider may be reached. + env: + CLOUD_OFFLINE: '1' timeout-minutes: 30 strategy: @@ -255,6 +258,9 @@ jobs: php-guard: name: Refusal on PHP 8.1 with Cacti 1.2.31 runs-on: ubuntu-latest + # The real pages and collector run below; no provider may be reached. + env: + CLOUD_OFFLINE: '1' timeout-minutes: 20 services: diff --git a/LICENSES/Apache-2.0.txt b/LICENSES/Apache-2.0.txt new file mode 100644 index 0000000..137069b --- /dev/null +++ b/LICENSES/Apache-2.0.txt @@ -0,0 +1,73 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/REUSE.toml b/REUSE.toml index 17da5e5..8d208f1 100644 --- a/REUSE.toml +++ b/REUSE.toml @@ -28,3 +28,12 @@ path = "CODE_OF_CONDUCT.md" precedence = "aggregate" SPDX-FileCopyrightText = "Contributor Covenant contributors " SPDX-License-Identifier = "CC-BY-4.0" + +# Example responses copied from DigitalOcean's public API specification +# (https://docs.digitalocean.com/reference/api/reference/openapi.json), +# which is published under Apache 2.0. +[[annotations]] +path = "tests/fixtures/digitalocean/**" +precedence = "aggregate" +SPDX-FileCopyrightText = "DigitalOcean, LLC" +SPDX-License-Identifier = "Apache-2.0" diff --git a/docs/PLAN.md b/docs/PLAN.md index 74ba26e..876bdc3 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -216,7 +216,7 @@ The implementation is a `stream_socket_client()` TLS connection with a small HTT ## Cacti objects -The proposed mapping, an open decision with maintainers: +The mapping, decided in [ADR 0010](decisions/0010-scope-devices-with-resource-data-queries.md): | Object | Created from | Notes | |---|---|---| @@ -378,7 +378,6 @@ Engineering targets, to be measured, not yet demonstrated: | Decision | Options | Needed before | Decided by | |---|---|---|---| -| How resources appear in Cacti | Scope device with data queries (proposed); a device per resource; graphs on existing devices | Milestone 3 | Core maintainers | | Repository home and plugin name | `Cacti/plugin_cloud`, or remain a community plugin | Before code is proposed upstream | Cacti maintainers | | Test harness | Whatever maintained plugins use | Milestone 2 | Cacti maintainers | | Outbound proxy support | No proxy (proposed for phase 1); an explicit proxy setting | Milestone 4 | Pilot feedback | diff --git a/docs/decisions/0010-scope-devices-with-resource-data-queries.md b/docs/decisions/0010-scope-devices-with-resource-data-queries.md new file mode 100644 index 0000000..c8f08ed --- /dev/null +++ b/docs/decisions/0010-scope-devices-with-resource-data-queries.md @@ -0,0 +1,28 @@ +# 0010. Cloud resources as data query indexes on one device per account scope + +Status: Accepted (2026-11-15) + +## Context + +Cloud resources need Cacti objects that graph, permission, and alert like any other Cacti data. An account can hold many resources, and autoscaled fleets create and delete them continually. Thold and Maint act on Cacti data sources and devices ([ADR 0006](0006-alert-through-cacti-data-sources.md)), so the choice of device decides what Maint can suppress. + +The decision was meant to go to Cacti maintainers through the upstream proposal (#15). The plugin owner decided it instead, so milestone 3 can build the objects; #15 is not being pursued for now. + +## Decision + +- Each account and scope gets one Cacti device, created from the plugin's "Cloud Scope" device template through `api_device_save()`, with availability None and the account's poller, only when the operator confirms. A scope is a DigitalOcean team, an AWS account and region, a Google Cloud project, or an Azure subscription and region. +- Each resource type is a script server data query on that device, for example "Cloud: DigitalOcean Droplets". Its indexes are provider resource IDs, and its descriptions are resource names. Cacti's normal reindexing adds, renames, and removes resources. +- Data and graph templates per resource type are generated from the metric catalog and shipped as template XML. +- The plugin creates and changes Cacti objects only through Cacti's APIs, never by writing Cacti tables. + +## Consequences + +- Device counts follow accounts, not resources, so autoscaling does not churn devices or the tree. +- Maint suppresses a whole scope, not one resource. Per-resource suppression would need a Thold-level filter or a later decision. +- A virtual machine's cloud graphs sit on its scope device, not on the Cacti device that polls the same machine over SNMP. +- Device-based graph permissions cover a whole scope; finer control uses Cacti's per-graph or per-template permissions. + +## Alternatives rejected + +- **A device per resource.** Gives per-resource Maint and tree placement, but devices churn with autoscaled fleets, and every create or delete runs Cacti's device lifecycle. +- **Graphs on existing Cacti devices.** Keeps cloud and SNMP graphs together, but needs a resource-to-device mapping the operator maintains, and resources with no Cacti device would have nowhere to go. It remains possible as a later, optional mapping. diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 89a2db6..2fb59c3 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -13,5 +13,6 @@ Each record captures one architecture decision: its context, the decision, its c | [0007](0007-credentials-outside-the-database-in-the-clear.md) | Never store a cloud credential in the clear in the Cacti database | Accepted | | [0008](0008-providers-in-releasing-phases.md) | Ship providers in phases that each release, DigitalOcean first | Accepted | | [0009](0009-http-transport.md) | Use a minimal socket client for HTTPS | Accepted | +| [0010](0010-scope-devices-with-resource-data-queries.md) | Cloud resources as data query indexes on one device per account scope | Accepted | Open decisions are tracked as issues labelled `type: decision`. diff --git a/include/unbooted-uninstall.php b/include/unbooted-uninstall.php index 0fef0fb..2ad72a0 100644 --- a/include/unbooted-uninstall.php +++ b/include/unbooted-uninstall.php @@ -31,7 +31,10 @@ function cloud_uninstall_unbooted(): void { $keep = !is_array($row) || $row === array() || (isset($row['value']) && $row['value'] === 'on'); if ($keep) { - db_execute_prepared("DELETE FROM plugin_db_changes WHERE plugin = ? AND method = 'create'", array('cloud')); + db_execute_prepared( + "DELETE FROM plugin_db_changes WHERE plugin = ? AND method IN ('create', 'addcolumn')", + array('cloud') + ); cacti_log('NOTE: Uninstall kept the plugin tables as configured', false, 'CLOUD'); } else { db_execute_prepared('DELETE FROM settings WHERE name = ?', array('cloud_schema_version')); diff --git a/lib/AccountHealth.php b/lib/AccountHealth.php index 7e8c844..894d388 100644 --- a/lib/AccountHealth.php +++ b/lib/AccountHealth.php @@ -36,6 +36,7 @@ public function __construct( public int $seriesRead = 0, public int $discoveredAt = 0, public CollectionState $discovery = CollectionState::Never, + public int $retryAt = 0, ) { } @@ -63,6 +64,7 @@ public static function fromRow(array $row): ?self { seriesRead: Row::int($row, 'series_read', 0, 0), discoveredAt: Row::int($row, 'discovered_at', 0, 0), discovery: CollectionState::tryFrom(Row::string($row, 'discovery')) ?? CollectionState::Never, + retryAt: Row::int($row, 'retry_at', 0, 0), ); } } diff --git a/lib/CollectResult.php b/lib/CollectResult.php index 1168cfc..dc5d6fa 100644 --- a/lib/CollectResult.php +++ b/lib/CollectResult.php @@ -27,6 +27,7 @@ public function __construct( public array $observations, public int $requests, public ?ErrorClass $error = null, + public int $retryAfter = 0, ) { } } diff --git a/lib/Collector.php b/lib/Collector.php index 36cbe19..a74be8e 100644 --- a/lib/Collector.php +++ b/lib/Collector.php @@ -108,6 +108,11 @@ private function runAccount(Account $account): void { $start = microtime(true); $previous = $this->health->find($account->id); + // The provider asked for a pause (REQ-BUDGET-003). + if ($previous->retryAt > $now) { + return; + } + // Each run starts a few seconds after its poller cycle, so the time // since the last start drifts around the interval. Without slack, an // interval equal to the poller interval would often read as not yet @@ -164,6 +169,7 @@ private function runAccount(Account $account): void { $requests = 0; $discoveredAt = $previous->discoveredAt; $discovery = $previous->discovery; + $throttled = null; if ($now - $previous->discoveredAt >= $account->discoverInterval) { try { @@ -176,11 +182,30 @@ private function runAccount(Account $account): void { } catch (DriverError|TransportError $e) { $discovery = CollectionState::Failed; Log::warning(sprintf('Account %d: discovery failed: %s', $account->id, $this->redactor->clean($e->getMessage()))); + + // Collecting now would only be throttled too. + if ($e instanceof DriverError && $e->errorClass === ErrorClass::Throttled) { + $throttled = new CollectResult([], 0, ErrorClass::Throttled, $e->retryAfter); + } } } - $wanted = $this->series->enabledFor($account->id); - $result = $wanted === [] ? new CollectResult([], 0) : $driver->collect($account, $credential, $wanted); + $wanted = $this->series->enabledFor($account->id); + [$fit, $left] = RequestBudget::split($account, $driver, $wanted, $requests); + + if ($left !== []) { + $this->observations->markUnread($account->id, $this->holder, $this->clock->now(), $left, RequestBudget::REASON); + Log::warning( + sprintf( + 'Account %d: %d of %d series exceed the request budget and were not read', + $account->id, + count($left), + count($wanted) + ) + ); + } + + $result = $throttled ?? ($fit === [] ? new CollectResult([], 0) : $driver->collect($account, $credential, $fit)); $read = 0; foreach ($result->observations as $observation) { @@ -190,7 +215,8 @@ private function runAccount(Account $account): void { $state = match (true) { $result->error !== null && $read === 0 => CollectionState::Failed, - $result->error !== null || $read < count($wanted) => CollectionState::Partial, + $result->error !== null || $read < count($fit) => CollectionState::Partial, + $left !== [] => CollectionState::Budget, default => CollectionState::Ok, }; @@ -206,6 +232,7 @@ private function runAccount(Account $account): void { seriesRead: $read, discoveredAt: $discoveredAt, discovery: $discovery, + retryAt: $result->retryAfter > 0 ? $now + $result->retryAfter : 0, ), $this->holder, $this->clock->now()); } } diff --git a/lib/DigitalOceanCatalog.php b/lib/DigitalOceanCatalog.php new file mode 100644 index 0000000..1b02c4c --- /dev/null +++ b/lib/DigitalOceanCatalog.php @@ -0,0 +1,136 @@ + + * 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 DigitalOcean metrics the plugin reads, from docs/research/metric-catalogs.md. + * Keys are the Cacti data source names. DigitalOcean documents no sample + * period or publication delay for any metric, so none is listed here until + * the live checks on #16 record them. + * + * Conversions: + * - cpu: CPU seconds per mode, read as cumulative (inferred from the API + * example, unconfirmed): percent busy between the two newest samples. + * - mbps: megabits per second, as the API states, to bits per second. + * - value: the newest value as it is. + * - single: the newest value as it is. Load balancer label sets are + * undocumented, so a response with several series is reported as + * malformed until the live check shows what they mean. + * + * Every conversion but cpu expects one series. + * + * Filesystem metrics are left out: they need one index per mount point. + */ +final class DigitalOceanCatalog { + public const DROPLET = 'droplet'; + public const LOAD_BALANCER = 'load_balancer'; + + /** + * Each row is [type, path, query, convert, agent]; metric() names the fields. + * + * @var array, 3: string, 4: bool}> + */ + private const METRICS = [ + 'do_cpu_pct' => [self::DROPLET, 'cpu', [], 'cpu', false], + 'do_bw_pub_in' => [self::DROPLET, 'bandwidth', ['interface' => 'public', 'direction' => 'inbound'], 'mbps', false], + 'do_bw_pub_out' => [ + self::DROPLET, 'bandwidth', ['interface' => 'public', 'direction' => 'outbound'], 'mbps', false, + ], + 'do_bw_prv_in' => [ + self::DROPLET, 'bandwidth', ['interface' => 'private', 'direction' => 'inbound'], 'mbps', false, + ], + 'do_bw_prv_out' => [ + self::DROPLET, 'bandwidth', ['interface' => 'private', 'direction' => 'outbound'], 'mbps', false, + ], + 'do_load_1' => [self::DROPLET, 'load_1', [], 'value', true], + 'do_load_5' => [self::DROPLET, 'load_5', [], 'value', true], + 'do_load_15' => [self::DROPLET, 'load_15', [], 'value', true], + 'do_mem_total' => [self::DROPLET, 'memory_total', [], 'value', true], + 'do_mem_avail' => [self::DROPLET, 'memory_available', [], 'value', true], + 'do_mem_free' => [self::DROPLET, 'memory_free', [], 'value', true], + 'do_mem_cached' => [self::DROPLET, 'memory_cached', [], 'value', true], + 'dolb_conn_cur' => [self::LOAD_BALANCER, 'frontend_connections_current', [], 'single', false], + 'dolb_conn_lim' => [self::LOAD_BALANCER, 'frontend_connections_limit', [], 'single', false], + 'dolb_cpu_pct' => [self::LOAD_BALANCER, 'frontend_cpu_utilization', [], 'single', false], + 'dolb_http_rps' => [self::LOAD_BALANCER, 'frontend_http_requests_per_second', [], 'single', false], + 'dolb_http_resp' => [self::LOAD_BALANCER, 'frontend_http_responses', [], 'single', false], + 'dolb_http_Bps' => [self::LOAD_BALANCER, 'frontend_network_throughput_http', [], 'single', false], + 'dolb_tcp_Bps' => [self::LOAD_BALANCER, 'frontend_network_throughput_tcp', [], 'single', false], + 'dolb_udp_Bps' => [self::LOAD_BALANCER, 'frontend_network_throughput_udp', [], 'single', false], + 'dolb_nlbtcp_Bps' => [self::LOAD_BALANCER, 'frontend_nlb_tcp_network_throughput', [], 'single', false], + 'dolb_nlbudp_Bps' => [self::LOAD_BALANCER, 'frontend_nlb_udp_network_throughput', [], 'single', false], + 'dolb_hc_status' => [self::LOAD_BALANCER, 'droplets_health_checks', [], 'single', false], + 'dolb_downtime' => [self::LOAD_BALANCER, 'droplets_downtime', [], 'single', false], + 'dolb_resp_avg_s' => [self::LOAD_BALANCER, 'droplets_http_response_time_avg', [], 'single', false], + 'dolb_resp_p95_s' => [self::LOAD_BALANCER, 'droplets_http_response_time_95p', [], 'single', false], + 'dolb_back_conn' => [self::LOAD_BALANCER, 'droplets_connections', [], 'single', false], + 'dolb_queue' => [self::LOAD_BALANCER, 'droplets_queue_size', [], 'single', false], + ]; + + private const FIELDS = ['type', 'path', 'query', 'convert', 'agent']; + + /** + * @return array{type: string, path: string, query: array, convert: string, agent: bool}|null + */ + public static function metric(string $name): ?array { + return isset(self::METRICS[$name]) ? self::named(self::METRICS[$name]) : null; + } + + /** + * Metrics read by default for a resource type: those that need no agent. + * + * @return list + */ + public static function defaults(string $type): array { + return array_keys(array_filter(self::all(), static fn (array $m): bool => $m['type'] === $type && !$m['agent'])); + } + + /** + * Every API path name of one resource type, for the operation list. + * + * @return list + */ + public static function paths(string $type): array { + return array_values( + array_unique( + array_column( + array_filter(self::all(), static fn (array $m): bool => $m['type'] === $type), + 'path' + ) + ) + ); + } + + /** + * @return array, convert: string, agent: bool}> + */ + private static function all(): array { + return array_map(self::named(...), self::METRICS); + } + + /** + * @param array{0: string, 1: string, 2: array, 3: string, 4: bool} $row + * @return array{type: string, path: string, query: array, convert: string, agent: bool} + */ + private static function named(array $row): array { + /** @var array{type: string, path: string, query: array, convert: string, agent: bool} */ + return array_combine(self::FIELDS, $row); + } +} diff --git a/lib/DigitalOceanDriver.php b/lib/DigitalOceanDriver.php new file mode 100644 index 0000000..4593a34 --- /dev/null +++ b/lib/DigitalOceanDriver.php @@ -0,0 +1,490 @@ + + * 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; + +/** + * DigitalOcean: a bearer token, Droplets and load balancers, and one GET per + * metric under /v2/monitoring/metrics (REQ-DO-001 to REQ-DO-006). Facts are + * from docs/research/provider-facts.md; the ones only a live account can + * settle are marked there and wait on #16. + * + * Every URL is built here from the fixed host, a catalog path, and a stored + * resource id checked against its type's pattern. Pagination counts pages + * itself instead of following links.pages.next, so no URL a response carries + * is ever requested. + */ +final class DigitalOceanDriver implements ProviderDriver { + public const HOST = 'api.digitalocean.com'; + + private const PER_PAGE = 100; + + /** Discovery fails rather than return a cut-off list, which would retire the rest. */ + private const MAX_PAGES = 1000; + + /** Seconds of history asked for per metric: enough for two CPU samples. */ + private const WINDOW = 900; + + private const MONTH = 2592000; + + /** The longest wait a provider may impose through Retry-After or ratelimit-reset. */ + private const MAX_WAIT = 3600; + + private const ID_PATTERNS = [ + DigitalOceanCatalog::DROPLET => '/^[1-9][0-9]{0,19}$/', + DigitalOceanCatalog::LOAD_BALANCER => '/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/', + ]; + + /** Percent of the token's limit this account may use; set per call. */ + private int $share = 100; + + /** + * Seconds to wait once the rate-limit headers show the account's share + * is used up: the rest of the token's limit is left to its other users + * (REQ-BUDGET-003). Null while there is room. + */ + private ?int $exhausted = null; + + public function __construct(private readonly HttpTransport $http, private readonly Clock $clock) { + } + + public function provider(): Provider { + return Provider::DigitalOcean; + } + + public function endpoints(Account $account): OutboundPolicy { + return new OutboundPolicy([self::HOST]); + } + + public function operations(): array { + $page = '/^per_page=[0-9]{1,3}&page=[0-9]{1,4}$/'; + $window = 'start=[0-9]{1,12}&end=[0-9]{1,12}'; + $droplet = implode('|', DigitalOceanCatalog::paths(DigitalOceanCatalog::DROPLET)); + $lb = implode('|', DigitalOceanCatalog::paths(DigitalOceanCatalog::LOAD_BALANCER)); + + return [ + new Operation('List Droplets', 'GET', self::HOST, '#^/v2/droplets$#', null, $page), + new Operation('List load balancers', 'GET', self::HOST, '#^/v2/load_balancers$#', null, $page), + new Operation( + 'Read Droplet metrics', + 'GET', + self::HOST, + "#^/v2/monitoring/metrics/droplet/($droplet)$#", + null, + "/^host_id=[0-9]{1,20}&$window(&interface=(public|private)&direction=(inbound|outbound))?$/" + ), + new Operation( + 'Read load balancer metrics', + 'GET', + self::HOST, + "#^/v2/monitoring/metrics/load_balancer/($lb)$#", + null, + "/^lb_id=[0-9a-f-]{36}&$window$/" + ), + ]; + } + + /** + * One read per scope the account needs. The monitoring scope can only be + * tested against a Droplet, so a team with none passes on the list scopes. + */ + public function verify(Account $account, Secret $credential): VerifyStatus { + $this->share = $account->requestShare; + + try { + $droplets = $this->get($credential, '/v2/droplets', ['per_page' => 1, 'page' => 1]); + $this->get($credential, '/v2/load_balancers', ['per_page' => 1, 'page' => 1]); + + $list = $droplets['droplets'] ?? null; + $first = is_array($list) && is_array($list[0] ?? null) ? ($list[0]['id'] ?? null) : null; + + if (is_int($first) && $first > 0) { + $now = $this->clock->now(); + $this->get( + $credential, + '/v2/monitoring/metrics/droplet/cpu', + ['host_id' => $first, 'start' => $now - self::WINDOW, 'end' => $now] + ); + } + + return VerifyStatus::Ok; + } catch (DriverError $error) { + return VerifyStatus::fromError($error->errorClass); + } + } + + public function discover(Account $account, Secret $credential): Inventory { + $this->share = $account->requestShare; + $resources = []; + $requests = 0; + + foreach ( + [DigitalOceanCatalog::DROPLET => 'droplets', DigitalOceanCatalog::LOAD_BALANCER => 'load_balancers'] as $type => $key + ) { + for ($page = 1; ; $page++) { + if ($page > self::MAX_PAGES) { + throw new DriverError(ErrorClass::Malformed, $key . ' list exceeds ' . self::MAX_PAGES . ' pages'); + } + + // Stopping part way would return a cut-off list. + if ($this->exhausted !== null) { + throw new DriverError(ErrorClass::Throttled, 'request share used up', $this->exhausted); + } + + $body = $this->get($credential, '/v2/' . $key, ['per_page' => self::PER_PAGE, 'page' => $page]); + $requests++; + + $items = $body[$key] ?? null; + + if (!is_array($items) || !array_is_list($items)) { + throw new DriverError(ErrorClass::Malformed, $key . ' list missing'); + } + + foreach ($items as $item) { + $resources[] = self::resource($type, $item); + } + + $pages = is_array($body['links'] ?? null) && is_array($body['links']['pages'] ?? null) + ? $body['links']['pages'] + : []; + + if ($items === [] || !isset($pages['next'])) { + break; + } + } + } + + return new Inventory($resources, $requests); + } + + public function collect(Account $account, Secret $credential, array $requests): CollectResult { + $this->share = $account->requestShare; + $observations = []; + $sent = 0; + $error = null; + $retryAfter = 0; + $now = $this->clock->now(); + + foreach ($requests as $request) { + if ($this->exhausted !== null) { + $error = ErrorClass::Throttled; + $retryAfter = $this->exhausted; + + break; + } + + $metric = DigitalOceanCatalog::metric($request->metric); + $id = self::ID_PATTERNS[$request->resourceType] ?? null; + + if ( + $metric === null + || $metric['type'] !== $request->resourceType + || $id === null + || preg_match($id, $request->providerId) !== 1 + ) { + $error ??= ErrorClass::Config; + + continue; + } + + $key = $metric['type'] === DigitalOceanCatalog::DROPLET ? 'host_id' : 'lb_id'; + $query = [$key => $request->providerId, 'start' => $now - self::WINDOW, 'end' => $now] + $metric['query']; + + try { + $sent++; + $point = self::convert( + $this->get($credential, '/v2/monitoring/metrics/' . $metric['type'] . '/' . $metric['path'], $query), + $metric['convert'] + ); + } catch (DriverError $e) { + // A credential, scope, or rate problem fails every later + // request too, so the run stops there. + $stops = in_array($e->errorClass, [ErrorClass::Auth, ErrorClass::Permission, ErrorClass::Throttled], true); + $error = $stops || $error === null ? $e->errorClass : $error; + $retryAfter = $e->retryAfter; + + if ($stops) { + break; + } + + continue; + } + + // No data: the Droplet is new, off, or lacks the metrics agent. + if ($point !== null) { + $observations[] = new Observation( + $request->resourceId, + $request->metric, + $point[1], + $point[0], + $this->clock->now() + ); + } + } + + return new CollectResult($observations, $sent, $error, $retryAfter); + } + + /** + * DigitalOcean documents no charge for API calls, only the rate limit, + * so the cost is zero and the page says "no charge documented". + */ + 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); + } + + /** + * @param array $query + * @return array + * @throws DriverError + */ + private function get(Secret $credential, string $path, array $query): array { + $url = 'https://' . self::HOST . $path . '?' . http_build_query($query, '', '&', PHP_QUERY_RFC3986); + + try { + $response = $this->http->send( + new HttpRequest( + 'GET', + $url, + ['Authorization' => 'Bearer ' . $credential->reveal(), 'Accept' => 'application/json'] + ) + ); + } catch (TransportError $e) { + throw DriverError::fromTransport($e); + } + + $class = match (true) { + $response->status === 200 => null, + $response->status === 401 => ErrorClass::Auth, + $response->status === 403 => ErrorClass::Permission, + $response->status === 429 => ErrorClass::Throttled, + $response->status >= 500 => ErrorClass::Transient, + default => ErrorClass::Malformed, + }; + + if ($class !== null) { + throw new DriverError( + $class, + 'HTTP ' . $response->status, + $class === ErrorClass::Throttled ? $this->retryAfter($response) : 0 + ); + } + + $this->checkShare($response); + + try { + $body = json_decode($response->body, true, 64, JSON_THROW_ON_ERROR); + } catch (\JsonException) { + throw new DriverError(ErrorClass::Malformed, 'response is not JSON'); + } + + if (!is_array($body)) { + throw new DriverError(ErrorClass::Malformed, 'response is not an object'); + } + + return $body; + } + + /** + * Retry-After as seconds or an HTTP date, bounded; 0 when absent. + */ + private function retryAfter(HttpResponse $response): int { + $value = trim($response->header('retry-after')); + $wait = ctype_digit($value) + ? (int) $value + : (($at = strtotime($value)) !== false && $value !== '' ? $at - $this->clock->now() : 0); + + return max(0, min(self::MAX_WAIT, $wait)); + } + + /** + * The hourly limit is a rolling count per token. Once what remains is no + * more than the part of it reserved for other users of the token, stop + * until ratelimit-reset, when the oldest request expires. + */ + private function checkShare(HttpResponse $response): void { + $limit = $response->header('ratelimit-limit'); + $remaining = $response->header('ratelimit-remaining'); + + if ( + !ctype_digit($limit) + || !ctype_digit($remaining) + || (int) $remaining > intdiv((int) $limit * (100 - $this->share), 100) + ) { + return; + } + + $reset = $response->header('ratelimit-reset'); + $this->exhausted = max(1, min(self::MAX_WAIT, ctype_digit($reset) ? (int) $reset - $this->clock->now() : 60)); + } + + /** + * @throws DriverError + */ + private static function resource(string $type, mixed $item): CloudResource { + if (!is_array($item)) { + throw new DriverError(ErrorClass::Malformed, $type . ' entry is not an object'); + } + + $id = $item['id'] ?? null; + $id = is_int($id) ? (string) $id : (is_string($id) ? $id : ''); + $name = is_string($item['name'] ?? null) ? $item['name'] : ''; + $region = is_array($item['region'] ?? null) && is_string($item['region']['slug'] ?? null) + ? $item['region']['slug'] + : ''; + + if (preg_match(self::ID_PATTERNS[$type], $id) !== 1) { + throw new DriverError(ErrorClass::Malformed, $type . ' id has an unexpected form'); + } + + return new CloudResource($type, $id, $name, $region); + } + + /** + * The newest datapoint as [time, value], or null when the response holds + * no data or the value cannot be computed from it. + * + * @param array $body + * @return array{int, ?float}|null + * @throws DriverError + */ + private static function convert(array $body, string $conversion): ?array { + $series = self::matrix($body); + + if ($series === []) { + return null; + } + + if ($conversion === 'cpu') { + return self::cpu($series); + } + + // One series expected; several are not combined until the live + // check shows what their labels mean. + if (count($series) !== 1) { + throw new DriverError(ErrorClass::Malformed, count($series) . ' series where one was expected'); + } + + $points = $series[0]['points']; + + if ($points === []) { + return null; + } + + [$time, $value] = $points[array_key_last($points)]; + + return [$time, $conversion === 'mbps' ? $value * 1000000 : $value]; + } + + /** + * Percent busy between the newest two times every mode reports. + * + * @param list, points: array}> $series + * @return array{int, ?float}|null + */ + private static function cpu(array $series): ?array { + $times = array_keys($series[0]['points']); + + foreach ($series as $one) { + $times = array_values(array_intersect($times, array_keys($one['points']))); + } + + sort($times); + + if (count($times) < 2) { + return null; + } + + $newest = $times[count($times) - 1]; + $before = $times[count($times) - 2]; + $total = 0.0; + $idle = null; + + foreach ($series as $one) { + $delta = $one['points'][$newest][1] - $one['points'][$before][1]; + $total += $delta; + + if (($one['labels']['mode'] ?? '') === 'idle') { + $idle = $delta; + } + } + + // Without an idle series, or across a counter reset, the value is + // unknown, never zero. + if ($idle === null || $total <= 0.0 || $idle < 0.0) { + return [$newest, null]; + } + + return [$newest, max(0.0, min(100.0, 100.0 * ($total - $idle) / $total))]; + } + + /** + * Series of a Prometheus-style matrix, each with its points keyed by time + * in ascending order. Points whose value is not a number are dropped. + * + * @param array $body + * @return list, points: array}> + * @throws DriverError + */ + private static function matrix(array $body): array { + $data = is_array($body['data'] ?? null) ? $body['data'] : null; + $result = $data['result'] ?? null; + + if ($data === null || ($data['resultType'] ?? null) !== 'matrix' || !is_array($result) || !array_is_list($result)) { + throw new DriverError(ErrorClass::Malformed, 'metrics response is not a matrix'); + } + + $series = []; + + foreach ($result as $entry) { + if (!is_array($entry) || !is_array($entry['values'] ?? null)) { + throw new DriverError(ErrorClass::Malformed, 'metrics series has no values'); + } + + $labels = []; + + foreach (is_array($entry['metric'] ?? null) ? $entry['metric'] : [] as $name => $value) { + if (is_string($value)) { + $labels[(string) $name] = $value; + } + } + + $points = []; + + foreach ($entry['values'] as $pair) { + if (!is_array($pair) || !is_int($pair[0] ?? null) || !is_string($pair[1] ?? null) || !is_numeric($pair[1])) { + continue; + } + + $value = (float) $pair[1]; + + if (is_finite($value)) { + $points[$pair[0]] = [$pair[0], $value]; + } + } + + ksort($points); + $series[] = ['labels' => $labels, 'points' => $points]; + } + + return $series; + } +} diff --git a/lib/DriverError.php b/lib/DriverError.php index cfa5009..e55bc2a 100644 --- a/lib/DriverError.php +++ b/lib/DriverError.php @@ -20,7 +20,14 @@ namespace Somethingwithproof\Cloud; final class DriverError extends \RuntimeException { - public function __construct(public readonly ErrorClass $errorClass, string $reason = '') { + /** + * @param int $retryAfter seconds the provider asked the plugin to wait, 0 when it did not + */ + public function __construct( + public readonly ErrorClass $errorClass, + string $reason = '', + public readonly int $retryAfter = 0 + ) { parent::__construct($errorClass->value . ($reason !== '' ? ': ' . $reason : '')); } diff --git a/lib/Drivers.php b/lib/Drivers.php index 1eb7505..42caa0b 100644 --- a/lib/Drivers.php +++ b/lib/Drivers.php @@ -21,9 +21,8 @@ /** * Builds the driver for an account, wired to a transport that enforces the - * account's outbound policy and the driver's operation list. No provider has - * a driver yet: DigitalOcean's arrives with milestone 3, and until then an - * account reports a configuration status instead of collecting. + * account's outbound policy and the driver's operation list. A provider + * without a driver reports a configuration status instead of collecting. */ final class Drivers { /** @@ -38,7 +37,21 @@ public function __construct(private readonly \Closure $transport) { } public static function production(): self { - return new self(static fn (OutboundPolicy $policy): HttpTransport => new SocketTransport($policy)); + // CLOUD_OFFLINE=1 refuses every provider request, so CI can drive the + // real pages and collector without reaching a provider. It can only + // take traffic away, never send it anywhere else. + $offline = getenv('CLOUD_OFFLINE') === '1'; + $drivers = new self( + static fn (OutboundPolicy $policy): HttpTransport => $offline + ? new RefusingTransport() + : new SocketTransport($policy) + ); + $drivers->register( + Provider::DigitalOcean, + static fn (HttpTransport $http): ProviderDriver => new DigitalOceanDriver($http, new SystemClock()) + ); + + return $drivers; } /** diff --git a/lib/HealthPage.php b/lib/HealthPage.php index b437571..16363f9 100644 --- a/lib/HealthPage.php +++ b/lib/HealthPage.php @@ -156,9 +156,13 @@ public function row(Account $account): array { } private function collectionLabel(AccountHealth $health): string { - return $health->error === null + $label = $health->error === null ? $health->collection->value : $health->collection->value . ' (' . $health->error->value . ')'; + $wait = $health->retryAt - $this->clock->now(); + + // The provider asked for a pause; the collector skips the account until then. + return $wait > 0 ? $label . ', ' . __('retry in %d s', $wait, 'cloud') : $label; } private function age(int $time): string { diff --git a/lib/HealthRepository.php b/lib/HealthRepository.php index b91ed27..770d135 100644 --- a/lib/HealthRepository.php +++ b/lib/HealthRepository.php @@ -41,20 +41,22 @@ public function find(int $accountId): AccountHealth { */ public function save(AccountHealth $health, string $holder, int $now): void { db_execute_prepared('INSERT INTO plugin_cloud_health (account_id, run_started, run_finished, run_duration, collection, - error_class, requests, series_total, series_read, discovered_at, discovery, credential) - SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? FROM plugin_cloud_lease l + error_class, requests, series_total, series_read, discovered_at, discovery, credential, retry_at) + SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? FROM plugin_cloud_lease l WHERE l.account_id = ? AND l.holder = ? AND l.expires_at >= ? ON DUPLICATE KEY UPDATE run_started = VALUES(run_started), run_finished = VALUES(run_finished), run_duration = VALUES(run_duration), collection = VALUES(collection), error_class = VALUES(error_class), requests = VALUES(requests), series_total = VALUES(series_total), series_read = VALUES(series_read), - discovered_at = VALUES(discovered_at), discovery = VALUES(discovery), credential = VALUES(credential)', [ + discovered_at = VALUES(discovered_at), discovery = VALUES(discovery), credential = VALUES(credential), + retry_at = VALUES(retry_at)', [ $health->accountId, $health->runStarted, $health->runFinished, $health->runDuration, $health->collection->value, $health->error->value ?? '', $health->requests, $health->seriesTotal, $health->seriesRead, $health->discoveredAt, $health->discovery->value, $health->error === ErrorClass::Auth ? 'invalid' : ($health->error === ErrorClass::Permission ? 'permission' : 'unknown'), + $health->retryAt, $health->accountId, $holder, $now, ], true, $this->connection); } diff --git a/lib/RequestBudget.php b/lib/RequestBudget.php new file mode 100644 index 0000000..9c4d3ed --- /dev/null +++ b/lib/RequestBudget.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. + */ + +namespace Somethingwithproof\Cloud; + +/** + * How many requests one collector run of an account may send, and which + * series fit in them (REQ-BUDGET-001, REQ-BUDGET-002). + * + * A run may use the account's share of the provider's hourly limit spread + * over its interval, and never more than its share of the per-minute limit, + * so runs a poller cycle apart stay inside both. A monthly cost ceiling + * cuts the series further. Series keep their stored order, so the same + * ones are read each run and the rest are marked unread with reason budget. + */ +final class RequestBudget { + public const REASON = 'budget'; + + /** + * Per-credential limits, [per hour, per minute], from + * docs/research/provider-facts.md. A provider not listed has no request + * budget until its phase adds one. + */ + private const LIMITS = [ + 'digitalocean' => [5000, 250], + ]; + + public static function perRun(Account $account): ?int { + $limits = self::LIMITS[$account->provider->value] ?? null; + + if ($limits === null) { + return null; + } + + [$hour, $minute] = $limits; + $interval = max(60, Collector::dueAfter($account->collectInterval)); + + return min(intdiv($hour * $account->requestShare * $interval, 360000), intdiv($minute * $account->requestShare, 100)); + } + + /** + * Split $wanted into the series this run reads and those it leaves, + * after $spent requests already went to discovery. + * + * @param list $wanted + * @return array{list, list} + */ + public static function split(Account $account, ProviderDriver $driver, array $wanted, int $spent): array { + if ($wanted === []) { + return [[], []]; + } + + $estimate = $driver->estimate($wanted, $account->collectInterval); + $fit = count($wanted); + $perRun = self::perRun($account); + + // Requests per series, so a provider that batches series counts right. + $cost = max(1, $estimate->requestsPerCollection) / count($wanted); + + if ($perRun !== null) { + $fit = min($fit, (int) floor(max(0, $perRun - $spent) / $cost)); + } + + if ($account->monthlyCeiling !== null && $estimate->monthlyCost > $account->monthlyCeiling) { + $fit = min($fit, (int) floor(count($wanted) * $account->monthlyCeiling / $estimate->monthlyCost)); + } + + return [array_slice($wanted, 0, $fit), array_slice($wanted, $fit)]; + } +} diff --git a/lib/Schema.php b/lib/Schema.php index 26bbad5..1b0b146 100644 --- a/lib/Schema.php +++ b/lib/Schema.php @@ -34,7 +34,7 @@ * the next run (REQ-LIFE-003). No migration calls a provider (REQ-LIFE-006). */ final class Schema { - public const VERSION = 1; + public const VERSION = 2; public const HOOKS = [ 'config_arrays' => 'cloud_config_arrays', @@ -145,12 +145,13 @@ public function hooksRegistered(): bool { } /** - * Stop Cacti from dropping the plugin tables on uninstall, and keep the - * schema version so a reinstall reuses them. + * Stop Cacti from dropping the plugin tables, or the columns migrations + * added to them, on uninstall, and keep the schema version so a + * reinstall reuses them. */ public function untrackTables(): void { db_execute_prepared( - "DELETE FROM plugin_db_changes WHERE plugin = ? AND method = 'create'", + "DELETE FROM plugin_db_changes WHERE plugin = ? AND method IN ('create', 'addcolumn')", [self::PLUGIN], true, $this->connection @@ -167,6 +168,8 @@ public function forgetVersion(): void { private function migrations(): array { return [ 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()), ]; } @@ -209,6 +212,39 @@ private function createTables(array $tables): bool { return true; } + /** + * @param array{name: string, type: string, unsigned: bool, NULL: bool, default: string} $column + */ + private function addColumn(string $table, array $column): bool { + api_plugin_db_add_column(self::PLUGIN, $table, $column); + + if ( + (int) db_fetch_cell_prepared( + 'SELECT COUNT(*) FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?', + [$table, $column['name']], + '', + true, + $this->connection + ) === 0 + ) { + Log::error(sprintf('Unable to add column %s.%s', $table, $column['name'])); + + return false; + } + + return true; + } + + /** + * When a throttled account may be collected again (REQ-BUDGET-003). + * + * @return array{name: string, type: string, unsigned: bool, NULL: bool, default: string} + */ + private static function retryAtColumn(): array { + return ['name' => 'retry_at', 'type' => 'int(10)', 'unsigned' => true, 'NULL' => false, 'default' => '0']; + } + private function tableExists(string $table): bool { return db_fetch_cell_prepared( 'SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?', @@ -364,6 +400,7 @@ public static function tables(): array { $time('discovered_at'), $text('discovery', 16, 'never'), $text('credential', 16, 'unknown'), + self::retryAtColumn(), ], 'primary' => 'account_id', ], diff --git a/locales/po/cacti.pot b/locales/po/cacti.pot index 91eb429..406952f 100644 --- a/locales/po/cacti.pot +++ b/locales/po/cacti.pot @@ -260,6 +260,11 @@ msgstr "" msgid "Never" msgstr "" +#: lib/HealthPage.php +#, php-format +msgid "retry in %d s" +msgstr "" + #: lib/HealthPage.php #, php-format msgid "%d seconds ago" diff --git a/tests/Integration/LifecycleTest.php b/tests/Integration/LifecycleTest.php index 7129520..6bd53a1 100644 --- a/tests/Integration/LifecycleTest.php +++ b/tests/Integration/LifecycleTest.php @@ -46,7 +46,7 @@ expect($state['plugin']['status'])->toEqual('4') ->and($state['plugin']['version'])->toEqual(CLOUD_VERSION) - ->and($state['schema'])->toEqual('1') + ->and($state['schema'])->toEqual('2') ->and(array_keys($state['tables']))->toBe(CLOUD_TABLES) ->and($state['tracked'])->toBe(CLOUD_TABLES) ->and(array_keys($state['hooks']))->toBe(CLOUD_HOOKS) @@ -116,7 +116,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('1') + ->and($state['schema'])->toEqual('2') ->and($state['plugin']['version'])->toEqual(CLOUD_VERSION); }); @@ -129,7 +129,30 @@ ->and($stopped['schema'])->toEqual('0'); $finished = lifecycle('upgrade'); - expect($finished['schema'])->toEqual('1'); + expect($finished['schema'])->toEqual('2'); +}); + +it('adds the retry column to a version 1 database, and a kept uninstall keeps it', function () { + lifecycle('install'); + lifecycle('seed'); + lifecycle('drop_column', 'plugin_cloud_health.retry_at'); + lifecycle('set_schema', '1'); + + $upgraded = lifecycle('upgrade'); + expect($upgraded['result'])->toBeTrue() + ->and($upgraded['schema'])->toEqual('2') + ->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); + + // Core drops tracked columns on uninstall; keeping tables keeps them too. + $kept = lifecycle('uninstall'); + expect($kept['health_columns'])->toContain('retry_at') + ->and($kept['tracked_columns'])->toBe([]); + + $reinstalled = lifecycle('install'); + expect($reinstalled['schema'])->toEqual('2') + ->and($reinstalled['health_columns'])->toContain('retry_at'); }); it('refuses a schema newer than the code and leaves the recorded version alone', function () { @@ -211,7 +234,19 @@ ->and($r['d2_lifecycle'])->toBe(['missing', 'missing', 'deleted']) ->and($r['health_unchanged'])->toBeTrue() ->and($r['order_run1']['stopped_early'])->toBeTrue() - ->and($r['order'])->toBe(['Second', 'Main']); + ->and($r['order'])->toBe(['Second', 'Main']) + // Over budget: the first series in stored order are read, the rest marked. + ->and($r['budget_collected'])->toBe(['b1/m_a', 'b1/m_b']) + ->and($r['budget_health'])->toEqual(['collection' => 'budget', 'series_total' => '3', 'series_read' => '2']) + ->and($r['budget_status'])->toBe(['m_a' => 'ok', 'm_b' => 'ok', 'm_c' => 'budget']) + // Throttled: no run until Retry-After has passed. + ->and($r['throttled_health'])->toEqual([ + 'collection' => 'failed', + 'error_class' => 'throttled', + 'retry_at' => (string) ($r['throttled_at'] + 900), + ]) + ->and($r['during_retry'])->toBe([]) + ->and($r['after_retry'])->toBe(['b1/m_a', 'b1/m_b']); }); it('honours keep tables on uninstall when the runtime is refused', function () { diff --git a/tests/Unit/DigitalOceanDriverTest.php b/tests/Unit/DigitalOceanDriverTest.php new file mode 100644 index 0000000..b280c2e --- /dev/null +++ b/tests/Unit/DigitalOceanDriverTest.php @@ -0,0 +1,505 @@ + + * 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\CloudResource; +use Somethingwithproof\Cloud\DigitalOceanCatalog; +use Somethingwithproof\Cloud\DigitalOceanDriver; +use Somethingwithproof\Cloud\DriverError; +use Somethingwithproof\Cloud\ErrorClass; +use Somethingwithproof\Cloud\FixedClock; +use Somethingwithproof\Cloud\GuardedTransport; +use Somethingwithproof\Cloud\HttpRequest; +use Somethingwithproof\Cloud\HttpResponse; +use Somethingwithproof\Cloud\HttpTransport; +use Somethingwithproof\Cloud\MetricRequest; +use Somethingwithproof\Cloud\Secret; +use Somethingwithproof\Cloud\TransportError; +use Somethingwithproof\Cloud\VerifyStatus; + +// Response bodies are DigitalOcean's own examples from its API +// specification (tests/fixtures/digitalocean). Paging, errors, and odd +// bodies are built from them here; none was recorded from a live account. + +// Built at run time: a literal token shape trips secret scanners. +define('CLOUD_DO_TOKEN', 'dop_v1_' . str_repeat('0123456789abcdef', 4)); +const CLOUD_DO_NOW = 1635387200; + +function cloud_do_fixture(string $name): array { + return json_decode( + (string) file_get_contents(__DIR__ . '/../fixtures/digitalocean/' . $name . '.json'), + true, + 64, + JSON_THROW_ON_ERROR + ); +} + +/** + * A transport answering by path with the response a closure returns, behind + * the driver's real policy and operation list, recording what passed both. + */ +final class DoScripted implements HttpTransport { + /** @var list */ + public array $sent = []; + + /** + * @param Closure(string, array): HttpResponse $answer + */ + public function __construct(private readonly Closure $answer) { + } + + public function send(HttpRequest $request): HttpResponse { + $parts = parse_url($request->url); + parse_str($parts['query'] ?? '', $query); + $this->sent[] = $request; + + return ($this->answer)($parts['path'] ?? '/', $query); + } +} + +/** + * @return array{DigitalOceanDriver, DoScripted} + */ +function cloud_do_driver(Closure $answer): array { + $inner = new DoScripted($answer); + $probe = new DigitalOceanDriver($inner, new FixedClock(CLOUD_DO_NOW)); + $guard = new class ($inner, $probe->operations(), $probe->endpoints(cloud_do_account())) implements HttpTransport { + public function __construct( + private readonly HttpTransport $inner, + private readonly array $operations, + private readonly \Somethingwithproof\Cloud\OutboundPolicy $policy + ) { + } + + public function send(HttpRequest $request): HttpResponse { + $this->policy->check($request->url); + + return (new GuardedTransport($this->inner, $this->operations))->send($request); + } + }; + + return [new DigitalOceanDriver($guard, new FixedClock(CLOUD_DO_NOW)), $inner]; +} + +function cloud_do_account(): Account { + return Account::fromRow(['id' => 1, 'provider' => 'digitalocean', 'credential_source' => 'vault']); +} + +function cloud_do_json(array $body, int $status = 200): HttpResponse { + return new HttpResponse($status, ['content-type' => 'application/json'], json_encode($body)); +} + +function cloud_do_status(int $status): Closure { + return static fn (): HttpResponse => cloud_do_json(cloud_do_fixture('error_401'), $status); +} + +function cloud_do_metric(string $metric, string $providerId = '222651441', int $resourceId = 7): MetricRequest { + return new MetricRequest($resourceId, DigitalOceanCatalog::metric($metric)['type'], $providerId, $metric); +} + +it('lists Droplets and load balancers from the documented examples', function () { + [$driver, $http] = cloud_do_driver( + static fn (string $path): HttpResponse => cloud_do_json( + cloud_do_fixture($path === '/v2/droplets' ? 'droplets' : 'load_balancers') + ) + ); + + $inventory = $driver->discover(cloud_do_account(), new Secret(CLOUD_DO_TOKEN)); + $found = array_map( + static fn (CloudResource $r): string => "$r->type $r->providerId $r->name $r->region", + $inventory->resources + ); + + expect($found)->toBe([ + 'droplet 3164444 example.com nyc3', + 'droplet 3164459 assets.example.com nyc3', + 'droplet 3164412 stage.example.com nyc3', + 'load_balancer 4de7ac8b-495b-4884-9a69-1050c6793cd6 example-lb-01 nyc3', + 'load_balancer 56775c3f-04ab-4fb3-a7ed-40ef9bc8eece prod-web-lb-01 nyc3', + ]) + ->and($inventory->requests)->toBe(2) + ->and($http->sent[0]->url)->toBe('https://api.digitalocean.com/v2/droplets?per_page=100&page=1') + ->and($http->sent[0]->headers['Authorization'])->toBe('Bearer ' . CLOUD_DO_TOKEN); +}); + +it('pages by number and never requests the URL a response links to', function () { + $pages = []; + + [$driver, $http] = cloud_do_driver(static function (string $path, array $query) use (&$pages): HttpResponse { + if ($path === '/v2/load_balancers') { + return cloud_do_json(['load_balancers' => [], 'links' => [], 'meta' => ['total' => 0]]); + } + + $pages[] = (int) $query['page']; + $body = cloud_do_fixture('droplets'); + + if ($query['page'] < 3) { + $body['links'] = ['pages' => ['next' => 'https://attacker.example/v2/droplets?page=2']]; + } + + return cloud_do_json($body); + }); + + $inventory = $driver->discover(cloud_do_account(), new Secret(CLOUD_DO_TOKEN)); + + expect($pages)->toBe([1, 2, 3]) + ->and(count($inventory->resources))->toBe(9) + ->and($inventory->requests)->toBe(4); + + foreach ($http->sent as $request) { + expect(parse_url($request->url, PHP_URL_HOST))->toBe('api.digitalocean.com'); + } +}); + +it('refuses a list entry whose id is not a Droplet id, rather than storing it', function () { + [$driver] = cloud_do_driver(static function (string $path): HttpResponse { + $body = cloud_do_fixture('droplets'); + $body['droplets'][1]['id'] = '3164459&x=1'; + + return cloud_do_json($body); + }); + + expect(fn () => $driver->discover(cloud_do_account(), new Secret(CLOUD_DO_TOKEN))) + ->toThrow(DriverError::class, 'malformed'); +}); + +it('computes CPU percent busy from the documented example', function () { + [$driver, $http] = cloud_do_driver(static fn (): HttpResponse => cloud_do_json(cloud_do_fixture('droplet_cpu'))); + + $result = $driver->collect(cloud_do_account(), new Secret(CLOUD_DO_TOKEN), [cloud_do_metric('do_cpu_pct')]); + $seen = $result->observations[0]; + + // Between 1635387000 and 1635387120 idle grew 119.88 s of 119.96 s. + expect($result->error)->toBeNull() + ->and($result->requests)->toBe(1) + ->and($seen->observedAt)->toBe(1635387120) + ->and($seen->value)->toEqualWithDelta(100 * 0.08 / 119.96, 1e-9) + ->and($seen->fetchedAt)->toBe(CLOUD_DO_NOW) + ->and($http->sent[0]->url)->toBe( + 'https://api.digitalocean.com/v2/monitoring/metrics/droplet/cpu?host_id=222651441&start=' + . (CLOUD_DO_NOW - 900) . '&end=' . CLOUD_DO_NOW + ); +}); + +it('reads bandwidth as bits per second with its interface and direction', function () { + [$driver, $http] = cloud_do_driver(static fn (): HttpResponse => cloud_do_json(cloud_do_fixture('droplet_bandwidth'))); + + $seen = $driver->collect(cloud_do_account(), new Secret(CLOUD_DO_TOKEN), [cloud_do_metric('do_bw_prv_in')]) + ->observations[0]; + + expect($seen->observedAt)->toBe(1634052720) + ->and($seen->value)->toEqualWithDelta(16214.285714285712, 1e-6) + ->and($http->sent[0]->url)->toEndWith('&interface=private&direction=inbound'); +}); + +it('reports no observation and no error for a metric with no data, as without the agent', function () { + [$driver] = cloud_do_driver( + static fn (): HttpResponse => cloud_do_json( + ['status' => 'success', 'data' => ['resultType' => 'matrix', 'result' => []]] + ) + ); + + $result = $driver->collect(cloud_do_account(), new Secret(CLOUD_DO_TOKEN), [cloud_do_metric('do_mem_avail')]); + + expect($result->observations)->toBe([]) + ->and($result->error)->toBeNull() + ->and($result->requests)->toBe(1); +}); + +it('records an unknown CPU value across a counter reset, never zero', function () { + $body = cloud_do_fixture('droplet_cpu'); + + foreach ($body['data']['result'] as &$series) { + $series['values'][2][1] = '0.5'; + } + + [$driver] = cloud_do_driver(static fn (): HttpResponse => cloud_do_json($body)); + + expect( + $driver->collect(cloud_do_account(), new Secret(CLOUD_DO_TOKEN), [cloud_do_metric('do_cpu_pct')]) + ->observations[0]->value + )->toBeNull(); +}); + +it('reports several load balancer series as malformed instead of guessing how to combine them', function () { + $series = ['metric' => ['lb_id' => '4de7ac8b-495b-4884-9a69-1050c6793cd6'], 'values' => [[1635387120, '3']]]; + + [$driver] = cloud_do_driver( + static fn (): HttpResponse => cloud_do_json( + ['status' => 'success', 'data' => ['resultType' => 'matrix', 'result' => [$series, $series]]] + ) + ); + + $result = $driver->collect( + cloud_do_account(), + new Secret(CLOUD_DO_TOKEN), + [cloud_do_metric('dolb_conn_cur', '4de7ac8b-495b-4884-9a69-1050c6793cd6')] + ); + + expect($result->observations)->toBe([])->and($result->error)->toBe(ErrorClass::Malformed); +}); + +it('maps 401, 403, 429, and 5xx, and stops at a credential, scope, or rate failure', function ( + int $status, + ErrorClass $class, + int $sent +) { + [$driver, $http] = cloud_do_driver(cloud_do_status($status)); + + $result = $driver->collect( + cloud_do_account(), + new Secret(CLOUD_DO_TOKEN), + [cloud_do_metric('do_cpu_pct'), cloud_do_metric('do_bw_pub_in'), cloud_do_metric('do_bw_pub_out')] + ); + + expect($result->error)->toBe($class) + ->and(count($http->sent))->toBe($sent) + ->and($result->requests)->toBe($sent); +})->with([ + 'expired or revoked token' => [401, ErrorClass::Auth, 1], + 'missing scope' => [403, ErrorClass::Permission, 1], + 'rate limited' => [429, ErrorClass::Throttled, 1], + 'provider error' => [503, ErrorClass::Transient, 3], + 'unexpected status' => [404, ErrorClass::Malformed, 3], +]); + +it('treats a body that is not JSON as malformed', function () { + [$driver] = cloud_do_driver(static fn (): HttpResponse => new HttpResponse(200, [], 'maintenance')); + + expect($driver->collect(cloud_do_account(), new Secret(CLOUD_DO_TOKEN), [cloud_do_metric('do_cpu_pct')])->error) + ->toBe(ErrorClass::Malformed); +}); + +it('never requests a series whose stored id or metric does not fit its type', function () { + [$driver, $http] = cloud_do_driver(static fn (): HttpResponse => cloud_do_json(cloud_do_fixture('droplet_cpu'))); + + $result = $driver->collect(cloud_do_account(), new Secret(CLOUD_DO_TOKEN), [ + cloud_do_metric('do_cpu_pct', '1&interface=x'), + new MetricRequest(7, 'droplet', '222651441', 'do_unknown'), + new MetricRequest(7, 'load_balancer', '222651441', 'do_cpu_pct'), + ]); + + // The driver refuses these itself; the operation list behind it is a + // second check, so nothing reaches the transport and no request counts. + expect($http->sent)->toBe([]) + ->and($result->requests)->toBe(0) + ->and($result->error)->toBe(ErrorClass::Config); +}); + +it('verifies each scope it needs, and the monitoring scope against a Droplet', function () { + [$driver, $http] = cloud_do_driver(static fn (string $path): HttpResponse => cloud_do_json( + cloud_do_fixture(match ($path) { + '/v2/droplets' => 'droplets', + '/v2/load_balancers' => 'load_balancers', + default => 'droplet_cpu', + }) + )); + + expect($driver->verify(cloud_do_account(), new Secret(CLOUD_DO_TOKEN)))->toBe(VerifyStatus::Ok) + ->and(array_map( + static fn (HttpRequest $r): string => (string) parse_url($r->url, PHP_URL_PATH), + $http->sent + ))->toBe(['/v2/droplets', '/v2/load_balancers', '/v2/monitoring/metrics/droplet/cpu']) + ->and($http->sent[2]->url)->toContain('host_id=3164444'); +}); + +it('reports a rejected token and a missing scope on verify', function (int $status, VerifyStatus $expected) { + [$driver] = cloud_do_driver(cloud_do_status($status)); + + expect($driver->verify(cloud_do_account(), new Secret(CLOUD_DO_TOKEN)))->toBe($expected); +})->with([ + [401, VerifyStatus::Invalid], + [403, VerifyStatus::Permission], + [429, VerifyStatus::Throttled], + [500, VerifyStatus::Unreachable], +]); + +it('allows only GET under the three documented prefixes, and every catalog path', function () { + $probe = new DigitalOceanDriver( + new DoScripted(static fn (): HttpResponse => cloud_do_json([])), + new FixedClock(CLOUD_DO_NOW) + ); + $guard = new GuardedTransport(new DoScripted(static fn (): HttpResponse => cloud_do_json([])), $probe->operations()); + + foreach ($probe->operations() as $operation) { + expect($operation->method)->toBe('GET') + ->and($operation->host)->toBe('api.digitalocean.com'); + } + + foreach (['droplet' => 'host_id=1', 'load_balancer' => 'lb_id=4de7ac8b-495b-4884-9a69-1050c6793cd6'] as $type => $id) { + foreach (DigitalOceanCatalog::paths($type) as $path) { + expect( + $guard->allows( + new HttpRequest('GET', "https://api.digitalocean.com/v2/monitoring/metrics/$type/$path?$id&start=1&end=2") + ) + )->not->toBeNull($path); + } + } + + foreach ([ + new HttpRequest( + 'POST', + 'https://api.digitalocean.com/v2/droplets', + ['Content-Type' => 'application/json'], + '{"name":"x"}' + ), + new HttpRequest('DELETE', 'https://api.digitalocean.com/v2/droplets?per_page=1&page=1'), + new HttpRequest('GET', 'https://api.digitalocean.com/v2/droplets/3164444/actions?per_page=1&page=1'), + new HttpRequest('GET', 'https://api.digitalocean.com/v2/account/keys?per_page=1&page=1'), + new HttpRequest('GET', 'https://api.digitalocean.com/v2/monitoring/alerts?per_page=1&page=1'), + new HttpRequest('GET', 'https://api.digitalocean.com/v2/droplets?per_page=1&page=1&tag_name=x'), + ] as $request) { + expect($guard->allows($request))->toBeNull($request->method . ' ' . $request->url); + } + +}); + +it('lists only metrics that need no agent by default', function () { + expect(DigitalOceanCatalog::defaults('droplet')) + ->toBe(['do_cpu_pct', 'do_bw_pub_in', 'do_bw_pub_out', 'do_bw_prv_in', 'do_bw_prv_out']) + ->and(count(DigitalOceanCatalog::defaults('load_balancer')))->toBe(16); + + foreach ( + array_merge(DigitalOceanCatalog::defaults('droplet'), DigitalOceanCatalog::defaults('load_balancer')) as $name + ) { + expect(strlen($name))->toBeLessThanOrEqual(19)->and(preg_match('/^[a-zA-Z0-9_]+$/', $name))->toBe(1); + } +}); + +it('estimates one request per series per collection and no charge', function () { + $estimate = (new DigitalOceanDriver( + new DoScripted(static fn (): HttpResponse => cloud_do_json([])), + new FixedClock(0) + )) + ->estimate( + array_map( + static fn (string $m): MetricRequest => cloud_do_metric($m), + DigitalOceanCatalog::defaults('droplet') + ), + 300 + ); + + expect($estimate->requestsPerCollection)->toBe(5) + ->and($estimate->requestsPerMonth)->toBe(5 * 8640) + ->and($estimate->monthlyCost)->toBe(0.0); +}); + +it('registers DigitalOcean in production, and refuses every request when offline', function () { + putenv('CLOUD_OFFLINE=1'); + + try { + $driver = \Somethingwithproof\Cloud\Drivers::production()->for(cloud_do_account()); + + expect($driver)->toBeInstanceOf(DigitalOceanDriver::class) + ->and($driver->verify(cloud_do_account(), new Secret(CLOUD_DO_TOKEN)))->toBe(VerifyStatus::Config) + ->and(fn () => $driver->discover(cloud_do_account(), new Secret(CLOUD_DO_TOKEN))) + ->toThrow(DriverError::class, 'operation_refused'); + } finally { + putenv('CLOUD_OFFLINE'); + } +}); + +function cloud_do_limited(int $limit, int $remaining, int $reset): Closure { + return static function () use ($limit, $remaining, $reset): HttpResponse { + $response = cloud_do_json(cloud_do_fixture('droplet_cpu')); + + return new HttpResponse( + 200, + $response->headers + [ + 'ratelimit-limit' => (string) $limit, + 'ratelimit-remaining' => (string) $remaining, + 'ratelimit-reset' => (string) $reset, + ], + $response->body + ); + }; +} + +it('passes on Retry-After from a 429, in seconds or as a date, bounded to an hour', function ( + string $header, + int $expected +) { + [$driver] = cloud_do_driver(static fn (): HttpResponse => new HttpResponse(429, ['retry-after' => $header], '{}')); + + $result = $driver->collect( + cloud_do_account(), + new Secret(CLOUD_DO_TOKEN), + [cloud_do_metric('do_cpu_pct'), cloud_do_metric('do_bw_pub_in')] + ); + + expect($result->error)->toBe(ErrorClass::Throttled) + ->and($result->requests)->toBe(1) + ->and($result->retryAfter)->toBe($expected); +})->with([ + 'seconds' => ['120', 120], + 'date' => [gmdate('D, d M Y H:i:s', CLOUD_DO_NOW + 300) . ' GMT', 300], + 'too long' => ['86400', 3600], + 'absent' => ['', 0], + 'nonsense' => ['soon', 0], +]); + +it('stops once the rate-limit headers leave only what other users of the token are owed', function () { + // A 50 percent share of 5,000 leaves 2,500 for others. + [$driver, $http] = cloud_do_driver(cloud_do_limited(5000, 2500, CLOUD_DO_NOW + 45)); + + $result = $driver->collect( + cloud_do_account(), + new Secret(CLOUD_DO_TOKEN), + [cloud_do_metric('do_cpu_pct'), cloud_do_metric('do_cpu_pct', '3164444', 8)] + ); + + expect(count($http->sent))->toBe(1) + ->and($result->observations)->toHaveCount(1) + ->and($result->error)->toBe(ErrorClass::Throttled) + ->and($result->retryAfter)->toBe(45); +}); + +it('keeps reading while the headers show room in its share', function () { + [$driver, $http] = cloud_do_driver(cloud_do_limited(5000, 2501, CLOUD_DO_NOW + 45)); + + $result = $driver->collect( + cloud_do_account(), + new Secret(CLOUD_DO_TOKEN), + [cloud_do_metric('do_cpu_pct'), cloud_do_metric('do_cpu_pct', '3164444', 8)] + ); + + expect(count($http->sent))->toBe(2)->and($result->error)->toBeNull(); +}); + +it('fails discovery rather than return a list cut off by the request share', function () { + [$driver] = cloud_do_driver(static function (): HttpResponse { + $body = cloud_do_fixture('droplets'); + $body['links'] = ['pages' => ['next' => 'https://api.digitalocean.com/v2/droplets?page=2']]; + + return new HttpResponse( + 200, + ['ratelimit-limit' => '5000', 'ratelimit-remaining' => '10', 'ratelimit-reset' => (string) (CLOUD_DO_NOW + 30)], + json_encode($body) + ); + }); + + try { + $driver->discover(cloud_do_account(), new Secret(CLOUD_DO_TOKEN)); + $caught = null; + } catch (DriverError $e) { + $caught = $e; + } + + expect($caught?->errorClass)->toBe(ErrorClass::Throttled)->and($caught?->retryAfter)->toBe(30); +}); diff --git a/tests/Unit/RequestBudgetTest.php b/tests/Unit/RequestBudgetTest.php new file mode 100644 index 0000000..62e2fe9 --- /dev/null +++ b/tests/Unit/RequestBudgetTest.php @@ -0,0 +1,198 @@ + + * 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\DigitalOceanDriver; +use Somethingwithproof\Cloud\FixedClock; +use Somethingwithproof\Cloud\HttpRequest; +use Somethingwithproof\Cloud\HttpResponse; +use Somethingwithproof\Cloud\HttpTransport; +use Somethingwithproof\Cloud\MetricRequest; +use Somethingwithproof\Cloud\RequestBudget; + +function cloud_budget_account(array $row = []): Account { + return Account::fromRow($row + [ + 'id' => 1, + 'provider' => 'digitalocean', + 'credential_source' => 'vault', + 'collect_interval' => 300, + 'request_share' => 50, + ]); +} + +function cloud_budget_driver(): DigitalOceanDriver { + return new DigitalOceanDriver(new class () implements HttpTransport { + public function send(HttpRequest $request): HttpResponse { + throw new LogicException('the budget never sends'); + } + }, new FixedClock(0)); +} + +/** + * @return list + */ +function cloud_budget_series(int $droplets): array { + $series = []; + + for ($i = 1; $i <= $droplets; $i++) { + foreach (['do_cpu_pct', 'do_bw_pub_in', 'do_bw_pub_out', 'do_bw_prv_in', 'do_bw_prv_out'] as $metric) { + $series[] = new MetricRequest($i, 'droplet', (string) (1000 + $i), $metric); + } + } + + return $series; +} + +it('allows the smaller of the hourly share per run and the per-minute share', function ( + int $interval, + int $share, + int $expected +) { + expect(RequestBudget::perRun(cloud_budget_account(['collect_interval' => $interval, 'request_share' => $share]))) + ->toBe($expected); +})->with([ + // 5,000 x 50% x 270 s / 3,600 s = 187, above 250 x 50% = 125. + '5 minutes at the default share' => [300, 50, 125], + // 5,000 x 10% x 60 s / 3,600 s = 8. + '1 minute at 10 percent' => [60, 10, 8], + // 5,000 x 1% x 270 s / 3,600 s = 3, above 250 x 1% = 2. + '5 minutes at 1 percent' => [300, 1, 2], +]); + +it('keeps 500 Droplets inside the per-minute and per-hour limits, reading in stored order', function () { + $account = cloud_budget_account(); + $wanted = cloud_budget_series(500); + $perRun = RequestBudget::perRun($account); + + // Hourly discovery: 5 Droplet pages and 1 load balancer page. + [$fit, $left] = RequestBudget::split($account, cloud_budget_driver(), $wanted, 6); + + expect(count($wanted))->toBe(2500) + ->and($fit)->toBe(array_slice($wanted, 0, 119)) + ->and($left)->toBe(array_slice($wanted, 119)) + // One run a poller cycle apart never exceeds the per-minute share. + ->and($perRun)->toBeLessThanOrEqual(125) + // Runs come no closer than the collector's due threshold (270 s). + ->and((int) ceil(3600 / 270) * $perRun)->toBeLessThanOrEqual(2500); +}); + +it('reads everything for a provider with no known limit', function () { + $account = Account::fromRow([ + 'id' => 1, + 'provider' => 'aws', + 'credential_source' => 'vault', + 'scope' => json_encode(['account_id' => '123456789012', 'regions' => 'us-east-1']), + ]); + + expect(RequestBudget::perRun($account))->toBeNull(); +}); + +it('cuts the series to the monthly cost ceiling', function () { + $driver = new class () implements \Somethingwithproof\Cloud\ProviderDriver { + public function provider(): \Somethingwithproof\Cloud\Provider { + return \Somethingwithproof\Cloud\Provider::Aws; + } + + public function endpoints(Account $account): \Somethingwithproof\Cloud\OutboundPolicy { + return new \Somethingwithproof\Cloud\OutboundPolicy([]); + } + + public function operations(): array { + return []; + } + + public function verify( + Account $account, + \Somethingwithproof\Cloud\Secret $credential + ): \Somethingwithproof\Cloud\VerifyStatus { + return \Somethingwithproof\Cloud\VerifyStatus::Ok; + } + + public function discover( + Account $account, + \Somethingwithproof\Cloud\Secret $credential + ): \Somethingwithproof\Cloud\Inventory { + return new \Somethingwithproof\Cloud\Inventory([], 0); + } + + public function collect( + Account $account, + \Somethingwithproof\Cloud\Secret $credential, + array $requests + ): \Somethingwithproof\Cloud\CollectResult { + return new \Somethingwithproof\Cloud\CollectResult([], 0); + } + + // $2.00 a month per series. + public function estimate(array $requests, int $intervalSeconds): \Somethingwithproof\Cloud\UsageEstimate { + return new \Somethingwithproof\Cloud\UsageEstimate(count($requests), 0, 2.0 * count($requests)); + } + }; + + $account = Account::fromRow([ + 'id' => 1, + 'provider' => 'aws', + 'credential_source' => 'vault', + 'monthly_ceiling' => 7.0, + 'scope' => json_encode(['account_id' => '123456789012', 'regions' => 'us-east-1']), + ]); + $wanted = cloud_budget_series(2); + + [$fit, $left] = RequestBudget::split($account, $driver, $wanted, 0); + + // 10 series cost $20; $7 pays for 3 of them. + expect($fit)->toBe(array_slice($wanted, 0, 3))->and($left)->toHaveCount(7); +}); + +it('shows a budget run, and how long a throttled account waits, on the health page', function ( + array $health, + string $expected +) { + $clock = new FixedClock(1800000000); + + $GLOBALS['__cloud_db_rows'] = [ + 'FROM plugin_cloud_health' => [$health + ['account_id' => 1, 'run_started' => 1800000000 - 60]], + ]; + + $page = new \Somethingwithproof\Cloud\HealthPage( + new \Somethingwithproof\Cloud\AccountRepository(false, $clock), + new \Somethingwithproof\Cloud\HealthRepository(false), + new \Somethingwithproof\Cloud\ResourceRepository(false, $clock), + new \Somethingwithproof\Cloud\ObservationRepository(false), + new \Somethingwithproof\Cloud\FreshnessEvaluator($clock), + new \Somethingwithproof\Cloud\HealthWarnings(static fn () => null, static fn () => null), + $clock, + ); + + try { + expect($page->row(cloud_budget_account(['admin_state' => 'enabled']))[1])->toBe($expected); + } finally { + $GLOBALS['__cloud_db_rows'] = []; + } +})->with([ + 'over budget' => [['collection' => 'budget'], 'budget'], + 'throttled, wait' => [ + ['collection' => 'failed', 'error_class' => 'throttled', 'retry_at' => 1800000000 + 840], + 'failed (throttled), retry in 840 s', + ], + 'wait has passed' => [ + ['collection' => 'failed', 'error_class' => 'throttled', 'retry_at' => 1800000000 - 1], + 'failed (throttled)', + ], +]); diff --git a/tests/bin/collector-flow.php b/tests/bin/collector-flow.php index 50d49eb..d8e45bd 100644 --- a/tests/bin/collector-flow.php +++ b/tests/bin/collector-flow.php @@ -62,6 +62,8 @@ final class FlowDriver implements ProviderDriver { public static ?FixedClock $clock = null; /** seconds each discovery takes on $clock */ public static int $tick = 0; + /** when set, collect answers throttled with this Retry-After */ + public static int $throttle = 0; public function __construct(HttpTransport $http) { } @@ -94,6 +96,10 @@ public function discover(Account $account, Secret $credential): Inventory { } public function collect(Account $account, Secret $credential, array $requests): CollectResult { + if (self::$throttle > 0) { + return new CollectResult([], 1, \Somethingwithproof\Cloud\ErrorClass::Throttled, self::$throttle); + } + $out = []; foreach ($requests as $request) { @@ -111,7 +117,7 @@ public function collect(Account $account, Secret $credential, array $requests): } public function estimate(array $requests, int $intervalSeconds): UsageEstimate { - return new UsageEstimate(0, 0, 0.0); + return new UsageEstimate(count($requests), 0, 0.0); } } @@ -273,6 +279,64 @@ function flow_collector($clock, $holder) { $result['order'] = FlowDriver::$order; FlowDriver::$clock = null; +// Budget: a 1 percent share of DigitalOcean's limits allows two requests a +// run, so two of three series are read in their stored order and the third +// is marked unread with reason budget. +FlowDriver::$present = array('b1'); +$budgeted = flow_account('Budgeted', 1, 'enabled'); +db_execute_prepared('UPDATE plugin_cloud_account SET request_share = 1 WHERE id = ?', array($budgeted)); +$flow_clock->advance(3700); +flow_collector($flow_clock, 'h10')->run(1, 240); +$b1 = (int) db_fetch_cell_prepared( + "SELECT id FROM plugin_cloud_resource WHERE account_id = ? AND provider_id = 'b1'", + array($budgeted) +); +db_execute_prepared( + 'INSERT INTO plugin_cloud_series (local_data_id, account_id, resource_id, metric) + VALUES (900001, ?, ?, ?), (900001, ?, ?, ?), (900001, ?, ?, ?)', + array($budgeted, $b1, 'm_a', $budgeted, $b1, 'm_b', $budgeted, $b1, 'm_c') +); + +$flow_b1 = static fn (): array => array_values( + array_filter(FlowDriver::$collected, static fn (string $c): bool => str_starts_with($c, 'b1/')) +); + +$flow_clock->advance(300); +FlowDriver::$collected = array(); +flow_collector($flow_clock, 'h11')->run(1, 240); +$result['budget_collected'] = $flow_b1(); +$result['budget_health'] = db_fetch_row_prepared( + 'SELECT collection, series_total, series_read FROM plugin_cloud_health WHERE account_id = ?', + array($budgeted) +); +$result['budget_status'] = array_column( + db_fetch_assoc_prepared( + 'SELECT metric, status FROM plugin_cloud_observation WHERE resource_id = ? ORDER BY metric', + array($b1) + ), + 'status', + 'metric' +); + +// A throttled run records when to try again; a due run before then does +// nothing, and the first run after it collects. +FlowDriver::$throttle = 900; +$flow_clock->advance(300); +$result['throttled_at'] = $flow_clock->now(); +flow_collector($flow_clock, 'h12')->run(1, 240); +$result['throttled_health'] = db_fetch_row_prepared( + 'SELECT collection, error_class, retry_at FROM plugin_cloud_health WHERE account_id = ?', + array($budgeted) +); +FlowDriver::$throttle = 0; +FlowDriver::$collected = array(); +$flow_clock->advance(300); +flow_collector($flow_clock, 'h13')->run(1, 240); +$result['during_retry'] = $flow_b1(); +$flow_clock->advance(700); +flow_collector($flow_clock, 'h14')->run(1, 240); +$result['after_retry'] = $flow_b1(); + db_execute('DELETE FROM data_template_data WHERE local_data_id IN (900001, 900002)'); unlink($flow_dir . '/token'); rmdir($flow_dir); diff --git a/tests/bin/lifecycle.php b/tests/bin/lifecycle.php index e6296cf..3dea67f 100644 --- a/tests/bin/lifecycle.php +++ b/tests/bin/lifecycle.php @@ -104,6 +104,12 @@ db_execute("DELETE FROM plugin_hooks WHERE name = 'cloud'"); db_execute("DELETE FROM plugin_realms WHERE plugin = 'cloud'"); + break; + case 'drop_column': + // A version 1 database: the column a later migration adds is absent. + list($table, $column) = explode('.', preg_replace('/[^a-z_.]/', '', $argument), 2); + db_execute('ALTER TABLE `' . $table . '` DROP COLUMN `' . $column . '`'); + break; case 'drop_table': db_execute('DROP TABLE IF EXISTS `' . preg_replace('/[^a-z_]/', '', $argument) . '`'); @@ -274,5 +280,19 @@ db_fetch_assoc("SELECT `table` FROM plugin_db_changes WHERE plugin = 'cloud' AND method = 'create' ORDER BY `table`"), 'table' ), + 'tracked_columns' => array_map( + static fn ($r) => $r['table'] . '.' . $r['column'], + db_fetch_assoc( + "SELECT `table`, `column` FROM plugin_db_changes WHERE plugin = 'cloud' AND method = 'addcolumn' " . + 'ORDER BY `table`, `column`' + ) + ), + 'health_columns' => array_column( + db_fetch_assoc( + 'SELECT COLUMN_NAME AS c FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() ' . + "AND TABLE_NAME = 'plugin_cloud_health' ORDER BY ORDINAL_POSITION" + ), + 'c' + ), 'tables' => $tables, ), JSON_PRETTY_PRINT) . PHP_EOL; diff --git a/tests/bin/page-permissions.php b/tests/bin/page-permissions.php index 5df44fc..c8d2f7b 100644 --- a/tests/bin/page-permissions.php +++ b/tests/bin/page-permissions.php @@ -243,7 +243,8 @@ function perm_login($user) { $responses[] = array($label, $code, $body, $page[1]); } -// No driver ships yet, so Verify records the configuration status. +// CI runs with CLOUD_OFFLINE=1, so Verify's requests are refused before +// they leave the host and it records the configuration status. list($code, $verified) = perm_http( $base . 'cloud_accounts.php', $jar, diff --git a/tests/fixtures/digitalocean/droplet_bandwidth.json b/tests/fixtures/digitalocean/droplet_bandwidth.json new file mode 100644 index 0000000..7ba822b --- /dev/null +++ b/tests/fixtures/digitalocean/droplet_bandwidth.json @@ -0,0 +1,33 @@ +{ + "status": "success", + "data": { + "resultType": "matrix", + "result": [ + { + "metric": { + "direction": "inbound", + "host_id": "222651441", + "interface": "private" + }, + "values": [ + [ + 1634052360, + "0.016600450090265357" + ], + [ + 1634052480, + "0.015085955677299055" + ], + [ + 1634052600, + "0.014941163855322308" + ], + [ + 1634052720, + "0.016214285714285712" + ] + ] + } + ] + } +} diff --git a/tests/fixtures/digitalocean/droplet_cpu.json b/tests/fixtures/digitalocean/droplet_cpu.json new file mode 100644 index 0000000..ab588f7 --- /dev/null +++ b/tests/fixtures/digitalocean/droplet_cpu.json @@ -0,0 +1,168 @@ +{ + "status": "success", + "data": { + "resultType": "matrix", + "result": [ + { + "metric": { + "host_id": "222651441", + "mode": "idle" + }, + "values": [ + [ + 1635386880, + "122901.18" + ], + [ + 1635387000, + "123020.92" + ], + [ + 1635387120, + "123140.8" + ] + ] + }, + { + "metric": { + "host_id": "222651441", + "mode": "iowait" + }, + "values": [ + [ + 1635386880, + "14.99" + ], + [ + 1635387000, + "15.01" + ], + [ + 1635387120, + "15.01" + ] + ] + }, + { + "metric": { + "host_id": "222651441", + "mode": "irq" + }, + "values": [ + [ + 1635386880, + "0" + ], + [ + 1635387000, + "0" + ], + [ + 1635387120, + "0" + ] + ] + }, + { + "metric": { + "host_id": "222651441", + "mode": "nice" + }, + "values": [ + [ + 1635386880, + "66.35" + ], + [ + 1635387000, + "66.35" + ], + [ + 1635387120, + "66.35" + ] + ] + }, + { + "metric": { + "host_id": "222651441", + "mode": "softirq" + }, + "values": [ + [ + 1635386880, + "2.13" + ], + [ + 1635387000, + "2.13" + ], + [ + 1635387120, + "2.13" + ] + ] + }, + { + "metric": { + "host_id": "222651441", + "mode": "steal" + }, + "values": [ + [ + 1635386880, + "7.89" + ], + [ + 1635387000, + "7.9" + ], + [ + 1635387120, + "7.91" + ] + ] + }, + { + "metric": { + "host_id": "222651441", + "mode": "system" + }, + "values": [ + [ + 1635386880, + "140.09" + ], + [ + 1635387000, + "140.2" + ], + [ + 1635387120, + "140.23" + ] + ] + }, + { + "metric": { + "host_id": "222651441", + "mode": "user" + }, + "values": [ + [ + 1635386880, + "278.57" + ], + [ + 1635387000, + "278.65" + ], + [ + 1635387120, + "278.69" + ] + ] + } + ] + } +} diff --git a/tests/fixtures/digitalocean/droplets.json b/tests/fixtures/digitalocean/droplets.json new file mode 100644 index 0000000..7e65ea6 --- /dev/null +++ b/tests/fixtures/digitalocean/droplets.json @@ -0,0 +1,446 @@ +{ + "droplets": [ + { + "id": 3164444, + "name": "example.com", + "memory": 1024, + "vcpus": 1, + "disk": 25, + "disk_info": [ + { + "type": "local", + "size": { + "amount": 25, + "unit": "gib" + } + } + ], + "locked": false, + "status": "active", + "kernel": null, + "created_at": "2020-07-21T18:37:44Z", + "features": [ + "backups", + "private_networking", + "ipv6" + ], + "backup_ids": [ + 53893572 + ], + "next_backup_window": { + "start": "2020-07-30T00:00:00Z", + "end": "2020-07-30T23:00:00Z" + }, + "snapshot_ids": [ + 67512819 + ], + "image": { + "id": 63663980, + "name": "20.04 (LTS) x64", + "distribution": "Ubuntu", + "slug": "ubuntu-20-04-x64", + "public": true, + "regions": [ + "ams2", + "ams3", + "blr1", + "fra1", + "lon1", + "nyc1", + "nyc2", + "nyc3", + "sfo1", + "sfo2", + "sfo3", + "sgp1", + "tor1" + ], + "created_at": "2020-05-15T05:47:50Z", + "type": "snapshot", + "min_disk_size": 20, + "size_gigabytes": 2.36, + "description": "", + "tags": [], + "status": "available", + "error_message": "" + }, + "volume_ids": [], + "size": { + "slug": "s-1vcpu-1gb", + "memory": 1024, + "vcpus": 1, + "disk": 25, + "transfer": 1, + "price_monthly": 5, + "price_hourly": 0.00743999984115362, + "regions": [ + "ams2", + "ams3", + "blr1", + "fra1", + "lon1", + "nyc1", + "nyc2", + "nyc3", + "sfo1", + "sfo2", + "sfo3", + "sgp1", + "tor1" + ], + "available": true, + "description": "Basic" + }, + "size_slug": "s-1vcpu-1gb", + "networks": { + "v4": [ + { + "ip_address": "10.128.192.124", + "netmask": "255.255.0.0", + "gateway": "nil", + "type": "private" + }, + { + "ip_address": "192.241.165.154", + "netmask": "255.255.255.0", + "gateway": "192.241.165.1", + "type": "public" + } + ], + "v6": [ + { + "ip_address": "2604:a880:0:1010::18a:a001", + "netmask": 64, + "gateway": "2604:a880:0:1010::1", + "type": "public" + } + ] + }, + "region": { + "name": "New York 3", + "slug": "nyc3", + "features": [ + "private_networking", + "backups", + "ipv6", + "metadata", + "install_agent", + "storage", + "image_transfer" + ], + "available": true, + "sizes": [ + "s-1vcpu-1gb", + "s-1vcpu-2gb", + "s-1vcpu-3gb", + "s-2vcpu-2gb", + "s-3vcpu-1gb", + "s-2vcpu-4gb", + "s-4vcpu-8gb", + "s-6vcpu-16gb", + "s-8vcpu-32gb", + "s-12vcpu-48gb", + "s-16vcpu-64gb", + "s-20vcpu-96gb", + "s-24vcpu-128gb", + "s-32vcpu-192g" + ] + }, + "tags": [ + "web", + "env:prod" + ], + "vpc_uuid": "760e09ef-dc84-11e8-981e-3cfdfeaae000", + "subnet_uuid": "9c7a0d63-3c4e-4d3d-9f56-3b0fb0e5e4a1" + }, + { + "id": 3164459, + "name": "assets.example.com", + "memory": 1024, + "vcpus": 1, + "disk": 25, + "disk_info": [ + { + "type": "local", + "size": { + "amount": 25, + "unit": "gib" + } + } + ], + "locked": false, + "status": "active", + "kernel": null, + "created_at": "2020-07-21T18:42:27Z", + "features": [ + "private_networking" + ], + "backup_ids": [], + "next_backup_window": { + "start": "2020-07-30T00:00:00Z", + "end": "2020-07-30T23:00:00Z" + }, + "snapshot_ids": [], + "image": { + "id": 63663980, + "name": "20.04 (LTS) x64", + "distribution": "Ubuntu", + "slug": "ubuntu-20-04-x64", + "public": true, + "regions": [ + "ams2", + "ams3", + "blr1", + "fra1", + "lon1", + "nyc1", + "nyc2", + "nyc3", + "sfo1", + "sfo2", + "sfo3", + "sgp1", + "tor1" + ], + "created_at": "2020-05-15T05:47:50Z", + "type": "snapshot", + "min_disk_size": 20, + "size_gigabytes": 2.36, + "description": "", + "tags": [], + "status": "available", + "error_message": "" + }, + "volume_ids": [ + "506f78a4-e098-11e5-ad9f-000f53306ae1" + ], + "size": { + "slug": "s-1vcpu-1gb", + "memory": 1024, + "vcpus": 1, + "disk": 25, + "transfer": 1, + "price_monthly": 5, + "price_hourly": 0.00743999984115362, + "regions": [ + "ams2", + "ams3", + "blr1", + "fra1", + "lon1", + "nyc1", + "nyc2", + "nyc3", + "sfo1", + "sfo2", + "sfo3", + "sgp1", + "tor1" + ], + "available": true, + "description": "Basic" + }, + "size_slug": "s-1vcpu-1gb", + "networks": { + "v4": [ + { + "ip_address": "10.128.192.138", + "netmask": "255.255.0.0", + "gateway": "nil", + "type": "private" + }, + { + "ip_address": "162.243.0.4", + "netmask": "255.255.255.0", + "gateway": "162.243.0.1", + "type": "public" + } + ], + "v6": [] + }, + "region": { + "name": "New York 3", + "slug": "nyc3", + "features": [ + "private_networking", + "backups", + "ipv6", + "metadata", + "install_agent", + "storage", + "image_transfer" + ], + "available": true, + "sizes": [ + "s-1vcpu-1gb", + "s-1vcpu-2gb", + "s-1vcpu-3gb", + "s-2vcpu-2gb", + "s-3vcpu-1gb", + "s-2vcpu-4gb", + "s-4vcpu-8gb", + "s-6vcpu-16gb", + "s-8vcpu-32gb", + "s-12vcpu-48gb", + "s-16vcpu-64gb", + "s-20vcpu-96gb", + "s-24vcpu-128gb", + "s-32vcpu-192g" + ] + }, + "tags": [ + "storage", + "env:prod" + ], + "vpc_uuid": "760e09ef-dc84-11e8-981e-3cfdfeaae000", + "subnet_uuid": "9c7a0d63-3c4e-4d3d-9f56-3b0fb0e5e4a1" + }, + { + "id": 3164412, + "name": "stage.example.com", + "memory": 1024, + "vcpus": 1, + "disk": 25, + "disk_info": [ + { + "type": "local", + "size": { + "amount": 25, + "unit": "gib" + } + } + ], + "locked": false, + "status": "active", + "kernel": null, + "created_at": "2020-07-21T18:32:55Z", + "features": [ + "private_networking" + ], + "backup_ids": [], + "next_backup_window": { + "start": "2020-07-30T00:00:00Z", + "end": "2020-07-30T23:00:00Z" + }, + "snapshot_ids": [], + "image": { + "id": 63663980, + "name": "20.04 (LTS) x64", + "distribution": "Ubuntu", + "slug": "ubuntu-20-04-x64", + "public": true, + "regions": [ + "ams2", + "ams3", + "blr1", + "fra1", + "lon1", + "nyc1", + "nyc2", + "nyc3", + "sfo1", + "sfo2", + "sfo3", + "sgp1", + "tor1" + ], + "created_at": "2020-05-15T05:47:50Z", + "type": "snapshot", + "min_disk_size": 20, + "size_gigabytes": 2.36, + "description": "", + "tags": [], + "status": "available", + "error_message": "" + }, + "volume_ids": [ + "7724db7c-e098-11e5-b522-000f53304e51" + ], + "size": { + "slug": "s-1vcpu-1gb", + "memory": 1024, + "vcpus": 1, + "disk": 25, + "transfer": 1, + "price_monthly": 5, + "price_hourly": 0.00743999984115362, + "regions": [ + "ams2", + "ams3", + "blr1", + "fra1", + "lon1", + "nyc1", + "nyc2", + "nyc3", + "sfo1", + "sfo2", + "sfo3", + "sgp1", + "tor1" + ], + "available": true, + "description": "Basic" + }, + "size_slug": "s-1vcpu-1gb", + "networks": { + "v4": [ + { + "ip_address": "10.128.192.125", + "netmask": "255.255.0.0", + "gateway": "nil", + "type": "private" + }, + { + "ip_address": "192.241.247.248", + "netmask": "255.255.255.0", + "gateway": "192.241.247.1", + "type": "public" + } + ], + "v6": [] + }, + "region": { + "name": "New York 3", + "slug": "nyc3", + "features": [ + "private_networking", + "backups", + "ipv6", + "metadata", + "install_agent", + "storage", + "image_transfer" + ], + "available": true, + "sizes": [ + "s-1vcpu-1gb", + "s-1vcpu-2gb", + "s-1vcpu-3gb", + "s-2vcpu-2gb", + "s-3vcpu-1gb", + "s-2vcpu-4gb", + "s-4vcpu-8gb", + "s-6vcpu-16gb", + "s-8vcpu-32gb", + "s-12vcpu-48gb", + "s-16vcpu-64gb", + "s-20vcpu-96gb", + "s-24vcpu-128gb", + "s-32vcpu-192g" + ] + }, + "tags": [ + "env:stage" + ], + "vpc_uuid": "5a4981aa-9653-4bd1-bef5-d6bff52042e4", + "subnet_uuid": "0f1a2b3c-4d5e-6f70-8192-a3b4c5d6e7f8" + } + ], + "links": { + "pages": {} + }, + "meta": { + "total": 3 + } +} diff --git a/tests/fixtures/digitalocean/error_401.json b/tests/fixtures/digitalocean/error_401.json new file mode 100644 index 0000000..a3f8eeb --- /dev/null +++ b/tests/fixtures/digitalocean/error_401.json @@ -0,0 +1,4 @@ +{ + "id": "unauthorized", + "message": "Unable to authenticate you." +} diff --git a/tests/fixtures/digitalocean/load_balancers.json b/tests/fixtures/digitalocean/load_balancers.json new file mode 100644 index 0000000..ac035d8 --- /dev/null +++ b/tests/fixtures/digitalocean/load_balancers.json @@ -0,0 +1,181 @@ +{ + "load_balancers": [ + { + "id": "4de7ac8b-495b-4884-9a69-1050c6793cd6", + "name": "example-lb-01", + "ip": "104.131.186.241", + "size": "lb-small", + "algorithm": "round_robin", + "status": "new", + "created_at": "2017-02-01T22:22:58Z", + "forwarding_rules": [ + { + "entry_protocol": "http", + "entry_port": 80, + "target_protocol": "http", + "target_port": 80, + "certificate_id": "", + "tls_passthrough": false + }, + { + "entry_protocol": "https", + "entry_port": 443, + "target_protocol": "https", + "target_port": 443, + "certificate_id": "", + "tls_passthrough": true + } + ], + "health_check": { + "protocol": "http", + "port": 80, + "path": "/", + "check_interval_seconds": 10, + "response_timeout_seconds": 5, + "healthy_threshold": 5, + "unhealthy_threshold": 3 + }, + "sticky_sessions": { + "type": "none" + }, + "region": { + "name": "New York 3", + "slug": "nyc3", + "sizes": [ + "s-1vcpu-1gb", + "s-1vcpu-2gb", + "s-1vcpu-3gb", + "s-2vcpu-2gb", + "s-3vcpu-1gb", + "s-2vcpu-4gb", + "s-4vcpu-8gb", + "s-6vcpu-16gb", + "s-8vcpu-32gb", + "s-12vcpu-48gb", + "s-16vcpu-64gb", + "s-20vcpu-96gb", + "s-24vcpu-128gb", + "s-32vcpu-192gb" + ], + "features": [ + "private_networking", + "backups", + "ipv6", + "metadata", + "install_agent" + ], + "available": true + }, + "tag": "", + "droplet_ids": [ + 3164444, + 3164445 + ], + "redirect_http_to_https": false, + "enable_proxy_protocol": false, + "enable_backend_keepalive": false, + "vpc_uuid": "c33931f2-a26a-4e61-b85c-4e95a2ec431b", + "subnet_uuid": "cbd79771-23eb-49be-b5ea-59cc56222622", + "disable_lets_encrypt_dns_records": false, + "firewall": { + "deny": [ + "cidr:1.2.0.0/16", + "ip:2.3.4.5" + ], + "allow": [ + "ip:1.2.3.4", + "cidr:2.3.4.0/24" + ] + } + }, + { + "id": "56775c3f-04ab-4fb3-a7ed-40ef9bc8eece", + "name": "prod-web-lb-01", + "ip": "45.55.125.24", + "size": "lb-small", + "algorithm": "round_robin", + "status": "active", + "created_at": "2020-09-08T18:58:04Z", + "forwarding_rules": [ + { + "entry_protocol": "https", + "entry_port": 443, + "target_protocol": "http", + "target_port": 8080, + "certificate_id": "892071a0-bb95-49bc-8021-3afd67a210bf", + "tls_passthrough": false + } + ], + "health_check": { + "protocol": "https", + "port": 443, + "path": "/", + "check_interval_seconds": 10, + "response_timeout_seconds": 5, + "healthy_threshold": 5, + "unhealthy_threshold": 3 + }, + "sticky_sessions": { + "type": "cookies", + "cookie_name": "DO-LB", + "cookie_ttl_seconds": 300 + }, + "region": { + "name": "New York 3", + "slug": "nyc3", + "sizes": [ + "s-1vcpu-1gb", + "s-1vcpu-2gb", + "s-1vcpu-3gb", + "s-2vcpu-2gb", + "s-3vcpu-1gb", + "s-2vcpu-4gb", + "s-4vcpu-8gb", + "s-6vcpu-16gb", + "s-8vcpu-32gb", + "s-12vcpu-48gb", + "s-16vcpu-64gb", + "s-20vcpu-96gb", + "s-24vcpu-128gb", + "s-32vcpu-192gb" + ], + "features": [ + "private_networking", + "backups", + "ipv6", + "metadata", + "install_agent" + ], + "available": true + }, + "tag": "prod:web", + "droplet_ids": [ + 55806512, + 55806515, + 55806524 + ], + "redirect_http_to_https": true, + "enable_proxy_protocol": false, + "enable_backend_keepalive": false, + "vpc_uuid": "587d698c-de84-11e8-80bc-3cfdfea9fcd1", + "subnet_uuid": "cbd79771-23eb-49be-b5ea-59cc56222622", + "disable_lets_encrypt_dns_records": false, + "project_id": "9cc10173-e9ea-4176-9dbc-a4cee4c4ff30", + "http_idle_timeout_seconds": 60, + "firewall": { + "deny": [ + "cidr:1.2.0.0/16", + "ip:2.3.4.5" + ], + "allow": [ + "ip:1.2.3.4", + "cidr:2.3.4.0/24" + ] + } + } + ], + "links": {}, + "meta": { + "total": 2 + } +}