diff --git a/.github/workflows/plugin-ci-workflow.yml b/.github/workflows/plugin-ci-workflow.yml index 24edb04..e9fdcc8 100644 --- a/.github/workflows/plugin-ci-workflow.yml +++ b/.github/workflows/plugin-ci-workflow.yml @@ -228,6 +228,57 @@ jobs: exit 1 fi + # End to end: a real net-snmp agent runs the extend lines from + # docs/node-setup.md against a fake nvidia-smi, the plugin reads it over + # SNMPv3, and Cacti's poller writes and graphs the RRD files. + - name: Start snmpd with the documented extend lines + working-directory: cacti/plugins/gpu + run: | + set -euo pipefail + sudo apt-get install -y snmpd + sudo systemctl stop snmpd || true + sudo install -m 755 tests/bin/fake-nvidia-smi /usr/bin/nvidia-smi + sudo install -d -o "$USER" -m 755 /var/lib/gpu-e2e + umask 077 + # Random SNMPv3 passphrases, kept in a file. + { openssl rand -hex 16; openssl rand -hex 16; } > "$RUNNER_TEMP/snmp-secrets" + php tests/bin/snmpd-conf.php "$RUNNER_TEMP/snmp-secrets" udp:127.0.0.1:1161 > "$RUNNER_TEMP/snmpd.conf" + sudo /usr/sbin/snmpd -Lf "$RUNNER_TEMP/snmpd.log" -C -c "$RUNNER_TEMP/snmpd.conf" -p "$RUNNER_TEMP/snmpd.pid" + sleep 1 + if ! sudo kill -0 "$(sudo cat "$RUNNER_TEMP/snmpd.pid")"; then + sudo cat "$RUNNER_TEMP/snmpd.log" || true + exit 1 + fi + + # The test provokes collection failures, which the plugin logs as + # warnings. Its log is checked here for anything else, and the main log + # is put back for the check below. + - name: Run the end-to-end collection test + working-directory: cacti + env: + GPU_TEST_DATABASE: disposable + GPU_E2E_AGENT: 127.0.0.1:1161 + GPU_E2E_FIXTURES: /var/lib/gpu-e2e + run: | + set -uo pipefail + mv log/cacti.log log/main.log + rc=0 + GPU_E2E_SECRETS="$RUNNER_TEMP/snmp-secrets" php plugins/gpu/tests/bin/e2e.php || rc=$? + mv log/cacti.log log/e2e.log + mv log/main.log log/cacti.log + echo "== end-to-end log" + cat log/e2e.log + if grep -E "FATAL:|ERROR:|WARNING:" log/e2e.log | grep -v "GPU WARNING: Node [0-9]*: collection failed"; then + rc=1 + fi + if [ "$rc" -ne 0 ]; then + echo "== snmpd log" + sudo cat "$RUNNER_TEMP/snmpd.log" || true + echo "== AppArmor messages" + sudo dmesg | grep -i apparmor || true + fi + exit "$rc" + - name: Check Cacti log for errors if: always() run: | diff --git a/README.md b/README.md index c16a895..1adfda8 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ A Cacti 1.2 plugin that brings per-GPU utilization, memory, temperature, power, ECC errors, XID errors, and throttling reasons from NVIDIA and AMD tools into Cacti. Each GPU becomes an index of a data query on its node's device, so GPU graphs sit next to the node's other graphs under Cacti's permissions, and Thold and Maint can alert on and suppress them. -> **Status: in development, no release yet.** Milestone 2 (foundation) is merged on `main`: the plugin installs, registers GPU nodes, and keeps GPU identity records, but it collects nothing. No vendor tool is run and no graph is created until milestone 3, which is not on `main`. Milestone 1 research is written up from documentation and source; checks that need GPU hardware are still open. Do not run the plugin in production. Everything below the milestone 2 section describes the plan, not shipped behavior. +> **Status: in development, no release yet.** Milestones 2 (foundation) and 3 (NVIDIA collection and Cacti objects) are merged on `main`. The plugin reads `nvidia-smi` on each GPU node through the node's SNMP agent, keeps GPU identity records, and creates one data query index, one data source, and eight graphs per GPU. It has been run only against a real `snmpd` with a fake `nvidia-smi` printing synthetic output, never on GPU hardware. Alerting, the health page, and the phase 1 release are milestone 4. Milestone 1 research is written up from documentation and source; checks that need GPU hardware are still open. Do not run it in production. ## Why @@ -21,6 +21,18 @@ The plugin closes that gap by turning vendor tool output into Cacti data sources Out of scope: any command that changes a GPU or node (clocks, power limits, resets, MIG layout), a plugin-owned alerting engine, a custom daemon or network protocol, and scheduler or job accounting. See the plan for the research backlog. +## What milestone 3 adds + +- **Collection through SNMP extend** ([ADR 0008](docs/decisions/0008-collect-through-snmp-extend.md)). The node's administrator adds two fixed `extend` lines to `snmpd.conf` ([docs/node-setup.md](docs/node-setup.md)); the plugin reads NET-SNMP-EXTEND-MIB through Cacti's SNMP functions with the device's own credentials, SNMPv3 recommended. It runs nothing on the Cacti server or the node. +- **Strict parsing.** Fields are read by position, each line names its GPU by UUID, and a nonzero exit status, a timeout, truncated output, a line with the wrong field count, or merged error text fails the whole collection: values become `U`, no GPU is marked absent, and GPU Nodes shows why. +- **A collector after each poller cycle.** It reads each enabled node's agent, updates the identity records, and caches the latest sample. The script server input reads only that cache, so a Cacti poll never waits on a GPU node. +- **Cacti objects** ([ADR 0010](docs/decisions/0010-attach-to-existing-node-devices.md)). The templates and the *GPU - Devices* data query ship as XML and are imported on install and upgrade. Saving a node attaches the data query to its existing device with reindex method None; GPU Nodes can create a device only when the node has none. Each GPU is an index keyed by vendor and UUID, with one data source shared by its Utilization, Memory, Temperature, Power, Clocks, Throttle, ECC Errors, and Sample Age graphs. Every model field is drawn by some graph, because Cacti stores only the fields a graph uses. The plugin reindexes after every GPU change, keeps a reindex Cacti skipped while the device was Down or disabled and runs it once the device is Up, and creates graphs for new GPUs. +- **History stays with the card.** An absent GPU stays an index, so its graphs show a gap and resume in the same RRD file when it returns. A replacement card in the same slot gets its own data source. **Remove from Data Query** on the node's page takes an absent GPU out of the listing; its RRD files and graphs are kept until you delete them. +- **Device permissions on GPU Nodes.** A GPU Admin sees, changes, exports, and moves only nodes and GPUs on devices they may see in Cacti; a GPU move needs both nodes. A node whose device was deleted can only be disabled. +- **The common metric model** ([ADR 0009](docs/decisions/0009-common-metric-core-with-vendor-extensions.md), [docs/metrics.md](docs/metrics.md)). Memory is in bytes, the clock event mask is decoded into `thr_*` indicators, and `age` is the age of the GPU's own sample time, or `U` when unknown. + +The installing (web server) user must be able to write `/resource/script_server/`, where the plugin places its data query XML; install and upgrade stop with a message otherwise and retry on the next attempt. Uninstall does not yet remove the templates or the XML (#30). Nodes on remote data collectors are not collected until phase 3. + ## What milestone 2 ships - **A guarded install.** On PHP below 8.2, install and enable are refused with a message naming the required version, and the rest of Cacti keeps working. `setup.php` and the page scripts parse on PHP 8.0. @@ -31,16 +43,17 @@ Out of scope: any command that changes a GPU or node (clocks, power limits, rese ### Install for evaluation -These steps install the milestone 2 code to try it. They require Cacti 1.2.31 or later on PHP 8.2 or later. +These steps install the milestone 3 code to try it. They require Cacti 1.2.31 or later on PHP 8.2 or later. 1. Copy the repository to `plugins/gpu` under your Cacti directory. The directory must be named `gpu`. 2. In Cacti, open **Configuration > Plugins**, then install and enable **GPU**. 3. Give users the *GPU View* or *GPU Admin* realm under **Configuration > Users**. The installing user gets both. -4. Optionally adjust **Configuration > Settings > GPU**: *Mark Absent After* (default 3 successful collections, from 1 to 100) and *Keep Plugin Tables on Uninstall* (default on). +4. Set up each GPU node's SNMP agent as described in [docs/node-setup.md](docs/node-setup.md), then add the node under **Management > GPU Nodes**. +5. Optionally adjust **Configuration > Settings > GPU**: *Mark Absent After* (default 3 successful collections, from 1 to 100), *Stale After* (how old a sample may be before its values print `U`), and *Keep Plugin Tables on Uninstall* (default on). -## Collection path +## How metrics reach Cacti -Decision [#7](https://github.com/somethingwithproof/plugin_gpu/issues/7) chose SNMP `extend` on the GPU node: the node's administrator configures `snmpd` to run the vendor tool with a fixed argument list, and the plugin reads the output through Cacti's SNMP polling of that device. The reasons and rejected alternatives are in [ADR 0008](docs/decisions/0008-collect-through-snmp-extend.md). The collector is not implemented yet. A poller on the node and a `dcgm-exporter` scrape remain possible later backends; see [Collection paths](docs/PLAN.md#collection-paths). +Decision [#7](https://github.com/somethingwithproof/plugin_gpu/issues/7) chose SNMP `extend` ([ADR 0008](docs/decisions/0008-collect-through-snmp-extend.md)): the node's own agent runs a fixed `nvidia-smi` command and the plugin only reads the result. The plan compares the options under [Collection paths](docs/PLAN.md#collection-paths). ## Compatibility targets @@ -60,7 +73,7 @@ Decision [#7](https://github.com/somethingwithproof/plugin_gpu/issues/7) chose S ```mermaid flowchart LR - NODE[GPU node: nvidia-smi, DCGM, amd-smi] -->|SNMP extend| C[Collector] + NODE[GPU node: snmpd extend running nvidia-smi] -->|SNMP reads, v3 recommended| C[Collector] C --> CACHE[(Plugin cache keyed by GPU UUID)] CACHE --> SS[Script server data query input] SS --> RRD[(Cacti RRD files, one data source per GPU)] diff --git a/REUSE.toml b/REUSE.toml index 6eb8db1..521d95e 100644 --- a/REUSE.toml +++ b/REUSE.toml @@ -2,8 +2,9 @@ version = 1 # Files that cannot carry a comment header, or whose format makes one # awkward: documentation, repository metadata, GitHub templates, test -# configuration and fixtures, and translation catalogs, which gettext -# regenerates. +# configuration and fixtures, translation catalogs, which gettext +# regenerates, and the Cacti template and data query XML, which +# lib/TemplateXml.php generates and Cacti imports as is. [[annotations]] path = [ "README.md", @@ -19,6 +20,8 @@ path = [ "tests/fixtures/**", "locales/po/**", "locales/LC_MESSAGES/**", + "templates/*.xml", + "resource/script_server/*.xml", ] precedence = "aggregate" SPDX-FileCopyrightText = "2026 Thomas Vincent " diff --git a/docs/PLAN.md b/docs/PLAN.md index db3708e..1c117d9 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -1,6 +1,6 @@ # Cacti 1.2 GPU Plugin Plan -Status: in development, plan revision 2 (2026-11-15). Revision 2 folds in the milestone 1 documentation and source research in [`docs/research/`](research/); items that need hardware are marked *live* and listed in each research page's Live checks table. Milestone 2 (foundation) is implemented: the PHP guard, lifecycle, realms and pages, node registry, GPU identity records, and the test harness. Where it differs from the text below, the difference is stated in place. Milestone 3 is not on `main`, so nothing collects from a GPU yet: no vendor tool is run, no data query exists, and no graph is created. There is no release. Statements about vendor tools, Cacti core, Thold, and net-snmp describe upstream behavior and cite the source that was checked, with the version or commit where one was available. Statements that could not be verified are listed as assumptions with the research issue that confirms them; they are not facts. Owner and estimates are not assigned; milestone 1 produces the estimates. +Status: in development, plan revision 2 (2026-11-15). Revision 2 folds in the milestone 1 documentation and source research in [`docs/research/`](research/); items that need hardware are marked *live* and listed in each research page's Live checks table. Milestone 2 (foundation) is implemented: the PHP guard, lifecycle, realms and pages, node registry, GPU identity records, and the test harness. Where it differs from the text below, the difference is stated in place. Milestone 3 (NVIDIA collection and Cacti objects) is merged too: the SNMP extend reader and parser, the collector and cache, the data query, templates, and eight graphs per GPU, tested only against a real `snmpd` with synthetic `nvidia-smi` output. Milestone 4 (alerting, health, release) is not done, and there is no release. Statements about vendor tools, Cacti core, Thold, and net-snmp describe upstream behavior and cite the source that was checked, with the version or commit where one was available. Statements that could not be verified are listed as assumptions with the research issue that confirms them; they are not facts. Owner and estimates are not assigned; milestone 1 produces the estimates. `plugin_gpu` brings per-GPU utilization, memory, temperature, power, ECC errors, XID errors, and clock throttling reasons from NVIDIA and AMD tools into Cacti 1.2. Each GPU becomes an index of a data query on its node's Cacti device, so operators see GPU graphs next to the node's other graphs, under Cacti's own permissions, and alert on them with Thold and Maint. @@ -199,7 +199,7 @@ flowchart TB subgraph Node["GPU node"] TOOL[nvidia-smi, DCGM, amd-smi] end - COL -->|collection path, decision 7| TOOL + COL -->|SNMP extend reads, ADR 0008| TOOL SS -->|poller_output| THOLD GR --> DQ[Data query indexes, one per GPU] SS --> DQ @@ -242,6 +242,8 @@ Rules, tested by fixtures (REQ-ID-001 to 006): | Data source and graphs | Graph templates per GPU | Created by Cacti's data query path from the templates | | Data source for staleness | A field of the same data query (`age`) | Always numeric | +As built in milestone 3: the data query is *GPU - Devices*, one data template (*GPU - Metrics*) holds every model field, and eight graph templates (Utilization, Memory, Temperature, Power, Clocks, Throttle, ECC Errors, Sample Age) are created for each present GPU. Every model field is drawn by one of them, because `rrdtool_function_create()` puts into the RRD file only the data source items some graph item uses; an undrawn field such as a throttle indicator or `age` would never be stored, so Thold could not use it. The plugin copies the data query XML to `/resource/script_server/plugin_gpu.xml`, so that directory must be writable by the installing user. Absent GPUs stay in the listing rather than using `index_transient`; an operator's **Remove from Data Query** on an absent GPU takes it out, and it returns if reported again. The index delimiter is `!`, which a `vendor/UUID` key cannot contain, and the data query sets `arg_num_indexes`. Uninstall leaves the templates and the XML in place for now (#30). + Templates ship as Cacti template XML and are imported with `import_xml_data()`, matched by hash so re-imports update rather than duplicate, under a lock so two upgrades cannot import together. The data query uses reindex method None; the plugin runs a forced reindex after each inventory change so titles refresh. `api_device_update_host_template()` (called from `api_device_save()` when a template is applied) runs `REPLACE INTO host_snmp_query` with the global default reindex method for data queries that have no cache rows yet, so the plugin sets None again afterward; `api_device_save()` itself only forces method 0 for devices with SNMP version 0. Confirmed by source at `release/1.2.31` and `1.2.x`; running it is *live* ([research/cacti-core.md](research/cacti-core.md)). A data query XML may instead set `index_transient`, which stops removed indexes being marked orphan; M3 chooses between that and keeping absent GPUs in the listing. When the device is Down or disabled, `run_data_query()` returns `true` without reindexing, even for a forced reindex, and method None schedules no later one. The plugin records each skipped reindex and runs it again once the device is Up and enabled, then checks that the expected indexes are present. @@ -258,16 +260,18 @@ One set of fields describes every GPU, so a single set of templates and Thold te |---|---|---|---|---| | `util_gpu` | percent | `utilization.gpu` | field 1613 (ratio, multiplied by 100; first in DCGM v4.6.0) or 203 (percent; deprecated at v4.7.0) | `amd-smi metric --usage` (#18) | | `util_mem` | percent | `utilization.memory` | #15 | #18 | -| `mem_used`, `mem_total` | one unit, chosen in #14 | `memory.used`, `memory.total` | 252 and 250 (MiB, deprecated) or 1627 and 1625 (used and capacity in bytes; 1627 first in DCGM v4.7.0) | #18 | +| `mem_used`, `mem_total` | bytes (milestone 3) | `memory.used`, `memory.total` | 252 and 250 (MiB, deprecated) or 1627 and 1625 (used and capacity in bytes; 1627 first in DCGM v4.7.0) | #18 | | `temp_gpu` | degrees C | `temperature.gpu` | 150 | `--temperature` | | `power`, `power_limit` | watts | `power.draw`, `power.limit` | 155 and 160 | `--power` | | `clock_sm`, `clock_mem` | MHz | `clocks.sm`, `clocks.mem` | #15 | #18 | -| `throttle_*` | 0 or 1 per reason | decoded from the event reasons bitmask | decoded from field 112 | accumulators, MI300 or newer (#18) | +| `thr_*` | 0 or 1 per reason | decoded from the event reasons bitmask | decoded from field 112 | accumulators, MI300 or newer (#18) | | `ecc_corr`, `ecc_uncorr` | count since driver load | `ecc.errors.*.volatile.total` | 310 and 311 | `--ecc` | | `retired_pending` | 0 or 1 | `retired_pages.pending` | 392 | #18 | | `xid_last` | XID number | per #8 | field 230 | not applicable | | `age` | seconds | computed | computed | computed | +Milestone 3 names the throttle indicators `thr_*` (for example `thr_sw_power_cap`, `thr_hw_slowdown`) so every data source name fits Cacti's 19-character limit, and reads the mask as hex or decimal. The NVIDIA backend reads the mask through the old query name `clocks_throttle_reasons.active`, because the new `clocks_event_reasons.*` names are not confirmed per driver line (#17); REQ-NVSMI-005 is therefore only partly met. GPU names come from a second extend entry, because a product name is free text that can contain the CSV separator. [docs/metrics.md](metrics.md) is generated from the model and is the field reference. + Rules: - A missing, unsupported, or stale value is `U`, never 0. @@ -318,7 +322,7 @@ A MIG-enabled GPU exposes GPU instances and compute instances that can be create ## Remote collectors -When GPU nodes are in other sites, a Cacti remote data collector near them runs the collector and script server input, following the pattern other collector-aware plugins use. +When GPU nodes are in other sites, a Cacti remote data collector near them runs the collector and script server input, following the pattern other collector-aware plugins use. Milestone 3 collects only nodes whose device is on the main poller and counts the rest as remote; the rest of this section is phase 3. - Plugin configuration tables replicate to remote collectors through the `replicate_out` hook. - The collector on each poller handles only nodes whose `poller_id` matches. @@ -408,7 +412,7 @@ Phase 2 needs a security review of the DCGM and amd-smi invocation paths and any - **Alerting.** Thold fires and recovers on fixture throttle, ECC, and staleness; Maint suppresses it. - **Remote.** Collector offline, recovery mode, replication after reconnect. - **Failure scenarios before each phase release:** tool missing, timeout, permission denied, driver unloaded, GPU lost mid-collection, node unreachable, clock skew, full disk, interrupted collector, duplicate collector start, interrupted upgrade. -- **Harness.** Use the harness maintained Cacti plugins use, and confirm with maintainers before adding test or CI infrastructure (#12). M2 adopts it provisionally: Pest from the locked plugin harness in Cacti's `tests/tools/plugin-harness`, as maintained plugins run it, until #12 is decided. Identity fixtures in M2 are synthetic sequences, not captured tool output; captured fixtures arrive with the first backend. +- **Harness.** Use the harness maintained Cacti plugins use, and confirm with maintainers before adding test or CI infrastructure (#12). M2 adopts it provisionally: Pest from the locked plugin harness in Cacti's `tests/tools/plugin-harness`, as maintained plugins run it, until #12 is decided. Identity fixtures in M2 are synthetic sequences, not captured tool output; captured fixtures arrive with the first backend. Milestone 3's `nvidia-smi` fixtures are also synthetic, written to the documented field order; captured output (#14) must replace them before a release. Its end-to-end test runs a real net-snmp `snmpd` with the documented extend lines and a fake `nvidia-smi`, and Cacti's own poller writes the RRD files. ## Milestones @@ -429,8 +433,8 @@ Milestone size estimates (ranges from measured reference plugins, no durations) |---|---|---|---| | Collection path (#7) | Decided 2026-11-15: SNMP extend ([ADR 0008](decisions/0008-collect-through-snmp-extend.md)) | Milestone 3 | Owner | | XID source (#8) | DCGM field, kernel log, none in phase 1 | Milestone 3 | #16 | -| Common metric model (#9) | Common core plus vendor extensions (proposed); vendor-specific templates | Milestone 3 | Cacti maintainers | -| Attach to existing devices (#10) | Existing device (proposed); plugin-owned devices | Milestone 3 | Cacti maintainers | +| Common metric model (#9) | Decided 2026-11-15: common core plus vendor extensions ([ADR 0009](decisions/0009-common-metric-core-with-vendor-extensions.md)) | Milestone 3 | Owner | +| Attach to existing devices (#10) | Decided 2026-11-15: attach to the existing device, create one only on request ([ADR 0010](decisions/0010-attach-to-existing-node-devices.md)) | Milestone 3 | Owner | | Repository home and name (#11) | `Cacti/plugin_gpu` (proposed); community plugin | Before code is published | Cacti maintainers | | Test harness (#12) | Whatever maintained plugins use | Milestone 2 | Cacti maintainers | | MIG representation (#13) | Indexes, separate data query, parent only | Milestone 6 | #20 | diff --git a/docs/decisions/0009-common-metric-core-with-vendor-extensions.md b/docs/decisions/0009-common-metric-core-with-vendor-extensions.md new file mode 100644 index 0000000..c7a9a75 --- /dev/null +++ b/docs/decisions/0009-common-metric-core-with-vendor-extensions.md @@ -0,0 +1,25 @@ +# 0009. One common metric core, with vendor extensions in their own templates + +Status: Accepted (2026-11-15). Decides #9. + +## Context + +NVIDIA and AMD tools report overlapping metrics under different names, units, and scales, and DCGM reports some of them as ratios where `nvidia-smi` prints percentages. A field set shared by every backend lets one data query, one set of graph templates, and one set of Thold templates cover a mixed fleet. Vendor-specific templates would keep each tool's own terms but double the templates and the thresholds, and a mixed fleet could not be graphed side by side. The plan proposed the common core; the owner accepted the proposed option on 2026-11-15. + +## Decision + +- The plugin defines one metric model in code (`MetricModel`). Each field has one data source name of at most 19 characters, one unit, its kind (gauge or 0/1 indicator), its range, and its source per backend. The table in [`docs/metrics.md`](../metrics.md) is generated from the model, and a test keeps the two equal. +- Utilization is percent 0 to 100, memory is bytes, temperature is degrees C, power is watts, and clocks are MHz, whatever the source scale or unit. A backend converts at parse time. +- ECC and retired-page fields are gauges of the reported total. Throttle reasons are decoded from the reported bitmask into 0/1 indicators named `thr_*`, and the raw mask is kept in the cache so that bits the decoder does not know are not lost. +- A field a backend cannot supply is unknown (`U`) for that backend and is never estimated. +- Fields only one vendor reports go into separate, vendor-named templates. The milestone 3 field set has none; every field in it has an NVIDIA source today and a proposed AMD source pending #18. + +## Consequences + +- One GPU data query, one data template, and one set of graph templates serve every backend. Adding the AMD backend adds parse rules, not templates. +- Field names are fixed once templates ship. Renaming one later means a template migration, so the names were checked against Cacti's 19-character data source item limit before release. +- A field that exists on one vendor only (for example a DCGM-only health signal) cannot join the core without a source for every vendor. + +## Alternatives rejected + +- **Fully vendor-specific templates.** Faithful to each tool, but it doubles the graph and Thold templates and splits a mixed fleet across two sets of graphs. diff --git a/docs/decisions/0010-attach-to-existing-node-devices.md b/docs/decisions/0010-attach-to-existing-node-devices.md new file mode 100644 index 0000000..e7229ca --- /dev/null +++ b/docs/decisions/0010-attach-to-existing-node-devices.md @@ -0,0 +1,25 @@ +# 0010. Attach the GPU data query to the node's existing Cacti device + +Status: Accepted (2026-11-15). Decides #10. + +## Context + +GPU nodes are usually already Cacti devices, monitored over SNMP for CPU, memory, and interfaces. The plugin can add its data query to that device, or create a device of its own for each node. ADR 0004 already makes each GPU an index of a data query on the node's device, and ADR 0008 reads the GPU output through SNMP on that device, with the credentials Cacti holds for it. The plan proposed attaching to the existing device; the owner accepted the proposed option on 2026-11-15. + +## Decision + +- An operator maps a node to an existing Cacti device on the GPU Nodes page. Saving the mapping is the confirmation: the plugin never infers a mapping from host names or addresses. +- Only devices the acting user may see are offered or accepted. +- On save, the plugin adds the GPU data query to that device through Cacti's API (`api_device_dq_add()`) with reindex method None, and it repairs the attachment if a later device template change removes or resets it. +- The plugin creates a device only when an operator asks for one because none exists. It uses Cacti's `api_device_save()` with the site's device defaults and the plugin's GPU Node device template, and the operator then edits the SNMP settings on Cacti's own device page. +- Deleting a mapped device disables its node through the `device_remove` hook. The node and its GPU records stay, and so do the device's graphs, data sources, and RRD files until Cacti's own device deletion removes them. + +## Consequences + +- GPU graphs sit next to the node's other graphs, under the device's permissions, and Thold and Maint scope them through the device as they do for every other graph. +- The plugin must not assume the device's host fields describe anything but the SNMP agent: the GPU path is the agent's `extend` table (ADR 0008). +- All device and data query changes go through Cacti's API functions, never direct writes to Cacti's tables. + +## Alternatives rejected + +- **Plugin-owned devices.** Isolates plugin objects, but splits one machine across two devices and complicates Thold and Maint scoping. diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 4f74b57..f309557 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -12,5 +12,7 @@ Each record captures one architecture decision: its context, the decision, its c | [0006](0006-php-82-floor-with-80-parse-guard.md) | Require PHP 8.2, keep entry points parseable on PHP 8.0 | Accepted | | [0007](0007-run-vendor-tools-with-fixed-argument-lists.md) | Run vendor tools with fixed argument lists, no shell, and no elevated privilege | Accepted | | [0008](0008-collect-through-snmp-extend.md) | Collect through SNMP `extend` on the GPU node | Accepted | +| [0009](0009-common-metric-core-with-vendor-extensions.md) | One common metric core, with vendor extensions in their own templates | Accepted | +| [0010](0010-attach-to-existing-node-devices.md) | Attach the GPU data query to the node's existing Cacti device | Accepted | -Open decisions are tracked as issues labelled `type: decision`. The collection path (#7) was decided on 2026-11-15 in record 0008. +Open decisions are tracked as issues labelled `type: decision`. The collection path (#7) was decided on 2026-11-15 in record 0008, the common metric model (#9) in record 0009, and attaching to existing devices (#10) in record 0010. diff --git a/docs/metrics.md b/docs/metrics.md new file mode 100644 index 0000000..7fbbcf9 --- /dev/null +++ b/docs/metrics.md @@ -0,0 +1,41 @@ +# GPU metric model + +Every backend fills the same fields ([ADR 0009](decisions/0009-common-metric-core-with-vendor-extensions.md)). Each field is one data source item of the GPU data template and one output field of the GPU data query, so one set of graph and Thold templates covers every vendor. The table between the markers is generated from `lib/MetricModel.php` (`MetricModel::table()`), and a unit test fails when the two differ. + +Milestone 3 implements the nvidia-smi column. The DCGM and AMD columns record the source a later backend will read, with the research issue that confirms it where it is not settled. + + +| Field | Meaning | Unit | Kind | Range | nvidia-smi source | DCGM source | AMD source | +|---|---|---|---|---|---|---|---| +| `util_gpu` | GPU utilization | percent | gauge | 0 to 100 | `utilization.gpu` | 1613 (ratio 0.0 to 1.0, times 100), or 203 (percent, deprecated) | `metric --usage` `gfx_activity` (#18) | +| `util_mem` | Memory controller utilization | percent | gauge | 0 to 100 | `utilization.memory` | 1614 (ratio 0.0 to 1.0, times 100), or 204 (unit not stated, #15) | `metric --usage` `umc_activity` (#18) | +| `mem_used` | Frame buffer memory used | bytes | gauge | 0 to U | `memory.used` (MiB, times 1,048,576) | 1627 (used, bytes), or 252 (MiB, deprecated) | `metric --mem-usage` `used_vram` (MiB, #18) | +| `mem_total` | Frame buffer memory total | bytes | gauge | 0 to U | `memory.total` (MiB, times 1,048,576) | 1625 (capacity, bytes), or 250 (MiB, deprecated); 1626 is free bytes and is not used | `metric --mem-usage` `total_vram` (MiB, #18) | +| `temp_gpu` | GPU temperature | degrees C | gauge | U to U | `temperature.gpu` | 150 | `metric --temperature` `edge` (#18) | +| `power` | Board power draw | watts | gauge | 0 to U | `power.draw` | 155 | `metric --power` `socket_power` | +| `power_limit` | Board power limit | watts | gauge | 0 to U | `power.limit` | 160 | #18 | +| `clock_sm` | SM clock | MHz | gauge | 0 to U | `clocks.sm` | 1603 (hertz, divided by 1,000,000), or 100 (unit not stated) | `metric --clock` (#18) | +| `clock_mem` | Memory clock | MHz | gauge | 0 to U | `clocks.mem` | 1604 (hertz, divided by 1,000,000), or 101 (unit not stated) | `metric --clock` (#18) | +| `ecc_corr` | Corrected ECC errors since driver load | count | gauge | 0 to U | `ecc.errors.corrected.volatile.total` | 310 | `metric --ecc` `total_correctable_count` | +| `ecc_uncorr` | Uncorrected ECC errors since driver load | count | gauge | 0 to U | `ecc.errors.uncorrected.volatile.total` | 311 | `metric --ecc` `total_uncorrectable_count` | +| `retired_pending` | Page retirement pending | 0 or 1 | indicator | 0 to 1 | `retired_pages.pending` | 392 | #18 | +| `thr_sw_power_cap` | Clocks held by the software power cap | 0 or 1 | indicator | 0 to 1 | `clocks_throttle_reasons.active`, bit 0x4 | field 112, bit 0x4 | `metric --violation` (MI300 or newer, #18) | +| `thr_hw_slowdown` | Hardware slowdown | 0 or 1 | indicator | 0 to 1 | `clocks_throttle_reasons.active`, bit 0x8 | field 112, bit 0x8 | not applicable | +| `thr_sw_thermal` | Software thermal slowdown | 0 or 1 | indicator | 0 to 1 | `clocks_throttle_reasons.active`, bit 0x20 | field 112, bit 0x20 | `metric --violation` (MI300 or newer, #18) | +| `thr_hw_thermal` | Hardware thermal slowdown | 0 or 1 | indicator | 0 to 1 | `clocks_throttle_reasons.active`, bit 0x40 | field 112, bit 0x40 | `metric --violation` (MI300 or newer, #18) | +| `thr_hw_power_brake` | Hardware power brake | 0 or 1 | indicator | 0 to 1 | `clocks_throttle_reasons.active`, bit 0x80 | field 112, bit 0x80 | not applicable | +| `age` | Seconds since the tool took the sample | seconds | gauge | 0 to U | computed from `timestamp` | computed from the sample timestamp | computed from the sample timestamp | + + +## Rules + +- A missing, unsupported, or stale value is stored and printed as `U`, never 0 (REQ-METRIC-004). nvidia-smi placeholders such as `N/A`, `[N/A]`, and `[Not Supported]`, and any other text in a numeric column, are unknown. +- Utilization is percent 0 to 100 whatever the source scale (REQ-METRIC-002). DCGM field 1613 is a ratio from 0.0 to 1.0 and is multiplied by 100. +- Memory is bytes (REQ-METRIC-003). nvidia-smi prints MiB with `nounits`; the unit in CSV output is a live check in #14. DCGM fields 1627 (used) and 1625 (capacity) are bytes; 1626 is free bytes and is not part of the model. +- ECC values are gauges of the reported total since the driver was loaded (REQ-METRIC-005). A driver reload resets them to 0, so a threshold on the total can clear after a reboot without the cause being fixed. +- Throttle indicators are 1 when their bit is set in the clock event reasons mask and 0 when it is clear, and unknown when the mask is. The mask is parsed as hexadecimal (`0x` prefix) or decimal. `thr_hw_slowdown` (0x8) keeps its own indicator until a live check (#17) shows whether it ever occurs without 0x40 or 0x80. The raw mask is kept in the plugin's cache, so bits without an indicator, including any a later driver adds, are not lost. +- `age` is the seconds since the tool took its sample, from the sample's own timestamp, never from when the plugin read it (REQ-METRIC-006). It is unknown only for a GPU that was never sampled, so a stopped collection shows as a growing age that Thold can alert on. +- Data source names are at most 19 characters, Cacti's limit. The plan's `throttle_*` names became `thr_*` because `throttle_sw_power_cap`, `throttle_hw_slowdown`, and `throttle_hw_power_brake` are longer. +- A field a backend cannot supply is unknown for that backend and is not estimated (REQ-METRIC-007). + +Each cached sample also records its observation time, ingestion time, backend, and tool version. diff --git a/docs/node-setup.md b/docs/node-setup.md new file mode 100644 index 0000000..060e96c --- /dev/null +++ b/docs/node-setup.md @@ -0,0 +1,65 @@ +# Setting up a GPU node + +The plugin reads each GPU node's `nvidia-smi` output through the node's SNMP agent, using NET-SNMP-EXTEND-MIB ([ADR 0008](decisions/0008-collect-through-snmp-extend.md)). The node's administrator adds two `extend` entries to `snmpd.conf`; the plugin sends the agent nothing but read requests, through the SNMP settings of the node's Cacti device. Nothing is installed on the node besides `snmpd` (net-snmp). + +## snmpd.conf + +Add these lines exactly as shown. The entry names, the field list, and its order are what the plugin parses; a changed list is rejected as invalid output, not misread. + + +``` +extend -cacheTime 30 cacti_gpu /usr/bin/env -i TZ=UTC /usr/bin/timeout -k 2 10 /usr/bin/nvidia-smi --query-gpu=timestamp,uuid,index,pci.bus_id,driver_version,utilization.gpu,utilization.memory,memory.used,memory.total,temperature.gpu,power.draw,power.limit,clocks.sm,clocks.mem,ecc.errors.corrected.volatile.total,ecc.errors.uncorrected.volatile.total,retired_pages.pending,clocks_throttle_reasons.active --format=csv,noheader,nounits +extend -cacheTime 300 cacti_gpu_names /usr/bin/env -i /usr/bin/timeout -k 2 10 /usr/bin/nvidia-smi --query-gpu=uuid,name --format=csv,noheader +``` + + +What each part does: + +- `extend` without `-execType sh` runs the program with a fixed argument vector and no shell. Nothing from Cacti, the node, or a GPU reaches the command line. +- `/usr/bin/env -i` starts the tool with an empty environment. The metrics entry sets only `TZ=UTC`, because `nvidia-smi` prints its sample time without a time zone and the plugin reads it as UTC. +- `/usr/bin/timeout -k 2 10` stops the tool after 10 seconds and kills it 2 seconds later. snmpd waits for its child with no timeout of its own, so without this a hung `nvidia-smi` can block the agent. +- `-cacheTime 30` keeps one sample for 30 seconds, and the timeout is below that window, so a run always ends before the next can start. Every Cacti poll inside the window sees the same sample, and the plugin reports the sample's own age. +- The GPU names come from a separate entry because a product name is free text that can contain the CSV separator. Names change rarely, so that entry is cached for 5 minutes. +- Both commands are well under extend's 510-byte limit for a command and its arguments. + +The plugin treats each of these as a failed collection with unknown values, not as data: a nonzero exit status (including the timeout), output cut at snmpd's 100 KiB or 1024-line limit, a line with more or fewer fields than requested, and any other text in the output, such as an error message that snmpd merged in from stderr. + +The metrics entry reads the clock event reasons as `clocks_throttle_reasons.active`, the name confirmed on every supported driver line; nvidia-smi renamed the reasons and then added the old query names back. `clocks_event_reasons.active` prints the same bitmask in the same position and may be used instead once #17 confirms it on your driver. + +## Run snmpd as an unprivileged user + +An `extend` command runs as the user `snmpd` runs as, which is root unless `agentuser` or `-u` is set. The fields above need no privilege ([research/privileges.md](research/privileges.md)). Run the agent as an unprivileged account: + +``` +agentuser Debian-snmp +``` + +Use the account your distribution's snmpd package provides (Debian and Ubuntu ship `Debian-snmp` and start snmpd with `-u Debian-snmp`), or create one. The plugin cannot see which user ran the command, so confirm it while a collection runs, for example with `ps -o user= -C nvidia-smi`. Which user each distribution uses by default is a live check in #22. + +## SNMPv3 is the default + +Use SNMPv3 with authentication and privacy, and limit the user to the system group and the extend tables: + +``` +view cactigpu included .1.3.6.1.2.1.1 +view cactigpu included .1.3.6.1.4.1.8072.1.3.2 +rouser -s usm cactigpu priv -V cactigpu +``` + +Create the user with `net-snmp-create-v3-user`, or with a `createUser cactigpu SHA-256 AES ` line in snmpd's persistent configuration (`/var/lib/snmp/snmpd.conf` on Debian and Ubuntu), added while snmpd is stopped. Then set the node's Cacti device to SNMP version 3 with the same user, SHA-256 authentication, and AES privacy. + +SNMP v1 and v2c also work, but they send the community and every value in plaintext. If you use them, restrict the community to the same view and to the Cacti poller's address, for example `rocommunity -V cactigpu`. + +## In Cacti + +1. Make sure the node is a Cacti device with working SNMP settings. If it is not, GPU Nodes can create one from the site's device defaults; set its SNMP settings on Cacti's device page afterwards. +2. In **Console > Management > GPU Nodes**, add a node for the device. Saving the node adds the GPU data query to the device. +3. The collector runs at the end of every poller cycle. Each GPU it finds becomes an index of the GPU data query, and the plugin creates the GPU graphs for it. + +Nodes on remote data collectors are not collected yet; remote collectors are phase 3. + +### An SNMP port other than 161 on Cacti 1.2.x + +Cacti's 1.2.x branch (after 1.2.31) puts the device's address in brackets for a single SNMP get when the port is not 161, as in `[192.0.2.10]:1161`. PHP's SNMP extension reads a bracketed name as an IPv6 address, so the get fails for an IPv4 address or for a host name with no IPv6 address, with `Unknown failure while resolving '[192.0.2.10]:1161'` in Cacti's log. Cacti 1.2.31 and a node on port 161 are not affected. + +The plugin reads the node through a Cacti SNMP session, as Cacti's poller does, which brackets only an address that contains a colon, so collection works on any port. Cacti's own SNMP availability check uses the single get, though, so with cmd.php as the poller a node on another port is marked down and the plugin then waits to reindex it. On Cacti 1.2.x, until that is fixed in Cacti, keep the node's agent on port 161, or set the device's Downed Device Detection to Ping or None. The end-to-end test does the latter. diff --git a/gpu_nodes.php b/gpu_nodes.php index 6ab6a63..958f835 100644 --- a/gpu_nodes.php +++ b/gpu_nodes.php @@ -31,12 +31,68 @@ exit; } -gpu_require_post('gpu_nodes.php', array('save', 'delete', 'confirm_move', 'reject_move')); +gpu_require_post('gpu_nodes.php', array('save', 'delete', 'confirm_move', 'reject_move', 'retire', 'create_device')); -$gpu_nodes = gpu_nodes(); -$gpu_gpus = gpu_gpus(); -$gpu_page = new \Somethingwithproof\Gpu\NodesPage($gpu_nodes, $gpu_gpus); -$gpu_action = (string) get_nfilter_request_var('action'); +$gpu_nodes = gpu_nodes(); +$gpu_gpus = gpu_gpus(); +$gpu_clock = new \Somethingwithproof\Gpu\SystemClock(); +$gpu_reindex = new \Somethingwithproof\Gpu\ReindexRepository(false); +// Every node and GPU action is checked against Cacti's device permissions +// for the node's device (and both nodes' for a move) before any write. +$gpu_access = new \Somethingwithproof\Gpu\NodeAccess(function (int $id): bool { + return is_device_allowed($id); +}); +$gpu_page = new \Somethingwithproof\Gpu\NodesPage($gpu_nodes, $gpu_gpus, $gpu_access, new \Somethingwithproof\Gpu\CollectionRepository(false), $gpu_clock); +$gpu_action = (string) get_nfilter_request_var('action'); +// Creating a device needs Cacti's own device management permission, the +// realm of host.php, in addition to GPU Admin. +$gpu_can_create = is_realm_allowed(3); + +/** + * Refuse an action on a node or GPU the user may not act on, the same way + * whether it does not exist or is on a device the user cannot see. + * + * @return never + */ +function gpu_nodes_refuse(): void { + raise_message('gpu_denied', __('That GPU node or GPU does not exist, or is on a device you do not have access to.', 'gpu'), MESSAGE_LEVEL_ERROR); + header('Location: gpu_nodes.php'); + exit; +} + +/** + * The GPU record and its node or nodes, when the user may act on them. + */ +function gpu_nodes_gpu(\Somethingwithproof\Gpu\NodeAccess $access, int $id, bool $move = true): \Somethingwithproof\Gpu\GpuRecord { + $record = gpu_gpus()->find($id); + $nodes = array(); + + if ($record !== null) { + // A move needs both nodes; anything else only the GPU's own node. + foreach ($move ? array($record->nodeId, $record->pendingNodeId) : array($record->nodeId) as $node_id) { + $node = $node_id > 0 ? gpu_nodes()->find($node_id) : null; + + if ($node !== null) { + $nodes[$node->id] = $node; + } + } + } + + if ($record === null || !($move ? $access->canManageGpu($record, $nodes) : $access->canManage($nodes[$record->nodeId] ?? null))) { + gpu_nodes_refuse(); + } + + return $record; +} + +/** + * Attach the GPU data query to a saved, enabled node's device. + */ +function gpu_nodes_attach(\Somethingwithproof\Gpu\Node $node): void { + if ($node->enabled() && $node->deviceExists && !gpu_provisioner()->attach($node)) { + raise_message('gpu_attach', __('The GPU data query could not be added to the device. Check that the plugin\'s templates are installed.', 'gpu'), MESSAGE_LEVEL_WARN); + } +} switch ($gpu_action) { case 'save': @@ -46,17 +102,17 @@ $gpu_node = $gpu_id > 0 ? $gpu_nodes->find($gpu_id) : null; $gpu_errors = array(); - if ($gpu_id > 0 && $gpu_node === null) { - header('Location: gpu_nodes.php'); - exit; - } + // An existing node needs access to its device. The one exemption: a + // node whose device was deleted may be disabled, and nothing else. + $gpu_disable_only = $gpu_node !== null && !$gpu_node->deviceExists; - // Keeping the recorded device is always allowed, even once it was - // deleted, so a node can still be disabled; a change must name a - // device that exists. - $gpu_same_host = $gpu_node !== null && $gpu_host === $gpu_node->hostId; + if ($gpu_id > 0 && !($gpu_access->canManage($gpu_node) || $gpu_disable_only)) { + gpu_nodes_refuse(); + } - if (!$gpu_same_host && !$gpu_nodes->deviceExists($gpu_host)) { + if ($gpu_disable_only && ($gpu_host !== $gpu_node->hostId || $gpu_enabled)) { + $gpu_errors['host_id'] = __('Device: the node\'s device was deleted, so the node can only be disabled.', 'gpu'); + } elseif (!$gpu_disable_only && (!$gpu_nodes->deviceExists($gpu_host) || !$gpu_access->deviceAllowed($gpu_host))) { $gpu_errors['host_id'] = __('Device: choose an existing Cacti device.', 'gpu'); } elseif ($gpu_nodes->hostTaken($gpu_host, $gpu_id)) { $gpu_errors['host_id'] = __('Device: this device is already a GPU node.', 'gpu'); @@ -71,8 +127,16 @@ $gpu_state = $gpu_enabled ? \Somethingwithproof\Gpu\AdminState::Enabled : \Somethingwithproof\Gpu\AdminState::Disabled; - if ($gpu_nodes->save($gpu_id, $gpu_host, $gpu_state) > 0) { + $gpu_saved = $gpu_nodes->save($gpu_id, $gpu_host, $gpu_state); + + if ($gpu_saved > 0) { raise_message('gpu_saved', __('The GPU node was saved.', 'gpu'), MESSAGE_LEVEL_INFO); + + $gpu_node = $gpu_nodes->find($gpu_saved); + + if ($gpu_node !== null && $gpu_access->canManage($gpu_node)) { + gpu_nodes_attach($gpu_node); + } } else { raise_message('gpu_saved', __('The GPU node could not be saved.', 'gpu'), MESSAGE_LEVEL_ERROR); } @@ -80,7 +144,13 @@ header('Location: gpu_nodes.php'); exit; case 'delete': - if ($gpu_nodes->delete((int) get_filter_request_var('id'))) { + $gpu_node = $gpu_nodes->find((int) get_filter_request_var('id')); + + if (!$gpu_access->canManage($gpu_node)) { + gpu_nodes_refuse(); + } + + if ($gpu_nodes->delete($gpu_node->id)) { raise_message('gpu_deleted', __('The GPU node was removed. Its Cacti device was left in place.', 'gpu'), MESSAGE_LEVEL_INFO); } else { raise_message('gpu_deleted', __('The GPU node was not removed because GPU records belong to it. Disable it instead; GPU records are never deleted.', 'gpu'), MESSAGE_LEVEL_WARN); @@ -89,17 +159,72 @@ header('Location: gpu_nodes.php'); exit; case 'confirm_move': - if ($gpu_gpus->confirmMove((int) get_filter_request_var('id'))) { + $gpu_record = gpu_nodes_gpu($gpu_access, (int) get_filter_request_var('id')); + + // Applied only as authorized: if a collection changed the pending + // node since it was read, nothing moves. + if ($gpu_gpus->confirmMove($gpu_record->id, $gpu_record->nodeId, $gpu_record->pendingNodeId)) { + // Both nodes' data query listings changed. + $gpu_reindex->request($gpu_record->nodeId, 'GPU moved away', $gpu_clock->now()); + $gpu_reindex->request($gpu_record->pendingNodeId, 'GPU moved here', $gpu_clock->now()); + raise_message('gpu_move', __('The GPU now belongs to the node it was seen at, with its history.', 'gpu'), MESSAGE_LEVEL_INFO); } header('Location: gpu_nodes.php'); exit; case 'reject_move': - if ($gpu_gpus->rejectMove((int) get_filter_request_var('id'))) { + $gpu_record = gpu_nodes_gpu($gpu_access, (int) get_filter_request_var('id')); + + if ($gpu_gpus->rejectMove($gpu_record->id, $gpu_record->nodeId, $gpu_record->pendingNodeId)) { raise_message('gpu_move', __('The GPU stays with its recorded node.', 'gpu'), MESSAGE_LEVEL_INFO); } + header('Location: gpu_nodes.php'); + exit; + case 'retire': + $gpu_record = gpu_nodes_gpu($gpu_access, (int) get_filter_request_var('id'), false); + $gpu_user = isset($_SESSION[SESS_USER_ID]) ? (int) $_SESSION[SESS_USER_ID] : 0; + + if ($gpu_gpus->retire($gpu_record->id, $gpu_record->nodeId, $gpu_user, $gpu_clock->now())) { + $gpu_reindex->request($gpu_record->nodeId, 'GPU retired', $gpu_clock->now()); + + raise_message('gpu_retire', __('The GPU will leave the data query at the next reindex. Its graphs and RRD files are kept.', 'gpu'), MESSAGE_LEVEL_INFO); + } else { + raise_message('gpu_retire', __('Only an absent GPU can be removed from the data query.', 'gpu'), MESSAGE_LEVEL_WARN); + } + + header('Location: gpu_nodes.php?action=edit&id=' . $gpu_record->nodeId); + exit; + case 'create_device': + $gpu_description = trim((string) get_nfilter_request_var('description')); + $gpu_hostname = trim((string) get_nfilter_request_var('hostname')); + $gpu_template = (new \Somethingwithproof\Gpu\CactiObjectRepository(false))->idByHash('host_template', \Somethingwithproof\Gpu\TemplateXml::hash('02', \Somethingwithproof\Gpu\TemplateXml::DEVICE_TEMPLATE)); + + if (!$gpu_can_create) { + raise_message('gpu_device', __('Creating a device needs permission to manage Cacti devices.', 'gpu'), MESSAGE_LEVEL_ERROR); + } elseif ($gpu_description === '' || strlen($gpu_description) > 150 || preg_match('/[\x00-\x1F\x7F]/', $gpu_description) === 1) { + raise_message('gpu_device', __('Description: enter up to 150 printable characters.', 'gpu'), MESSAGE_LEVEL_ERROR); + } elseif (preg_match('/^[A-Za-z0-9][A-Za-z0-9.:_-]{0,99}$/', $gpu_hostname) !== 1) { + raise_message('gpu_device', __('Hostname: enter a host name or IP address.', 'gpu'), MESSAGE_LEVEL_ERROR); + } elseif ($gpu_template === 0) { + raise_message('gpu_device', __('The GPU Node device template is not installed.', 'gpu'), MESSAGE_LEVEL_ERROR); + } else { + $gpu_host = gpu_create_device($gpu_description, $gpu_hostname, $gpu_template); + // The new device is checked like any other: under a restrictive + // device policy the user may not see a device they just created. + $gpu_id = $gpu_host > 0 && $gpu_access->deviceAllowed($gpu_host) && !$gpu_nodes->hostTaken($gpu_host, 0) ? $gpu_nodes->save(0, $gpu_host, \Somethingwithproof\Gpu\AdminState::Enabled) : 0; + $gpu_node = $gpu_id > 0 ? $gpu_nodes->find($gpu_id) : null; + + if ($gpu_node !== null && $gpu_access->canManage($gpu_node)) { + gpu_nodes_attach($gpu_node); + + raise_message('gpu_device', __('The device and its GPU node were created. Set the device\'s SNMP settings on its device page.', 'gpu'), MESSAGE_LEVEL_INFO); + } else { + raise_message('gpu_device', __('The device could not be created; see the Cacti log.', 'gpu'), MESSAGE_LEVEL_ERROR); + } + } + header('Location: gpu_nodes.php'); exit; case 'export': @@ -109,13 +234,29 @@ header('Content-Disposition: attachment; filename="gpu-records-' . gmdate('Ymd-His') . '.json"'); header('X-Content-Type-Options: nosniff'); - print \Somethingwithproof\Gpu\InventoryExport::json($gpu_nodes->all(), $gpu_gpus->all(), $gpu_info['version'], (new \Somethingwithproof\Gpu\SystemClock())->now()); + // Only nodes the user may manage, with their GPUs: a node whose + // device was deleted can no longer be checked, so it is left out. + $gpu_export = array_values(array_filter($gpu_nodes->all(), function ($node) use ($gpu_access) { + return $gpu_access->canManage($node); + })); + $gpu_by_id = array(); + + foreach ($gpu_export as $gpu_export_node) { + $gpu_by_id[$gpu_export_node->id] = $gpu_export_node; + } + + print \Somethingwithproof\Gpu\InventoryExport::json($gpu_export, $gpu_access->visibleGpus($gpu_gpus->all(), $gpu_by_id), $gpu_info['version'], $gpu_clock->now()); exit; case 'edit': - $gpu_id = (int) get_filter_request_var('id'); + $gpu_id = (int) get_filter_request_var('id'); + $gpu_node = $gpu_id > 0 ? $gpu_nodes->find($gpu_id) : null; + + if ($gpu_id > 0 && !$gpu_access->canSee($gpu_node)) { + gpu_nodes_refuse(); + } top_header(); - $gpu_page->renderEdit($gpu_id > 0 ? $gpu_nodes->find($gpu_id) : null); + $gpu_page->renderEdit($gpu_node, 0, null, array(), $gpu_can_create); bottom_footer(); exit; default: diff --git a/lib/CacheRepository.php b/lib/CacheRepository.php new file mode 100644 index 0000000..030df80 --- /dev/null +++ b/lib/CacheRepository.php @@ -0,0 +1,88 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu; + +/** + * The reads behind the script server input (REQ-SS-001): GPU records, + * stored samples, and collection results, never a GPU node. Each call is + * one indexed query, so a poll stays well under 50 ms with 10,000 GPUs in + * the cache (REQ-SS-005). + */ +final class CacheRepository { + private const COLUMNS = 'g.id, g.vendor, g.uuid, g.gpu_index, g.name, g.pci_bus_id, g.presence'; + + public function __construct(private readonly \PDO|false $connection) { + } + + /** + * Every GPU at the node of a Cacti device that the data query lists: + * present and absent alike, so Cacti keeps the data sources of absent + * GPUs attached (REQ-INDEX-002), but not those an operator removed. + * + * @return list>|null null when the read failed + */ + public function listed(int $hostId): ?array { + $rows = db_fetch_assoc_prepared( + 'SELECT ' . self::COLUMNS . ' FROM plugin_gpu_node AS n + INNER JOIN plugin_gpu_gpu AS g ON g.node_id = n.id + LEFT JOIN plugin_gpu_retired AS r ON r.gpu_id = g.id + WHERE n.host_id = ? AND r.gpu_id IS NULL + ORDER BY g.gpu_index IS NULL, g.gpu_index, g.vendor, g.uuid', + [$hostId], + true, + $this->connection, + ); + + return is_array($rows) ? Row::rows($rows) : null; + } + + /** + * Every listed GPU with its stored sample and its node's latest + * collection, for a query of one value across the indexes. + * + * @return list>|null + */ + public function samples(int $hostId): ?array { + $rows = db_fetch_assoc_prepared(self::sampleSelect() . ' WHERE n.host_id = ? AND r.gpu_id IS NULL', [$hostId], true, $this->connection); + + return is_array($rows) ? Row::rows($rows) : null; + } + + /** + * One GPU's stored sample, by the data query index (vendor/UUID). + * + * @return array|null + */ + public function sample(int $hostId, Vendor $vendor, string $uuid): ?array { + $row = db_fetch_row_prepared(self::sampleSelect() . ' WHERE g.vendor = ? AND g.uuid = ? AND n.host_id = ? AND r.gpu_id IS NULL', [$vendor->value, $uuid, $hostId], true, $this->connection); + + return is_array($row) && $row !== [] ? $row : null; + } + + private static function sampleSelect(): string { + return 'SELECT ' . self::COLUMNS . ', o.observed_at, o.reported_at, o.' . implode(', o.', Schema::OBSERVATION_METRICS) . ', + c.state AS collection_state, c.finished_at AS collection_finished_at + FROM plugin_gpu_gpu AS g + INNER JOIN plugin_gpu_node AS n ON n.id = g.node_id + LEFT JOIN plugin_gpu_retired AS r ON r.gpu_id = g.id + LEFT JOIN plugin_gpu_observation AS o ON o.gpu_id = g.id AND o.node_id = g.node_id + LEFT JOIN plugin_gpu_collection AS c ON c.node_id = g.node_id'; + } +} diff --git a/lib/CactiObjectRepository.php b/lib/CactiObjectRepository.php new file mode 100644 index 0000000..ba8bd34 --- /dev/null +++ b/lib/CactiObjectRepository.php @@ -0,0 +1,175 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu; + +/** + * Reads of Cacti's own objects that the plugin shipped or attaches to. The + * plugin never writes these tables: objects change only through Cacti's + * APIs (REQ-DEV-004). + */ +final class CactiObjectRepository { + public function __construct(private readonly \PDO|false $connection) { + } + + /** + * The site's default data source profile, as core's template import + * picks it. + */ + public function defaultProfileId(): int { + return (int) db_fetch_cell_prepared('SELECT id FROM data_source_profiles ORDER BY `default` DESC, id LIMIT 1', [], '', true, $this->connection); + } + + /** + * The id of an object by its export hash (the 32 hex characters after + * the type and version codes), or 0. + * + * @param 'snmp_query'|'host_template'|'data_template'|'graph_templates' $table + */ + public function idByHash(string $table, string $hash): int { + return (int) db_fetch_cell_prepared("SELECT id FROM `$table` WHERE hash = ?", [substr($hash, -32)], '', true, $this->connection); + } + + /** + * The device's reindex method for a data query, or null when the data + * query is not attached to the device. + */ + public function reindexMethod(int $hostId, int $dataQueryId): ?int { + $row = db_fetch_row_prepared('SELECT reindex_method FROM host_snmp_query WHERE host_id = ? AND snmp_query_id = ?', [$hostId, $dataQueryId], true, $this->connection); + + return is_array($row) && $row !== [] ? Row::int($row, 'reindex_method') : null; + } + + /** + * The indexes Cacti has cached for the device's data query, which is + * what its last reindex found. + * + * @return list|null null when the read failed + */ + public function cachedIndexes(int $hostId, int $dataQueryId): ?array { + $rows = db_fetch_assoc_prepared('SELECT DISTINCT snmp_index FROM host_snmp_cache WHERE host_id = ? AND snmp_query_id = ? ORDER BY snmp_index', [$hostId, $dataQueryId], true, $this->connection); + + return is_array($rows) ? array_map(static fn (array $row): string => Row::string($row, 'snmp_index'), Row::rows($rows)) : null; + } + + /** + * The values Cacti has cached for the given fields of the device's data + * query: index => field name => value, each index's fields in the order + * given. + * + * @param list $fields + * + * @return array>|null null when the read failed + */ + public function cachedFields(int $hostId, int $dataQueryId, array $fields): ?array { + $rows = db_fetch_assoc_prepared('SELECT snmp_index, field_name, field_value FROM host_snmp_cache WHERE host_id = ? AND snmp_query_id = ? AND field_name IN (' . implode(', ', array_fill(0, count($fields), '?')) . ')', array_merge([$hostId, $dataQueryId], $fields), true, $this->connection); + + if (!is_array($rows)) { + return null; + } + + $values = []; + + foreach (Row::rows($rows) as $row) { + $values[Row::string($row, 'snmp_index')][Row::string($row, 'field_name')] = Row::untrimmed($row, 'field_value'); + } + + $out = []; + + foreach ($values as $index => $byField) { + foreach ($fields as $field) { + if (isset($byField[$field])) { + $out[(string) $index][$field] = $byField[$field]; + } + } + } + + return $out; + } + + /** + * Whether Cacti would skip a reindex of the device now: it is down or + * disabled. Null when the device row could not be read. + */ + public function reindexBlocked(int $hostId): ?bool { + $row = db_fetch_row_prepared('SELECT status, disabled FROM host WHERE id = ?', [$hostId], true, $this->connection); + + if (!is_array($row) || $row === []) { + return null; + } + + return NodeDevice::fromRow($row + ['id' => $hostId])->reindexBlocked(); + } + + /** + * Remove every cached index of the device's data query and mark its + * data sources orphaned: what run_data_query() does for removed + * indexes, for the case it does not handle, a listing with none. + */ + public function clearIndexes(int $hostId, int $dataQueryId): bool { + $cleared = db_execute_prepared('DELETE FROM host_snmp_cache WHERE host_id = ? AND snmp_query_id = ?', [$hostId, $dataQueryId], true, $this->connection); + + return db_execute_prepared('UPDATE data_local SET orphan = 1 WHERE host_id = ? AND snmp_query_id = ?', [$hostId, $dataQueryId], true, $this->connection) && $cleared; + } + + /** + * The data query's graph types: snmp_query_graph id => graph template id. + * + * @return array + */ + public function queryGraphs(int $dataQueryId): array { + $out = []; + + foreach (Row::rows(db_fetch_assoc_prepared('SELECT id, graph_template_id FROM snmp_query_graph WHERE snmp_query_id = ? ORDER BY id', [$dataQueryId], true, $this->connection)) as $row) { + $out[Row::int($row, 'id')] = Row::int($row, 'graph_template_id'); + } + + return $out; + } + + /** + * The graphs the device already has for the data query, as + * "graph type id:index" keys. + * + * @return array|null + */ + public function graphed(int $hostId, int $dataQueryId): ?array { + $rows = db_fetch_assoc_prepared('SELECT snmp_query_graph_id, snmp_index FROM graph_local WHERE host_id = ? AND snmp_query_id = ?', [$hostId, $dataQueryId], true, $this->connection); + + if (!is_array($rows)) { + return null; + } + + $out = []; + + foreach (Row::rows($rows) as $row) { + $out[Row::int($row, 'snmp_query_graph_id') . ':' . Row::string($row, 'snmp_index')] = true; + } + + return $out; + } + + public function setting(string $name): string { + return (string) db_fetch_cell_prepared('SELECT value FROM settings WHERE name = ?', [$name], '', true, $this->connection); + } + + public function saveSetting(string $name, string $value): bool { + return (bool) db_execute_prepared('REPLACE INTO settings (name, value) VALUES (?, ?)', [$name, $value], true, $this->connection); + } +} diff --git a/lib/Collection.php b/lib/Collection.php new file mode 100644 index 0000000..70dcb21 --- /dev/null +++ b/lib/Collection.php @@ -0,0 +1,44 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu; + +/** + * A successful collection at one node: the identity snapshot and the values, + * taken from the same tool output (REQ-INV-001). + */ +final readonly class Collection { + /** + * @param list $readings one per report, in the same order + */ + public function __construct( + public GpuSnapshot $snapshot, + public array $readings, + public string $backend, + ) { + } + + public function state(): ExecutionState { + return $this->readings === [] ? ExecutionState::Empty : ExecutionState::Ok; + } + + public function newestSample(): int { + return $this->readings === [] ? 0 : max(array_map(static fn (Reading $reading): int => $reading->observedAt, $this->readings)); + } +} diff --git a/lib/CollectionError.php b/lib/CollectionError.php new file mode 100644 index 0000000..6d684bd --- /dev/null +++ b/lib/CollectionError.php @@ -0,0 +1,31 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu; + +/** + * A collection that produced no usable result. The message names what was + * wrong and never quotes tool output, which is untrusted and may hold host + * details; it is safe to log at the default level. + */ +final class CollectionError extends \RuntimeException { + public function __construct(public readonly ExecutionState $state, string $message, public readonly int $rejectedLines = 0) { + parent::__construct($message); + } +} diff --git a/lib/CollectionRepository.php b/lib/CollectionRepository.php new file mode 100644 index 0000000..07b2051 --- /dev/null +++ b/lib/CollectionRepository.php @@ -0,0 +1,77 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu; + +/** + * The latest collection result per node: one row each, overwritten by every + * run, so the table never grows with time. + */ +final class CollectionRepository { + public function __construct(private readonly \PDO|false $connection) { + } + + public function find(int $nodeId): ?CollectionStatus { + $row = db_fetch_row_prepared('SELECT * FROM plugin_gpu_collection WHERE node_id = ?', [$nodeId], true, $this->connection); + + return is_array($row) && $row !== [] ? CollectionStatus::fromRow($row) : null; + } + + /** + * @return array node id => status + */ + public function all(): array { + $out = []; + + foreach (Row::rows(db_fetch_assoc_prepared('SELECT * FROM plugin_gpu_collection', [], true, $this->connection)) as $row) { + $status = CollectionStatus::fromRow($row); + + $out[$status->nodeId] = $status; + } + + return $out; + } + + public function start(int $nodeId, int $now): void { + db_execute_prepared('INSERT INTO plugin_gpu_collection (node_id, started_at) VALUES (?, ?) ON DUPLICATE KEY UPDATE started_at = VALUES(started_at)', [$nodeId, $now], true, $this->connection); + } + + public function finish(int $nodeId, ExecutionState $state, string $detail, int $now, int $observedAt = 0, int $gpus = 0, int $newGpus = 0, int $rejectedLines = 0): bool { + $ok = $state->succeeded() ? $now : 0; + + return (bool) db_execute_prepared( + 'INSERT INTO plugin_gpu_collection (node_id, state, detail, started_at, finished_at, observed_at, gpus, new_gpus, rejected_lines, skipped, last_ok_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?) + ON DUPLICATE KEY UPDATE state = VALUES(state), detail = VALUES(detail), finished_at = VALUES(finished_at), + observed_at = IF(VALUES(observed_at) > 0, VALUES(observed_at), observed_at), gpus = VALUES(gpus), new_gpus = VALUES(new_gpus), + rejected_lines = VALUES(rejected_lines), skipped = 0, last_ok_at = IF(VALUES(last_ok_at) > 0, VALUES(last_ok_at), last_ok_at)', + [$nodeId, $state->value, mb_substr($detail, 0, 255), $now, $now, $observedAt, $gpus, $newGpus, $rejectedLines, $ok], + true, + $this->connection, + ); + } + + /** + * Count a run that found the node already being collected. The result + * of the run in progress stays. + */ + public function skipped(int $nodeId): void { + db_execute_prepared('INSERT INTO plugin_gpu_collection (node_id, skipped) VALUES (?, 1) ON DUPLICATE KEY UPDATE skipped = skipped + 1', [$nodeId], true, $this->connection); + } +} diff --git a/lib/CollectionStatus.php b/lib/CollectionStatus.php new file mode 100644 index 0000000..bf64f3e --- /dev/null +++ b/lib/CollectionStatus.php @@ -0,0 +1,71 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu; + +/** + * How the latest collection at one node went. A node never collected has + * no status. + */ +final readonly class CollectionStatus { + public function __construct( + public int $nodeId, + // Null while the first collection is still running. + public ?ExecutionState $state, + public string $detail, + public int $startedAt, + public int $finishedAt, + public int $observedAt, + public int $gpus, + public int $newGpus, + public int $rejectedLines, + public int $skipped, + public int $lastOkAt, + ) { + } + + /** + * @param array $row a plugin_gpu_collection row + */ + public static function fromRow(array $row): self { + $state = Row::string($row, 'state'); + + return new self( + nodeId: Row::int($row, 'node_id'), + state: $state === '' ? null : (ExecutionState::tryFrom($state) ?? ExecutionState::ToolError), + detail: Row::string($row, 'detail'), + startedAt: Row::int($row, 'started_at', 0, 0), + finishedAt: Row::int($row, 'finished_at', 0, 0), + observedAt: Row::int($row, 'observed_at', 0, 0), + gpus: Row::int($row, 'gpus', 0, 0), + newGpus: Row::int($row, 'new_gpus', 0, 0), + rejectedLines: Row::int($row, 'rejected_lines', 0, 0), + skipped: Row::int($row, 'skipped', 0, 0), + lastOkAt: Row::int($row, 'last_ok_at', 0, 0), + ); + } + + /** + * Whether the latest finished collection succeeded. A run that started + * after it and has not finished does not change the answer. + */ + public function succeeded(): bool { + return $this->state !== null && $this->state->succeeded(); + } +} diff --git a/lib/Collector.php b/lib/Collector.php new file mode 100644 index 0000000..d672b16 --- /dev/null +++ b/lib/Collector.php @@ -0,0 +1,218 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu; + +/** + * Collects one node: reads both extend entries, parses them, records the + * inventory, and stores the values, all from the same output (REQ-INV-001). + * + * A failed collection stores no value and changes no GPU record, so it can + * never mark a GPU absent (REQ-INV-003); its state is recorded instead. A + * collection that changes what the data query lists asks for a reindex + * (REQ-INDEX-004). + */ +final class Collector { + public function __construct( + private readonly ExtendReader $reader, + private readonly NvidiaSmiParser $parser, + private readonly Inventory $inventory, + private readonly GpuRepository $gpus, + private readonly ObservationRepository $observations, + private readonly CollectionRepository $collections, + private readonly ReindexRepository $reindex, + private readonly LockRepository $locks, + private readonly Clock $clock, + ) { + } + + public function collect(Node $node, NodeDevice $device, Settings $settings): ExecutionState { + // REQ-INV-005: nothing is recorded for a node that is not enabled. + if (!$node->enabled() || $device->id !== $node->hostId) { + return ExecutionState::Skipped; + } + + $lock = 'node_' . $node->id; + + if (!$this->locks->acquire($lock)) { + $this->collections->skipped($node->id); + + Log::info(sprintf('Node %d: collection skipped because another collection of it is still running', $node->id)); + + return ExecutionState::Skipped; + } + + try { + $previous = $this->collections->find($node->id); + + $this->collections->start($node->id, $this->clock->now()); + + [$state, $detail] = $this->run($node, $device, $settings); + } finally { + $this->locks->release($lock); + } + + $this->logChange($node, $previous, $state, $detail); + + return $state; + } + + /** + * @return array{ExecutionState, string} the state and its detail + */ + private function run(Node $node, NodeDevice $device, Settings $settings): array { + try { + $collection = $this->parser->parse( + $this->reader->read($device, SnmpdConfig::METRICS), + $this->reader->read($device, SnmpdConfig::NAMES), + ); + } catch (CollectionError $e) { + $this->collections->finish($node->id, $e->state, $e->getMessage(), $this->clock->now(), rejectedLines: $e->rejectedLines); + + return [$e->state, $e->getMessage()]; + } + + $changes = $this->inventory->record($node, $collection->snapshot, $settings->absentAfter); + $records = $this->gpus->forReconcile($node, $collection->snapshot); + + if ($records === null) { + $detail = 'The GPU records could not be read after the inventory was recorded'; + + $this->collections->finish($node->id, ExecutionState::NotStored, $detail, $this->clock->now()); + + return [ExecutionState::NotStored, $detail]; + } + + $byKey = []; + + foreach ($records as $record) { + $byKey[$record->key()] = $record; + } + + $now = $this->clock->now(); + $stored = 0; + $reported = []; + $missing = 0; + + // Ask for the reindex as soon as the records changed, so a failure + // to store the samples below does not lose it. + $reason = self::reindexReason($changes); + + if ($reason !== '') { + $this->reindex->request($node->id, $reason, $now); + } + + foreach ($collection->readings as $reading) { + $record = $byKey[$reading->report->key()] ?? null; + + // A GPU whose record belongs to another node is waiting for an + // operator to confirm the move (REQ-ID-004). Its values are not + // stored until then, so they never appear under the old node's + // graphs. + if ($record === null || $record->id === 0) { + // The record for a reported GPU should exist once the + // inventory was recorded; its insert failed. + $missing++; + + continue; + } + + if ($record->nodeId !== $node->id) { + continue; + } + + $reported[] = $record->id; + + if ($this->observations->store($record->id, $node->id, $reading, $collection->backend, $collection->snapshot->toolVersion, $now)) { + $stored++; + } + } + + $state = $collection->state(); + $total = count($collection->readings); + + if ($stored < count($reported) || $missing > 0) { + $detail = sprintf('%d of %d GPU samples could not be stored', count($reported) - $stored + $missing, count($reported) + $missing); + + $this->collections->finish($node->id, ExecutionState::NotStored, $detail, $now, $collection->newestSample(), $total, count($changes->created)); + + return [ExecutionState::NotStored, $detail]; + } + + $returned = $this->gpus->unretire($reported); + + if ($reason === '' && $returned > 0) { + $this->reindex->request($node->id, 'retired GPU returned', $now); + } + + if (!$this->collections->finish($node->id, $state, '', $now, $collection->newestSample(), $total, count($changes->created))) { + $detail = 'The collection status could not be stored'; + + Log::warning(sprintf('Node %d: %s', $node->id, $detail)); + + return [ExecutionState::NotStored, $detail]; + } + + return [$state, '']; + } + + /** + * Why the node's data query needs a reindex after this collection, or '' + * when its listing is unchanged. The listing holds each GPU at the node + * with its index, name, and bus ID, so a change to any of those, a new + * GPU, a GPU moving in or out, or a retired GPU returning changes it. + */ + public static function reindexReason(Reconciliation $changes, int $returned = 0): string { + if ($changes->created !== []) { + return 'new GPU'; + } + + if ($returned > 0) { + return 'retired GPU returned'; + } + + foreach ($changes->updated as $record) { + $read = $changes->read[$record->id] ?? null; + + if ($read === null || $read->nodeId !== $record->nodeId || $read->index !== $record->index || $read->name !== $record->name || $read->pciBusId !== $record->pciBusId) { + return 'GPU changed'; + } + } + + return ''; + } + + /** + * Log a node's collection state when it changes, not every cycle, so a + * node that stays down does not fill the log. + */ + private function logChange(Node $node, ?CollectionStatus $previous, ExecutionState $state, string $detail): void { + $was = $previous?->state; + + if ($was === $state || ($state->succeeded() && ($was === null || $was->succeeded()))) { + return; + } + + if ($state->succeeded()) { + Log::info(sprintf('Node %d: collection recovered (%s)', $node->id, $state->value)); + } else { + Log::warning(sprintf('Node %d: collection failed (%s): %s', $node->id, $state->value, $detail)); + } + } +} diff --git a/lib/ExecutionState.php b/lib/ExecutionState.php new file mode 100644 index 0000000..20869a3 --- /dev/null +++ b/lib/ExecutionState.php @@ -0,0 +1,85 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu; + +/** + * How the last collection at a node ended (PLAN, Measurement state). + * + * Every state but Ok and Empty is an error: it writes no values and marks + * no GPU absent (REQ-EXEC-006, REQ-INV-003). + */ +enum ExecutionState: string { + case Ok = 'ok'; + // The tool succeeded and reported no GPU. + case Empty = 'empty'; + case Unreachable = 'unreachable'; + // The agent answers but has no extend entry under the documented name. + case NotConfigured = 'not_configured'; + case TimedOut = 'timed_out'; + case PermissionDenied = 'permission_denied'; + case DriverNotLoaded = 'driver_not_loaded'; + case ToolMissing = 'tool_missing'; + case ToolError = 'tool_error'; + case Truncated = 'truncated'; + case InvalidOutput = 'invalid_output'; + // Another collection held the node (REQ-EXEC-005). + case Skipped = 'skipped'; + // The tool output was good but the plugin could not store the result. + case NotStored = 'not_stored'; + + public function succeeded(): bool { + return $this === self::Ok || $this === self::Empty; + } + + /** + * The state for an extend command's exit status. nvidia-smi documents 4 + * as no permission and 9 as driver not loaded; timeout(1) exits 124 when + * it stops the command and 137 when it has to kill it; 126 and 127 are + * the shell convention env(1) follows for a program it cannot run. + */ + public static function fromExitStatus(int $status): self { + return match ($status) { + 0 => self::Ok, + 124, 137 => self::TimedOut, + 4 => self::PermissionDenied, + 9 => self::DriverNotLoaded, + 126, 127 => self::ToolMissing, + default => self::ToolError, + }; + } + + public function label(): string { + return match ($this) { + self::Ok => __('Collected', 'gpu'), + self::Empty => __('No GPUs reported', 'gpu'), + self::Unreachable => __('SNMP agent unreachable', 'gpu'), + self::NotConfigured => __('Extend entry missing', 'gpu'), + self::TimedOut => __('Timed out', 'gpu'), + self::PermissionDenied => __('Permission denied', 'gpu'), + self::DriverNotLoaded => __('Driver not loaded', 'gpu'), + self::ToolMissing => __('Tool not found', 'gpu'), + self::ToolError => __('Tool error', 'gpu'), + self::Truncated => __('Output truncated', 'gpu'), + self::InvalidOutput => __('Output rejected', 'gpu'), + self::Skipped => __('Skipped: already running', 'gpu'), + self::NotStored => __('Result not stored', 'gpu'), + }; + } +} diff --git a/lib/ExtendOutput.php b/lib/ExtendOutput.php new file mode 100644 index 0000000..5b44d7a --- /dev/null +++ b/lib/ExtendOutput.php @@ -0,0 +1,53 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu; + +/** + * One NET-SNMP-EXTEND-MIB entry as read: the command's exit status + * (nsExtendResult), the line count snmpd stored (nsExtendOutNumLines), and + * the lines (nsExtendOutput2Table), in order. + */ +final readonly class ExtendOutput { + // net-snmp 5.9.5.2 keeps at most 100 KiB of output and, in practice, + // 1024 lines (research/snmp-extend.md). Output that reaches either may be + // cut, so it is refused rather than parsed. + public const MAX_BYTES = 102400; + public const MAX_LINES = 1024; + + /** + * @param list $lines + */ + public function __construct( + public int $result, + public int $declaredLines, + public array $lines, + ) { + } + + public function truncated(): bool { + $bytes = 0; + + foreach ($this->lines as $line) { + $bytes += strlen($line) + 1; + } + + return count($this->lines) !== $this->declaredLines || count($this->lines) >= self::MAX_LINES || $bytes >= self::MAX_BYTES - 1; + } +} diff --git a/lib/ExtendReader.php b/lib/ExtendReader.php new file mode 100644 index 0000000..35712b3 --- /dev/null +++ b/lib/ExtendReader.php @@ -0,0 +1,33 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu; + +/** + * Reads one extend entry from a node (ADR 0008). The plugin sends the agent + * nothing but the read requests; the command is fixed in the node's + * snmpd.conf. + */ +interface ExtendReader { + /** + * @throws CollectionError when the agent cannot be read or has no entry + * by that name + */ + public function read(NodeDevice $device, string $token): ExtendOutput; +} diff --git a/lib/Freshness.php b/lib/Freshness.php new file mode 100644 index 0000000..87e00be --- /dev/null +++ b/lib/Freshness.php @@ -0,0 +1,100 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu; + +/** + * Decides what the script server input prints for one stored value + * (REQ-SS-002, REQ-SS-004, REQ-INDEX-003, REQ-METRIC-006). Null prints U. + * + * A value is printed only while all of these hold: the GPU is present, the + * node's latest collection succeeded and reported it, and the tool took the + * sample no longer ago than the staleness limit. Otherwise it is unknown, so + * a stopped or failing collection shows as a gap, never as a held value or + * a zero. + * + * age is the exception: it is the seconds since the sample was taken, from + * the sample's own time, and stays numeric whenever a sample exists, so an + * alert on it fires when collection stops. It is unknown only for a GPU + * never sampled, or a sample stamped further in the future than clock skew + * explains. + */ +final class Freshness { + // Seconds a node's clock may run ahead of Cacti's before its sample + // time is distrusted. + public const SKEW_ALLOWANCE = 120; + + /** + * @param array $row the GPU's record, observation, and + * its node's latest collection, as + * CacheRepository reads them + */ + public static function value(string $field, array $row, int $now, int $staleAfter): ?float { + $observed = Row::int($row, 'observed_at', 0, 0); + + if ($observed === 0) { + return null; + } + + $age = $now - $observed; + + if ($age < -self::SKEW_ALLOWANCE) { + return null; + } + + if ($field === 'age') { + return (float) max(0, $age); + } + + $state = ExecutionState::tryFrom(Row::string($row, 'collection_state')); + + if (Row::string($row, 'presence') !== Presence::Present->value || $state === null || !$state->succeeded()) { + return null; + } + + // Reported by an earlier collection, but not by the latest. + if (Row::int($row, 'reported_at', 0, 0) < Row::int($row, 'collection_finished_at', 0, 0)) { + return null; + } + + if ($age > $staleAfter) { + return null; + } + + return in_array($field, Schema::OBSERVATION_METRICS, true) ? Row::float($row, $field) : null; + } + + /** + * A value as Cacti reads it: plain decimal, never exponent notation, + * which RRDtool would refuse, and U for unknown. + */ + public static function format(?float $value): string { + if ($value === null || !is_finite($value)) { + return 'U'; + } + + if (floor($value) === $value && abs($value) < 1e15) { + return sprintf('%.0f', $value); + } + + $text = rtrim(rtrim(sprintf('%.6F', $value), '0'), '.'); + + return $text === '-0' ? '0' : $text; + } +} diff --git a/lib/GpuRepository.php b/lib/GpuRepository.php index fdd56c5..6318b39 100644 --- a/lib/GpuRepository.php +++ b/lib/GpuRepository.php @@ -116,18 +116,65 @@ public function apply(Reconciliation $changes): bool { * The operator's confirmation of a pending move (REQ-ID-004). The GPU * keeps its record, and so its history; only its node changes. */ - public function confirmMove(int $id): bool { - $ok = db_execute_prepared("UPDATE plugin_gpu_gpu SET node_id = pending_node_id, pending_node_id = 0, pending_since = 0, missing_count = 0, presence = 'present' WHERE id = ? AND pending_node_id > 0", [$id], true, $this->connection); + /** + * Move a GPU to the node it was seen at. Only the move the operator was + * shown and authorized is applied: if a collection changed the record's + * node or pending node since, nothing changes. + */ + public function confirmMove(int $id, int $fromNodeId, int $toNodeId): bool { + $ok = db_execute_prepared("UPDATE plugin_gpu_gpu SET node_id = pending_node_id, pending_node_id = 0, pending_since = 0, missing_count = 0, presence = 'present' WHERE id = ? AND node_id = ? AND pending_node_id = ? AND pending_node_id > 0", [$id, $fromNodeId, $toNodeId], true, $this->connection); + + return $ok && db_affected_rows($this->connection) === 1; + } + + public function rejectMove(int $id, int $fromNodeId, int $toNodeId): bool { + $ok = db_execute_prepared('UPDATE plugin_gpu_gpu SET pending_node_id = 0, pending_since = 0 WHERE id = ? AND node_id = ? AND pending_node_id = ? AND pending_node_id > 0', [$id, $fromNodeId, $toNodeId], true, $this->connection); return $ok && db_affected_rows($this->connection) === 1; } - public function rejectMove(int $id): bool { - $ok = db_execute_prepared('UPDATE plugin_gpu_gpu SET pending_node_id = 0, pending_since = 0 WHERE id = ? AND pending_node_id > 0', [$id], true, $this->connection); + /** + * Remove an absent GPU from its node's data query, on an operator's + * request (REQ-INDEX-005). A present GPU is refused: the next collection + * would only return it. + */ + public function retire(int $id, int $nodeId, int $userId, int $now): bool { + $ok = db_execute_prepared("INSERT IGNORE INTO plugin_gpu_retired (gpu_id, retired_at, retired_by) SELECT id, ?, ? FROM plugin_gpu_gpu WHERE id = ? AND node_id = ? AND presence = 'absent'", [$now, $userId, $id, $nodeId], true, $this->connection); return $ok && db_affected_rows($this->connection) === 1; } + /** + * @return list + */ + public function retiredIds(): array { + return array_map(static fn (array $row): int => Row::int($row, 'gpu_id'), Row::rows(db_fetch_assoc_prepared('SELECT gpu_id FROM plugin_gpu_retired ORDER BY gpu_id', [], true, $this->connection))); + } + + public function find(int $id): ?GpuRecord { + $row = db_fetch_row_prepared('SELECT * FROM plugin_gpu_gpu WHERE id = ?', [$id], true, $this->connection); + + return is_array($row) && $row !== [] ? GpuRecord::fromRow($row) : null; + } + + /** + * Return GPUs an operator removed from the data query to it, because a + * collection reported them again (REQ-INDEX-005). + * + * @param list $ids + * + * @return int how many were retired + */ + public function unretire(array $ids): int { + if ($ids === []) { + return 0; + } + + $ok = db_execute_prepared('DELETE FROM plugin_gpu_retired WHERE gpu_id IN (' . implode(', ', array_fill(0, count($ids), '?')) . ')', $ids, true, $this->connection); + + return $ok ? max(0, (int) db_affected_rows($this->connection)) : 0; + } + /** * @return list */ diff --git a/lib/InventoryPage.php b/lib/InventoryPage.php index cc8afce..692013e 100644 --- a/lib/InventoryPage.php +++ b/lib/InventoryPage.php @@ -66,7 +66,7 @@ public function render(): void { } if ($shown === 0) { - print '' . html_escape(__('No GPUs recorded yet. GPUs appear here once collection, which arrives in a later release, reports them.', 'gpu')) . ''; + print '' . html_escape(__('No GPUs recorded yet. GPUs appear here once a node\'s collection reports them.', 'gpu')) . ''; } html_end_box(); diff --git a/lib/LockRepository.php b/lib/LockRepository.php new file mode 100644 index 0000000..920bfb9 --- /dev/null +++ b/lib/LockRepository.php @@ -0,0 +1,47 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu; + +/** + * Named MySQL advisory locks, scoped to the Cacti database so two Cacti + * installs on one server never share one. A lock belongs to the database + * connection, so the server frees it if the holder dies (REQ-EXEC-005, + * REQ-TPL-005). + */ +final class LockRepository { + // The server-wide lock name: hashed, because MySQL and MariaDB limit + // lock names to 64 characters and a database name alone may be longer. + private const NAME = "SHA2(CONCAT(DATABASE(), '.plugin_gpu.', ?), 256)"; + + public function __construct(private readonly \PDO|false $connection) { + } + + /** + * Take a lock without waiting. False when another connection holds it or + * the server could not be asked. + */ + public function acquire(string $name): bool { + return (int) db_fetch_cell_prepared('SELECT GET_LOCK(' . self::NAME . ', 0)', [$name], '', true, $this->connection) === 1; + } + + public function release(string $name): void { + db_fetch_cell_prepared('SELECT RELEASE_LOCK(' . self::NAME . ')', [$name], '', true, $this->connection); + } +} diff --git a/lib/Metric.php b/lib/Metric.php new file mode 100644 index 0000000..36fd9ed --- /dev/null +++ b/lib/Metric.php @@ -0,0 +1,77 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu; + +/** + * One field of the common metric model (ADR 0009, REQ-METRIC-001): its data + * source name, unit, kind, range, and source per backend. + * + * A field is read from an nvidia-smi query field, decoded from one bit of + * the clock event reasons mask, or computed. The DCGM and AMD columns + * document the source each later backend will read; milestone 3 implements + * the nvidia-smi column only. + */ +final readonly class Metric { + public const GAUGE = 'gauge'; + public const INDICATOR = 'indicator'; + + public function __construct( + // Data source item name: Cacti allows ^[a-zA-Z0-9_]{1,19}$. + public string $name, + public string $label, + public string $unit, + public string $kind, + public ?float $min, + public ?float $max, + // The nvidia-smi --query-gpu field, or null when not read from one. + public ?string $nvidiaField, + // Multiplier from the nvidia-smi value to the model unit. + public float $nvidiaScale, + // The clock event reasons bit an indicator decodes, or null. + public ?int $maskBit, + public string $dcgm, + // Multiplier from the DCGM field named first in $dcgm to the model unit. + public float $dcgmScale, + public string $amd, + ) { + } + + /** + * A source value converted to the model unit; null stays unknown. + */ + public static function scale(?float $value, float $factor): ?float { + return $value === null ? null : $value * $factor; + } + + /** + * The range as RRDtool takes it: a number, or U for unbounded. + */ + public function rrdMin(): string { + return $this->min === null ? 'U' : self::number($this->min); + } + + public function rrdMax(): string { + return $this->max === null ? 'U' : self::number($this->max); + } + + private static function number(float $value): string { + return rtrim(rtrim(sprintf('%.6F', $value), '0'), '.'); + } +} diff --git a/lib/MetricModel.php b/lib/MetricModel.php new file mode 100644 index 0000000..ae59f70 --- /dev/null +++ b/lib/MetricModel.php @@ -0,0 +1,149 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu; + +/** + * The common metric model (ADR 0009, REQ-METRIC-001 to REQ-METRIC-007). + * + * Every backend fills these fields and nothing else, so one data query, one + * data template, and one set of graph templates serve every vendor. Units + * are fixed here: utilization in percent 0 to 100 whatever the source scale, + * memory in bytes, temperature in degrees C, power in watts, clocks in MHz. + * A value a backend cannot supply is unknown (U) and is never estimated. + * + * docs/metrics.md is generated from table(); a unit test keeps them equal. + */ +final class MetricModel { + public const MIB = 1048576.0; + + // The field that carries the clock event reasons bitmask. The old name is + // the one confirmed on every supported driver line: nvidia-smi renamed the + // reasons in its v530 changelog and added the old query names back in + // v535 (research/clock-event-reasons.md). Both names print the same + // bitmask in the same position, so the parser accepts either. + public const MASK_FIELD = 'clocks_throttle_reasons.active'; + + // Bits of the mask that get an indicator. The rest (idle, application + // clocks, sync boost, display, board limit, reliability, and any bit a + // later driver adds) stay in the raw mask only. + public const BITS = [ + 'thr_sw_power_cap' => 0x4, + 'thr_hw_slowdown' => 0x8, + 'thr_sw_thermal' => 0x20, + 'thr_hw_thermal' => 0x40, + 'thr_hw_power_brake' => 0x80, + ]; + + /** + * @return list + */ + public static function all(): array { + $gauge = Metric::GAUGE; + $flag = Metric::INDICATOR; + + return [ + new Metric('util_gpu', 'GPU utilization', 'percent', $gauge, 0.0, 100.0, 'utilization.gpu', 1.0, null, '1613 (ratio 0.0 to 1.0, times 100), or 203 (percent, deprecated)', 100.0, '`metric --usage` `gfx_activity` (#18)'), + new Metric('util_mem', 'Memory controller utilization', 'percent', $gauge, 0.0, 100.0, 'utilization.memory', 1.0, null, '1614 (ratio 0.0 to 1.0, times 100), or 204 (unit not stated, #15)', 100.0, '`metric --usage` `umc_activity` (#18)'), + new Metric('mem_used', 'Frame buffer memory used', 'bytes', $gauge, 0.0, null, 'memory.used', self::MIB, null, '1627 (used, bytes), or 252 (MiB, deprecated)', 1.0, '`metric --mem-usage` `used_vram` (MiB, #18)'), + new Metric('mem_total', 'Frame buffer memory total', 'bytes', $gauge, 0.0, null, 'memory.total', self::MIB, null, '1625 (capacity, bytes), or 250 (MiB, deprecated); 1626 is free bytes and is not used', 1.0, '`metric --mem-usage` `total_vram` (MiB, #18)'), + new Metric('temp_gpu', 'GPU temperature', 'degrees C', $gauge, null, null, 'temperature.gpu', 1.0, null, '150', 1.0, '`metric --temperature` `edge` (#18)'), + new Metric('power', 'Board power draw', 'watts', $gauge, 0.0, null, 'power.draw', 1.0, null, '155', 1.0, '`metric --power` `socket_power`'), + new Metric('power_limit', 'Board power limit', 'watts', $gauge, 0.0, null, 'power.limit', 1.0, null, '160', 1.0, '#18'), + new Metric('clock_sm', 'SM clock', 'MHz', $gauge, 0.0, null, 'clocks.sm', 1.0, null, '1603 (hertz, divided by 1,000,000), or 100 (unit not stated)', 1.0e-6, '`metric --clock` (#18)'), + new Metric('clock_mem', 'Memory clock', 'MHz', $gauge, 0.0, null, 'clocks.mem', 1.0, null, '1604 (hertz, divided by 1,000,000), or 101 (unit not stated)', 1.0e-6, '`metric --clock` (#18)'), + new Metric('ecc_corr', 'Corrected ECC errors since driver load', 'count', $gauge, 0.0, null, 'ecc.errors.corrected.volatile.total', 1.0, null, '310', 1.0, '`metric --ecc` `total_correctable_count`'), + new Metric('ecc_uncorr', 'Uncorrected ECC errors since driver load', 'count', $gauge, 0.0, null, 'ecc.errors.uncorrected.volatile.total', 1.0, null, '311', 1.0, '`metric --ecc` `total_uncorrectable_count`'), + new Metric('retired_pending', 'Page retirement pending', '0 or 1', $flag, 0.0, 1.0, 'retired_pages.pending', 1.0, null, '392', 1.0, '#18'), + new Metric('thr_sw_power_cap', 'Clocks held by the software power cap', '0 or 1', $flag, 0.0, 1.0, null, 1.0, self::BITS['thr_sw_power_cap'], 'field 112, bit 0x4', 1.0, '`metric --violation` (MI300 or newer, #18)'), + new Metric('thr_hw_slowdown', 'Hardware slowdown', '0 or 1', $flag, 0.0, 1.0, null, 1.0, self::BITS['thr_hw_slowdown'], 'field 112, bit 0x8', 1.0, 'not applicable'), + new Metric('thr_sw_thermal', 'Software thermal slowdown', '0 or 1', $flag, 0.0, 1.0, null, 1.0, self::BITS['thr_sw_thermal'], 'field 112, bit 0x20', 1.0, '`metric --violation` (MI300 or newer, #18)'), + new Metric('thr_hw_thermal', 'Hardware thermal slowdown', '0 or 1', $flag, 0.0, 1.0, null, 1.0, self::BITS['thr_hw_thermal'], 'field 112, bit 0x40', 1.0, '`metric --violation` (MI300 or newer, #18)'), + new Metric('thr_hw_power_brake', 'Hardware power brake', '0 or 1', $flag, 0.0, 1.0, null, 1.0, self::BITS['thr_hw_power_brake'], 'field 112, bit 0x80', 1.0, 'not applicable'), + new Metric('age', 'Seconds since the tool took the sample', 'seconds', $gauge, 0.0, null, null, 1.0, null, 'computed from the sample timestamp', 1.0, 'computed from the sample timestamp'), + ]; + } + + public static function find(string $name): ?Metric { + foreach (self::all() as $metric) { + if ($metric->name === $name) { + return $metric; + } + } + + return null; + } + + /** + * @return list + */ + public static function names(): array { + return array_map(static fn (Metric $metric): string => $metric->name, self::all()); + } + + /** + * The nvidia-smi --query-gpu field list, in output order (REQ-NVSMI-001, + * REQ-NVSMI-002). Identity and the sample time come first, in the same + * query as the metrics, so one line describes one GPU at one moment. The + * GPU name is free text that may contain the separator, so it is read by + * its own query (namesFields()) and never shifts these fields. + * + * @return list + */ + public static function nvidiaFields(): array { + $fields = ['timestamp', 'uuid', 'index', 'pci.bus_id', 'driver_version']; + + foreach (self::all() as $metric) { + if ($metric->nvidiaField !== null) { + $fields[] = $metric->nvidiaField; + } + } + + $fields[] = self::MASK_FIELD; + + return $fields; + } + + /** + * @return list + */ + public static function namesFields(): array { + return ['uuid', 'name']; + } + + /** + * The model as the Markdown table in docs/metrics.md. + */ + public static function table(): string { + $rows = ['| Field | Meaning | Unit | Kind | Range | nvidia-smi source | DCGM source | AMD source |', '|---|---|---|---|---|---|---|---|']; + + foreach (self::all() as $metric) { + $nvidia = match (true) { + $metric->nvidiaField !== null && $metric->nvidiaScale !== 1.0 => sprintf('`%s` (MiB, times 1,048,576)', $metric->nvidiaField), + $metric->nvidiaField !== null => sprintf('`%s`', $metric->nvidiaField), + $metric->maskBit !== null => sprintf('`%s`, bit 0x%X', self::MASK_FIELD, $metric->maskBit), + default => 'computed from `timestamp`', + }; + + $rows[] = sprintf('| `%s` | %s | %s | %s | %s to %s | %s | %s | %s |', $metric->name, $metric->label, $metric->unit, $metric->kind, $metric->rrdMin(), $metric->rrdMax(), $nvidia, $metric->dcgm, $metric->amd); + } + + return implode("\n", $rows) . "\n"; + } +} diff --git a/lib/NodeAccess.php b/lib/NodeAccess.php new file mode 100644 index 0000000..7bd2464 --- /dev/null +++ b/lib/NodeAccess.php @@ -0,0 +1,82 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu; +/** + * Which GPU nodes and GPU records the acting user may see and act on, from + * Cacti's device permissions (REQ-DEV-002). A GPU Admin acts only on nodes + * whose device the user may see. A move needs both nodes. + * + * One exemption: a node whose device was deleted is visible, and may only be + * disabled, so a stale node can be stopped. No device permission can be + * checked for it, so nothing else is allowed on it, and its GPU records are + * not shown or exported. + */ +final class NodeAccess { + /** + * @param \Closure(int): bool $deviceAllowed Cacti's is_device_allowed() for the acting user + */ + public function __construct(private readonly \Closure $deviceAllowed) { + } + + public function deviceAllowed(int $hostId): bool { + return $hostId > 0 && ($this->deviceAllowed)($hostId); + } + + public function canManage(?Node $node): bool { + return $node !== null && $node->deviceExists && $this->deviceAllowed($node->hostId); + } + + public function canSee(?Node $node): bool { + return $node !== null && (!$node->deviceExists || $this->canManage($node)); + } + + /** + * @param array $nodes by id + */ + public function canManageGpu(GpuRecord $gpu, array $nodes): bool { + return $this->canManage($nodes[$gpu->nodeId] ?? null) + && ($gpu->pendingNodeId === 0 || $this->canManage($nodes[$gpu->pendingNodeId] ?? null)); + } + + /** + * @param list $nodes + * @return array the nodes the user may see, by id + */ + public function visibleNodes(array $nodes): array { + $visible = []; + + foreach ($nodes as $node) { + if ($this->canSee($node)) { + $visible[$node->id] = $node; + } + } + + return $visible; + } + + /** + * @param list $gpus + * @param array $nodes by id + * @return list GPUs recorded at a node the user may manage + */ + public function visibleGpus(array $gpus, array $nodes): array { + return array_values(array_filter($gpus, fn (GpuRecord $gpu): bool => $this->canManage($nodes[$gpu->nodeId] ?? null))); + } +} diff --git a/lib/NodeDevice.php b/lib/NodeDevice.php new file mode 100644 index 0000000..5aa9231 --- /dev/null +++ b/lib/NodeDevice.php @@ -0,0 +1,87 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu; + +/** + * The Cacti device a node is mapped to, with what the collector needs: its + * SNMP settings, availability, and poller. The SNMP secrets stay in this + * object and are never logged or printed. + */ +final readonly class NodeDevice { + public const HOST_DOWN = 1; + + public function __construct( + public int $id, + public string $description, + public string $hostname, + public int $pollerId, + public int $status, + public bool $disabled, + public int $snmpVersion, + public string $snmpCommunity, + public string $snmpUsername, + public string $snmpPassword, + public string $snmpAuthProtocol, + public string $snmpPrivPassphrase, + public string $snmpPrivProtocol, + public string $snmpContext, + public string $snmpEngineId, + public int $snmpPort, + public int $snmpTimeout, + public int $maxOids, + ) { + } + + /** + * @param array $row a host row + */ + public static function fromRow(array $row): self { + return new self( + id: Row::int($row, 'id'), + description: Row::string($row, 'description'), + hostname: Row::string($row, 'hostname'), + pollerId: Row::int($row, 'poller_id', 1, 1), + status: Row::int($row, 'status'), + disabled: Row::string($row, 'disabled') === 'on', + snmpVersion: Row::int($row, 'snmp_version'), + snmpCommunity: Row::string($row, 'snmp_community'), + snmpUsername: Row::string($row, 'snmp_username'), + // Cacti stores passphrases as entered; a trimmed one would not + // match the agent's user. + snmpPassword: Row::untrimmed($row, 'snmp_password'), + snmpAuthProtocol: Row::string($row, 'snmp_auth_protocol'), + snmpPrivPassphrase: Row::untrimmed($row, 'snmp_priv_passphrase'), + snmpPrivProtocol: Row::string($row, 'snmp_priv_protocol'), + snmpContext: Row::string($row, 'snmp_context'), + snmpEngineId: Row::string($row, 'snmp_engine_id'), + snmpPort: Row::int($row, 'snmp_port', 161, 1), + snmpTimeout: Row::int($row, 'snmp_timeout', 500, 1), + maxOids: Row::int($row, 'max_oids', 10, 1), + ); + } + + /** + * Cacti's run_data_query() returns true without reindexing a device in + * this state, even when forced (research/cacti-core.md). + */ + public function reindexBlocked(): bool { + return $this->status === self::HOST_DOWN || $this->disabled; + } +} diff --git a/lib/NodeRepository.php b/lib/NodeRepository.php index 827a56e..f361ad0 100644 --- a/lib/NodeRepository.php +++ b/lib/NodeRepository.php @@ -59,6 +59,38 @@ public function devicesFor(int $nodeId): array { return $devices; } + /** + * The node's Cacti device with its SNMP settings, for the collector. + */ + public function device(Node $node): ?NodeDevice { + $row = db_fetch_row_prepared('SELECT id, description, hostname, poller_id, status, disabled, snmp_version, snmp_community, snmp_username, snmp_password, snmp_auth_protocol, snmp_priv_passphrase, snmp_priv_protocol, snmp_context, snmp_engine_id, snmp_port, snmp_timeout, max_oids FROM host WHERE id = ?', [$node->hostId], true, $this->connection); + + return is_array($row) && $row !== [] ? NodeDevice::fromRow($row) : null; + } + + public function findByHost(int $hostId): ?Node { + $row = db_fetch_row_prepared(self::SELECT . ' WHERE n.host_id = ?', [$hostId], true, $this->connection); + + return is_array($row) && $row !== [] ? Node::fromRow($row) : null; + } + + /** + * Disable the nodes of Cacti devices being deleted (ADR 0010). The nodes + * and their GPU records stay; Cacti's own deletion decides what happens + * to the device's graphs and data sources. + * + * @param list $hostIds + */ + public function disableForHosts(array $hostIds): int { + if ($hostIds === []) { + return 0; + } + + $ok = db_execute_prepared("UPDATE plugin_gpu_node SET admin_state = 'disabled', updated_at = ? WHERE admin_state != 'disabled' AND host_id IN (" . implode(', ', array_fill(0, count($hostIds), '?')) . ')', array_merge([$this->clock->now()], $hostIds), true, $this->connection); + + return $ok ? max(0, (int) db_affected_rows($this->connection)) : 0; + } + public function deviceExists(int $hostId): bool { return (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM host WHERE id = ?', [$hostId], '', true, $this->connection) === 1; } diff --git a/lib/NodesPage.php b/lib/NodesPage.php index 8401a77..d9460b4 100644 --- a/lib/NodesPage.php +++ b/lib/NodesPage.php @@ -20,10 +20,14 @@ namespace Somethingwithproof\Gpu; /** - * The GPU Nodes page (GPU Admin): register Cacti devices as GPU nodes, - * confirm or reject GPU moves, and export the records. Every action that + * The GPU Nodes page (GPU Admin): map Cacti devices to GPU nodes, see how + * each node's collection went, confirm or reject GPU moves, remove absent + * GPUs from the data query, and export the records. Every action that * changes state is a POST form, and csrf-magic adds its token to each * (REQ-UI-004). Nothing here takes a command, path, or URL. + * + * Only nodes, GPUs, and devices the acting user may see are shown or + * offered (NodeAccess, REQ-DEV-002). */ final class NodesPage { public const FILE = 'gpu_nodes.php'; @@ -31,25 +35,29 @@ final class NodesPage { public function __construct( private readonly NodeRepository $nodes, private readonly GpuRepository $gpus, + private readonly NodeAccess $access, + private readonly ?CollectionRepository $collections = null, + private readonly ?Clock $clock = null, ) { } public function renderList(): void { - $nodes = $this->nodes->all(); - $counts = []; + $nodes = $this->access->visibleNodes($this->nodes->all()); + $statuses = $this->collections?->all() ?? []; + $counts = []; - foreach ($this->gpus->all() as $gpu) { + foreach ($this->access->visibleGpus($this->gpus->all(), $nodes) as $gpu) { $counts[$gpu->nodeId][$gpu->presence->value] = ($counts[$gpu->nodeId][$gpu->presence->value] ?? 0) + 1; } html_start_box(__('GPU Nodes', 'gpu'), '100%', '', '3', 'center', self::FILE . '?action=edit'); print '' . implode('', array_map('html_escape', [ - __('Device', 'gpu'), __('State', 'gpu'), __('GPUs Present', 'gpu'), __('GPUs Absent', 'gpu'), __('Actions', 'gpu'), + __('Device', 'gpu'), __('State', 'gpu'), __('Last Collection', 'gpu'), __('GPUs Present', 'gpu'), __('GPUs Absent', 'gpu'), __('Actions', 'gpu'), ])) . ''; if ($nodes === []) { - print '' . html_escape(__('No GPU nodes yet. Add a Cacti device that has GPUs.', 'gpu')) . ''; + print '' . html_escape(__('No GPU nodes yet. Add a Cacti device that has GPUs.', 'gpu')) . ''; } foreach ($nodes as $node) { @@ -58,9 +66,10 @@ public function renderList(): void { print '' . '' . html_escape($label) . '' . '' . html_escape($node->enabled() ? __('Enabled', 'gpu') : __('Disabled', 'gpu')) . '' + . '' . html_escape($this->collection($statuses[$node->id] ?? null)) . '' . '' . ($counts[$node->id][Presence::Present->value] ?? 0) . '' . '' . ($counts[$node->id][Presence::Absent->value] ?? 0) . '' - . '' . $this->actionForm($node->id, 'delete', __('Delete', 'gpu')) . '' + . '' . ($this->access->canManage($node) ? $this->actionForm($node->id, 'delete', __('Delete', 'gpu')) : '') . '' . ''; } @@ -69,16 +78,48 @@ public function renderList(): void { $this->renderPendingMoves($nodes); html_start_box(__('Export', 'gpu'), '100%', '', '3', 'center', ''); - print '' . html_escape(__('Download every node and GPU record as JSON. Take an export before an uninstall that drops the plugin tables.', 'gpu')) + print '' . html_escape(__('Download the node and GPU records of the devices you may see as JSON. Take an export before an uninstall that drops the plugin tables.', 'gpu')) . ' ' . html_escape(__('Export Records', 'gpu')) . ''; html_end_box(); } /** - * @param list $nodes + * How the node's latest collection went, as one line of text. The + * detail never contains tool output (CollectionError). + */ + public function collection(?CollectionStatus $status): string { + if ($status === null || $status->state === null) { + return __('Not collected yet', 'gpu'); + } + + $text = $status->state->label(); + + if ($status->succeeded()) { + $text = __('%s: %d GPUs', $text, $status->gpus, 'gpu'); + + if ($status->newGpus > 0) { + $text .= '; ' . __('%d new GPUs recorded', $status->newGpus, 'gpu'); + } + } elseif ($status->detail !== '') { + $text .= ': ' . $status->detail; + } + + if ($this->clock !== null && $status->finishedAt > 0) { + $text .= ' (' . __('%d s ago', max(0, $this->clock->now() - $status->finishedAt), 'gpu') . ')'; + } + + if ($status->skipped > 0) { + $text .= '; ' . __('%d runs skipped while one was still running', $status->skipped, 'gpu'); + } + + return $text; + } + + /** + * @param array $nodes the visible nodes, by id */ private function renderPendingMoves(array $nodes): void { - $moves = $this->gpus->pendingMoves(); + $moves = array_values(array_filter($this->gpus->pendingMoves(), fn (GpuRecord $gpu): bool => $this->access->canManageGpu($gpu, $nodes))); if ($moves === []) { return; @@ -112,8 +153,8 @@ private function renderPendingMoves(array $nodes): void { /** * @param array $errors field => message */ - public function renderEdit(?Node $node, int $hostId = 0, ?bool $enabled = null, array $errors = []): void { - $devices = $this->nodes->devicesFor($node->id ?? 0); + public function renderEdit(?Node $node, int $hostId = 0, ?bool $enabled = null, array $errors = [], bool $canCreateDevice = false): void { + $devices = array_filter($this->nodes->devicesFor($node->id ?? 0), fn (int $id): bool => $this->access->deviceAllowed($id), ARRAY_FILTER_USE_KEY); $current = $hostId > 0 ? $hostId : ($node->hostId ?? 0); $enabled ??= $node?->enabled() ?? true; @@ -139,6 +180,7 @@ public function renderEdit(?Node $node, int $hostId = 0, ?bool $enabled = null, print ''; print ''; + print '' . html_escape(__('Saving adds the GPU data query to the device, with Cacti\'s automatic reindex turned off: the plugin reindexes after every GPU change. Configure the device\'s SNMP agent first; see docs/node-setup.md.', 'gpu')) . ''; html_end_box(); @@ -146,6 +188,59 @@ public function renderEdit(?Node $node, int $hostId = 0, ?bool $enabled = null, . '' . '' . ''; + + if ($node !== null && $this->access->canManage($node)) { + $this->renderRetire($node); + } elseif ($canCreateDevice) { + $this->renderCreateDevice(); + } + } + + /** + * Absent GPUs of a node, each with the explicit action that removes it + * from the data query (REQ-INDEX-005). + */ + private function renderRetire(Node $node): void { + $absent = array_values(array_filter($this->gpus->all(), static fn (GpuRecord $gpu): bool => $gpu->nodeId === $node->id && $gpu->presence === Presence::Absent)); + + if ($absent === []) { + return; + } + + $retired = array_flip($this->gpus->retiredIds()); + + html_start_box(__('Absent GPUs', 'gpu'), '100%', '', '3', 'center', ''); + + print '' . html_escape(__('An absent GPU stays an index of the data query, so its graphs and RRD files stay attached and show a gap. Removing it from the data query stops that: at the next reindex Cacti no longer lists it, its graphs stop updating and its data sources show as orphaned, and its RRD files and graphs are kept until you delete them. The GPU record stays, and the GPU returns to the data query if it is reported again.', 'gpu')) . ''; + print '' . implode('', array_map('html_escape', [__('UUID', 'gpu'), __('Name', 'gpu'), __('Last Seen', 'gpu'), __('Actions', 'gpu')])) . ''; + + foreach ($absent as $gpu) { + print '' + . '' . html_escape($gpu->uuid) . '' + . '' . html_escape($gpu->name) . '' + . '' . ($gpu->lastSeen > 0 ? html_escape(date('Y-m-d H:i', $gpu->lastSeen)) : '-') . '' + . '' . (isset($retired[$gpu->id]) ? html_escape(__('Removed from the data query', 'gpu')) : $this->actionForm($gpu->id, 'retire', __('Remove from Data Query', 'gpu'))) . '' + . ''; + } + + html_end_box(); + } + + /** + * Create a device for a node that has none (ADR 0010). The device takes + * the site's device defaults and the GPU Node device template; its SNMP + * settings are then set on Cacti's own device page. + */ + private function renderCreateDevice(): void { + print '
'; + html_start_box(__('Create a Device for a New Node', 'gpu'), '100%', '', '3', 'center', ''); + print '' . html_escape(__('Only when the node is not a Cacti device yet. The device uses the site\'s device defaults and the GPU Node device template; set its SNMP settings on the device page afterwards.', 'gpu')) . ''; + print ''; + print ''; + html_end_box(); + print '' + . '' + . '
'; } private function actionForm(int $id, string $action, string $label): string { diff --git a/lib/NvidiaSmiParser.php b/lib/NvidiaSmiParser.php new file mode 100644 index 0000000..0de658d --- /dev/null +++ b/lib/NvidiaSmiParser.php @@ -0,0 +1,194 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu; + +/** + * Parses the two nvidia-smi extend entries (REQ-NVSMI-001 to REQ-NVSMI-006, + * REQ-EXEC-006, REQ-EXEC-007). + * + * The metrics entry prints one line per GPU with the fields of + * MetricModel::nvidiaFields(), in that order. It holds no free text, so a + * line with more or fewer fields than requested is rejected. The names entry + * prints "uuid, name"; the name is everything after the first separator, so + * a comma in a product name never shifts a field. + * + * Output is untrusted. Anything that is not exactly what was requested, such + * as stderr text that snmpd merged into the output, a nonzero exit status, or + * output cut at snmpd's limit, fails the whole collection: no value is + * stored and no GPU is marked absent. + */ +final class NvidiaSmiParser { + public const BACKEND = 'nvidia-smi'; + + // Not a value: what nvidia-smi prints for a field it cannot report. + private const NUMBER = '/^-?[0-9]+(\.[0-9]+)?$/'; + + // nvidia-smi's timestamp, "YYYY/MM/DD HH:MM:SS.mmm". It carries no zone, + // so the documented extend line runs the tool with TZ=UTC. + private const TIMESTAMP = '/^[0-9]{4}\/[0-9]{2}\/[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]{1,6})?$/'; + + /** + * @throws CollectionError + */ + public function parse(ExtendOutput $metrics, ExtendOutput $names): Collection { + $this->check($metrics, 'GPU metrics'); + $this->check($names, 'GPU names'); + + $fields = MetricModel::nvidiaFields(); + $position = array_flip($fields); + $labels = $this->names($names); + $reports = []; + $readings = []; + $version = ''; + + foreach ($this->lines($metrics) as $number => $line) { + $values = array_map('trim', explode(',', $line)); + + if (count($values) !== count($fields)) { + throw new CollectionError(ExecutionState::InvalidOutput, sprintf('GPU metrics line %d has %d fields where %d were requested', $number + 1, count($values), count($fields)), 1); + } + + $observed = $this->timestamp($values[$position['timestamp']]); + + if ($observed === null) { + throw new CollectionError(ExecutionState::InvalidOutput, sprintf('GPU metrics line %d has no valid sample time', $number + 1), 1); + } + + try { + $uuid = $values[$position['uuid']]; + $report = GpuReport::create( + Vendor::Nvidia, + $uuid, + $this->index($values[$position['index']]), + $values[$position['pci.bus_id']], + $labels[strtolower($uuid)] ?? '', + $values[$position['driver_version']], + ); + } catch (\InvalidArgumentException $e) { + throw new CollectionError(ExecutionState::InvalidOutput, sprintf('GPU metrics line %d: %s', $number + 1, $e->getMessage()), 1); + } + + $mask = ThrottleMask::parse($values[$position[MetricModel::MASK_FIELD]]); + $read = ThrottleMask::indicators($mask); + + foreach (MetricModel::all() as $metric) { + if ($metric->nvidiaField === null) { + continue; + } + + $raw = $values[$position[$metric->nvidiaField]]; + + $read[$metric->name] = $metric->kind === Metric::INDICATOR + ? $this->flag($raw) + : Metric::scale($this->number($raw), $metric->nvidiaScale); + } + + $version = $version === '' ? $report->driverVersion : $version; + $reports[] = $report; + $readings[] = new Reading($report, $observed, $read, $mask); + } + + try { + $snapshot = GpuSnapshot::create(self::BACKEND, $version, $reports); + } catch (\InvalidArgumentException $e) { + throw new CollectionError(ExecutionState::InvalidOutput, $e->getMessage()); + } + + return new Collection($snapshot, $readings, self::BACKEND); + } + + private function check(ExtendOutput $output, string $what): void { + if ($output->result !== 0) { + throw new CollectionError(ExecutionState::fromExitStatus($output->result), sprintf('The %s command exited with status %d', $what, $output->result)); + } + + if ($output->truncated()) { + throw new CollectionError(ExecutionState::Truncated, sprintf('The %s output was cut short or reached the SNMP agent\'s limit', $what)); + } + } + + /** + * @return list the output lines; a trailing empty line is dropped + */ + private function lines(ExtendOutput $output): array { + $lines = $output->lines; + + if ($lines !== [] && trim((string) end($lines)) === '') { + array_pop($lines); + } + + return $lines; + } + + /** + * @return array lower-cased UUID => name + */ + private function names(ExtendOutput $names): array { + $out = []; + + foreach ($this->lines($names) as $number => $line) { + $parts = explode(',', $line, 2); + + if (count($parts) !== 2 || preg_match('/^GPU-[0-9a-f-]{36}$/i', trim($parts[0])) !== 1) { + throw new CollectionError(ExecutionState::InvalidOutput, sprintf('GPU names line %d is not a UUID and a name', $number + 1), 1); + } + + $out[strtolower(trim($parts[0]))] = trim($parts[1]); + } + + return $out; + } + + private function timestamp(string $raw): ?int { + if (preg_match(self::TIMESTAMP, $raw) !== 1) { + return null; + } + + $time = \DateTimeImmutable::createFromFormat('!Y/m/d H:i:s', substr($raw, 0, 19), new \DateTimeZone('UTC')); + $errors = \DateTimeImmutable::getLastErrors(); + + // A date such as 2026/02/30 parses with a warning and rolls over. + if ($time === false || ($errors !== false && $errors['warning_count'] > 0)) { + return null; + } + + return $time->getTimestamp(); + } + + private function index(string $raw): ?int { + if (preg_match('/^-?[0-9]+$/', $raw) === 1) { + return (int) $raw; + } + + return null; + } + + private function number(string $raw): ?float { + return preg_match(self::NUMBER, $raw) === 1 ? (float) $raw : null; + } + + private function flag(string $raw): ?float { + return match (strtolower($raw)) { + 'yes', '1' => 1.0, + 'no', '0' => 0.0, + default => null, + }; + } +} diff --git a/lib/ObservationRepository.php b/lib/ObservationRepository.php new file mode 100644 index 0000000..f9db9ca --- /dev/null +++ b/lib/ObservationRepository.php @@ -0,0 +1,61 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu; + +/** + * The latest sample of each GPU (Schema, plugin_gpu_observation). + */ +final class ObservationRepository { + public function __construct(private readonly \PDO|false $connection) { + } + + /** + * Store one GPU's reading. The values replace the stored ones only when + * the tool took this sample later than the stored one, so snmpd handing + * back a cached sample, or a slow run finishing after a faster one, never + * moves a value back in time. reported_at always moves, because the GPU + * was reported either way. + */ + public function store(int $gpuId, int $nodeId, Reading $reading, string $backend, string $toolVersion, int $now): bool { + $columns = Schema::OBSERVATION_METRICS; + $values = []; + + foreach ($columns as $column) { + $values[] = $reading->values[$column] ?? null; + } + + $all = array_merge(['gpu_id', 'node_id', 'observed_at', 'ingested_at', 'reported_at', 'backend', 'tool_version'], $columns, ['thr_mask']); + $newer = 'VALUES(observed_at) > observed_at'; + $update = ['node_id = VALUES(node_id)']; + + // observed_at is assigned last: MySQL applies the assignments in + // order, so every other column still compares against the old time. + foreach (array_merge(['ingested_at', 'backend', 'tool_version'], $columns, ['thr_mask']) as $column) { + $update[] = "$column = IF($newer, VALUES($column), $column)"; + } + + $update[] = 'reported_at = VALUES(reported_at)'; + $update[] = "observed_at = IF($newer, VALUES(observed_at), observed_at)"; + + $sql = 'INSERT INTO plugin_gpu_observation (' . implode(', ', $all) . ') VALUES (' . implode(', ', array_fill(0, count($all), '?')) . ') ON DUPLICATE KEY UPDATE ' . implode(', ', $update); + + return (bool) db_execute_prepared($sql, array_merge([$gpuId, $nodeId, $reading->observedAt, $now, $now, $backend, $toolVersion], $values, [$reading->mask]), true, $this->connection); + } +} diff --git a/lib/Poller.php b/lib/Poller.php new file mode 100644 index 0000000..acdc720 --- /dev/null +++ b/lib/Poller.php @@ -0,0 +1,103 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu; + +/** + * One collector run, started from Cacti's poller_bottom hook by + * poller_gpu.php. Nodes are collected one at a time, least recently + * finished first, so a run that hits its time budget leaves the nodes it + * did not reach first in line for the next one. After a node is collected, + * its device is provisioned: data query attached, reindex run, graphs + * created. + * + * Only nodes whose device the main poller polls are collected. Remote data + * collectors are phase 3; their nodes are counted and left alone. + */ +final class Poller { + public const MAIN_POLLER = 1; + + public function __construct( + private readonly NodeRepository $nodes, + private readonly CollectionRepository $collections, + private readonly Collector $collector, + private readonly Provisioner $provisioner, + private readonly ReindexRepository $reindex, + private readonly Clock $clock, + ) { + } + + /** + * @return array{nodes: int, ok: int, failed: int, skipped: int, remote: int, reindexed: int, deferred: int, graphs: int, stopped_early: bool} + */ + public function run(Settings $settings, int $budget): array { + $stats = ['nodes' => 0, 'ok' => 0, 'failed' => 0, 'skipped' => 0, 'remote' => 0, 'reindexed' => 0, 'deferred' => 0, 'graphs' => 0, 'stopped_early' => false]; + $started = $this->clock->now(); + $statuses = $this->collections->all(); + $nodes = array_values(array_filter($this->nodes->all(), static fn (Node $node): bool => $node->enabled() && $node->deviceExists)); + + $last = static fn (Node $node): int => isset($statuses[$node->id]) ? $statuses[$node->id]->finishedAt : 0; + + usort($nodes, static fn (Node $a, Node $b): int => [$last($a), $a->id] <=> [$last($b), $b->id]); + + foreach ($nodes as $node) { + if ($this->clock->now() - $started >= $budget) { + $stats['stopped_early'] = true; + + break; + } + + $device = $this->nodes->device($node); + + if ($device === null || $device->disabled) { + $stats['skipped']++; + + continue; + } + + if ($device->pollerId !== self::MAIN_POLLER) { + $stats['remote']++; + + continue; + } + + $stats['nodes']++; + + $state = $this->collector->collect($node, $device, $settings); + + if ($state === ExecutionState::Skipped) { + $stats['skipped']++; + + continue; + } + + $stats[$state->succeeded() ? 'ok' : 'failed']++; + + // Read after the collection, which may have asked for one. + $request = $this->reindex->pending()[$node->id] ?? null; + $done = $this->provisioner->provision($node, $device, $request); + + $stats['reindexed'] += $done['reindexed'] ? 1 : 0; + $stats['deferred'] += $done['deferred'] ? 1 : 0; + $stats['graphs'] += $done['graphs']; + } + + return $stats; + } +} diff --git a/lib/Provisioner.php b/lib/Provisioner.php new file mode 100644 index 0000000..f52afab --- /dev/null +++ b/lib/Provisioner.php @@ -0,0 +1,287 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu; + +/** + * Keeps each node's Cacti device in step with its GPUs (ADR 0004, ADR 0010): + * the GPU data query attached, its indexes current, and a graph of each + * type for every present GPU. Every change goes through Cacti's own API + * (REQ-DEV-004). + * + * The data query is attached with reindex method None, because the plugin + * reindexes after each inventory change itself (REQ-INDEX-004) and must not + * depend on Cacti's scheduled reindex. Cacti's run_data_query() returns true + * without reindexing a device that is down or disabled, so a reindex counts + * as done only once Cacti's cache lists exactly the GPUs the plugin lists + * and the device was not down when it ran; until then the request stays and + * is retried every cycle. A cycle without a request still compares the two + * listings and asks for a reindex when they differ, so a request that was + * lost (a failed write, an interrupted collection) is made again. + */ +final class Provisioner { + // Cacti's DATA_QUERY_AUTOINDEX_NONE. + public const REINDEX_NONE = 0; + + public function __construct( + private readonly CactiObjectRepository $cacti, + private readonly CacheRepository $cache, + private readonly ReindexRepository $reindex, + private readonly Clock $clock, + ) { + } + + public function dataQueryId(): int { + return $this->cacti->idByHash('snmp_query', TemplateXml::hash('04', TemplateXml::DATA_QUERY)); + } + + /** + * Attach the GPU data query to the node's device, or reset its reindex + * method to None after a device template change set another. A new + * attachment asks for a reindex, which the next poller cycle verifies. + */ + public function attach(Node $node): bool { + $query = $this->dataQueryId(); + + if ($query === 0 || !$node->deviceExists) { + return false; + } + + $method = $this->cacti->reindexMethod($node->hostId, $query); + + if ($method === self::REINDEX_NONE) { + return true; + } + + api_device_dq_add($node->hostId, $query, self::REINDEX_NONE); + + if ($method === null) { + $this->reindex->request($node->id, 'data query attached', $this->clock->now()); + } + + return $this->cacti->reindexMethod($node->hostId, $query) === self::REINDEX_NONE; + } + + /** + * One poller cycle's work for a node: attach, run a requested reindex, + * and create missing graphs. + * + * @param array{requested_at: int, reason: string, attempts: int, detail: string, generation: int}|null $request + * + * @return array{reindexed: bool, deferred: bool, graphs: int} + */ + public function provision(Node $node, NodeDevice $device, ?array $request): array { + $result = ['reindexed' => false, 'deferred' => false, 'graphs' => 0]; + $query = $this->dataQueryId(); + + if ($query === 0 || !$this->attach($node)) { + return $result; + } + + if ($request !== null) { + if ($this->reindexNode($node, $device, $query, $request['generation'])) { + $result['reindexed'] = true; + } else { + $result['deferred'] = true; + } + } elseif (!$device->reindexBlocked()) { + $expected = $this->expected($node); + $cached = $this->cached($node, $query); + + if ($expected !== null && $cached !== null && $expected !== $cached) { + $this->reindex->request($node->id, 'listing differs from the cache', $this->clock->now()); + } + } + + if (!$device->disabled) { + $result['graphs'] = $this->createGraphs($node, $query); + } + + return $result; + } + + private function reindexNode(Node $node, NodeDevice $device, int $query, int $generation): bool { + $now = $this->clock->now(); + + if ($device->reindexBlocked()) { + $this->reindex->deferred($node->id, 'Cacti does not reindex a device that is down or disabled; retried once it is up', $now); + + return false; + } + + // Forced, because Cacti refreshes titles only for indexes that + // changed, and a GPU's index (its identity key) never does: a new + // GPU index, name, or bus ID would otherwise stay out of the titles. + $expected = $this->expected($node); + + if ($expected === null) { + $this->reindex->deferred($node->id, 'The GPU records could not be read; retried next cycle', $now); + + return false; + } + + if ($expected === []) { + // Cacti keeps its cache when a script data query lists no index, + // so the last GPU removed from the listing would stay cached. + // Drop the device's cache for the query and mark its data + // sources orphaned, as Cacti does for each removed index. An + // empty cache would match the empty listing below even if the + // data sources were not marked, so a failure keeps the request. + if (!$this->cacti->clearIndexes($node->hostId, $query)) { + $this->reindex->deferred($node->id, 'The GPU data query cache could not be cleared; retried next cycle', $now); + + return false; + } + } else { + run_data_query($node->hostId, $query, false, true); + } + + $cached = $this->cached($node, $query); + + // Cacti reads the device's status when it starts, and skips the + // reindex (still returning true) if the device went down after this + // cycle read it. The comparison below also catches a skipped + // reindex the status no longer shows, through the fields. + if ($this->cacti->reindexBlocked($node->hostId) !== false) { + $this->reindex->deferred($node->id, 'The device went down or was disabled during the reindex; retried once it is up', $now); + + return false; + } + + if ($cached === null || array_keys($cached) !== array_keys($expected)) { + $this->reindex->deferred($node->id, sprintf('The reindex listed %d of %d GPUs; retried next cycle', count(array_intersect_key($expected, $cached ?? [])), count($expected)), $now); + + return false; + } + + if ($cached !== $expected) { + $this->reindex->deferred($node->id, 'Cacti did not cache every GPU\'s current index, name, and bus ID; retried next cycle', $now); + + return false; + } + + $this->reindex->done($node->id, $generation); + + Log::info(sprintf('Node %d: GPU data query reindexed (%d GPUs)', $node->id, count($expected))); + + return true; + } + + /** + * What the plugin lists for the node, as Cacti caches it: identity key + * => input field values, sorted by key; null when the records could not + * be read. The fields are compared too, so a changed GPU index, name, + * or bus ID that Cacti has not cached is found without a request. + * + * @return array>|null + */ + private function expected(Node $node): ?array { + $listed = $this->cache->listed($node->hostId); + + if ($listed === null) { + return null; + } + + $out = []; + + foreach ($listed as $row) { + $out[ScriptServer::key($row)] = ScriptServer::inputs($row); + } + + ksort($out, SORT_STRING); + + return $out; + } + + /** + * @return array>|null what Cacti has cached, in the same form + */ + private function cached(Node $node, int $query): ?array { + $cached = $this->cacti->cachedFields($node->hostId, $query, array_keys(TemplateXml::INPUT_FIELDS)); + + if ($cached !== null) { + ksort($cached, SORT_STRING); + } + + return $cached; + } + + /** + * A graph of each type for every present GPU that Cacti has cached and + * that has none yet. A GPU's graphs share one data source, which + * create_complete_graph_from_template() reuses once it exists. Absent + * GPUs get no new graphs; the graphs they have stay. + */ + private function createGraphs(Node $node, int $query): int { + $graphed = $this->cacti->graphed($node->hostId, $query); + $cached = $this->cacti->cachedIndexes($node->hostId, $query); + $listed = $this->cache->listed($node->hostId); + + if ($graphed === null || $cached === null || $listed === null) { + return 0; + } + + $cachedSet = array_flip($cached); + $created = 0; + + foreach ($listed as $row) { + $index = Row::string($row, 'vendor') . '/' . Row::string($row, 'uuid'); + + if (Row::string($row, 'presence') !== Presence::Present->value || !isset($cachedSet[$index])) { + continue; + } + + foreach ($this->cacti->queryGraphs($query) as $queryGraph => $template) { + if (isset($graphed[$queryGraph . ':' . $index])) { + continue; + } + + $suggested = []; + $graph = create_complete_graph_from_template($template, $node->hostId, [ + 'snmp_query_id' => $query, + // Always the identity key, never Cacti's best guess. + 'snmp_index_on' => TemplateXml::SORT_FIELD, + 'snmp_query_graph_id' => $queryGraph, + 'snmp_index' => $index, + ], $suggested); + + if (!is_array($graph) || !isset($graph['local_graph_id'])) { + Log::warning(sprintf('Node %d: a GPU graph could not be created', $node->id)); + + continue; + } + + foreach ((array) ($graph['local_data_id'] ?? []) as $dataSource) { + if (is_numeric($dataSource)) { + push_out_host($node->hostId, (int) $dataSource); + } + } + + $graphed[$queryGraph . ':' . $index] = true; + $created++; + } + } + + if ($created > 0) { + Log::info(sprintf('Node %d: %d GPU graphs created', $node->id, $created)); + } + + return $created; + } +} diff --git a/lib/Reading.php b/lib/Reading.php new file mode 100644 index 0000000..390719f --- /dev/null +++ b/lib/Reading.php @@ -0,0 +1,38 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu; + +/** + * One GPU's values from one collection, in model units, with the time the + * tool took the sample. A null value is unknown, never zero. + */ +final readonly class Reading { + /** + * @param array $values metric name => value, for every + * model field the backend reads + */ + public function __construct( + public GpuReport $report, + public int $observedAt, + public array $values, + public ?int $mask, + ) { + } +} diff --git a/lib/ReindexRepository.php b/lib/ReindexRepository.php new file mode 100644 index 0000000..597a07a --- /dev/null +++ b/lib/ReindexRepository.php @@ -0,0 +1,74 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu; + +/** + * Data query reindexes the plugin owes node devices (Schema, + * plugin_gpu_reindex). A request is removed only once a reindex has run. + */ +final class ReindexRepository { + public function __construct(private readonly \PDO|false $connection) { + } + + /** + * Ask for a reindex. A request already waiting keeps its first time and + * its attempts, and its generation moves on, so a reindex that read the + * request before this one does not remove it. + */ + public function request(int $nodeId, string $reason, int $now): void { + db_execute_prepared('INSERT INTO plugin_gpu_reindex (node_id, requested_at, reason, generation) VALUES (?, ?, ?, 1) ON DUPLICATE KEY UPDATE reason = VALUES(reason), generation = generation + 1', [$nodeId, $now, mb_substr($reason, 0, 64)], true, $this->connection); + } + + /** + * @return array node id => request + */ + public function pending(): array { + $out = []; + + foreach (Row::rows(db_fetch_assoc_prepared('SELECT * FROM plugin_gpu_reindex ORDER BY requested_at, node_id', [], true, $this->connection)) as $row) { + $out[Row::int($row, 'node_id')] = [ + 'requested_at' => Row::int($row, 'requested_at'), + 'reason' => Row::string($row, 'reason'), + 'attempts' => Row::int($row, 'attempts', 0, 0), + 'detail' => Row::string($row, 'detail'), + 'generation' => Row::int($row, 'generation', 0, 0), + ]; + } + + return $out; + } + + /** + * Record an attempt that could not reindex, such as a device Cacti + * holds down; the request stays for the next cycle. + */ + public function deferred(int $nodeId, string $detail, int $now): void { + db_execute_prepared('UPDATE plugin_gpu_reindex SET attempts = attempts + 1, last_attempt_at = ?, detail = ? WHERE node_id = ?', [$now, mb_substr($detail, 0, 255), $nodeId], true, $this->connection); + } + + /** + * Remove a request that a reindex has served. Only the request as it was + * read is removed: one made after the reindex started has a later generation + * and stays. + */ + public function done(int $nodeId, int $generation): void { + db_execute_prepared('DELETE FROM plugin_gpu_reindex WHERE node_id = ? AND generation = ?', [$nodeId, $generation], true, $this->connection); + } +} diff --git a/lib/Row.php b/lib/Row.php index 117111a..9a62944 100644 --- a/lib/Row.php +++ b/lib/Row.php @@ -82,6 +82,18 @@ public static function string(array $row, string $key): string { return is_scalar($value) ? trim((string) $value) : ''; } + /** + * A string exactly as stored, for values whose spaces are significant, + * such as SNMPv3 passphrases. + * + * @param array $row + */ + public static function untrimmed(array $row, string $key): string { + $value = $row[$key] ?? null; + + return is_scalar($value) ? (string) $value : ''; + } + /** * Result of a db_fetch_assoc*() call, which returns false on error. An * error reads as no rows, and non-array rows are dropped. diff --git a/lib/Schema.php b/lib/Schema.php index c7436ba..3cd3ea3 100644 --- a/lib/Schema.php +++ b/lib/Schema.php @@ -35,12 +35,24 @@ * RRD file, or contacts a GPU node (REQ-LIFE-003, REQ-LIFE-005). */ final class Schema { - public const VERSION = 1; + public const VERSION = 2; public const HOOKS = [ 'config_arrays' => 'gpu_config_arrays', 'config_settings' => 'gpu_config_settings', 'draw_navigation_text' => 'gpu_draw_navigation_text', + 'poller_bottom' => 'gpu_poller_bottom', + 'device_remove' => 'gpu_device_remove', + 'api_device_new' => 'gpu_api_device_new', + ]; + + // The metric columns of plugin_gpu_observation, as migration 2 created + // them. A later model change adds a migration; it never edits this list. + // age is computed when it is read, so it has no column. + public const OBSERVATION_METRICS = [ + 'util_gpu', 'util_mem', 'mem_used', 'mem_total', 'temp_gpu', 'power', 'power_limit', + 'clock_sm', 'clock_mem', 'ecc_corr', 'ecc_uncorr', 'retired_pending', + 'thr_sw_power_cap', 'thr_hw_slowdown', 'thr_sw_thermal', 'thr_hw_thermal', 'thr_hw_power_brake', ]; private const PLUGIN = 'gpu'; @@ -108,7 +120,7 @@ public function pluginEnabled(): bool { return (int) db_fetch_cell_prepared('SELECT status FROM plugin_config WHERE directory = ?', [self::PLUGIN], '', true, $this->connection) === 1; } - public function hooksRegistered(): bool { + public function hooksRegistered(): bool { $placeholders = implode(', ', array_fill(0, count(self::HOOKS), '?')); $hooks = (int) db_fetch_cell_prepared("SELECT COUNT(DISTINCT hook) FROM plugin_hooks WHERE name = ? AND hook IN ($placeholders)", array_merge([self::PLUGIN], array_keys(self::HOOKS)), '', true, $this->connection); @@ -137,7 +149,8 @@ public function forgetVersion(): void { */ private function migrations(): array { return [ - 1 => fn (): bool => $this->createTables(self::tables()), + 1 => fn (): bool => $this->createTables(array_intersect_key(self::tables(), array_flip(['plugin_gpu_node', 'plugin_gpu_gpu']))), + 2 => fn (): bool => $this->createTables(array_intersect_key(self::tables(), array_flip(['plugin_gpu_observation', 'plugin_gpu_collection', 'plugin_gpu_reindex', 'plugin_gpu_retired']))), ]; } @@ -191,12 +204,14 @@ public static function tables(): array { $id = static fn (string $name): array => ['name' => $name, 'type' => 'int(10)', 'unsigned' => true, 'NULL' => false]; $time = static fn (string $name): array => ['name' => $name, 'type' => 'int(10)', 'unsigned' => true, 'NULL' => false, 'default' => '0']; $text = static fn (string $name, int $length, string $default = ''): array => ['name' => $name, 'type' => "varchar($length)", 'NULL' => false, 'default' => $default]; + $count = static fn (string $name): array => ['name' => $name, 'type' => 'int(10)', 'unsigned' => true, 'NULL' => false, 'default' => '0']; + $metric = static fn (string $name): array => ['name' => $name, 'type' => 'double', 'NULL' => true]; return [ // GPU nodes: Cacti devices an operator has registered for GPU - // monitoring. How a node is reached is decided by #7 and added - // by the collector's migration; nothing here is a command, path, - // or URL. + // monitoring. A node is read through its device's SNMP settings + // (ADR 0008), so nothing here is a command, path, credential, or + // URL. 'plugin_gpu_node' => $innodb + [ 'comment' => 'Cacti devices registered as GPU nodes', 'columns' => [ @@ -241,6 +256,88 @@ public static function tables(): array { 'unique_keys' => [['name' => 'vendor_uuid', 'columns' => ['vendor', 'uuid']]], 'keys' => [['name' => 'node_id', 'columns' => ['node_id']]], ], + // The latest sample of each GPU, in model units (ADR 0009); NULL + // is unknown. The script server input reads only this table and + // the records above (REQ-SS-001). A sample replaces the stored + // one only when the tool took it later, so a delayed or repeated + // read never moves a value back in time. + 'plugin_gpu_observation' => $innodb + [ + 'comment' => 'Latest GPU samples', + 'columns' => array_merge( + [ + $id('gpu_id'), + $id('node_id'), + // When the tool took the sample, from its own timestamp. + $time('observed_at'), + // When the plugin stored it. + $time('ingested_at'), + // When a successful collection last reported this GPU, + // even with an unchanged sample. + $time('reported_at'), + $text('backend', 32), + $text('tool_version', 64), + ], + array_map($metric, self::OBSERVATION_METRICS), + // The raw clock event reasons mask, so bits without an + // indicator are kept (ADR 0009). + [['name' => 'thr_mask', 'type' => 'bigint(20)', 'unsigned' => true, 'NULL' => true]], + ), + 'primary' => 'gpu_id', + 'keys' => [['name' => 'node_id', 'columns' => ['node_id']]], + ], + // How the latest collection at each node ended (PLAN, + // Measurement state). The state is an ExecutionState value; the + // detail never quotes tool output. + 'plugin_gpu_collection' => $innodb + [ + 'comment' => 'Latest collection result per node', + 'columns' => [ + $id('node_id'), + $text('state', 32), + $text('detail', 255), + $time('started_at'), + $time('finished_at'), + // The newest sample time in the collection. + $time('observed_at'), + $count('gpus'), + $count('new_gpus'), + $count('rejected_lines'), + // Runs skipped because another held the node, since the + // last one that ran. + $count('skipped'), + $time('last_ok_at'), + ], + 'primary' => 'node_id', + ], + // A data query reindex the plugin owes a node's device, kept + // until it runs. Cacti's run_data_query() returns true without + // reindexing a device that is down or disabled, so a request + // stays here until the device is up (REQ-INDEX-004). + 'plugin_gpu_reindex' => $innodb + [ + 'comment' => 'Pending data query reindexes per node', + 'columns' => [ + $id('node_id'), + $time('requested_at'), + $text('reason', 64), + // Moves on with every request; see ReindexRepository::done(). + $count('generation'), + $count('attempts'), + $time('last_attempt_at'), + $text('detail', 255), + ], + 'primary' => 'node_id', + ], + // GPUs an operator removed from the data query (REQ-INDEX-005). + // The identity record and its graphs stay; the GPU only stops + // being an index, and returns as one if it is reported again. + 'plugin_gpu_retired' => $innodb + [ + 'comment' => 'GPUs removed from the data query by an operator', + 'columns' => [ + $id('gpu_id'), + $time('retired_at'), + $id('retired_by') + ['default' => '0'], + ], + 'primary' => 'gpu_id', + ], ]; } } diff --git a/lib/ScriptServer.php b/lib/ScriptServer.php new file mode 100644 index 0000000..532814a --- /dev/null +++ b/lib/ScriptServer.php @@ -0,0 +1,163 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu; + +/** + * The GPU data query's script server input (REQ-SS-001 to REQ-SS-004): + * index, num_indexes, query, and get, as resource/script_server/ + * plugin_gpu.xml defines them. It reads only the plugin's cache. + * + * Arguments come from Cacti's poller, but are still checked: the device id + * must be a number and an index must be a GPU identity key. A bad argument + * or a failed read prints an empty listing or U, never 0. + */ +final class ScriptServer { + public function __construct( + private readonly CacheRepository $cache, + private readonly Clock $clock, + private readonly int $staleAfter, + ) { + } + + public function call(string $hostId, string $command, string $field = '', string $index = ''): string { + if (preg_match('/^[1-9][0-9]{0,9}$/', $hostId) !== 1) { + return $command === 'get' ? 'U' : ''; + } + + return match ($command) { + 'index' => $this->index((int) $hostId), + 'num_indexes' => $this->count((int) $hostId), + 'query' => $this->query((int) $hostId, $field), + 'get' => $this->get((int) $hostId, $field, $index), + default => '', + }; + } + + private function index(int $hostId): string { + return implode("\n", array_map(self::key(...), $this->cache->listed($hostId) ?? [])); + } + + private function count(int $hostId): string { + $rows = $this->cache->listed($hostId); + + return $rows === null ? '' : (string) count($rows); + } + + private function query(int $hostId, string $field): string { + $input = self::input($field); + + if ($input === null && MetricModel::find($field) === null) { + return ''; + } + + $rows = $input === null ? $this->cache->samples($hostId) : $this->cache->listed($hostId); + $now = $this->clock->now(); + $out = []; + + foreach ($rows ?? [] as $row) { + $value = $input === null ? Freshness::format(Freshness::value($field, $row, $now, $this->staleAfter)) : self::text($row, $input); + $out[] = self::key($row) . '!' . $value; + } + + return implode("\n", $out); + } + + private function get(int $hostId, string $field, string $index): string { + if (MetricModel::find($field) === null) { + $input = self::input($field); + + if ($input === null) { + return 'U'; + } + + foreach ($this->cache->listed($hostId) ?? [] as $row) { + if (self::key($row) === $index) { + return self::text($row, $input); + } + } + + return 'U'; + } + + $parts = explode('/', $index, 2); + $vendor = Vendor::tryFrom($parts[0]); + + if ($vendor === null || count($parts) !== 2 || preg_match('/^[A-Za-z0-9-]{1,96}$/', $parts[1]) !== 1) { + return 'U'; + } + + $row = $this->cache->sample($hostId, $vendor, $parts[1]); + + return $row === null ? 'U' : Freshness::format(Freshness::value($field, $row, $this->clock->now(), $this->staleAfter)); + } + + /** + * The record column an input field's query name reads, or null. + */ + private static function input(string $queryName): ?string { + return match ($queryName) { + 'index' => 'key', + 'gpu_index' => 'gpu_index', + 'name' => 'name', + 'pci_bus_id' => 'pci_bus_id', + default => null, + }; + } + + /** + * Each input field's value for a GPU record, by data query field name, + * as Cacti stores it in its cache from this listing: the listed text, + * hex encoded when it is not valid text, as data_query_format_record() + * does. + * + * @param array $row + * + * @return array + */ + public static function inputs(array $row): array { + $out = []; + + foreach (TemplateXml::INPUT_FIELDS as $field => [$queryName]) { + $value = self::text($row, self::input($queryName) ?? ''); + $out[$field] = mb_detect_encoding($value) === false ? bin2hex($value) : $value; + } + + return $out; + } + + /** + * @param array $row + */ + public static function key(array $row): string { + return Row::string($row, 'vendor') . '/' . Row::string($row, 'uuid'); + } + + /** + * An input field's text, on one line, so it cannot add a row to the + * listing Cacti parses. + * + * @param array $row + */ + private static function text(array $row, string $column): string { + $text = $column === 'key' ? self::key($row) : Row::string($row, $column); + + return trim((string) preg_replace('/[\x00-\x1F\x7F]+/', ' ', $text)); + } +} diff --git a/lib/Settings.php b/lib/Settings.php index aaca644..e854ac2 100644 --- a/lib/Settings.php +++ b/lib/Settings.php @@ -21,20 +21,29 @@ /** * Plugin settings, read once per request from Cacti's settings table - * (REQ-UI-003). Collection settings arrive with the collector. + * (REQ-UI-003). */ final readonly class Settings { public const NAMES = [ 'gpu_absent_after', + 'gpu_stale_after', 'gpu_uninstall_keep_tables', ]; public const DEFAULT_ABSENT_AFTER = 3; public const MAX_ABSENT_AFTER = 100; + // Seconds after which a stored sample is too old to graph (REQ-SS-004). + // Twice the default poller interval, so one late collection leaves no + // gap, while a stopped collector shows as gaps within ten minutes. + public const DEFAULT_STALE_AFTER = 600; + public const MIN_STALE_AFTER = 60; + public const MAX_STALE_AFTER = 86400; + public function __construct( public int $absentAfter, public bool $keepTablesOnUninstall, + public int $staleAfter = self::DEFAULT_STALE_AFTER, ) { } @@ -49,6 +58,7 @@ public static function fromRow(array $row): self { return new self( absentAfter: min(Row::int($row, 'gpu_absent_after', self::DEFAULT_ABSENT_AFTER, 1), self::MAX_ABSENT_AFTER), keepTablesOnUninstall: array_key_exists('gpu_uninstall_keep_tables', $row) ? Row::bool($row, 'gpu_uninstall_keep_tables') : true, + staleAfter: max(self::MIN_STALE_AFTER, min(Row::int($row, 'gpu_stale_after', self::DEFAULT_STALE_AFTER, 1), self::MAX_STALE_AFTER)), ); } @@ -73,6 +83,20 @@ public static function form(): array { 'max_length' => '3', 'size' => '3', ], + 'gpu_header_collection' => [ + 'friendly_name' => __('GPU Collection', 'gpu'), + 'method' => 'spacer', + ], + 'gpu_stale_after' => [ + 'friendly_name' => __('Stale After', 'gpu'), + 'description' => __('Seconds after the tool took a sample that its values stop being graphed, from 60 to 86400. An older value is reported as unknown, so a stopped collection shows as a gap, never as a flat line. The GPU age value keeps counting so it can be alerted on.', 'gpu'), + 'method' => 'textbox', + 'default' => (string) self::DEFAULT_STALE_AFTER, + 'filter' => FILTER_VALIDATE_INT, + 'options' => ['options' => ['min_range' => self::MIN_STALE_AFTER, 'max_range' => self::MAX_STALE_AFTER]], + 'max_length' => '5', + 'size' => '5', + ], 'gpu_header_uninstall' => [ 'friendly_name' => __('Uninstall', 'gpu'), 'method' => 'spacer', diff --git a/lib/SnmpExtendReader.php b/lib/SnmpExtendReader.php new file mode 100644 index 0000000..19b0d09 --- /dev/null +++ b/lib/SnmpExtendReader.php @@ -0,0 +1,143 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu; + +/** + * NET-SNMP-EXTEND-MIB through Cacti's own SNMP functions, with the + * credentials Cacti holds for the device (ADR 0008). + * + * The tables are indexed by the entry name, encoded as its length and then + * one sub-identifier per byte, and, in nsExtendOutput2Table, by line number. + * The line number is a position, never an identity: the GPU UUID comes from + * the line itself (ADR 0003). + */ +final class SnmpExtendReader implements ExtendReader { + // NET-SNMP-EXTEND-MIB::nsExtendObjects + private const OBJECTS = '.1.3.6.1.4.1.8072.1.3.2'; + // nsExtendOutput1Entry columns 3 and 4. + private const NUM_LINES = self::OBJECTS . '.3.1.3'; + private const RESULT = self::OBJECTS . '.3.1.4'; + // nsExtendOutput2Entry column 2. + private const OUT_LINE = self::OBJECTS . '.4.1.2'; + // SNMPv2-MIB::sysUpTime.0, read only to tell a missing entry from a + // silent agent. + private const UPTIME = '.1.3.6.1.2.1.1.3.0'; + + // The first read after snmpd's cache expires waits while the agent runs + // the command, up to timeout(1)'s limit and kill delay, so it gets that + // long plus a margin for the network, whatever the device's timeout. + public const EXTEND_TIMEOUT_MS = (SnmpdConfig::TIMEOUT + SnmpdConfig::KILL_AFTER + 3) * 1000; + + public function __construct(private readonly int $retries) { + } + + public static function index(string $token): string { + return strlen($token) . '.' . implode('.', array_map('ord', str_split($token))); + } + + public function read(NodeDevice $device, string $token): ExtendOutput { + $index = self::index($token); + $result = $this->value($device, self::RESULT . '.' . $index, max($device->snmpTimeout, self::EXTEND_TIMEOUT_MS)); + + if (!is_numeric($result)) { + $uptime = $this->value($device, self::UPTIME); + + throw $uptime !== '' && $uptime !== 'U' + ? new CollectionError(ExecutionState::NotConfigured, sprintf('The SNMP agent has no extend entry named %s', $token)) + : new CollectionError(ExecutionState::Unreachable, 'The SNMP agent did not answer'); + } + + $declared = $this->value($device, self::NUM_LINES . '.' . $index); + $lines = []; + $prefix = ltrim(self::OUT_LINE . '.' . $index . '.', '.'); + + foreach ($this->walk($device, self::OUT_LINE . '.' . $index) as $entry) { + $oid = ltrim(Row::string($entry, 'oid'), '.'); + + if (!str_starts_with($oid, $prefix) || !ctype_digit(substr($oid, strlen($prefix)))) { + continue; + } + + $lines[(int) substr($oid, strlen($prefix))] = Row::string($entry, 'value'); + } + + ksort($lines); + + // The result, the line count, and the lines are separate requests, + // and snmpd may run the command again between them when its cache + // expires. Reading the result and count again after the lines shows + // whether they all came from one run; a run that changed them (a + // timeout that left partial output, for example) is not used. + $after = $this->value($device, self::RESULT . '.' . $index, max($device->snmpTimeout, self::EXTEND_TIMEOUT_MS)); + $declaredAfter = $this->value($device, self::NUM_LINES . '.' . $index); + + if ($after !== $result || $declaredAfter !== $declared) { + throw new CollectionError(ExecutionState::InvalidOutput, sprintf('The output of %s changed while it was read; the next collection reads it again', $token)); + } + + return new ExtendOutput((int) $result, is_numeric($declared) ? (int) $declared : -1, array_values($lines)); + } + + /** + * One value from the device, trimmed; '' or 'U' when it gave none. + * + * Read through a Cacti SNMP session built from the device's fields, as + * Cacti's poller and data queries read a device. Cacti 1.2.x's + * cacti_snmp_get() puts an IPv4 address or a host name in brackets when + * the port is not 161, and PHP's SNMP extension then resolves the name + * as IPv6 only, so every read of such a device fails ("Unknown failure + * while resolving '[192.0.2.10]:1161'"). Its sessions bracket only an + * address that contains a colon. cacti_snmp_get() is still used when no + * session can be made, such as on Cacti 1.2.31 without PHP's SNMP + * extension, where it runs the Net-SNMP tools and is not affected. + */ + public function value(NodeDevice $device, string $oid, ?int $timeout = null): string { + $timeout ??= $device->snmpTimeout; + + try { + $session = cacti_snmp_session($device->hostname, $device->snmpCommunity, $device->snmpVersion, $device->snmpUsername, $device->snmpPassword, $device->snmpAuthProtocol, $device->snmpPrivPassphrase, $device->snmpPrivProtocol, $device->snmpContext, $device->snmpEngineId, $device->snmpPort, $timeout, $this->retries, $device->maxOids); + } catch (\Throwable) { + // Cacti 1.2.31 lets an Error from PHP's SNMP class through: the + // class is missing, or it rejects an SNMPv3 protocol. + $session = false; + } + + if (!is_object($session)) { + return trim((string) cacti_snmp_get($device->hostname, $device->snmpCommunity, $oid, $device->snmpVersion, $device->snmpUsername, $device->snmpPassword, $device->snmpAuthProtocol, $device->snmpPrivPassphrase, $device->snmpPrivProtocol, $device->snmpContext, $device->snmpPort, $timeout, $this->retries, 'GPU', $device->snmpEngineId)); + } + + try { + $value = cacti_snmp_session_get($session, $oid); + } catch (\Throwable) { + $value = false; + } + + return is_scalar($value) && $value !== false ? trim((string) $value) : ''; + } + + /** + * @return list> + */ + private function walk(NodeDevice $device, string $oid): array { + $rows = cacti_snmp_walk($device->hostname, $device->snmpCommunity, $oid, $device->snmpVersion, $device->snmpUsername, $device->snmpPassword, $device->snmpAuthProtocol, $device->snmpPrivPassphrase, $device->snmpPrivProtocol, $device->snmpContext, $device->snmpPort, $device->snmpTimeout, $this->retries, $device->maxOids, 'GPU', $device->snmpEngineId); + + return is_array($rows) ? array_values(array_filter($rows, 'is_array')) : []; + } +} diff --git a/lib/SnmpdConfig.php b/lib/SnmpdConfig.php new file mode 100644 index 0000000..6877834 --- /dev/null +++ b/lib/SnmpdConfig.php @@ -0,0 +1,91 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu; + +/** + * The snmpd.conf lines a GPU node's administrator installs (ADR 0008). They + * are generated here so the documentation, the collector's entry names, and + * the field list the parser expects cannot drift apart; a unit test compares + * them with docs/node-setup.md. + * + * Each entry runs nvidia-smi with a fixed argument vector and no shell + * (extend without -execType sh), with an empty environment apart from TZ=UTC + * so the sample time is UTC, under timeout(1) so the child always exits + * before snmpd's cache for the entry expires. The plugin sends the agent + * nothing but read requests. + */ +final class SnmpdConfig { + public const METRICS = 'cacti_gpu'; + public const NAMES = 'cacti_gpu_names'; + + // Seconds snmpd keeps a result. Every Cacti poll inside the window sees + // the same sample, so the window bounds how fresh a value can be. + public const METRICS_CACHE = 30; + public const NAMES_CACHE = 300; + + // timeout(1) sends TERM after TIMEOUT seconds and KILL KILL_AFTER later, + // so the command ends well inside the cache window. + public const TIMEOUT = 10; + public const KILL_AFTER = 2; + + public const NVIDIA_SMI = '/usr/bin/nvidia-smi'; + + // extend.c formats the command and its arguments into 255 * 2 + 2 bytes. + public const MAX_COMMAND = 510; + + /** + * @return list + */ + public static function extendLines(): array { + return [ + self::line(self::METRICS, self::METRICS_CACHE, ['TZ=UTC'], MetricModel::nvidiaFields(), 'csv,noheader,nounits'), + self::line(self::NAMES, self::NAMES_CACHE, [], MetricModel::namesFields(), 'csv,noheader'), + ]; + } + + /** + * The command and arguments of each entry, as extend.c formats them. + * + * @return array entry name => command line + */ + public static function commands(): array { + $out = []; + + foreach (self::extendLines() as $line) { + $parts = explode(' ', $line, 5); + + $out[$parts[3]] = $parts[4]; + } + + return $out; + } + + /** + * @param list $env + * @param list $fields + */ + private static function line(string $name, int $cache, array $env, array $fields, string $format): string { + return implode(' ', array_merge( + ['extend', '-cacheTime', (string) $cache, $name, '/usr/bin/env', '-i'], + $env, + ['/usr/bin/timeout', '-k', (string) self::KILL_AFTER, (string) self::TIMEOUT, self::NVIDIA_SMI, '--query-gpu=' . implode(',', $fields), '--format=' . $format], + )); + } +} diff --git a/lib/TemplateInstaller.php b/lib/TemplateInstaller.php new file mode 100644 index 0000000..59aca02 --- /dev/null +++ b/lib/TemplateInstaller.php @@ -0,0 +1,190 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu; + +/** + * Installs the shipped Cacti objects (REQ-TPL-001 to REQ-TPL-005). + * + * The data query XML is copied to /resource/script_server/, + * the one place outside its own directory the plugin writes, and the path + * it wrote is recorded in the gpu_data_query_file setting. The templates + * are imported with import_xml_data(), which matches every object by hash, + * so a second import updates the first instead of adding copies. Both run + * under one advisory lock, so two upgrades cannot import at once. + * + * The import is skipped when the same file was imported before and the + * objects are still there. Nothing here creates a device, data source, + * graph, or RRD file. + */ +final class TemplateInstaller { + public const SETTING_FILE = 'gpu_data_query_file'; + public const SETTING_HASH = 'gpu_templates_sha256'; + + private const LOCK = 'templates'; + + public function __construct( + private readonly CactiObjectRepository $cacti, + private readonly LockRepository $locks, + private readonly string $pluginPath, + private readonly string $cactiPath, + ) { + } + + public function install(): bool { + if (!$this->locks->acquire(self::LOCK)) { + Log::info('Template import skipped because another upgrade is importing them'); + + return false; + } + + try { + return $this->placeDataQuery() && $this->importTemplates(); + } finally { + $this->locks->release(self::LOCK); + } + } + + public function dataQueryTarget(): string { + return $this->cactiPath . '/resource/script_server/' . TemplateXml::DATA_QUERY_FILE; + } + + private function placeDataQuery(): bool { + $source = (string) @file_get_contents($this->pluginPath . '/resource/script_server/' . TemplateXml::DATA_QUERY_FILE); + $target = $this->dataQueryTarget(); + + if ($source === '') { + Log::error('The GPU data query XML is missing from the plugin directory'); + + return false; + } + + if (@file_get_contents($target) !== $source) { + // Written beside the target and renamed over it, so the script + // server never reads a half-written file. + $temporary = $target . '.' . bin2hex(random_bytes(6)) . '.tmp'; + + if (@file_put_contents($temporary, $source) !== strlen($source) || !@rename($temporary, $target)) { + @unlink($temporary); + + Log::error(sprintf('Unable to write the GPU data query XML to %s; make the directory writable by the web server user', dirname($target))); + + return false; + } + } + + if (@file_get_contents($target) !== $source) { + Log::error('The GPU data query XML could not be verified after it was written'); + + return false; + } + + return $this->cacti->setting(self::SETTING_FILE) === $target || $this->cacti->saveSetting(self::SETTING_FILE, $target); + } + + private function importTemplates(): bool { + $xml = (string) @file_get_contents($this->pluginPath . '/templates/' . TemplateXml::TEMPLATE_FILE); + + if ($xml === '') { + Log::error('The GPU template XML is missing from the plugin directory'); + + return false; + } + + $digest = hash('sha256', $xml); + + if ($this->cacti->setting(self::SETTING_HASH) === $digest && $this->installed()) { + return true; + } + + $profile = $this->cacti->defaultProfileId(); + + if ($profile === 0) { + Log::error('The GPU templates were not imported because Cacti has no data source profile'); + + return false; + } + + $result = import_xml_data($xml, false, $profile); + + if (!self::succeeded($result) || !$this->installed()) { + Log::error('The GPU templates could not be imported; see the Cacti log for the import messages'); + + return false; + } + + Log::info('GPU templates imported'); + + return $this->cacti->saveSetting(self::SETTING_HASH, $digest); + } + + /** + * Whether every top-level object the template file defines exists, and + * Cacti's copy of the data query XML matches the plugin's: a Cacti + * redeployment can remove the copy while the database objects stay, and + * Cacti cannot run the query without it. + */ + public function installed(): bool { + $source = (string) @file_get_contents($this->pluginPath . '/resource/script_server/' . TemplateXml::DATA_QUERY_FILE); + + $target = $this->dataQueryTarget(); + + if ($source === '' || !is_file($target) || @file_get_contents($target) !== $source) { + return false; + } + + if ($this->cacti->idByHash('snmp_query', TemplateXml::hash('04', TemplateXml::DATA_QUERY)) === 0 + || $this->cacti->idByHash('host_template', TemplateXml::hash('02', TemplateXml::DEVICE_TEMPLATE)) === 0 + || $this->cacti->idByHash('data_template', TemplateXml::hash('01', TemplateXml::DATA_TEMPLATE)) === 0) { + return false; + } + + foreach (array_keys(TemplateXml::graphs()) as $graph) { + if ($this->cacti->idByHash('graph_templates', TemplateXml::hash('00', $graph)) === 0) { + return false; + } + } + + return true; + } + + /** + * import_xml_data() returns false or a list of objects per type, each + * with a result of success or fail. + */ + private static function succeeded(mixed $result): bool { + if (!is_array($result) || $result === []) { + return false; + } + + foreach ($result as $type => $objects) { + if ($type === 'files' || !is_array($objects)) { + continue; + } + + foreach ($objects as $object) { + if (is_array($object) && ($object['result'] ?? '') === 'fail') { + return false; + } + } + } + + return true; + } +} diff --git a/lib/TemplateXml.php b/lib/TemplateXml.php new file mode 100644 index 0000000..38797af --- /dev/null +++ b/lib/TemplateXml.php @@ -0,0 +1,344 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu; + +/** + * Generates the Cacti objects the plugin ships (REQ-TPL-001): the GPU data + * query's resource XML, and one template export holding the data template, + * the graph templates, the data query, and the GPU Node device template. + * + * The files under resource/ and templates/ are this class's output, and a + * unit test fails when they differ, so the shipped XML is reviewable and + * never drifts from the metric model. Hashes are derived from fixed names, + * so every release produces the same hash for the same object and a + * re-import updates it in place instead of adding a copy. + * + * Core objects are referenced by their own hashes and are not exported: + * import_xml_data() loads every existing hash before it resolves references. + */ +final class TemplateXml { + public const DATA_QUERY_FILE = 'plugin_gpu.xml'; + public const TEMPLATE_FILE = 'gpu_templates.xml'; + + // The Cacti 1.2 export format version code. + private const VERSION = '0103'; + + // Core's "Get Script Server Data (Indexed)" method and its fields. + private const SCRIPT_SERVER_DIM = 'hash_030103332111d8b54ac8ce939af87a7eac0c06'; + private const DIM_FIELDS = [ + 'hash_070103172b4b0eacee4948c6479f587b62e512', // index_type + 'hash_07010330fb5d5bcf3d66bb5abe88596f357c26', // index_value + 'hash_07010331112c85ae4ff821d3b288336288818c', // output_type + ]; + + // Core's "Normal" GPRINT preset and "5 Minute Collection" profile. + // import_xml_data() replaces the profile with the one it is given. + private const GPRINT = 'hash_060103e9c43831e54eca8069317a2ce8c6f751'; + private const PROFILE = 'hash_200103d62c52891f4f9688729a5bc9fad91b18'; + + private const LINE1 = 4; + private const LINE2 = 5; + private const AREA = 7; + private const GPRINT_ITEM = 9; + + private const CF_AVERAGE = 1; + private const CF_MAX = 3; + private const CF_LAST = 4; + + public const DATA_TEMPLATE = 'GPU - Metrics'; + public const DATA_QUERY = 'GPU - Devices'; + public const DEVICE_TEMPLATE = 'GPU Node'; + + // The data query's sort field: the identity key (ADR 0003). + public const SORT_FIELD = 'gpuKey'; + + // Identity fields the data query lists for each GPU. + public const INPUT_FIELDS = [ + 'gpuKey' => ['index', 'Identity key'], + 'gpuIndex' => ['gpu_index', 'GPU index'], + 'gpuName' => ['name', 'Product name'], + 'gpuBusId' => ['pci_bus_id', 'PCI bus ID'], + ]; + + /** + * The graph templates (REQ-GRAPH-001). Each item draws one model field; + * none uses a vendor-only field (REQ-GRAPH-004). Unknown values are + * drawn as gaps because no item applies a CDEF (REQ-GRAPH-002). + * + * Every model field must be drawn by some graph: Cacti's + * rrdtool_function_create() puts only data source items that a graph + * item uses into the RRD file, so an undrawn field (a throttle + * indicator, an ECC count, the sample age) would never be stored. + * + * @return array}> + */ + public static function graphs(): array { + return [ + 'GPU - Utilization' => ['label' => 'percent', 'base' => 1000, 'upper' => '100', 'items' => [ + ['util_gpu', self::LINE2, '76B900', 'GPU'], + ['util_mem', self::LINE1, '0072C6', 'Memory controller'], + ]], + 'GPU - Memory' => ['label' => 'bytes', 'base' => 1024, 'upper' => '0', 'items' => [ + ['mem_total', self::AREA, 'C9DDF0', 'Total'], + ['mem_used', self::AREA, '0072C6', 'Used'], + ]], + 'GPU - Temperature' => ['label' => 'degrees C', 'base' => 1000, 'upper' => '0', 'items' => [ + ['temp_gpu', self::LINE2, 'D9541E', 'GPU'], + ]], + 'GPU - Power' => ['label' => 'watts', 'base' => 1000, 'upper' => '0', 'items' => [ + ['power', self::AREA, 'F2B705', 'Draw'], + ['power_limit', self::LINE1, 'B00020', 'Limit'], + ]], + 'GPU - Clocks' => ['label' => 'MHz', 'base' => 1000, 'upper' => '0', 'items' => [ + ['clock_sm', self::LINE2, '76B900', 'SM'], + ['clock_mem', self::LINE1, '7A3E9D', 'Memory'], + ]], + 'GPU - Throttle' => ['label' => 'active (0 or 1)', 'base' => 1000, 'upper' => '1', 'items' => [ + ['thr_sw_power_cap', self::LINE1, 'F2B705', 'Software power cap'], + ['thr_hw_slowdown', self::LINE1, '7A3E9D', 'Hardware slowdown'], + ['thr_sw_thermal', self::LINE1, 'D9541E', 'Software thermal'], + ['thr_hw_thermal', self::LINE1, 'B00020', 'Hardware thermal'], + ['thr_hw_power_brake', self::LINE1, '0072C6', 'Hardware power brake'], + ['retired_pending', self::LINE1, '555555', 'Page retirement pending'], + ]], + 'GPU - ECC Errors' => ['label' => 'errors since driver load', 'base' => 1000, 'upper' => '0', 'items' => [ + ['ecc_corr', self::LINE1, '0072C6', 'Corrected'], + ['ecc_uncorr', self::LINE2, 'B00020', 'Uncorrected'], + ]], + 'GPU - Sample Age' => ['label' => 'seconds', 'base' => 1000, 'upper' => '0', 'items' => [ + ['age', self::LINE1, '555555', 'Age of the latest sample'], + ]], + ]; + } + + /** + * A Cacti hash: type code, version code, and the md5 of a fixed name. + */ + public static function hash(string $type, string $name): string { + return 'hash_' . $type . self::VERSION . md5('plugin_gpu:' . $type . ':' . $name); + } + + public static function title(string $graph): string { + return '|host_description| - GPU |query_gpuIndex| |query_gpuName| - ' . substr($graph, strlen('GPU - ')); + } + + public static function dataQuery(): string { + $fields = []; + + foreach (self::INPUT_FIELDS as $field => [$query, $name]) { + $fields[] = self::element($field, ['name' => $name, 'direction' => 'input', 'query_name' => $query], 2); + } + + foreach (MetricModel::all() as $metric) { + $fields[] = self::element($metric->name, ['name' => $metric->label, 'direction' => 'output', 'query_name' => $metric->name], 2); + } + + return "\n" . self::lines([ + 'name' => 'GPU devices', + 'description' => 'GPUs from the GPU plugin cache, one index per GPU identity', + 'script_path' => '|path_cacti|/plugins/gpu/ss_gpu.php', + 'script_function' => 'ss_gpu', + 'script_server' => 'php', + 'arg_prepend' => '|host_id|', + 'arg_index' => 'index', + 'arg_num_indexes' => 'num_indexes', + 'arg_query' => 'query', + 'arg_get' => 'get', + // The index is vendor/UUID, which never contains this character. + 'output_delimiter' => '!', + // Cacti re-maps data sources to indexes by the sort field's value + // at each reindex, so it must be the identity key alone: sorting + // by the GPU index would follow a slot, not a card. + 'index_order' => self::SORT_FIELD, + 'index_order_type' => 'alphabetic', + 'index_title_format' => '|chosen_order_field|', + ], 1) . "\t\n" . implode('', $fields) . "\t\n\n"; + } + + public static function templates(): string { + $dataTemplate = self::hash('01', self::DATA_TEMPLATE); + $dataQuery = self::hash('04', self::DATA_QUERY); + $out = "\n"; + + $out .= self::element(self::hash('02', self::DEVICE_TEMPLATE), [ + 'name' => self::DEVICE_TEMPLATE, + 'class' => 'hpc', + 'graph_templates' => '', + 'data_queries' => $dataQuery, + ], 1); + + foreach (self::graphs() as $name => $graph) { + $out .= self::graphTemplate($name, $graph, $dataTemplate); + } + + $out .= self::dataTemplate($dataTemplate); + $out .= self::queryExport($dataQuery, $dataTemplate); + + return $out . "\n"; + } + + /** + * @param array{label: string, base: int, upper: string, items: list} $graph + */ + private static function graphTemplate(string $name, array $graph, string $dataTemplate): string { + $settings = [ + 'title' => self::title($name), 'vertical_label' => $graph['label'], 'image_format_id' => '3', 'height' => '200', 'width' => '700', + 'base_value' => (string) $graph['base'], 'slope_mode' => 'on', 'auto_scale' => 'on', 'auto_scale_opts' => '2', 'auto_scale_log' => '', + 'scale_log_units' => '', 'auto_scale_rigid' => '', 'upper_limit' => $graph['upper'], 'lower_limit' => '0', 'unit_value' => '', + 'unit_exponent_value' => '', 'unit_length' => '', 'no_gridfit' => '', 'alt_y_grid' => '', 'right_axis' => '', 'right_axis_label' => '', + 'right_axis_format' => '0', 'right_axis_formatter' => '0', 'left_axis_formatter' => '0', 'auto_padding' => 'on', 'dynamic_labels' => '', + 'force_rules_legend' => '', 'tab_width' => '', 'legend_position' => '0', 'legend_direction' => '0', + ]; + + $graphXml = ''; + + foreach ($settings as $field => $value) { + $graphXml .= self::line('t_' . $field, $field === 'title' ? 'on' : '', 3) . self::line($field, $value, 3); + } + + $items = ''; + $inputs = ''; + $sequence = 0; + + foreach ($graph['items'] as [$metric, $type, $color, $text]) { + $members = []; + $task = self::hash('08', $metric); + + $draws = [ + [$type, $color, self::CF_AVERAGE, $text, ''], + [self::GPRINT_ITEM, '', self::CF_LAST, 'Current:', ''], + [self::GPRINT_ITEM, '', self::CF_AVERAGE, 'Average:', ''], + [self::GPRINT_ITEM, '', self::CF_MAX, 'Maximum:', 'on'], + ]; + + foreach ($draws as [$itemType, $itemColor, $cf, $itemText, $return]) { + $sequence++; + + $hash = self::hash('10', $name . ':' . $sequence); + $members[] = 'hash_00' . substr($hash, 7); + + $items .= self::element($hash, [ + 'graph_type_id' => (string) $itemType, 'task_item_id' => $task, 'color_id' => $itemColor === '' ? '0' : $itemColor, 'alpha' => 'FF', + 'consolidation_function_id' => (string) $cf, 'cdef_id' => '0', 'vdef_id' => '0', 'shift' => '', 'value' => '', 'gprint_id' => self::GPRINT, + 'textalign' => '', 'text_format' => $itemText, 'hard_return' => $return, 'line_width' => $itemType === self::LINE2 ? '2.00' : '1.00', + 'dashes' => '', 'dash_offset' => '0', 'sequence' => (string) $sequence, + ], 3); + } + + $inputs .= self::element(self::hash('09', $name . ':' . $metric), [ + 'name' => 'Data Source [' . $metric . ']', 'description' => '', 'column_name' => 'task_item_id', 'items' => implode('|', $members), + ], 3); + } + + return "\t<" . self::hash('00', $name) . ">\n" . self::lines(['name' => $name, 'multiple' => '', 'test_source' => ''], 2) + . "\t\t\n" . $graphXml . "\t\t\n" + . "\t\t\n" . $items . "\t\t\n" + . "\t\t\n" . $inputs . "\t\t\n" + . "\t\n"; + } + + private static function dataTemplate(string $hash): string { + $ds = self::lines([ + 't_name' => '', 'name' => '|host_description| - GPU |query_gpuIndex| |query_gpuName|', 'data_source_path' => '', + 'data_input_id' => self::SCRIPT_SERVER_DIM, 't_data_source_profile_id' => '', 'data_source_profile_id' => self::PROFILE, + 't_rrd_step' => '', 'rrd_step' => '300', 't_active' => '', 'active' => 'on', + ], 3); + + $items = ''; + + foreach (MetricModel::all() as $metric) { + $items .= self::element(self::hash('08', $metric->name), [ + 't_data_source_name' => '', 'data_source_name' => $metric->name, 't_rrd_minimum' => '', 'rrd_minimum' => $metric->rrdMin(), + 't_rrd_maximum' => '', 'rrd_maximum' => $metric->rrdMax(), 't_data_source_type_id' => '', 'data_source_type_id' => '1', + 't_rrd_heartbeat' => '', 'rrd_heartbeat' => '600', 't_data_input_field_id' => '', 'data_input_field_id' => '0', + ], 3); + } + + $data = ''; + + foreach (self::DIM_FIELDS as $i => $field) { + $data .= self::element(sprintf('item_%03d', $i), ['data_input_field_id' => $field, 't_value' => 'on', 'value' => ''], 3); + } + + return "\t<$hash>\n" . self::line('name', self::DATA_TEMPLATE, 2) + . "\t\t\n" . $ds . "\t\t\n" + . "\t\t\n" . $items . "\t\t\n" + . "\t\t\n" . $data . "\t\t\n" + . "\t\n"; + } + + private static function queryExport(string $hash, string $dataTemplate): string { + $graphs = ''; + + // Every graph maps every field, so whichever graph creates a GPU's + // data source first, the data source polls all of them and the other + // graphs reuse it: one RRD file per GPU. + foreach (array_keys(self::graphs()) as $name) { + $rrd = ''; + + foreach (MetricModel::all() as $i => $metric) { + $rrd .= self::element(sprintf('item_%03d', $i), [ + 'snmp_field_name' => $metric->name, 'data_template_id' => $dataTemplate, 'data_template_rrd_id' => self::hash('08', $metric->name), + ], 5); + } + + $graphHash = self::hash('11', $name); + + $graphs .= "\t\t\t<$graphHash>\n" . self::lines(['graph_template_id' => self::hash('00', $name), 'name' => $name], 4) + . "\t\t\t\t\n" . $rrd . "\t\t\t\t\n" + . "\t\t\t\t\n" . self::element(self::hash('12', $name . ':title'), ['field_name' => 'title', 'sequence' => '1', 'text' => self::title($name)], 5) . "\t\t\t\t\n" + . "\t\t\t\t\n" . self::element(self::hash('13', $name . ':name'), ['field_name' => 'name', 'data_template_id' => $dataTemplate, 'sequence' => '1', 'text' => '|host_description| - GPU |query_gpuIndex| |query_gpuName|'], 5) . "\t\t\t\t\n" + . "\t\t\t\n"; + } + + return "\t<$hash>\n" . self::lines([ + 'name' => self::DATA_QUERY, + 'description' => 'GPUs reported by the GPU plugin, one index per GPU identity', + 'xml_path' => '/resource/script_server/' . self::DATA_QUERY_FILE, + 'data_input_id' => self::SCRIPT_SERVER_DIM, + ], 2) . "\t\t\n" . $graphs . "\t\t\n\t\n"; + } + + /** + * @param array $children + */ + private static function element(string $name, array $children, int $depth): string { + $tabs = str_repeat("\t", $depth); + + return "$tabs<$name>\n" . self::lines($children, $depth + 1) . "$tabs\n"; + } + + /** + * @param array $children + */ + private static function lines(array $children, int $depth): string { + $out = ''; + + foreach ($children as $name => $value) { + $out .= self::line($name, $value, $depth); + } + + return $out; + } + + private static function line(string $name, string $value, int $depth): string { + return str_repeat("\t", $depth) . "<$name>" . htmlspecialchars($value, ENT_XML1 | ENT_QUOTES, 'UTF-8') . "\n"; + } +} diff --git a/lib/ThrottleMask.php b/lib/ThrottleMask.php new file mode 100644 index 0000000..cc779a0 --- /dev/null +++ b/lib/ThrottleMask.php @@ -0,0 +1,60 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu; + +/** + * The clock event reasons bitmask (research/clock-event-reasons.md). + * + * The help text says only "Bitmask ... See nvml.h", and whether nvidia-smi + * prints it in hexadecimal or decimal is a live check, so both are read. A + * 0x prefix is hexadecimal and must not be taken for an unknown value. + */ +final class ThrottleMask { + public static function parse(string $raw): ?int { + $raw = trim($raw); + + if (preg_match('/^0x([0-9a-f]{1,16})$/i', $raw, $hex) === 1) { + // Bits above 2^62 would not fit an int; no defined bit is near. + return strlen(ltrim($hex[1], '0')) <= 15 ? (int) hexdec($hex[1]) : null; + } + + if (preg_match('/^[0-9]{1,18}$/', $raw) === 1) { + return (int) $raw; + } + + return null; + } + + /** + * One indicator per decoded reason: 1 when its bit is set, 0 when clear, + * unknown when the mask is. + * + * @return array + */ + public static function indicators(?int $mask): array { + $out = []; + + foreach (MetricModel::BITS as $name => $bit) { + $out[$name] = $mask === null ? null : (($mask & $bit) !== 0 ? 1.0 : 0.0); + } + + return $out; + } +} diff --git a/locales/po/cacti.pot b/locales/po/cacti.pot index 6cbd79a..13e31c2 100644 --- a/locales/po/cacti.pot +++ b/locales/po/cacti.pot @@ -16,6 +16,18 @@ msgstr "" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" +#: gpu_nodes.php +msgid "That GPU node or GPU does not exist, or is on a device you do not have access to." +msgstr "" + +#: gpu_nodes.php +msgid "The GPU data query could not be added to the device. Check that the plugin's templates are installed." +msgstr "" + +#: gpu_nodes.php +msgid "Device: the node's device was deleted, so the node can only be disabled." +msgstr "" + #: gpu_nodes.php msgid "Device: choose an existing Cacti device." msgstr "" @@ -48,6 +60,90 @@ msgstr "" msgid "The GPU stays with its recorded node." msgstr "" +#: gpu_nodes.php +msgid "The GPU will leave the data query at the next reindex. Its graphs and RRD files are kept." +msgstr "" + +#: gpu_nodes.php +msgid "Only an absent GPU can be removed from the data query." +msgstr "" + +#: gpu_nodes.php +msgid "Creating a device needs permission to manage Cacti devices." +msgstr "" + +#: gpu_nodes.php +msgid "Description: enter up to 150 printable characters." +msgstr "" + +#: gpu_nodes.php +msgid "Hostname: enter a host name or IP address." +msgstr "" + +#: gpu_nodes.php +msgid "The GPU Node device template is not installed." +msgstr "" + +#: gpu_nodes.php +msgid "The device and its GPU node were created. Set the device's SNMP settings on its device page." +msgstr "" + +#: gpu_nodes.php +msgid "The device could not be created; see the Cacti log." +msgstr "" + +#: lib/ExecutionState.php +msgid "Collected" +msgstr "" + +#: lib/ExecutionState.php +msgid "No GPUs reported" +msgstr "" + +#: lib/ExecutionState.php +msgid "SNMP agent unreachable" +msgstr "" + +#: lib/ExecutionState.php +msgid "Extend entry missing" +msgstr "" + +#: lib/ExecutionState.php +msgid "Timed out" +msgstr "" + +#: lib/ExecutionState.php +msgid "Permission denied" +msgstr "" + +#: lib/ExecutionState.php +msgid "Driver not loaded" +msgstr "" + +#: lib/ExecutionState.php +msgid "Tool not found" +msgstr "" + +#: lib/ExecutionState.php +msgid "Tool error" +msgstr "" + +#: lib/ExecutionState.php +msgid "Output truncated" +msgstr "" + +#: lib/ExecutionState.php +msgid "Output rejected" +msgstr "" + +#: lib/ExecutionState.php +msgid "Skipped: already running" +msgstr "" + +#: lib/ExecutionState.php +msgid "Result not stored" +msgstr "" + #: lib/InventoryPage.php msgid "Driver" msgstr "" @@ -56,7 +152,7 @@ msgstr "" msgid "Index" msgstr "" -#: lib/InventoryPage.php +#: lib/InventoryPage.php lib/NodesPage.php msgid "Last Seen" msgstr "" @@ -89,7 +185,7 @@ msgid "GPU Inventory" msgstr "" #: lib/InventoryPage.php -msgid "No GPUs recorded yet. GPUs appear here once collection, which arrives in a later release, reports them." +msgid "No GPUs recorded yet. GPUs appear here once a node's collection reports them." msgstr "" #: lib/InventoryPage.php @@ -158,6 +254,10 @@ msgstr "" msgid "GPUs Present" msgstr "" +#: lib/NodesPage.php +msgid "Last Collection" +msgstr "" + #: lib/NodesPage.php msgid "No GPU nodes yet. Add a Cacti device that has GPUs." msgstr "" @@ -184,13 +284,37 @@ msgid "Export" msgstr "" #: lib/NodesPage.php -msgid "Download every node and GPU record as JSON. Take an export before an uninstall that drops the plugin tables." +msgid "Download the node and GPU records of the devices you may see as JSON. Take an export before an uninstall that drops the plugin tables." msgstr "" #: lib/NodesPage.php msgid "Export Records" msgstr "" +#: lib/NodesPage.php +msgid "Not collected yet" +msgstr "" + +#: lib/NodesPage.php +#, php-format +msgid "%s: %d GPUs" +msgstr "" + +#: lib/NodesPage.php +#, php-format +msgid "%d new GPUs recorded" +msgstr "" + +#: lib/NodesPage.php +#, php-format +msgid "%d s ago" +msgstr "" + +#: lib/NodesPage.php +#, php-format +msgid "%d runs skipped while one was still running" +msgstr "" + #: lib/NodesPage.php msgid "GPU Moves Awaiting Confirmation" msgstr "" @@ -225,10 +349,50 @@ msgstr "" msgid "Deleted device (ID %d)" msgstr "" +#: lib/NodesPage.php +msgid "Saving adds the GPU data query to the device, with Cacti's automatic reindex turned off: the plugin reindexes after every GPU change. Configure the device's SNMP agent first; see docs/node-setup.md." +msgstr "" + #: lib/NodesPage.php msgid "Save" msgstr "" +#: lib/NodesPage.php +msgid "Absent GPUs" +msgstr "" + +#: lib/NodesPage.php +msgid "An absent GPU stays an index of the data query, so its graphs and RRD files stay attached and show a gap. Removing it from the data query stops that: at the next reindex Cacti no longer lists it, its graphs stop updating and its data sources show as orphaned, and its RRD files and graphs are kept until you delete them. The GPU record stays, and the GPU returns to the data query if it is reported again." +msgstr "" + +#: lib/NodesPage.php +msgid "Remove from Data Query" +msgstr "" + +#: lib/NodesPage.php +msgid "Removed from the data query" +msgstr "" + +#: lib/NodesPage.php +msgid "Create a Device for a New Node" +msgstr "" + +#: lib/NodesPage.php +msgid "Only when the node is not a Cacti device yet. The device uses the site's device defaults and the GPU Node device template; set its SNMP settings on the device page afterwards." +msgstr "" + +#: lib/NodesPage.php +msgid "Description" +msgstr "" + +#: lib/NodesPage.php +msgid "Hostname" +msgstr "" + +#: lib/NodesPage.php +msgid "Create Device and Node" +msgstr "" + #: lib/Pages.php msgid "GPU View" msgstr "" @@ -249,6 +413,18 @@ msgstr "" msgid "Consecutive successful collections that must miss a GPU before it is marked absent, from 1 to 100. A failed collection, or one that reports no GPUs, never counts. Absent GPUs keep their records and history and are never deleted automatically." msgstr "" +#: lib/Settings.php +msgid "GPU Collection" +msgstr "" + +#: lib/Settings.php +msgid "Stale After" +msgstr "" + +#: lib/Settings.php +msgid "Seconds after the tool took a sample that its values stop being graphed, from 60 to 86400. An older value is reported as unknown, so a stopped collection shows as a gap, never as a flat line. The GPU age value keeps counting so it can be alerted on." +msgstr "" + #: lib/Settings.php msgid "Uninstall" msgstr "" diff --git a/poller_gpu.php b/poller_gpu.php new file mode 100644 index 0000000..9ad892a --- /dev/null +++ b/poller_gpu.php @@ -0,0 +1,95 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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. + */ + +/* + * The GPU collector, started by the poller_bottom hook after each poller + * cycle: + * + * php plugins/gpu/poller_gpu.php [--force] [--debug] + * + * One instance at a time, through Cacti's process registry. It reads each + * enabled node's SNMP extend entries and writes the plugin's cache; the + * script server input reads only that cache. This file must parse on PHP + * 8.0 and refuses to run below 8.2. + */ + +chdir(__DIR__ . '/../..'); + +require('./include/cli_check.php'); +require_once($config['base_path'] . '/lib/poller.php'); +require_once($config['base_path'] . '/lib/snmp.php'); +require_once($config['base_path'] . '/plugins/gpu/setup.php'); + +ini_set('max_execution_time', '0'); + +$gpu_force = false; + +foreach (array_slice($argv, 1) as $gpu_arg) { + if ($gpu_arg === '--force') { + $gpu_force = true; + } elseif ($gpu_arg === '--debug') { + $debug = true; + } else { + fwrite(STDERR, 'ERROR: Unknown argument ' . $gpu_arg . PHP_EOL . 'usage: poller_gpu.php [--force] [--debug]' . PHP_EOL); + exit(1); + } +} + +if (gpu_refuse_unsupported()) { + exit(1); +} + +gpu_boot(); + +if (!$gpu_force && !api_plugin_is_enabled('gpu')) { + exit(0); +} + +if (!(new \Somethingwithproof\Gpu\Schema(false))->isCurrent()) { + cacti_log('ERROR: The GPU collector did not run because the plugin schema is not current; open the Plugins page to finish the upgrade', false, 'GPU'); + exit(1); +} + +// Leave a fifth of the poller interval free, so a run ends before the next +// cycle starts another. +$gpu_interval = (int) read_config_option('poller_interval'); +$gpu_budget = max(30, (int) (($gpu_interval > 0 ? $gpu_interval : 300) * 0.8)); + +// One collector at a time, held through collection and provisioning. The +// database lock is atomic; Cacti's process registry is kept for monitoring +// but can let two starts through together. +$gpu_lock = new \Somethingwithproof\Gpu\LockRepository(false); + +if (!$gpu_lock->acquire('collector') || !register_process_start('gpu', 'collector', 0, $gpu_budget + 120)) { + cacti_log('NOTE: The GPU collector is already running', false, 'GPU', POLLER_VERBOSITY_MEDIUM); + exit(0); +} + +$gpu_start = microtime(true); + +try { + $gpu_stats = gpu_poller()->run(gpu_settings(), $gpu_budget); +} finally { + unregister_process('gpu', 'collector', 0); + $gpu_lock->release('collector'); +} + +cacti_log(sprintf('STATS: Time:%.2f Nodes:%d Ok:%d Failed:%d Skipped:%d Remote:%d Reindexed:%d Deferred:%d Graphs:%d StoppedEarly:%s', microtime(true) - $gpu_start, $gpu_stats['nodes'], $gpu_stats['ok'], $gpu_stats['failed'], $gpu_stats['skipped'], $gpu_stats['remote'], $gpu_stats['reindexed'], $gpu_stats['deferred'], $gpu_stats['graphs'], $gpu_stats['stopped_early'] ? 'yes' : 'no'), false, 'GPU', POLLER_VERBOSITY_MEDIUM); + +exit(0); diff --git a/resource/script_server/plugin_gpu.xml b/resource/script_server/plugin_gpu.xml new file mode 100644 index 0000000..4bdee05 --- /dev/null +++ b/resource/script_server/plugin_gpu.xml @@ -0,0 +1,128 @@ + + GPU devices + GPUs from the GPU plugin cache, one index per GPU identity + |path_cacti|/plugins/gpu/ss_gpu.php + ss_gpu + php + |host_id| + index + num_indexes + query + get + ! + gpuKey + alphabetic + |chosen_order_field| + + + Identity key + input + index + + + GPU index + input + gpu_index + + + Product name + input + name + + + PCI bus ID + input + pci_bus_id + + + GPU utilization + output + util_gpu + + + Memory controller utilization + output + util_mem + + + Frame buffer memory used + output + mem_used + + + Frame buffer memory total + output + mem_total + + + GPU temperature + output + temp_gpu + + + Board power draw + output + power + + + Board power limit + output + power_limit + + + SM clock + output + clock_sm + + + Memory clock + output + clock_mem + + + Corrected ECC errors since driver load + output + ecc_corr + + + Uncorrected ECC errors since driver load + output + ecc_uncorr + + + Page retirement pending + output + retired_pending + + + Clocks held by the software power cap + output + thr_sw_power_cap + + + Hardware slowdown + output + thr_hw_slowdown + + + Software thermal slowdown + output + thr_sw_thermal + + + Hardware thermal slowdown + output + thr_hw_thermal + + + Hardware power brake + output + thr_hw_power_brake + + + Seconds since the tool took the sample + output + age + + + diff --git a/setup.php b/setup.php index 0363ac0..6172f48 100644 --- a/setup.php +++ b/setup.php @@ -150,8 +150,58 @@ function gpu_gpus(): \Somethingwithproof\Gpu\GpuRepository { return new \Somethingwithproof\Gpu\GpuRepository(false); } +function gpu_poller(): \Somethingwithproof\Gpu\Poller { + $clock = new \Somethingwithproof\Gpu\SystemClock(); + $gpus = gpu_gpus(); + $collections = new \Somethingwithproof\Gpu\CollectionRepository(false); + $retries = (int) read_config_option('snmp_retries'); + + $collector = new \Somethingwithproof\Gpu\Collector( + new \Somethingwithproof\Gpu\SnmpExtendReader(max(0, $retries)), + new \Somethingwithproof\Gpu\NvidiaSmiParser(), + new \Somethingwithproof\Gpu\Inventory($gpus, new \Somethingwithproof\Gpu\IdentityReconciler(), $clock), + $gpus, + new \Somethingwithproof\Gpu\ObservationRepository(false), + $collections, + new \Somethingwithproof\Gpu\ReindexRepository(false), + new \Somethingwithproof\Gpu\LockRepository(false), + $clock, + ); + + return new \Somethingwithproof\Gpu\Poller(gpu_nodes(), $collections, $collector, gpu_provisioner(), new \Somethingwithproof\Gpu\ReindexRepository(false), $clock); +} + /** - * Bring the schema, hooks, and realms up to the code's version. + * The provisioner, with the core libraries its API calls need loaded. + */ +function gpu_provisioner(): \Somethingwithproof\Gpu\Provisioner { + global $config; + + foreach (array('api_device', 'data_query', 'template', 'api_graph', 'api_data_source', 'utility', 'poller', 'variables', 'functions') as $library) { + include_once($config['library_path'] . '/' . $library . '.php'); + } + + return new \Somethingwithproof\Gpu\Provisioner(new \Somethingwithproof\Gpu\CactiObjectRepository(false), new \Somethingwithproof\Gpu\CacheRepository(false), new \Somethingwithproof\Gpu\ReindexRepository(false), new \Somethingwithproof\Gpu\SystemClock()); +} + +function gpu_templates(): \Somethingwithproof\Gpu\TemplateInstaller { + global $config; + + // What core's cli/import_template.php loads for an import: the import + // itself replicates and repairs through poller.php and utility.php. + include_once($config['library_path'] . '/import.php'); + include_once($config['library_path'] . '/poller.php'); + include_once($config['library_path'] . '/utility.php'); + + return new \Somethingwithproof\Gpu\TemplateInstaller(new \Somethingwithproof\Gpu\CactiObjectRepository(false), new \Somethingwithproof\Gpu\LockRepository(false), __DIR__, rtrim((string) $config['base_path'], '/')); +} + +function gpu_script_server(): \Somethingwithproof\Gpu\ScriptServer { + return new \Somethingwithproof\Gpu\ScriptServer(new \Somethingwithproof\Gpu\CacheRepository(false), new \Somethingwithproof\Gpu\SystemClock(), gpu_settings()->staleAfter); +} + +/** + * Bring the schema, hooks, realms, and shipped templates up to the code's version. * * Cacti 1.2.31 never calls this itself; check_config and the config_arrays * hook do. Fresh installs take the same path as upgrades. The version stored @@ -171,7 +221,7 @@ function plugin_gpu_upgrade(bool $grant = false): bool { $info = plugin_gpu_version(); $schema = new \Somethingwithproof\Gpu\Schema(false); - if ($schema->isCurrent() && $schema->recordedPluginVersion() === $info['version'] && $schema->hooksRegistered()) { + if ($schema->isCurrent() && $schema->recordedPluginVersion() === $info['version'] && $schema->hooksRegistered() && gpu_templates()->installed()) { return true; } @@ -183,6 +233,12 @@ function plugin_gpu_upgrade(bool $grant = false): bool { gpu_setup_hooks($grant); + // The version is recorded only once the templates are in place, so a + // failed import is retried by the next repair. + if (!gpu_templates()->install()) { + return false; + } + $schema->recordPluginVersion($info['version'], $info['author'], $info['homepage']); return true; @@ -256,6 +312,120 @@ function plugin_gpu_uninstall(): void { } } +/** + * Create a Cacti device for a node that has none, through Cacti's own + * api_device_save() with the site's device defaults (ADR 0010). Returns the + * new device id, or 0. + */ +function gpu_create_device(string $description, string $hostname, int $template): int { + global $config; + + include_once($config['library_path'] . '/api_device.php'); + + $availability = (int) read_config_option('availability_method'); + $max_oids = (int) read_config_option('max_get_size'); + $threads = (int) read_config_option('device_threads'); + + $id = api_device_save(0, $template, $description, $hostname, + read_config_option('snmp_community'), read_config_option('snmp_version'), + read_config_option('snmp_username'), read_config_option('snmp_password'), + read_config_option('snmp_port'), read_config_option('snmp_timeout'), '', + $availability > 0 ? $availability : 1, read_config_option('ping_method'), read_config_option('ping_port'), + read_config_option('ping_timeout'), read_config_option('ping_retries'), '', + read_config_option('snmp_auth_protocol'), read_config_option('snmp_priv_passphrase'), read_config_option('snmp_priv_protocol'), '', '', + $max_oids > 0 ? $max_oids : 10, $threads > 0 ? $threads : 1, 1, max(0, (int) read_config_option('default_site'))); + + return is_numeric($id) ? (int) $id : 0; +} + +/** + * poller_bottom hook: start the collector in the background once the + * poller cycle has finished. The collector reads the GPU nodes; the poller + * itself and the script server input never do (REQ-SS-001). + */ +function gpu_poller_bottom(): void { + global $config; + + if (!gpu_boot()) { + return; + } + + // Remote data collectors are phase 3; only the main poller collects. + if ((int) $config['poller_id'] !== \Somethingwithproof\Gpu\Poller::MAIN_POLLER) { + return; + } + + if (!function_exists('exec_background')) { + include_once($config['library_path'] . '/poller.php'); + } + + // exec_background() silently does nothing for a binary that does not + // exist, so a bare 'php' fallback would never start the collector. + $php = trim((string) read_config_option('path_php_binary')); + + if ($php === '' || !is_file($php) || !is_executable($php)) { + cacti_log('ERROR: The GPU collector was not started because the PHP binary path setting is empty or not an executable file', false, 'GPU'); + + return; + } + + // The one argument is escaped, so no part of it is parsed by a shell. + $args = '-q ' . cacti_escapeshellarg(__DIR__ . '/poller_gpu.php'); + + exec_background($php, $args); +} + +/** + * device_remove hook: Cacti is deleting these devices. Their nodes are + * disabled and keep their GPU records (ADR 0010). + * + * @param mixed $device_ids + * @return mixed + */ +function gpu_device_remove($device_ids) { + if (!gpu_boot() || !is_array($device_ids)) { + return $device_ids; + } + + $ids = array(); + + foreach ($device_ids as $id) { + if (is_numeric($id) && (int) $id > 0) { + $ids[] = (int) $id; + } + } + + $disabled = gpu_nodes()->disableForHosts($ids); + + if ($disabled > 0) { + \Somethingwithproof\Gpu\Log::info(sprintf('%d GPU nodes disabled because their Cacti devices were deleted', $disabled)); + } + + return $device_ids; +} + +/** + * api_device_new hook: a device was saved. If it is a GPU node, make sure + * a device template change did not detach the GPU data query or change its + * reindex method (ADR 0010). + * + * @param mixed $save + * @return mixed + */ +function gpu_api_device_new($save) { + if (!gpu_boot() || !is_array($save) || !isset($save['id']) || !is_numeric($save['id'])) { + return $save; + } + + $node = gpu_nodes()->findByHost((int) $save['id']); + + if ($node !== null) { + gpu_provisioner()->attach($node); + } + + return $save; +} + function gpu_config_arrays(): void { global $menu; diff --git a/ss_gpu.php b/ss_gpu.php new file mode 100644 index 0000000..5fc9e54 --- /dev/null +++ b/ss_gpu.php @@ -0,0 +1,62 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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. + */ + +/* + * The GPU data query's script server input (resource/script_server/ + * plugin_gpu.xml). Cacti's script server includes this file and calls + * ss_gpu() for each get; index and query also run it from the command line: + * + * php plugins/gpu/ss_gpu.php index|num_indexes|query|get [field] [index] + * + * It reads only the plugin's cache, never a GPU node (REQ-SS-001), and never + * throws (REQ-SS-002). This file must parse on PHP 8.0. + */ + +if (!isset($called_by_script_server)) { + include_once(__DIR__ . '/../../include/cli_check.php'); + include_once(__DIR__ . '/setup.php'); + + array_shift($argv); + + print call_user_func_array('ss_gpu', $argv); +} else { + include_once(__DIR__ . '/setup.php'); +} + +/** + * @param mixed $host_id + * @param mixed $cmd + * @param mixed $arg1 + * @param mixed $arg2 + */ +function ss_gpu($host_id = '', $cmd = '', $arg1 = '', $arg2 = ''): string { + $fallback = $cmd === 'get' ? 'U' : ''; + + if (!gpu_boot()) { + return $fallback; + } + + try { + return gpu_script_server()->call((string) $host_id, (string) $cmd, (string) $arg1, (string) $arg2); + } catch (Throwable $e) { + cacti_log('ERROR: The GPU script server input failed: ' . get_class($e), false, 'GPU'); + + return $fallback; + } +} diff --git a/templates/gpu_templates.xml b/templates/gpu_templates.xml new file mode 100644 index 0000000..83d663c --- /dev/null +++ b/templates/gpu_templates.xml @@ -0,0 +1,3234 @@ + + + GPU Node + hpc + + hash_0401031fae36a99f928500ad9a03432c124646 + + + GPU - Utilization + + + + on + |host_description| - GPU |query_gpuIndex| |query_gpuName| - Utilization + + percent + + 3 + + 200 + + 700 + + 1000 + + on + + on + + 2 + + + + + + + + 100 + + 0 + + + + + + + + + + + + + + + + 0 + + 0 + + 0 + + on + + + + + + + + 0 + + 0 + + + + 5 + hash_080103386498e2ba28dc691ae80400fd9f81cb + 76B900 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + GPU + + 2.00 + + 0 + 1 + + + 9 + hash_080103386498e2ba28dc691ae80400fd9f81cb + 0 + FF + 4 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Current: + + 1.00 + + 0 + 2 + + + 9 + hash_080103386498e2ba28dc691ae80400fd9f81cb + 0 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Average: + + 1.00 + + 0 + 3 + + + 9 + hash_080103386498e2ba28dc691ae80400fd9f81cb + 0 + FF + 3 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Maximum: + on + 1.00 + + 0 + 4 + + + 4 + hash_080103fcfd3c9bc04ccdce72e777c017bd52ec + 0072C6 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Memory controller + + 1.00 + + 0 + 5 + + + 9 + hash_080103fcfd3c9bc04ccdce72e777c017bd52ec + 0 + FF + 4 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Current: + + 1.00 + + 0 + 6 + + + 9 + hash_080103fcfd3c9bc04ccdce72e777c017bd52ec + 0 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Average: + + 1.00 + + 0 + 7 + + + 9 + hash_080103fcfd3c9bc04ccdce72e777c017bd52ec + 0 + FF + 3 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Maximum: + on + 1.00 + + 0 + 8 + + + + + Data Source [util_gpu] + + task_item_id + hash_0001031e52cb61d9bada80ae883b809312d7c4|hash_0001034750da40195b14e86950c1931c7340fb|hash_00010321e4a1bb7de7142e310db07fb411ac35|hash_000103309c29143f309513a5c123b725479569 + + + Data Source [util_mem] + + task_item_id + hash_000103dd22590054532b775486e908aa75d138|hash_000103b636bc58b83f125fe0dfc064e00fcb90|hash_000103ec0ef68c9da989718531f2a7bcc38e76|hash_00010393325c2b56e7eefd679cccdf522190d9 + + + + + GPU - Memory + + + + on + |host_description| - GPU |query_gpuIndex| |query_gpuName| - Memory + + bytes + + 3 + + 200 + + 700 + + 1024 + + on + + on + + 2 + + + + + + + + 0 + + 0 + + + + + + + + + + + + + + + + 0 + + 0 + + 0 + + on + + + + + + + + 0 + + 0 + + + + 7 + hash_0801031ef6a201b4c8317435dd4f8f03c97c3e + C9DDF0 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Total + + 1.00 + + 0 + 1 + + + 9 + hash_0801031ef6a201b4c8317435dd4f8f03c97c3e + 0 + FF + 4 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Current: + + 1.00 + + 0 + 2 + + + 9 + hash_0801031ef6a201b4c8317435dd4f8f03c97c3e + 0 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Average: + + 1.00 + + 0 + 3 + + + 9 + hash_0801031ef6a201b4c8317435dd4f8f03c97c3e + 0 + FF + 3 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Maximum: + on + 1.00 + + 0 + 4 + + + 7 + hash_080103fe69c23cfa14f29431c620ef604c30f3 + 0072C6 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Used + + 1.00 + + 0 + 5 + + + 9 + hash_080103fe69c23cfa14f29431c620ef604c30f3 + 0 + FF + 4 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Current: + + 1.00 + + 0 + 6 + + + 9 + hash_080103fe69c23cfa14f29431c620ef604c30f3 + 0 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Average: + + 1.00 + + 0 + 7 + + + 9 + hash_080103fe69c23cfa14f29431c620ef604c30f3 + 0 + FF + 3 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Maximum: + on + 1.00 + + 0 + 8 + + + + + Data Source [mem_total] + + task_item_id + hash_0001030f48aaa7ec327a12caf47ea7588c3df4|hash_0001030ca5dd75aa861f1693acd2cb6a17c3c3|hash_000103cebfe708ab38d66e3dc0b3bea9c565c6|hash_000103d3378cc5a14d539adfe93ec503a44bad + + + Data Source [mem_used] + + task_item_id + hash_0001036a71552da99d1c5c10ca291d8d90eb1e|hash_0001036ab62fbc67623fb18cb6f47457a102eb|hash_000103a648f2fa12ac1a8f5dee8246adc9241f|hash_000103ae0381e7372306611421b16db578d163 + + + + + GPU - Temperature + + + + on + |host_description| - GPU |query_gpuIndex| |query_gpuName| - Temperature + + degrees C + + 3 + + 200 + + 700 + + 1000 + + on + + on + + 2 + + + + + + + + 0 + + 0 + + + + + + + + + + + + + + + + 0 + + 0 + + 0 + + on + + + + + + + + 0 + + 0 + + + + 5 + hash_080103a269082db3ee8d772f5f44f27b3f7a23 + D9541E + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + GPU + + 2.00 + + 0 + 1 + + + 9 + hash_080103a269082db3ee8d772f5f44f27b3f7a23 + 0 + FF + 4 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Current: + + 1.00 + + 0 + 2 + + + 9 + hash_080103a269082db3ee8d772f5f44f27b3f7a23 + 0 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Average: + + 1.00 + + 0 + 3 + + + 9 + hash_080103a269082db3ee8d772f5f44f27b3f7a23 + 0 + FF + 3 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Maximum: + on + 1.00 + + 0 + 4 + + + + + Data Source [temp_gpu] + + task_item_id + hash_000103d98aba96042625f414eda5ec18ebd686|hash_0001032901005475ad8ff0ccd43b8f961e6360|hash_000103bf8a552364bb351eb991a0d3d73daacf|hash_0001039c456c676a7efe1339243e2360d096e2 + + + + + GPU - Power + + + + on + |host_description| - GPU |query_gpuIndex| |query_gpuName| - Power + + watts + + 3 + + 200 + + 700 + + 1000 + + on + + on + + 2 + + + + + + + + 0 + + 0 + + + + + + + + + + + + + + + + 0 + + 0 + + 0 + + on + + + + + + + + 0 + + 0 + + + + 7 + hash_0801038cbec3da5106f36e5d6c2394eb3ec1a2 + F2B705 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Draw + + 1.00 + + 0 + 1 + + + 9 + hash_0801038cbec3da5106f36e5d6c2394eb3ec1a2 + 0 + FF + 4 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Current: + + 1.00 + + 0 + 2 + + + 9 + hash_0801038cbec3da5106f36e5d6c2394eb3ec1a2 + 0 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Average: + + 1.00 + + 0 + 3 + + + 9 + hash_0801038cbec3da5106f36e5d6c2394eb3ec1a2 + 0 + FF + 3 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Maximum: + on + 1.00 + + 0 + 4 + + + 4 + hash_08010315673384900d4c1c618661df74458d3a + B00020 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Limit + + 1.00 + + 0 + 5 + + + 9 + hash_08010315673384900d4c1c618661df74458d3a + 0 + FF + 4 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Current: + + 1.00 + + 0 + 6 + + + 9 + hash_08010315673384900d4c1c618661df74458d3a + 0 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Average: + + 1.00 + + 0 + 7 + + + 9 + hash_08010315673384900d4c1c618661df74458d3a + 0 + FF + 3 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Maximum: + on + 1.00 + + 0 + 8 + + + + + Data Source [power] + + task_item_id + hash_00010344595acb4b011a836241d9feea4a58d1|hash_000103127ff3b0ffecb9feb7f7ad8d6e50581b|hash_000103bea7769d079bd62673afc687948b8f75|hash_0001037aff178e3850586fb8d2e99a22d98bbe + + + Data Source [power_limit] + + task_item_id + hash_000103ead8e5cfdadd00d47b9bbde7d6ab07e8|hash_0001032c7b2ca389350aac91d919fbc5752d18|hash_00010319153958494dcc34c5854f6b45631328|hash_0001039f49e25ad9cfafc934be5836102ead35 + + + + + GPU - Clocks + + + + on + |host_description| - GPU |query_gpuIndex| |query_gpuName| - Clocks + + MHz + + 3 + + 200 + + 700 + + 1000 + + on + + on + + 2 + + + + + + + + 0 + + 0 + + + + + + + + + + + + + + + + 0 + + 0 + + 0 + + on + + + + + + + + 0 + + 0 + + + + 5 + hash_0801031fcd3d5df2d1a8ec6eb2e7943e3aeda3 + 76B900 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + SM + + 2.00 + + 0 + 1 + + + 9 + hash_0801031fcd3d5df2d1a8ec6eb2e7943e3aeda3 + 0 + FF + 4 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Current: + + 1.00 + + 0 + 2 + + + 9 + hash_0801031fcd3d5df2d1a8ec6eb2e7943e3aeda3 + 0 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Average: + + 1.00 + + 0 + 3 + + + 9 + hash_0801031fcd3d5df2d1a8ec6eb2e7943e3aeda3 + 0 + FF + 3 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Maximum: + on + 1.00 + + 0 + 4 + + + 4 + hash_080103a8fa9aab83a40aa7739c39ef9c8ea184 + 7A3E9D + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Memory + + 1.00 + + 0 + 5 + + + 9 + hash_080103a8fa9aab83a40aa7739c39ef9c8ea184 + 0 + FF + 4 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Current: + + 1.00 + + 0 + 6 + + + 9 + hash_080103a8fa9aab83a40aa7739c39ef9c8ea184 + 0 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Average: + + 1.00 + + 0 + 7 + + + 9 + hash_080103a8fa9aab83a40aa7739c39ef9c8ea184 + 0 + FF + 3 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Maximum: + on + 1.00 + + 0 + 8 + + + + + Data Source [clock_sm] + + task_item_id + hash_00010358d7469ea503e2907529abe9659595fd|hash_000103fc1ad292c7261bcca667b9e82e5540fd|hash_000103888d8fd7334278af6885bf3ec0b07343|hash_00010307fb7dc616fb561a5458dddb7c59dc46 + + + Data Source [clock_mem] + + task_item_id + hash_000103eceda564bc65dd77368e763696e22c71|hash_000103630496da1eb1d8c8afbbdc65cb79d4ca|hash_000103e07d22fbc482b9a49dea0b4bdc4aa744|hash_000103150c34f4424cdd5de84ddae091b3cd10 + + + + + GPU - Throttle + + + + on + |host_description| - GPU |query_gpuIndex| |query_gpuName| - Throttle + + active (0 or 1) + + 3 + + 200 + + 700 + + 1000 + + on + + on + + 2 + + + + + + + + 1 + + 0 + + + + + + + + + + + + + + + + 0 + + 0 + + 0 + + on + + + + + + + + 0 + + 0 + + + + 4 + hash_080103e2d56f87cdaca55a819207fe6a19cd9d + F2B705 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Software power cap + + 1.00 + + 0 + 1 + + + 9 + hash_080103e2d56f87cdaca55a819207fe6a19cd9d + 0 + FF + 4 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Current: + + 1.00 + + 0 + 2 + + + 9 + hash_080103e2d56f87cdaca55a819207fe6a19cd9d + 0 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Average: + + 1.00 + + 0 + 3 + + + 9 + hash_080103e2d56f87cdaca55a819207fe6a19cd9d + 0 + FF + 3 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Maximum: + on + 1.00 + + 0 + 4 + + + 4 + hash_08010315564beb5b304bad49dbca0cb469bb2f + 7A3E9D + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Hardware slowdown + + 1.00 + + 0 + 5 + + + 9 + hash_08010315564beb5b304bad49dbca0cb469bb2f + 0 + FF + 4 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Current: + + 1.00 + + 0 + 6 + + + 9 + hash_08010315564beb5b304bad49dbca0cb469bb2f + 0 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Average: + + 1.00 + + 0 + 7 + + + 9 + hash_08010315564beb5b304bad49dbca0cb469bb2f + 0 + FF + 3 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Maximum: + on + 1.00 + + 0 + 8 + + + 4 + hash_080103684afab926b998321a7a6fac6f5a393b + D9541E + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Software thermal + + 1.00 + + 0 + 9 + + + 9 + hash_080103684afab926b998321a7a6fac6f5a393b + 0 + FF + 4 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Current: + + 1.00 + + 0 + 10 + + + 9 + hash_080103684afab926b998321a7a6fac6f5a393b + 0 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Average: + + 1.00 + + 0 + 11 + + + 9 + hash_080103684afab926b998321a7a6fac6f5a393b + 0 + FF + 3 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Maximum: + on + 1.00 + + 0 + 12 + + + 4 + hash_0801035f35b5a45efe842fa4a8dec1cdac348e + B00020 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Hardware thermal + + 1.00 + + 0 + 13 + + + 9 + hash_0801035f35b5a45efe842fa4a8dec1cdac348e + 0 + FF + 4 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Current: + + 1.00 + + 0 + 14 + + + 9 + hash_0801035f35b5a45efe842fa4a8dec1cdac348e + 0 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Average: + + 1.00 + + 0 + 15 + + + 9 + hash_0801035f35b5a45efe842fa4a8dec1cdac348e + 0 + FF + 3 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Maximum: + on + 1.00 + + 0 + 16 + + + 4 + hash_08010340894c404284f5ad11902bd285da8568 + 0072C6 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Hardware power brake + + 1.00 + + 0 + 17 + + + 9 + hash_08010340894c404284f5ad11902bd285da8568 + 0 + FF + 4 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Current: + + 1.00 + + 0 + 18 + + + 9 + hash_08010340894c404284f5ad11902bd285da8568 + 0 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Average: + + 1.00 + + 0 + 19 + + + 9 + hash_08010340894c404284f5ad11902bd285da8568 + 0 + FF + 3 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Maximum: + on + 1.00 + + 0 + 20 + + + 4 + hash_080103db6f1d51fd093d2d28b0cab3c1bd19a0 + 555555 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Page retirement pending + + 1.00 + + 0 + 21 + + + 9 + hash_080103db6f1d51fd093d2d28b0cab3c1bd19a0 + 0 + FF + 4 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Current: + + 1.00 + + 0 + 22 + + + 9 + hash_080103db6f1d51fd093d2d28b0cab3c1bd19a0 + 0 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Average: + + 1.00 + + 0 + 23 + + + 9 + hash_080103db6f1d51fd093d2d28b0cab3c1bd19a0 + 0 + FF + 3 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Maximum: + on + 1.00 + + 0 + 24 + + + + + Data Source [thr_sw_power_cap] + + task_item_id + hash_00010376c45aae1214634b01a43ea90c166785|hash_00010314d13cdb5d632f4224584dcbdbe40d2f|hash_00010319b92c3e55e2dcf8a2012009e444b1e4|hash_000103e2c9009ce437b8c8c75c4aec6cf28e93 + + + Data Source [thr_hw_slowdown] + + task_item_id + hash_0001038429579985e03d0c83f0b96cc4dda1c2|hash_000103a2970cf720d6836ace018fd5500b28bf|hash_000103c7f1686363505d338d8242db24078955|hash_0001033d8167af3d6cd51899c068b11bce4bc3 + + + Data Source [thr_sw_thermal] + + task_item_id + hash_0001037b5a9733d5bb9d53104739a4943252a7|hash_000103723527140629b5be36c7769c2b31886b|hash_0001037459ee0651a5d845178be34af0684cdd|hash_00010342bb0199dd0b1dfa9615e9672991a656 + + + Data Source [thr_hw_thermal] + + task_item_id + hash_0001036c8a2c8f1ec59f233f98b825ca0e99bc|hash_000103ceafd24fe372942413aee83a366b6856|hash_0001032adbd871d8f40bf08bb73d7bb443ea7b|hash_000103db1a097dbe95c8b8dcc27a372002547d + + + Data Source [thr_hw_power_brake] + + task_item_id + hash_0001034c450a7117cfcbeafea4c6d352f04c38|hash_0001037d6c0a6bb569c21ab8e63a8cca945c88|hash_000103dac35487d246017ac6e073d46d3cf8d0|hash_000103e3f4cc978cc6e2cce7eb45cf054e4ef4 + + + Data Source [retired_pending] + + task_item_id + hash_0001030a2c3631efcdc432736630cbe408f6f7|hash_00010368e3df2d4f1493adcb98cd4336abb60c|hash_000103ac63e1b981f5664e07f2e198ffd75ac8|hash_000103ce34836c77ca44c9a7b70a25e23b8ed4 + + + + + GPU - ECC Errors + + + + on + |host_description| - GPU |query_gpuIndex| |query_gpuName| - ECC Errors + + errors since driver load + + 3 + + 200 + + 700 + + 1000 + + on + + on + + 2 + + + + + + + + 0 + + 0 + + + + + + + + + + + + + + + + 0 + + 0 + + 0 + + on + + + + + + + + 0 + + 0 + + + + 4 + hash_080103a6324b601765f3fba880c82483cab1a4 + 0072C6 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Corrected + + 1.00 + + 0 + 1 + + + 9 + hash_080103a6324b601765f3fba880c82483cab1a4 + 0 + FF + 4 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Current: + + 1.00 + + 0 + 2 + + + 9 + hash_080103a6324b601765f3fba880c82483cab1a4 + 0 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Average: + + 1.00 + + 0 + 3 + + + 9 + hash_080103a6324b601765f3fba880c82483cab1a4 + 0 + FF + 3 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Maximum: + on + 1.00 + + 0 + 4 + + + 5 + hash_0801031ad88ffa3dd274846760a8d68f2a0a60 + B00020 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Uncorrected + + 2.00 + + 0 + 5 + + + 9 + hash_0801031ad88ffa3dd274846760a8d68f2a0a60 + 0 + FF + 4 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Current: + + 1.00 + + 0 + 6 + + + 9 + hash_0801031ad88ffa3dd274846760a8d68f2a0a60 + 0 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Average: + + 1.00 + + 0 + 7 + + + 9 + hash_0801031ad88ffa3dd274846760a8d68f2a0a60 + 0 + FF + 3 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Maximum: + on + 1.00 + + 0 + 8 + + + + + Data Source [ecc_corr] + + task_item_id + hash_0001034a6c5746c9529d0951c50b01a4f03482|hash_0001032f4bbaa29a697f2dc008d11dc23e854e|hash_000103d12f7700ffcd57fd6b8adf611d47b2cf|hash_000103b7f17f551cc2fd86130a7d01a90b15dd + + + Data Source [ecc_uncorr] + + task_item_id + hash_000103c921461dd4b41e33aa98cde3fb5eab2b|hash_000103a1ed6a57381d313948e1e1ab0af74c9e|hash_00010350bfe1192d9450d879fceeaa482dc0eb|hash_000103dc9a4d1cc15c03d41544376a0f3cbcaf + + + + + GPU - Sample Age + + + + on + |host_description| - GPU |query_gpuIndex| |query_gpuName| - Sample Age + + seconds + + 3 + + 200 + + 700 + + 1000 + + on + + on + + 2 + + + + + + + + 0 + + 0 + + + + + + + + + + + + + + + + 0 + + 0 + + 0 + + on + + + + + + + + 0 + + 0 + + + + 4 + hash_08010391f7fdb74f0d794e1fbe5e362a45dd1f + 555555 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Age of the latest sample + + 1.00 + + 0 + 1 + + + 9 + hash_08010391f7fdb74f0d794e1fbe5e362a45dd1f + 0 + FF + 4 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Current: + + 1.00 + + 0 + 2 + + + 9 + hash_08010391f7fdb74f0d794e1fbe5e362a45dd1f + 0 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Average: + + 1.00 + + 0 + 3 + + + 9 + hash_08010391f7fdb74f0d794e1fbe5e362a45dd1f + 0 + FF + 3 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Maximum: + on + 1.00 + + 0 + 4 + + + + + Data Source [age] + + task_item_id + hash_000103450f9a1a98c7cef3bd4551f9d7aa91cf|hash_0001036d96de2ffb6c54b753f67404eac86c4c|hash_000103bbfe5af10938a59e034f446f49ebcccf|hash_0001034368383ea860430ab47a756ecb6f8bae + + + + + GPU - Metrics + + + |host_description| - GPU |query_gpuIndex| |query_gpuName| + + hash_030103332111d8b54ac8ce939af87a7eac0c06 + + hash_200103d62c52891f4f9688729a5bc9fad91b18 + + 300 + + on + + + + + util_gpu + + 0 + + 100 + + 1 + + 600 + + 0 + + + + util_mem + + 0 + + 100 + + 1 + + 600 + + 0 + + + + mem_used + + 0 + + U + + 1 + + 600 + + 0 + + + + mem_total + + 0 + + U + + 1 + + 600 + + 0 + + + + temp_gpu + + U + + U + + 1 + + 600 + + 0 + + + + power + + 0 + + U + + 1 + + 600 + + 0 + + + + power_limit + + 0 + + U + + 1 + + 600 + + 0 + + + + clock_sm + + 0 + + U + + 1 + + 600 + + 0 + + + + clock_mem + + 0 + + U + + 1 + + 600 + + 0 + + + + ecc_corr + + 0 + + U + + 1 + + 600 + + 0 + + + + ecc_uncorr + + 0 + + U + + 1 + + 600 + + 0 + + + + retired_pending + + 0 + + 1 + + 1 + + 600 + + 0 + + + + thr_sw_power_cap + + 0 + + 1 + + 1 + + 600 + + 0 + + + + thr_hw_slowdown + + 0 + + 1 + + 1 + + 600 + + 0 + + + + thr_sw_thermal + + 0 + + 1 + + 1 + + 600 + + 0 + + + + thr_hw_thermal + + 0 + + 1 + + 1 + + 600 + + 0 + + + + thr_hw_power_brake + + 0 + + 1 + + 1 + + 600 + + 0 + + + + age + + 0 + + U + + 1 + + 600 + + 0 + + + + + hash_070103172b4b0eacee4948c6479f587b62e512 + on + + + + hash_07010330fb5d5bcf3d66bb5abe88596f357c26 + on + + + + hash_07010331112c85ae4ff821d3b288336288818c + on + + + + + + GPU - Devices + GPUs reported by the GPU plugin, one index per GPU identity + <path_cacti>/resource/script_server/plugin_gpu.xml + hash_030103332111d8b54ac8ce939af87a7eac0c06 + + + hash_00010327b99d70fc0fc6ddb084bf9e0d562792 + GPU - Utilization + + + util_gpu + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103386498e2ba28dc691ae80400fd9f81cb + + + util_mem + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103fcfd3c9bc04ccdce72e777c017bd52ec + + + mem_used + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103fe69c23cfa14f29431c620ef604c30f3 + + + mem_total + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801031ef6a201b4c8317435dd4f8f03c97c3e + + + temp_gpu + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103a269082db3ee8d772f5f44f27b3f7a23 + + + power + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801038cbec3da5106f36e5d6c2394eb3ec1a2 + + + power_limit + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010315673384900d4c1c618661df74458d3a + + + clock_sm + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801031fcd3d5df2d1a8ec6eb2e7943e3aeda3 + + + clock_mem + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103a8fa9aab83a40aa7739c39ef9c8ea184 + + + ecc_corr + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103a6324b601765f3fba880c82483cab1a4 + + + ecc_uncorr + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801031ad88ffa3dd274846760a8d68f2a0a60 + + + retired_pending + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103db6f1d51fd093d2d28b0cab3c1bd19a0 + + + thr_sw_power_cap + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103e2d56f87cdaca55a819207fe6a19cd9d + + + thr_hw_slowdown + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010315564beb5b304bad49dbca0cb469bb2f + + + thr_sw_thermal + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103684afab926b998321a7a6fac6f5a393b + + + thr_hw_thermal + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801035f35b5a45efe842fa4a8dec1cdac348e + + + thr_hw_power_brake + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010340894c404284f5ad11902bd285da8568 + + + age + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010391f7fdb74f0d794e1fbe5e362a45dd1f + + + + + title + 1 + |host_description| - GPU |query_gpuIndex| |query_gpuName| - Utilization + + + + + name + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + 1 + |host_description| - GPU |query_gpuIndex| |query_gpuName| + + + + + hash_0001031f7fc035100b6ccfacb4cada93f8267a + GPU - Memory + + + util_gpu + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103386498e2ba28dc691ae80400fd9f81cb + + + util_mem + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103fcfd3c9bc04ccdce72e777c017bd52ec + + + mem_used + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103fe69c23cfa14f29431c620ef604c30f3 + + + mem_total + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801031ef6a201b4c8317435dd4f8f03c97c3e + + + temp_gpu + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103a269082db3ee8d772f5f44f27b3f7a23 + + + power + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801038cbec3da5106f36e5d6c2394eb3ec1a2 + + + power_limit + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010315673384900d4c1c618661df74458d3a + + + clock_sm + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801031fcd3d5df2d1a8ec6eb2e7943e3aeda3 + + + clock_mem + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103a8fa9aab83a40aa7739c39ef9c8ea184 + + + ecc_corr + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103a6324b601765f3fba880c82483cab1a4 + + + ecc_uncorr + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801031ad88ffa3dd274846760a8d68f2a0a60 + + + retired_pending + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103db6f1d51fd093d2d28b0cab3c1bd19a0 + + + thr_sw_power_cap + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103e2d56f87cdaca55a819207fe6a19cd9d + + + thr_hw_slowdown + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010315564beb5b304bad49dbca0cb469bb2f + + + thr_sw_thermal + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103684afab926b998321a7a6fac6f5a393b + + + thr_hw_thermal + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801035f35b5a45efe842fa4a8dec1cdac348e + + + thr_hw_power_brake + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010340894c404284f5ad11902bd285da8568 + + + age + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010391f7fdb74f0d794e1fbe5e362a45dd1f + + + + + title + 1 + |host_description| - GPU |query_gpuIndex| |query_gpuName| - Memory + + + + + name + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + 1 + |host_description| - GPU |query_gpuIndex| |query_gpuName| + + + + + hash_000103a5a788934a0519975f187c376bce7d4e + GPU - Temperature + + + util_gpu + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103386498e2ba28dc691ae80400fd9f81cb + + + util_mem + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103fcfd3c9bc04ccdce72e777c017bd52ec + + + mem_used + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103fe69c23cfa14f29431c620ef604c30f3 + + + mem_total + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801031ef6a201b4c8317435dd4f8f03c97c3e + + + temp_gpu + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103a269082db3ee8d772f5f44f27b3f7a23 + + + power + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801038cbec3da5106f36e5d6c2394eb3ec1a2 + + + power_limit + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010315673384900d4c1c618661df74458d3a + + + clock_sm + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801031fcd3d5df2d1a8ec6eb2e7943e3aeda3 + + + clock_mem + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103a8fa9aab83a40aa7739c39ef9c8ea184 + + + ecc_corr + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103a6324b601765f3fba880c82483cab1a4 + + + ecc_uncorr + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801031ad88ffa3dd274846760a8d68f2a0a60 + + + retired_pending + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103db6f1d51fd093d2d28b0cab3c1bd19a0 + + + thr_sw_power_cap + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103e2d56f87cdaca55a819207fe6a19cd9d + + + thr_hw_slowdown + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010315564beb5b304bad49dbca0cb469bb2f + + + thr_sw_thermal + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103684afab926b998321a7a6fac6f5a393b + + + thr_hw_thermal + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801035f35b5a45efe842fa4a8dec1cdac348e + + + thr_hw_power_brake + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010340894c404284f5ad11902bd285da8568 + + + age + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010391f7fdb74f0d794e1fbe5e362a45dd1f + + + + + title + 1 + |host_description| - GPU |query_gpuIndex| |query_gpuName| - Temperature + + + + + name + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + 1 + |host_description| - GPU |query_gpuIndex| |query_gpuName| + + + + + hash_000103457ae08592c3f41860e35b5f466a1274 + GPU - Power + + + util_gpu + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103386498e2ba28dc691ae80400fd9f81cb + + + util_mem + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103fcfd3c9bc04ccdce72e777c017bd52ec + + + mem_used + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103fe69c23cfa14f29431c620ef604c30f3 + + + mem_total + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801031ef6a201b4c8317435dd4f8f03c97c3e + + + temp_gpu + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103a269082db3ee8d772f5f44f27b3f7a23 + + + power + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801038cbec3da5106f36e5d6c2394eb3ec1a2 + + + power_limit + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010315673384900d4c1c618661df74458d3a + + + clock_sm + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801031fcd3d5df2d1a8ec6eb2e7943e3aeda3 + + + clock_mem + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103a8fa9aab83a40aa7739c39ef9c8ea184 + + + ecc_corr + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103a6324b601765f3fba880c82483cab1a4 + + + ecc_uncorr + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801031ad88ffa3dd274846760a8d68f2a0a60 + + + retired_pending + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103db6f1d51fd093d2d28b0cab3c1bd19a0 + + + thr_sw_power_cap + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103e2d56f87cdaca55a819207fe6a19cd9d + + + thr_hw_slowdown + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010315564beb5b304bad49dbca0cb469bb2f + + + thr_sw_thermal + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103684afab926b998321a7a6fac6f5a393b + + + thr_hw_thermal + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801035f35b5a45efe842fa4a8dec1cdac348e + + + thr_hw_power_brake + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010340894c404284f5ad11902bd285da8568 + + + age + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010391f7fdb74f0d794e1fbe5e362a45dd1f + + + + + title + 1 + |host_description| - GPU |query_gpuIndex| |query_gpuName| - Power + + + + + name + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + 1 + |host_description| - GPU |query_gpuIndex| |query_gpuName| + + + + + hash_0001039731ead9f1bdb18ff2a968a804253ba0 + GPU - Clocks + + + util_gpu + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103386498e2ba28dc691ae80400fd9f81cb + + + util_mem + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103fcfd3c9bc04ccdce72e777c017bd52ec + + + mem_used + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103fe69c23cfa14f29431c620ef604c30f3 + + + mem_total + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801031ef6a201b4c8317435dd4f8f03c97c3e + + + temp_gpu + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103a269082db3ee8d772f5f44f27b3f7a23 + + + power + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801038cbec3da5106f36e5d6c2394eb3ec1a2 + + + power_limit + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010315673384900d4c1c618661df74458d3a + + + clock_sm + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801031fcd3d5df2d1a8ec6eb2e7943e3aeda3 + + + clock_mem + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103a8fa9aab83a40aa7739c39ef9c8ea184 + + + ecc_corr + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103a6324b601765f3fba880c82483cab1a4 + + + ecc_uncorr + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801031ad88ffa3dd274846760a8d68f2a0a60 + + + retired_pending + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103db6f1d51fd093d2d28b0cab3c1bd19a0 + + + thr_sw_power_cap + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103e2d56f87cdaca55a819207fe6a19cd9d + + + thr_hw_slowdown + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010315564beb5b304bad49dbca0cb469bb2f + + + thr_sw_thermal + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103684afab926b998321a7a6fac6f5a393b + + + thr_hw_thermal + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801035f35b5a45efe842fa4a8dec1cdac348e + + + thr_hw_power_brake + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010340894c404284f5ad11902bd285da8568 + + + age + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010391f7fdb74f0d794e1fbe5e362a45dd1f + + + + + title + 1 + |host_description| - GPU |query_gpuIndex| |query_gpuName| - Clocks + + + + + name + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + 1 + |host_description| - GPU |query_gpuIndex| |query_gpuName| + + + + + hash_000103a3b2a1e103b387430075b176c004c97d + GPU - Throttle + + + util_gpu + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103386498e2ba28dc691ae80400fd9f81cb + + + util_mem + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103fcfd3c9bc04ccdce72e777c017bd52ec + + + mem_used + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103fe69c23cfa14f29431c620ef604c30f3 + + + mem_total + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801031ef6a201b4c8317435dd4f8f03c97c3e + + + temp_gpu + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103a269082db3ee8d772f5f44f27b3f7a23 + + + power + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801038cbec3da5106f36e5d6c2394eb3ec1a2 + + + power_limit + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010315673384900d4c1c618661df74458d3a + + + clock_sm + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801031fcd3d5df2d1a8ec6eb2e7943e3aeda3 + + + clock_mem + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103a8fa9aab83a40aa7739c39ef9c8ea184 + + + ecc_corr + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103a6324b601765f3fba880c82483cab1a4 + + + ecc_uncorr + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801031ad88ffa3dd274846760a8d68f2a0a60 + + + retired_pending + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103db6f1d51fd093d2d28b0cab3c1bd19a0 + + + thr_sw_power_cap + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103e2d56f87cdaca55a819207fe6a19cd9d + + + thr_hw_slowdown + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010315564beb5b304bad49dbca0cb469bb2f + + + thr_sw_thermal + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103684afab926b998321a7a6fac6f5a393b + + + thr_hw_thermal + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801035f35b5a45efe842fa4a8dec1cdac348e + + + thr_hw_power_brake + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010340894c404284f5ad11902bd285da8568 + + + age + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010391f7fdb74f0d794e1fbe5e362a45dd1f + + + + + title + 1 + |host_description| - GPU |query_gpuIndex| |query_gpuName| - Throttle + + + + + name + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + 1 + |host_description| - GPU |query_gpuIndex| |query_gpuName| + + + + + hash_000103a74a22a26e30e91efb4e805bff01e83b + GPU - ECC Errors + + + util_gpu + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103386498e2ba28dc691ae80400fd9f81cb + + + util_mem + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103fcfd3c9bc04ccdce72e777c017bd52ec + + + mem_used + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103fe69c23cfa14f29431c620ef604c30f3 + + + mem_total + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801031ef6a201b4c8317435dd4f8f03c97c3e + + + temp_gpu + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103a269082db3ee8d772f5f44f27b3f7a23 + + + power + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801038cbec3da5106f36e5d6c2394eb3ec1a2 + + + power_limit + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010315673384900d4c1c618661df74458d3a + + + clock_sm + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801031fcd3d5df2d1a8ec6eb2e7943e3aeda3 + + + clock_mem + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103a8fa9aab83a40aa7739c39ef9c8ea184 + + + ecc_corr + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103a6324b601765f3fba880c82483cab1a4 + + + ecc_uncorr + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801031ad88ffa3dd274846760a8d68f2a0a60 + + + retired_pending + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103db6f1d51fd093d2d28b0cab3c1bd19a0 + + + thr_sw_power_cap + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103e2d56f87cdaca55a819207fe6a19cd9d + + + thr_hw_slowdown + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010315564beb5b304bad49dbca0cb469bb2f + + + thr_sw_thermal + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103684afab926b998321a7a6fac6f5a393b + + + thr_hw_thermal + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801035f35b5a45efe842fa4a8dec1cdac348e + + + thr_hw_power_brake + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010340894c404284f5ad11902bd285da8568 + + + age + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010391f7fdb74f0d794e1fbe5e362a45dd1f + + + + + title + 1 + |host_description| - GPU |query_gpuIndex| |query_gpuName| - ECC Errors + + + + + name + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + 1 + |host_description| - GPU |query_gpuIndex| |query_gpuName| + + + + + hash_0001039f12a36681425f2d9faa64323165254c + GPU - Sample Age + + + util_gpu + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103386498e2ba28dc691ae80400fd9f81cb + + + util_mem + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103fcfd3c9bc04ccdce72e777c017bd52ec + + + mem_used + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103fe69c23cfa14f29431c620ef604c30f3 + + + mem_total + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801031ef6a201b4c8317435dd4f8f03c97c3e + + + temp_gpu + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103a269082db3ee8d772f5f44f27b3f7a23 + + + power + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801038cbec3da5106f36e5d6c2394eb3ec1a2 + + + power_limit + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010315673384900d4c1c618661df74458d3a + + + clock_sm + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801031fcd3d5df2d1a8ec6eb2e7943e3aeda3 + + + clock_mem + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103a8fa9aab83a40aa7739c39ef9c8ea184 + + + ecc_corr + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103a6324b601765f3fba880c82483cab1a4 + + + ecc_uncorr + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801031ad88ffa3dd274846760a8d68f2a0a60 + + + retired_pending + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103db6f1d51fd093d2d28b0cab3c1bd19a0 + + + thr_sw_power_cap + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103e2d56f87cdaca55a819207fe6a19cd9d + + + thr_hw_slowdown + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010315564beb5b304bad49dbca0cb469bb2f + + + thr_sw_thermal + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103684afab926b998321a7a6fac6f5a393b + + + thr_hw_thermal + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801035f35b5a45efe842fa4a8dec1cdac348e + + + thr_hw_power_brake + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010340894c404284f5ad11902bd285da8568 + + + age + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010391f7fdb74f0d794e1fbe5e362a45dd1f + + + + + title + 1 + |host_description| - GPU |query_gpuIndex| |query_gpuName| - Sample Age + + + + + name + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + 1 + |host_description| - GPU |query_gpuIndex| |query_gpuName| + + + + + + diff --git a/tests/Integration/LifecycleTest.php b/tests/Integration/LifecycleTest.php index c5e41b1..dfff7a4 100644 --- a/tests/Integration/LifecycleTest.php +++ b/tests/Integration/LifecycleTest.php @@ -20,9 +20,12 @@ // The version INFO declares, which Cacti records as the installed version. define('GPU_VERSION', (string) (parse_ini_file(dirname(__DIR__, 2) . '/INFO', true)['info']['version'] ?? '')); -const GPU_TABLES = ['plugin_gpu_gpu', 'plugin_gpu_node']; +const GPU_TABLES = ['plugin_gpu_collection', 'plugin_gpu_gpu', 'plugin_gpu_node', 'plugin_gpu_observation', 'plugin_gpu_reindex', 'plugin_gpu_retired']; -const GPU_HOOKS = ['config_arrays', 'config_settings', 'draw_navigation_text']; +// Row counts after the seed action: one node and one GPU record. +const GPU_SEEDED = ['plugin_gpu_collection' => 0, 'plugin_gpu_gpu' => 1, 'plugin_gpu_node' => 1, 'plugin_gpu_observation' => 0, 'plugin_gpu_reindex' => 0, 'plugin_gpu_retired' => 0]; + +const GPU_HOOKS = ['api_device_new', 'config_arrays', 'config_settings', 'device_remove', 'draw_navigation_text', 'poller_bottom']; beforeEach(function () { lifecycle('reset'); @@ -37,7 +40,7 @@ expect($state['plugin']['status'])->toEqual('4') ->and($state['plugin']['version'])->toEqual(GPU_VERSION) - ->and($state['schema'])->toEqual('1') + ->and($state['schema'])->toEqual('2') ->and(array_keys($state['tables']))->toBe(GPU_TABLES) ->and($state['tracked'])->toBe(GPU_TABLES) ->and(array_keys($state['hooks']))->toBe(GPU_HOOKS) @@ -58,7 +61,7 @@ $disabled = lifecycle('disable'); expect($disabled['plugin']['status'])->toEqual('4') - ->and($disabled['tables'])->toBe(['plugin_gpu_gpu' => 1, 'plugin_gpu_node' => 1]); + ->and($disabled['tables'])->toBe(GPU_SEEDED); }); it('upgrades from an older recorded version and is idempotent on repeated runs', function () { @@ -79,7 +82,19 @@ ->and($run['plugin'])->toBe($first['plugin']); } - expect($first['tables'])->toBe(['plugin_gpu_gpu' => 1, 'plugin_gpu_node' => 1]); + expect($first['tables'])->toBe(GPU_SEEDED); +}); + +it('imports the shipped templates once, and a forced re-import updates them in place', function () { + $objects = ['data_query' => 1, 'data_template' => 1, 'graph_templates' => 8, 'graph_items' => 72, 'device_template' => 1, 'dq_graphs' => 8, 'dq_file' => true]; + + expect(lifecycle('install')['objects'])->toBe($objects); + + lifecycle('set_setting', 'gpu_templates_sha256='); + lifecycle('set_version', '0.0'); + + expect(lifecycle('upgrade')['objects'])->toBe($objects) + ->and(lifecycle('upgrade')['objects'])->toBe($objects); }); it('re-registers hooks and realms that went missing', function () { @@ -122,7 +137,7 @@ expect($state['result'])->toBeTrue() ->and(array_keys($state['tables']))->toBe(GPU_TABLES) ->and($state['tables']['plugin_gpu_node'])->toBe(1) - ->and($state['schema'])->toEqual('1') + ->and($state['schema'])->toEqual('2') ->and($state['plugin']['version'])->toEqual(GPU_VERSION); }); @@ -135,7 +150,26 @@ ->and($stopped['schema'])->toEqual('0'); $finished = lifecycle('upgrade'); - expect($finished['schema'])->toEqual('1'); + expect($finished['schema'])->toEqual('2'); +}); + +it('upgrades a version 1 schema by adding the collection tables and keeping the records', function () { + lifecycle('install'); + lifecycle('seed'); + + foreach (['plugin_gpu_observation', 'plugin_gpu_collection', 'plugin_gpu_reindex', 'plugin_gpu_retired'] as $table) { + lifecycle('drop_table', $table); + } + + lifecycle('set_schema', '1'); + + $state = lifecycle('upgrade'); + + expect($state['result'])->toBeTrue() + ->and($state['schema'])->toEqual('2') + ->and(array_keys($state['tables']))->toBe(GPU_TABLES) + ->and($state['tracked'])->toBe(GPU_TABLES) + ->and($state['tables']['plugin_gpu_node'])->toBe(1); }); it('refuses a schema newer than the code and leaves the recorded version alone', function () { diff --git a/tests/Security/SourceRulesTest.php b/tests/Security/SourceRulesTest.php index df05d97..4998965 100644 --- a/tests/Security/SourceRulesTest.php +++ b/tests/Security/SourceRulesTest.php @@ -263,10 +263,12 @@ function gpu_entry_points(): array { } }); -it('starts no process: milestone 2 runs no command on any host', function () { - // REQ-LIFE-005 and ADR 0007. The command runner arrives with collection - // in milestone 3; until then nothing may run a program at all. - $banned = ['exec', 'shell_exec', 'system', 'passthru', 'proc_open', 'popen', 'pcntl_exec', 'exec_background']; +it('runs no command on a GPU node, and starts one process: the collector', function () { + // REQ-LIFE-005 and ADR 0008. The plugin reads GPU nodes over SNMP only; + // the one program it starts is its own collector, from poller_bottom, + // with an escaped argument. + $banned = ['exec', 'shell_exec', 'system', 'passthru', 'proc_open', 'popen', 'pcntl_exec', 'exec_background', 'exec_into_array', 'proc_nice']; + $allowed = []; foreach (gpu_sources() as $file) { $tokens = array_values(array_filter(PhpToken::tokenize((string) file_get_contents(gpu_root() . '/' . $file)), fn ($t) => !$t->is([T_WHITESPACE, T_COMMENT, T_DOC_COMMENT]))); @@ -275,10 +277,16 @@ function gpu_entry_points(): array { expect($token->text)->not->toBe('`', "$file:{$token->line} uses a backtick command"); if ($token->is(T_STRING) && in_array(strtolower($token->text), $banned, true) && ($tokens[$i + 1]->text ?? '') === '(' && !($tokens[$i - 1]->is([T_OBJECT_OPERATOR, T_DOUBLE_COLON, T_FUNCTION]))) { - expect(false)->toBeTrue("$file:{$token->line} calls {$token->text}()"); + $allowed[] = "$file:" . $token->text . '(' . ($tokens[$i + 2]->text ?? '') . ', ' . ($tokens[$i + 4]->text ?? '') . ')'; } } } + + expect($allowed)->toBe(['setup.php:exec_background($php, $args)']); + + $setup = (string) file_get_contents(gpu_root() . '/setup.php'); + + expect($setup)->toContain("\$args = '-q ' . cacti_escapeshellarg(__DIR__ . '/poller_gpu.php');"); }); it('names no state-changing vendor command anywhere', function () { diff --git a/tests/Unit/CollectorTest.php b/tests/Unit/CollectorTest.php new file mode 100644 index 0000000..10d85c5 --- /dev/null +++ b/tests/Unit/CollectorTest.php @@ -0,0 +1,266 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu\AdminState; +use Somethingwithproof\Gpu\CollectionError; +use Somethingwithproof\Gpu\CollectionRepository; +use Somethingwithproof\Gpu\Collector; +use Somethingwithproof\Gpu\ExecutionState; +use Somethingwithproof\Gpu\ExtendOutput; +use Somethingwithproof\Gpu\ExtendReader; +use Somethingwithproof\Gpu\FixedClock; +use Somethingwithproof\Gpu\GpuRecord; +use Somethingwithproof\Gpu\GpuRepository; +use Somethingwithproof\Gpu\IdentityReconciler; +use Somethingwithproof\Gpu\Inventory; +use Somethingwithproof\Gpu\LockRepository; +use Somethingwithproof\Gpu\Node; +use Somethingwithproof\Gpu\NodeDevice; +use Somethingwithproof\Gpu\NvidiaSmiParser; +use Somethingwithproof\Gpu\ObservationRepository; +use Somethingwithproof\Gpu\Presence; +use Somethingwithproof\Gpu\Reconciliation; +use Somethingwithproof\Gpu\ReindexRepository; +use Somethingwithproof\Gpu\Schema; +use Somethingwithproof\Gpu\Settings; +use Somethingwithproof\Gpu\SnmpdConfig; +use Somethingwithproof\Gpu\Vendor; + +const COLLECT_NOW = 1800000100; + +beforeEach(function () { + $GLOBALS['__gpu_db_exec'] = []; + $GLOBALS['__gpu_db_rows'] = ['GET_LOCK' => [['l' => 1]]]; + $GLOBALS['__gpu_log'] = []; + $GLOBALS['__gpu_affected_rows'] = 0; + $GLOBALS['__gpu_db_fail'] = []; +}); + +/** + * An extend reader that answers from nvidia-smi fixture files, or fails. + */ +final class FixtureReader implements ExtendReader { + /** @var list */ + public array $reads = []; + + public function __construct(private readonly string $fixture, private readonly ?CollectionError $error = null, private readonly int $status = 0) { + } + + public function read(NodeDevice $device, string $token): ExtendOutput { + $this->reads[] = $token; + + if ($this->error !== null) { + throw $this->error; + } + + $file = dirname(__DIR__) . '/fixtures/nvidia-smi/' . $this->fixture . ($token === SnmpdConfig::METRICS ? '.metrics' : '.names'); + $text = $this->fixture === '' ? '' : str_replace('@NOW@', '2027/01/15 08:00:00.250', (string) file_get_contents($file)); + $lines = $text === '' ? [] : explode("\n", rtrim($text, "\n")); + + return new ExtendOutput($token === SnmpdConfig::METRICS ? $this->status : 0, count($lines), $lines); + } +} + +function collector(ExtendReader $reader): Collector { + $clock = new FixedClock(COLLECT_NOW); + $gpus = new GpuRepository(false); + + return new Collector($reader, new NvidiaSmiParser(), new Inventory($gpus, new IdentityReconciler(), $clock), $gpus, new ObservationRepository(false), new CollectionRepository(false), new ReindexRepository(false), new LockRepository(false), $clock); +} + +function collect_node(AdminState $state = AdminState::Enabled): Node { + return new Node(3, 40, $state, 'gpu-node', true, 0, 0); +} + +function collect_device(): NodeDevice { + return NodeDevice::fromRow(['id' => 40, 'hostname' => 'gpu-node', 'snmp_version' => 3]); +} + +/** + * @return list statements that write, in order + */ +function collect_writes(string $table): array { + return array_values(array_map(fn ($e) => $e['sql'], array_filter($GLOBALS['__gpu_db_exec'], fn ($e) => preg_match('/^\s*(INSERT|UPDATE|DELETE)\b.*\b' . $table . '\b/s', $e['sql']) === 1))); +} + +/** + * Stored records for the r595-1gpu fixture's GPU, at node 3. + */ +function collect_known(int $node = 3): array { + return [[ + 'id' => 9, 'vendor' => 'nvidia', 'uuid' => 'GPU-00000000-0000-4000-8000-000000000001', 'node_id' => $node, 'gpu_index' => 0, + 'pci_bus_id' => '00000000:18:00.0', 'name' => 'NVIDIA H100 80GB HBM3', 'driver_version' => '595.45.04', 'tool' => 'nvidia-smi', + 'tool_version' => '595.45.04', 'presence' => 'present', 'first_seen' => 1, 'last_seen' => 1, + ]]; +} + +it('stores nothing and changes no GPU record when the collection fails', function (CollectionError|int $failure, ExecutionState $state) { + $GLOBALS['__gpu_db_rows']['FROM plugin_gpu_gpu'] = collect_known(); + + $reader = is_int($failure) ? new FixtureReader('r595-1gpu', status: $failure) : new FixtureReader('r595-1gpu', $failure); + + expect(collector($reader)->collect(collect_node(), collect_device(), Settings::fromRow([])))->toBe($state) + ->and(collect_writes('plugin_gpu_gpu'))->toBe([]) + ->and(collect_writes('plugin_gpu_observation'))->toBe([]) + ->and(collect_writes('plugin_gpu_reindex'))->toBe([]); + + $finish = array_values(array_filter($GLOBALS['__gpu_db_exec'], fn ($e) => str_contains($e['sql'], 'last_ok_at'))); + + expect($finish)->toHaveCount(1) + ->and($finish[0]['params'][1])->toBe($state->value) + ->and(end($finish[0]['params']))->toBe(0); + + expect(array_column($GLOBALS['__gpu_log'], 'message'))->toContain('WARNING: Node 3: collection failed (' . $state->value . '): ' . $finish[0]['params'][2]); +})->with([ + 'agent down' => [new CollectionError(ExecutionState::Unreachable, 'The SNMP agent did not answer'), ExecutionState::Unreachable], + 'entry missing' => [new CollectionError(ExecutionState::NotConfigured, 'The SNMP agent has no extend entry named cacti_gpu'), ExecutionState::NotConfigured], + 'tool timed out' => [124, ExecutionState::TimedOut], + 'driver not ready' => [9, ExecutionState::DriverNotLoaded], +]); + +it('records an empty collection as successful without marking any GPU absent', function () { + $GLOBALS['__gpu_db_rows']['FROM plugin_gpu_gpu'] = collect_known(); + + expect(collector(new FixtureReader(''))->collect(collect_node(), collect_device(), Settings::fromRow([])))->toBe(ExecutionState::Empty) + ->and(collect_writes('plugin_gpu_gpu'))->toBe([]) + ->and(collect_writes('plugin_gpu_observation'))->toBe([]); +}); + +it('stores each reported GPU\'s values against its record and asks for a reindex for a new GPU', function () { + // The first read finds no record; the second finds the one just inserted. + $reads = 0; + $GLOBALS['__gpu_db_rows']['FROM plugin_gpu_gpu'] = function () use (&$reads) { + return $reads++ === 0 ? [] : collect_known(); + }; + + expect(collector(new FixtureReader('r595-1gpu'))->collect(collect_node(), collect_device(), Settings::fromRow([])))->toBe(ExecutionState::Ok) + ->and(collect_writes('plugin_gpu_gpu'))->toHaveCount(1) + ->and(collect_writes('plugin_gpu_observation'))->toHaveCount(1) + ->and(collect_writes('plugin_gpu_reindex'))->toHaveCount(1); + + $store = array_values(array_filter($GLOBALS['__gpu_db_exec'], fn ($e) => str_contains($e['sql'], 'INSERT INTO plugin_gpu_observation')))[0]; + $named = array_combine(array_merge(['gpu_id', 'node_id', 'observed_at', 'ingested_at', 'reported_at', 'backend', 'tool_version'], Schema::OBSERVATION_METRICS, ['thr_mask']), $store['params']); + + expect($named['gpu_id'])->toBe(9) + ->and($named['node_id'])->toBe(3) + ->and($named['observed_at'])->toBe(1800000000) + ->and($named['ingested_at'])->toBe(COLLECT_NOW) + ->and($named['backend'])->toBe('nvidia-smi') + ->and($named['util_gpu'])->toBe(30.0) + ->and($named['power'])->toBeNull() + ->and($named['thr_mask'])->toBe(0) + ->and($store['sql'])->toContain('observed_at = IF(VALUES(observed_at) > observed_at, VALUES(observed_at), observed_at)') + ->and(strrpos($store['sql'], 'observed_at = IF('))->toBeGreaterThan(strrpos($store['sql'], 'thr_mask = IF(')); + + $reindex = array_values(array_filter($GLOBALS['__gpu_db_exec'], fn ($e) => str_contains($e['sql'], 'plugin_gpu_reindex')))[0]; + + expect($reindex['params'])->toBe([3, COLLECT_NOW, 'new GPU']); +}); + +it('fails the collection as not stored when a new GPU\'s record could not be inserted', function () { + // The insert fails, so the second read still finds no record. + $GLOBALS['__gpu_db_rows']['FROM plugin_gpu_gpu'] = []; + $GLOBALS['__gpu_db_fail'] = ['INSERT INTO plugin_gpu_gpu']; + + expect(collector(new FixtureReader('r595-1gpu'))->collect(collect_node(), collect_device(), Settings::fromRow([])))->toBe(ExecutionState::NotStored) + ->and(collect_writes('plugin_gpu_observation'))->toBe([]); + + $finish = array_values(array_filter($GLOBALS['__gpu_db_exec'], fn ($e) => str_contains($e['sql'], 'INSERT INTO plugin_gpu_collection (node_id, state'))); + + expect($finish[0]['params'][1])->toBe('not_stored') + ->and($finish[0]['params'][2])->toBe('1 of 1 GPU samples could not be stored'); +}); + +it('keeps the reindex request for a new GPU when its sample could not be stored', function () { + $reads = 0; + $GLOBALS['__gpu_db_rows']['FROM plugin_gpu_gpu'] = function () use (&$reads) { + return $reads++ === 0 ? [] : collect_known(); + }; + $GLOBALS['__gpu_db_fail'] = ['INSERT INTO plugin_gpu_observation']; + + expect(collector(new FixtureReader('r595-1gpu'))->collect(collect_node(), collect_device(), Settings::fromRow([])))->toBe(ExecutionState::NotStored) + ->and(collect_writes('plugin_gpu_reindex'))->toHaveCount(1); +}); + +it('reports a collection whose status could not be stored as not stored', function () { + $GLOBALS['__gpu_db_rows']['FROM plugin_gpu_gpu'] = collect_known(); + $GLOBALS['__gpu_db_fail'] = ['INSERT INTO plugin_gpu_collection (node_id, state']; + + expect(collector(new FixtureReader('r595-1gpu'))->collect(collect_node(), collect_device(), Settings::fromRow([])))->toBe(ExecutionState::NotStored); +}); + +it('does not store values for a GPU whose record waits for a move to be confirmed', function () { + $GLOBALS['__gpu_db_rows']['FROM plugin_gpu_gpu'] = collect_known(node: 5); + + expect(collector(new FixtureReader('r595-1gpu'))->collect(collect_node(), collect_device(), Settings::fromRow([])))->toBe(ExecutionState::Ok) + ->and(collect_writes('plugin_gpu_observation'))->toBe([]); +}); + +it('asks for no reindex when the listing is unchanged', function () { + $GLOBALS['__gpu_db_rows']['FROM plugin_gpu_gpu'] = collect_known(); + + collector(new FixtureReader('r595-1gpu'))->collect(collect_node(), collect_device(), Settings::fromRow([])); + + expect(collect_writes('plugin_gpu_observation'))->toHaveCount(1) + ->and(collect_writes('plugin_gpu_reindex'))->toBe([]); +}); + +it('skips a node another collection holds, and never collects a disabled node', function () { + $GLOBALS['__gpu_db_rows']['GET_LOCK'] = [['l' => 0]]; + $reader = new FixtureReader('r595-1gpu'); + + expect(collector($reader)->collect(collect_node(), collect_device(), Settings::fromRow([])))->toBe(ExecutionState::Skipped) + ->and($reader->reads)->toBe([]) + ->and($GLOBALS['__gpu_db_exec'][0]['sql'])->toContain('skipped = skipped + 1'); + + $GLOBALS['__gpu_db_rows']['GET_LOCK'] = [['l' => 1]]; + $GLOBALS['__gpu_db_exec'] = []; + + expect(collector($reader)->collect(collect_node(AdminState::Disabled), collect_device(), Settings::fromRow([])))->toBe(ExecutionState::Skipped) + ->and($reader->reads)->toBe([]) + ->and($GLOBALS['__gpu_db_exec'])->toBe([]); +}); + +it('asks for a reindex when a GPU\'s index, name, bus ID, or node changes, and not for presence or driver alone', function () { + $read = GpuRecord::fromRow(collect_known()[0]); + + $changed = static fn (array $diff): Reconciliation => new Reconciliation([], [GpuRecord::fromRow(array_merge(collect_known()[0], $diff))], [9 => $read]); + + expect(Collector::reindexReason(new Reconciliation()))->toBe('') + ->and(Collector::reindexReason(new Reconciliation(), 1))->toBe('retired GPU returned') + ->and(Collector::reindexReason($changed(['gpu_index' => 1])))->toBe('GPU changed') + ->and(Collector::reindexReason($changed(['name' => 'NVIDIA H200'])))->toBe('GPU changed') + ->and(Collector::reindexReason($changed(['pci_bus_id' => '00000000:28:00.0'])))->toBe('GPU changed') + ->and(Collector::reindexReason($changed(['node_id' => 5])))->toBe('GPU changed') + ->and(Collector::reindexReason($changed(['presence' => Presence::Absent->value, 'missing_count' => 3])))->toBe('') + ->and(Collector::reindexReason($changed(['driver_version' => '620.70.06'])))->toBe(''); +}); + +it('reads the staleness limit within its bounds', function (mixed $stored, int $expected) { + expect(Settings::fromRow(['gpu_stale_after' => $stored])->staleAfter)->toBe($expected); +})->with([ + ['', Settings::DEFAULT_STALE_AFTER], + ['10', Settings::MIN_STALE_AFTER], + ['900', 900], + ['999999', Settings::MAX_STALE_AFTER], +]); + +it('keeps one observation column per stored model field', function () { + expect(Schema::OBSERVATION_METRICS)->toBe(array_values(array_diff(\Somethingwithproof\Gpu\MetricModel::names(), ['age']))); +}); diff --git a/tests/Unit/InventoryPageTest.php b/tests/Unit/InventoryPageTest.php index 0a00b81..cd76e8f 100644 --- a/tests/Unit/InventoryPageTest.php +++ b/tests/Unit/InventoryPageTest.php @@ -23,6 +23,7 @@ use Somethingwithproof\Gpu\GpuRepository; use Somethingwithproof\Gpu\InventoryPage; use Somethingwithproof\Gpu\Node; +use Somethingwithproof\Gpu\NodeAccess; use Somethingwithproof\Gpu\NodeRepository; use Somethingwithproof\Gpu\NodesPage; use Somethingwithproof\Gpu\Presence; @@ -51,7 +52,7 @@ function page_node(int $id): Node { it('keeps a deleted device selected when a node is edited, instead of the first device listed', function () { $GLOBALS['__gpu_db_rows'] = ['FROM host AS h LEFT JOIN' => [['id' => '5', 'description' => 'other device']]]; - $page = new NodesPage(new NodeRepository(false, new FixedClock(0)), new GpuRepository(false)); + $page = new NodesPage(new NodeRepository(false, new FixedClock(0)), new GpuRepository(false), new NodeAccess(fn (int $id): bool => true)); $node = new Node(1, 101, AdminState::Enabled, '', false, 0, 0); ob_start(); diff --git a/tests/Unit/MetricModelTest.php b/tests/Unit/MetricModelTest.php new file mode 100644 index 0000000..2c33892 --- /dev/null +++ b/tests/Unit/MetricModelTest.php @@ -0,0 +1,107 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu\Metric; +use Somethingwithproof\Gpu\MetricModel; + +it('names every field within Cacti\'s data source item limit, once', function () { + $names = MetricModel::names(); + + expect($names)->toBe(array_values(array_unique($names))); + + foreach ($names as $name) { + expect($name)->toMatch('/^[a-zA-Z0-9_]{1,19}$/', $name); + } + + // The two the research found too long for the limit are renamed. + expect($names)->not->toContain('throttle_hw_slowdown') + ->and($names)->not->toContain('throttle_hw_power_brake') + ->and($names)->toContain('thr_hw_slowdown') + ->and($names)->toContain('thr_hw_power_brake'); +}); + +it('gives every field a unit, a kind, and a source for each backend', function () { + foreach (MetricModel::all() as $metric) { + expect($metric->unit)->not->toBe('', $metric->name) + ->and($metric->kind)->toBeIn([Metric::GAUGE, Metric::INDICATOR]) + ->and($metric->dcgm)->not->toBe('') + ->and($metric->amd)->not->toBe(''); + + // Read from a field, decoded from a mask bit, or computed: never two. + expect(($metric->nvidiaField !== null ? 1 : 0) + ($metric->maskBit !== null ? 1 : 0))->toBeLessThanOrEqual(1, $metric->name); + + if ($metric->kind === Metric::INDICATOR) { + expect([$metric->min, $metric->max])->toBe([0.0, 1.0], $metric->name); + } + } +}); + +it('stores utilization in percent and memory in bytes whatever the source scale', function () { + $gpu = MetricModel::find('util_gpu'); + $mem = MetricModel::find('mem_used'); + $sm = MetricModel::find('clock_sm'); + + // nvidia-smi prints percent; DCGM field 1613 is a 0.0 to 1.0 ratio. + expect(Metric::scale(37.0, $gpu->nvidiaScale))->toBe(37.0) + ->and(Metric::scale(0.37, $gpu->dcgmScale))->toEqualWithDelta(37.0, 1e-9) + ->and([$gpu->min, $gpu->max])->toBe([0.0, 100.0]); + + // nvidia-smi prints MiB with nounits; DCGM 1627 is already bytes. + expect(Metric::scale(1024.0, $mem->nvidiaScale))->toBe(1073741824.0) + ->and(Metric::scale(1073741824.0, $mem->dcgmScale))->toBe(1073741824.0) + ->and($mem->dcgm)->toStartWith('1627 (used, bytes)') + ->and(MetricModel::find('mem_total')->dcgm)->toStartWith('1625 (capacity, bytes)'); + + // DCGM 1603 is hertz; the model is MHz. + expect(Metric::scale(1410000000.0, $sm->dcgmScale))->toEqualWithDelta(1410.0, 1e-6) + ->and(Metric::scale(null, 100.0))->toBeNull(); +}); + +it('decodes the throttle indicators the research names, including hardware slowdown', function () { + expect(MetricModel::BITS)->toBe([ + 'thr_sw_power_cap' => 0x4, + 'thr_hw_slowdown' => 0x8, + 'thr_sw_thermal' => 0x20, + 'thr_hw_thermal' => 0x40, + 'thr_hw_power_brake' => 0x80, + ]); + + foreach (MetricModel::BITS as $name => $bit) { + expect(MetricModel::find($name)->maskBit)->toBe($bit); + } +}); + +it('queries identity and the sample time in the same nvidia-smi query as the metrics', function () { + $fields = MetricModel::nvidiaFields(); + + expect(array_slice($fields, 0, 5))->toBe(['timestamp', 'uuid', 'index', 'pci.bus_id', 'driver_version']) + ->and(end($fields))->toBe('clocks_throttle_reasons.active') + ->and($fields)->not->toContain('name') + ->and($fields)->not->toContain('serial') + ->and($fields)->toBe(array_values(array_unique($fields))) + ->and(MetricModel::namesFields())->toBe(['uuid', 'name']); +}); + +it('matches the generated table in docs/metrics.md', function () { + $doc = (string) file_get_contents(dirname(__DIR__, 2) . '/docs/metrics.md'); + + preg_match('/\n(.*)/s', $doc, $match); + + expect($match[1] ?? '')->toBe(MetricModel::table()); +}); diff --git a/tests/Unit/NodeAccessTest.php b/tests/Unit/NodeAccessTest.php new file mode 100644 index 0000000..8960de0 --- /dev/null +++ b/tests/Unit/NodeAccessTest.php @@ -0,0 +1,69 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu\AdminState; +use Somethingwithproof\Gpu\GpuRecord; +use Somethingwithproof\Gpu\Node; +use Somethingwithproof\Gpu\NodeAccess; + +function access_node(int $id, int $host, bool $exists = true): Node { + return new Node($id, $host, AdminState::Enabled, 'node' . $id, $exists, 0, 0); +} + +function access_gpu(int $node, int $pending = 0): GpuRecord { + return GpuRecord::fromRow(['id' => 1, 'vendor' => 'nvidia', 'uuid' => 'GPU-00000000-0000-4000-8000-000000000001', 'node_id' => $node, 'pending_node_id' => $pending]); +} + +// The user may see device 10 only. +function access(): NodeAccess { + return new NodeAccess(fn (int $host): bool => $host === 10); +} + +it('lets a user manage only nodes on devices it may see', function () { + expect(access()->canManage(access_node(1, 10)))->toBeTrue() + ->and(access()->canManage(access_node(2, 20)))->toBeFalse() + ->and(access()->canManage(null))->toBeFalse() + ->and(access()->deviceAllowed(0))->toBeFalse(); +}); + +it('shows a node whose device was deleted, but never lets it be managed', function () { + $orphan = access_node(3, 10, false); + + expect(access()->canSee($orphan))->toBeTrue() + ->and(access()->canManage($orphan))->toBeFalse() + ->and(access()->canSee(access_node(2, 20)))->toBeFalse(); +}); + +it('requires both nodes of a GPU move', function () { + $nodes = [1 => access_node(1, 10), 2 => access_node(2, 20), 4 => access_node(4, 10)]; + + expect(access()->canManageGpu(access_gpu(1), $nodes))->toBeTrue() + ->and(access()->canManageGpu(access_gpu(1, 4), $nodes))->toBeTrue() + ->and(access()->canManageGpu(access_gpu(1, 2), $nodes))->toBeFalse() + ->and(access()->canManageGpu(access_gpu(2, 1), $nodes))->toBeFalse() + ->and(access()->canManageGpu(access_gpu(1, 9), $nodes))->toBeFalse(); +}); + +it('lists only GPUs recorded at nodes the user may manage', function () { + $nodes = access()->visibleNodes([access_node(1, 10), access_node(2, 20), access_node(3, 30, false)]); + $gpus = access()->visibleGpus([access_gpu(1), access_gpu(2), access_gpu(3)], $nodes); + + expect(array_keys($nodes))->toBe([1, 3]) + ->and(array_column(array_map(fn (GpuRecord $gpu): array => $gpu->toRow(), $gpus), 'node_id'))->toBe([1]); +}); diff --git a/tests/Unit/NvidiaSmiParserTest.php b/tests/Unit/NvidiaSmiParserTest.php new file mode 100644 index 0000000..a1c96a4 --- /dev/null +++ b/tests/Unit/NvidiaSmiParserTest.php @@ -0,0 +1,359 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu\CollectionError; +use Somethingwithproof\Gpu\ExecutionState; +use Somethingwithproof\Gpu\ExtendOutput; +use Somethingwithproof\Gpu\MetricModel; +use Somethingwithproof\Gpu\NvidiaSmiParser; +use Somethingwithproof\Gpu\SnmpdConfig; +use Somethingwithproof\Gpu\SnmpExtendReader; +use Somethingwithproof\Gpu\ThrottleMask; + +const SMI_NOW = '2027/01/15 08:00:00.250'; +const SMI_TS = 1800000000; + +/** + * @return list + */ +function smi_lines(string $fixture): array { + $text = (string) file_get_contents(dirname(__DIR__) . '/fixtures/nvidia-smi/' . $fixture); + + return explode("\n", rtrim(str_replace('@NOW@', SMI_NOW, $text), "\n")); +} + +/** + * @param list $lines + */ +function smi_out(array $lines, int $result = 0, ?int $declared = null): ExtendOutput { + return new ExtendOutput($result, $declared ?? count($lines), $lines); +} + +function smi_parse(string $name): \Somethingwithproof\Gpu\Collection { + return (new NvidiaSmiParser())->parse(smi_out(smi_lines("$name.metrics")), smi_out(smi_lines("$name.names"))); +} + +function smi_error(ExtendOutput $metrics, ?ExtendOutput $names = null): CollectionError { + try { + (new NvidiaSmiParser())->parse($metrics, $names ?? smi_out([])); + } catch (CollectionError $e) { + return $e; + } + + throw new RuntimeException('the output was accepted'); +} + +it('parses each driver line\'s fixture into one reading per GPU, in model units', function (string $fixture, int $gpus, string $driver) { + $collection = smi_parse($fixture); + $first = $collection->readings[0]; + + expect($collection->readings)->toHaveCount($gpus) + ->and($collection->snapshot->reports)->toHaveCount($gpus) + ->and($collection->state())->toBe(ExecutionState::Ok) + ->and($collection->backend)->toBe('nvidia-smi') + ->and($collection->snapshot->toolVersion)->toBe($driver) + ->and($first->observedAt)->toBe(SMI_TS) + ->and($first->report->uuid)->toBe('GPU-00000000-0000-4000-8000-000000000001') + ->and($first->report->index)->toBe(0) + ->and($first->report->pciBusId)->toBe('00000000:18:00.0') + ->and($first->report->name)->toBe('NVIDIA H100 80GB HBM3') + ->and($first->values['util_gpu'])->toBe(30.0) + ->and($first->values['mem_used'])->toBe(2048 * 1048576.0) + ->and($first->values['mem_total'])->toBe(81559 * 1048576.0) + ->and($first->values['clock_sm'])->toBe(1410.0) + ->and(array_keys($first->values))->toEqualCanonicalizing(array_values(array_diff(MetricModel::names(), ['age']))); +})->with([ + ['r580-8gpu', 8, '580.95.05'], + ['r595-1gpu', 1, '595.45.04'], + ['r620-16gpu', 16, '620.70.06'], +]); + +it('stores placeholders as unknown, never zero', function () { + $values = smi_parse('r595-1gpu')->readings[0]->values; + + expect($values['power'])->toBeNull() + ->and($values['power_limit'])->toBeNull() + ->and($values['ecc_corr'])->toBeNull() + ->and($values['ecc_uncorr'])->toBeNull() + ->and($values['retired_pending'])->toBeNull() + ->and($values['thr_hw_slowdown'])->toBe(0.0); +}); + +it('decodes the throttle mask in hex or decimal, keeping the raw bits', function () { + $eight = smi_parse('r580-8gpu')->readings; + $sixteen = smi_parse('r620-16gpu')->readings; + + expect($eight[1]->mask)->toBe(0x4) + ->and($eight[1]->values['thr_sw_power_cap'])->toBe(1.0) + ->and($eight[0]->mask)->toBe(0x1) + ->and($eight[0]->values['thr_sw_power_cap'])->toBe(0.0) + ->and($sixteen[3]->values['thr_hw_slowdown'])->toBe(1.0) + ->and($sixteen[3]->values['thr_hw_thermal'])->toBe(1.0) + ->and($sixteen[3]->values['thr_hw_power_brake'])->toBe(0.0); + + expect(ThrottleMask::parse('0x0000000000000400'))->toBe(0x400) + ->and(ThrottleMask::parse('1024'))->toBe(1024) + ->and(ThrottleMask::parse('0x7FF'))->toBe(0x7ff) + ->and(ThrottleMask::parse('[N/A]'))->toBeNull() + ->and(ThrottleMask::parse('Not Active'))->toBeNull() + ->and(ThrottleMask::parse('-4'))->toBeNull() + ->and(ThrottleMask::indicators(null))->toBe(array_fill_keys(array_keys(MetricModel::BITS), null)); +}); + +it('reads a product name with commas and shell metacharacters as one field, and keeps it off every command line', function () { + $hostile = 'NVIDIA $(reboot); `id` | x, "y" & z'; + $metrics = smi_lines('r595-1gpu.metrics'); + $names = ['GPU-00000000-0000-4000-8000-000000000001, ' . $hostile]; + + $reading = (new NvidiaSmiParser())->parse(smi_out($metrics), smi_out($names))->readings[0]; + + expect($reading->report->name)->toBe($hostile) + ->and($reading->values['util_gpu'])->toBe(30.0) + ->and($reading->report->pciBusId)->toBe('00000000:18:00.0'); + + // The commands are fixed in the documented snmpd.conf; nothing the node + // or a GPU reports is part of them. + foreach (SnmpdConfig::commands() as $command) { + expect($command)->not->toContain('$(') + ->and($command)->not->toContain('`') + ->and($command)->not->toContain(';') + ->and($command)->not->toContain('|'); + } +}); + +it('rejects a line with fewer or more fields than requested', function () { + $line = smi_lines('r595-1gpu.metrics')[0]; + $short = smi_error(smi_out([substr($line, 0, (int) strrpos($line, ','))])); + $extra = smi_error(smi_out([$line . ', 42'])); + + expect($short->state)->toBe(ExecutionState::InvalidOutput) + ->and($short->getMessage())->toBe('GPU metrics line 1 has 17 fields where 18 were requested') + ->and($short->rejectedLines)->toBe(1) + ->and($extra->getMessage())->toBe('GPU metrics line 1 has 19 fields where 18 were requested'); +}); + +it('rejects stderr text that snmpd merged into the output', function () { + $lines = smi_lines('r580-8gpu.metrics'); + array_splice($lines, 2, 0, ['Failed to initialize NVML: Driver/library version mismatch']); + + $error = smi_error(smi_out($lines)); + + expect($error->state)->toBe(ExecutionState::InvalidOutput) + ->and($error->getMessage())->toBe('GPU metrics line 3 has 1 fields where 18 were requested') + ->and($error->getMessage())->not->toContain('NVML'); + + expect(smi_error(smi_out(smi_lines('r595-1gpu.metrics')), smi_out(['WARNING: infoROM is corrupted at gpu 0000:18:00.0']))->getMessage()) + ->toBe('GPU names line 1 is not a UUID and a name'); +}); + +it('treats a nonzero exit status as an error state, never as values', function (int $status, ExecutionState $state) { + expect(smi_error(smi_out(smi_lines('r595-1gpu.metrics'), $status))->state)->toBe($state) + ->and(smi_error(smi_out(smi_lines('r595-1gpu.metrics')), smi_out([], $status))->state)->toBe($state); +})->with([ + 'timeout(1) stopped it' => [124, ExecutionState::TimedOut], + 'timeout(1) killed it' => [137, ExecutionState::TimedOut], + 'no permission' => [4, ExecutionState::PermissionDenied], + 'driver not loaded' => [9, ExecutionState::DriverNotLoaded], + 'not found' => [127, ExecutionState::ToolMissing], + 'GPU fell off the bus' => [15, ExecutionState::ToolError], +]); + +it('treats output cut at snmpd\'s limits as truncated', function () { + $lines = smi_lines('r580-8gpu.metrics'); + + expect(smi_error(smi_out($lines, 0, count($lines) + 3))->state)->toBe(ExecutionState::Truncated) + ->and(smi_error(smi_out(array_fill(0, ExtendOutput::MAX_LINES, $lines[0])))->state)->toBe(ExecutionState::Truncated) + ->and(smi_error(smi_out([str_repeat('x', ExtendOutput::MAX_BYTES)]))->state)->toBe(ExecutionState::Truncated); +}); + +it('rejects a sample time that is missing, malformed, or impossible', function (string $time) { + $line = str_replace(SMI_NOW, $time, smi_lines('r595-1gpu.metrics')[0]); + + expect(smi_error(smi_out([$line]))->getMessage())->toBe('GPU metrics line 1 has no valid sample time'); +})->with(['[N/A]', '2027-01-15 08:00:00', '2027/02/30 08:00:00.000', '']); + +it('rejects identity it cannot trust, refusing the whole collection', function (string $from, string $to, string $message) { + $lines = smi_lines('r580-8gpu.metrics'); + $lines[1] = str_replace($from, $to, $lines[1]); + + expect(smi_error(smi_out($lines))->getMessage())->toBe($message); +})->with([ + 'MIG UUID' => ['GPU-00000000-0000-4000-8000-000000000002', 'MIG-00000000-0000-4000-8000-000000000002', 'GPU metrics line 2: GPU UUID is a MIG instance UUID, which is not an identity key'], + 'duplicate UUID' => ['GPU-00000000-0000-4000-8000-000000000002', 'GPU-00000000-0000-4000-8000-000000000001', 'Two GPUs in one collection report the same UUID'], + 'bad bus ID' => ['00000000:28:00.0', 'slot 2', 'GPU metrics line 2: PCI bus ID is not domain:bus:device.function'], + 'negative index' => [', 1, 00000000:28', ', -1, 00000000:28', 'GPU metrics line 2: GPU index is negative'], +]); + +it('reports an empty but successful collection as empty', function () { + $collection = (new NvidiaSmiParser())->parse(smi_out([]), smi_out([])); + + expect($collection->state())->toBe(ExecutionState::Empty) + ->and($collection->snapshot->reports)->toBe([]) + ->and($collection->newestSample())->toBe(0); +}); + +it('documents the exact extend lines it parses, within extend\'s command limit', function () { + $doc = (string) file_get_contents(dirname(__DIR__, 2) . '/docs/node-setup.md'); + + preg_match('/\n```\n(.*)\n```\n/s', $doc, $match); + + expect($match[1] ?? '')->toBe(implode("\n", SnmpdConfig::extendLines())) + ->and(SnmpdConfig::TIMEOUT + SnmpdConfig::KILL_AFTER)->toBeLessThan(SnmpdConfig::METRICS_CACHE); + + foreach (SnmpdConfig::commands() as $name => $command) { + expect(strlen($command))->toBeLessThan(SnmpdConfig::MAX_COMMAND, $name) + ->and($command)->toStartWith('/usr/bin/env -i ') + ->and($command)->toContain(' /usr/bin/timeout -k 2 10 /usr/bin/nvidia-smi --query-gpu='); + } + + expect(SnmpdConfig::commands()[SnmpdConfig::METRICS])->toContain('--query-gpu=' . implode(',', MetricModel::nvidiaFields()) . ' --format=csv,noheader,nounits'); +}); + +it('encodes extend entry names as NET-SNMP-EXTEND-MIB indexes', function () { + expect(SnmpExtendReader::index('cacti_gpu'))->toBe('9.99.97.99.116.105.95.103.112.117'); +}); + +function smi_device(): \Somethingwithproof\Gpu\NodeDevice { + return \Somethingwithproof\Gpu\NodeDevice::fromRow(['id' => 4, 'hostname' => 'node', 'snmp_version' => 3]); +} + +it('reads an extend entry\'s status, line count, and lines in line order', function () { + $index = SnmpExtendReader::index('cacti_gpu'); + + $GLOBALS['__gpu_snmp'] = [ + "1.3.6.1.4.1.8072.1.3.2.3.1.4.$index" => '0', + "1.3.6.1.4.1.8072.1.3.2.3.1.3.$index" => '2', + // Walk order is not trusted; the line number is the last component. + "1.3.6.1.4.1.8072.1.3.2.4.1.2.$index.2" => 'second', + "1.3.6.1.4.1.8072.1.3.2.4.1.2.$index.1" => 'first', + // Another entry whose name starts the same way is not mixed in. + '1.3.6.1.4.1.8072.1.3.2.4.1.2.' . SnmpExtendReader::index('cacti_gpu_names') . '.1' => 'other', + ]; + + $output = (new SnmpExtendReader(0))->read(smi_device(), 'cacti_gpu'); + + $GLOBALS['__gpu_snmp'] = []; + + expect($output->result)->toBe(0) + ->and($output->declaredLines)->toBe(2) + ->and($output->lines)->toBe(['first', 'second']) + ->and($output->truncated())->toBeFalse(); +}); + +it('gives the first read of an entry time for snmpd to run the command, whatever the device timeout', function () { + $index = SnmpExtendReader::index('cacti_gpu'); + + $GLOBALS['__gpu_snmp'] = ["1.3.6.1.4.1.8072.1.3.2.3.1.4.$index" => '0', "1.3.6.1.4.1.8072.1.3.2.3.1.3.$index" => '0']; + $GLOBALS['__gpu_snmp_gets'] = []; + + (new SnmpExtendReader(0))->read(smi_device(), 'cacti_gpu'); + + $gets = $GLOBALS['__gpu_snmp_gets']; + $GLOBALS['__gpu_snmp'] = []; + + expect($gets[0])->toBe(["1.3.6.1.4.1.8072.1.3.2.3.1.4.$index", 15000]) + ->and(SnmpExtendReader::EXTEND_TIMEOUT_MS)->toBeGreaterThan((\Somethingwithproof\Gpu\SnmpdConfig::TIMEOUT + \Somethingwithproof\Gpu\SnmpdConfig::KILL_AFTER) * 1000); +}); + +it('rejects output that snmpd replaced with another run while it was read', function () { + $index = SnmpExtendReader::index('cacti_gpu'); + $results = ['0', '124']; + + // The cache expired after the first result: the next run timed out. + $GLOBALS['__gpu_snmp'] = [ + "1.3.6.1.4.1.8072.1.3.2.3.1.4.$index" => function () use (&$results) { + return array_shift($results) ?? '124'; + }, + "1.3.6.1.4.1.8072.1.3.2.3.1.3.$index" => '1', + "1.3.6.1.4.1.8072.1.3.2.4.1.2.$index.1" => 'partial', + ]; + + try { + (new SnmpExtendReader(0))->read(smi_device(), 'cacti_gpu'); + } catch (CollectionError $e) { + $changed = $e; + } + + $GLOBALS['__gpu_snmp'] = []; + + expect($changed->state)->toBe(ExecutionState::InvalidOutput) + ->and($changed->getMessage())->toContain('changed while it was read'); +}); + +it('tells a missing extend entry from an agent that does not answer', function () { + $GLOBALS['__gpu_snmp'] = ['1.3.6.1.2.1.1.3.0' => '123456']; + + try { + (new SnmpExtendReader(0))->read(smi_device(), 'cacti_gpu'); + } catch (CollectionError $e) { + $missing = $e; + } + + $GLOBALS['__gpu_snmp'] = []; + + try { + (new SnmpExtendReader(0))->read(smi_device(), 'cacti_gpu'); + } catch (CollectionError $e) { + $silent = $e; + } + + expect($missing->state)->toBe(ExecutionState::NotConfigured) + ->and($missing->getMessage())->toBe('The SNMP agent has no extend entry named cacti_gpu') + ->and($silent->state)->toBe(ExecutionState::Unreachable); +}); + +it('reads through a Cacti SNMP session with the device\'s host and port as stored', function () { + $device = \Somethingwithproof\Gpu\NodeDevice::fromRow(['id' => 4, 'hostname' => '192.0.2.10', 'snmp_version' => 3, 'snmp_port' => 1161, 'snmp_timeout' => 700]); + + $GLOBALS['__gpu_snmp'] = ['1.3.6.1.2.1.1.3.0' => '123456']; + $GLOBALS['__gpu_snmp_sessions'] = []; + $GLOBALS['__gpu_snmp_direct'] = []; + + $value = (new SnmpExtendReader(0))->value($device, '.1.3.6.1.2.1.1.3.0'); + + $sessions = $GLOBALS['__gpu_snmp_sessions']; + $direct = $GLOBALS['__gpu_snmp_direct']; + $GLOBALS['__gpu_snmp'] = []; + + // Not cacti_snmp_get(): Cacti 1.2.x puts this address in brackets. + expect($value)->toBe('123456') + ->and($sessions)->toBe([['192.0.2.10', 1161, 700]]) + ->and($direct)->toBe([]); +}); + +it('falls back to cacti_snmp_get() when Cacti cannot make an SNMP session', function (\Throwable|false $session) { + $device = \Somethingwithproof\Gpu\NodeDevice::fromRow(['id' => 4, 'hostname' => '192.0.2.10', 'snmp_version' => 3, 'snmp_port' => 1161]); + + $GLOBALS['__gpu_snmp'] = ['1.3.6.1.2.1.1.3.0' => '123456']; + $GLOBALS['__gpu_snmp_session'] = $session; + $GLOBALS['__gpu_snmp_direct'] = []; + + $value = (new SnmpExtendReader(0))->value($device, '.1.3.6.1.2.1.1.3.0'); + + $direct = $GLOBALS['__gpu_snmp_direct']; + $GLOBALS['__gpu_snmp'] = []; + $GLOBALS['__gpu_snmp_session'] = true; + + expect($value)->toBe('123456') + ->and($direct)->toBe([['192.0.2.10', 1161]]); +})->with([ + 'no session' => [false], + 'PHP\'s SNMP class missing' => [new \Error('Class "SNMP" not found')], + 'an SNMPv3 protocol refused' => [new \ValueError('Authentication protocol must be "SHA" or "MD5"')], +]); diff --git a/tests/Unit/ProvisionerTest.php b/tests/Unit/ProvisionerTest.php new file mode 100644 index 0000000..31802f6 --- /dev/null +++ b/tests/Unit/ProvisionerTest.php @@ -0,0 +1,310 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu\AdminState; +use Somethingwithproof\Gpu\CacheRepository; +use Somethingwithproof\Gpu\CactiObjectRepository; +use Somethingwithproof\Gpu\CollectionStatus; +use Somethingwithproof\Gpu\FixedClock; +use Somethingwithproof\Gpu\GpuRepository; +use Somethingwithproof\Gpu\Node; +use Somethingwithproof\Gpu\NodeDevice; +use Somethingwithproof\Gpu\NodeAccess; +use Somethingwithproof\Gpu\NodeRepository; +use Somethingwithproof\Gpu\NodesPage; +use Somethingwithproof\Gpu\Provisioner; +use Somethingwithproof\Gpu\ReindexRepository; + +const PROV_KEY_A = 'nvidia/GPU-00000000-0000-4000-8000-000000000001'; +const PROV_KEY_B = 'nvidia/GPU-00000000-0000-4000-8000-000000000002'; + +beforeEach(function () { + $GLOBALS['__gpu_db_exec'] = []; + $GLOBALS['__gpu_log'] = []; + $GLOBALS['__gpu_cacti'] = []; + $GLOBALS['__gpu_affected_rows'] = 1; + $GLOBALS['__gpu_db_fail'] = []; + $GLOBALS['__gpu_db_rows'] = [ + 'FROM `snmp_query`' => [['id' => 78]], + 'FROM host_snmp_query' => [['reindex_method' => 0]], + 'FROM snmp_query_graph' => [['id' => 11, 'graph_template_id' => 343], ['id' => 12, 'graph_template_id' => 344]], + 'FROM graph_local' => [], + 'FROM host_snmp_cache' => prov_cache(PROV_KEY_B, PROV_KEY_A), + 'SELECT status, disabled FROM host' => [['status' => 3, 'disabled' => '']], + 'LEFT JOIN plugin_gpu_retired' => [ + ['vendor' => 'nvidia', 'uuid' => 'GPU-00000000-0000-4000-8000-000000000001', 'gpu_index' => 0, 'name' => 'NVIDIA A100', 'pci_bus_id' => '00000000:01:00.0', 'presence' => 'present'], + ['vendor' => 'nvidia', 'uuid' => 'GPU-00000000-0000-4000-8000-000000000002', 'gpu_index' => 1, 'name' => 'NVIDIA A100', 'pci_bus_id' => '00000000:02:00.0', 'presence' => 'absent'], + ], + ]; +}); + +/** + * Cacti's cache rows for the given GPUs, as a reindex of the listing above + * stores them; $fields overrides values by field name. + */ +function prov_cache(string ...$keys): array { + return prov_cache_with([], ...$keys); +} + +function prov_cache_with(array $fields, string ...$keys): array { + $rows = []; + + foreach ($keys as $key) { + $n = $key === PROV_KEY_A ? 0 : 1; + $values = $fields + ['gpuKey' => $key, 'gpuIndex' => (string) $n, 'gpuName' => 'NVIDIA A100', 'gpuBusId' => sprintf('00000000:%02d:00.0', $n + 1)]; + + foreach ($values as $field => $value) { + $rows[] = ['snmp_index' => $key, 'field_name' => $field, 'field_value' => $value]; + } + } + + return $rows; +} + +function prov(): Provisioner { + return new Provisioner(new CactiObjectRepository(false), new CacheRepository(false), new ReindexRepository(false), new FixedClock(1000)); +} + +function prov_node(): Node { + return new Node(3, 40, AdminState::Enabled, 'gpu-node', true, 0, 0); +} + +function prov_device(int $status = 3, string $disabled = ''): NodeDevice { + return NodeDevice::fromRow(['id' => 40, 'hostname' => 'gpu-node', 'status' => $status, 'disabled' => $disabled]); +} + +function prov_request(): array { + return ['requested_at' => 900, 'reason' => 'new GPU', 'attempts' => 0, 'detail' => '', 'generation' => 4]; +} + +function prov_calls(string $function): array { + return array_values(array_filter($GLOBALS['__gpu_cacti'], fn ($c) => $c[0] === $function)); +} + +it('attaches the data query with reindex method None through Cacti\'s API, and asks for a reindex', function () { + $reads = 0; + $GLOBALS['__gpu_db_rows']['FROM host_snmp_query'] = function () use (&$reads) { + return $reads++ === 0 ? [] : [['reindex_method' => 0]]; + }; + + expect(prov()->attach(prov_node()))->toBeTrue() + ->and(prov_calls('api_device_dq_add'))->toBe([['api_device_dq_add', 40, 78, 0]]); + + $request = array_values(array_filter($GLOBALS['__gpu_db_exec'], fn ($e) => str_contains($e['sql'], 'plugin_gpu_reindex'))); + + expect($request[0]['params'])->toBe([3, 1000, 'data query attached']); +}); + +it('resets a reindex method a device template change set, and leaves a correct attachment alone', function () { + $reads = 0; + $GLOBALS['__gpu_db_rows']['FROM host_snmp_query'] = function () use (&$reads) { + return $reads++ === 0 ? [['reindex_method' => 1]] : [['reindex_method' => 0]]; + }; + + expect(prov()->attach(prov_node()))->toBeTrue() + ->and(prov_calls('api_device_dq_add'))->toHaveCount(1) + ->and(array_filter($GLOBALS['__gpu_db_exec'], fn ($e) => str_contains($e['sql'], 'plugin_gpu_reindex')))->toBe([]); + + $GLOBALS['__gpu_cacti'] = []; + $GLOBALS['__gpu_db_rows']['FROM host_snmp_query'] = [['reindex_method' => 0]]; + + expect(prov()->attach(prov_node()))->toBeTrue() + ->and($GLOBALS['__gpu_cacti'])->toBe([]); +}); + +it('keeps a reindex request while Cacti holds the device down or disabled, without calling run_data_query', function (int $status, string $disabled) { + $result = prov()->provision(prov_node(), prov_device($status, $disabled), prov_request()); + + expect($result['deferred'])->toBeTrue() + ->and($result['reindexed'])->toBeFalse() + ->and(prov_calls('run_data_query'))->toBe([]); + + $deferred = array_values(array_filter($GLOBALS['__gpu_db_exec'], fn ($e) => str_contains($e['sql'], 'attempts = attempts + 1'))); + + expect($deferred)->toHaveCount(1) + ->and(array_filter($GLOBALS['__gpu_db_exec'], fn ($e) => str_starts_with($e['sql'], 'DELETE FROM plugin_gpu_reindex')))->toBe([]); +})->with([ + 'down' => [1, ''], + 'disabled' => [3, 'on'], +]); + +it('completes a reindex only once Cacti lists exactly the plugin\'s GPUs', function () { + $result = prov()->provision(prov_node(), prov_device(), prov_request()); + + expect($result['reindexed'])->toBeTrue() + ->and(prov_calls('run_data_query'))->toBe([['run_data_query', 40, 78, true]]); + + $done = array_values(array_filter($GLOBALS['__gpu_db_exec'], fn ($e) => str_starts_with($e['sql'], 'DELETE FROM plugin_gpu_reindex'))); + + expect($done[0]['params'])->toBe([3, 4]); + + // run_data_query() returned true but the cache still lacks a GPU. + $GLOBALS['__gpu_db_exec'] = []; + $GLOBALS['__gpu_db_rows']['FROM host_snmp_cache'] = prov_cache(PROV_KEY_A); + + $result = prov()->provision(prov_node(), prov_device(), prov_request()); + + expect($result['deferred'])->toBeTrue() + ->and(array_filter($GLOBALS['__gpu_db_exec'], fn ($e) => str_starts_with($e['sql'], 'DELETE FROM plugin_gpu_reindex')))->toBe([]); +}); + +it('keeps the request when the device went down while Cacti reindexed it', function () { + $GLOBALS['__gpu_db_rows']['SELECT status, disabled FROM host'] = [['status' => 1, 'disabled' => '']]; + + $result = prov()->provision(prov_node(), prov_device(), prov_request()); + + expect($result['deferred'])->toBeTrue() + ->and(array_filter($GLOBALS['__gpu_db_exec'], fn ($e) => str_starts_with($e['sql'], 'DELETE FROM plugin_gpu_reindex')))->toBe([]); +}); + +it('keeps the request when the GPU records cannot be read, instead of reading them as none', function () { + $GLOBALS['__gpu_db_rows']['LEFT JOIN plugin_gpu_retired'] = fn () => false; + + $result = prov()->provision(prov_node(), prov_device(), prov_request()); + + expect($result['deferred'])->toBeTrue() + ->and(prov_calls('run_data_query'))->toBe([]) + ->and(array_filter($GLOBALS['__gpu_db_exec'], fn ($e) => str_starts_with($e['sql'], 'DELETE FROM host_snmp_cache')))->toBe([]); +}); + +it('clears the cache and orphans the data sources when the listing has no GPU left', function () { + $cleared = false; + $GLOBALS['__gpu_db_rows']['LEFT JOIN plugin_gpu_retired'] = []; + $GLOBALS['__gpu_db_rows']['FROM host_snmp_cache'] = function () use (&$cleared) { + $cleared = array_filter($GLOBALS['__gpu_db_exec'], fn ($e) => str_starts_with($e['sql'], 'DELETE FROM host_snmp_cache')) !== []; + + return $cleared ? [] : prov_cache(PROV_KEY_A); + }; + + $result = prov()->provision(prov_node(), prov_device(), prov_request()); + $writes = array_column($GLOBALS['__gpu_db_exec'], 'sql'); + + expect($result['reindexed'])->toBeTrue() + ->and(prov_calls('run_data_query'))->toBe([]) + ->and($writes)->toContain('DELETE FROM host_snmp_cache WHERE host_id = ? AND snmp_query_id = ?') + ->and($writes)->toContain('UPDATE data_local SET orphan = 1 WHERE host_id = ? AND snmp_query_id = ?'); +}); + +it('asks for a reindex when no request waits but the listing differs from Cacti\'s cache', function () { + $GLOBALS['__gpu_db_rows']['FROM host_snmp_cache'] = prov_cache(PROV_KEY_A); + + prov()->provision(prov_node(), prov_device(), null); + + $request = array_values(array_filter($GLOBALS['__gpu_db_exec'], fn ($e) => str_starts_with($e['sql'], 'INSERT INTO plugin_gpu_reindex'))); + + expect($request)->toHaveCount(1) + ->and($request[0]['params'])->toBe([3, 1000, 'listing differs from the cache']); + + // Matching listings ask for nothing; neither does a device Cacti holds down. + $GLOBALS['__gpu_db_exec'] = []; + $GLOBALS['__gpu_db_rows']['FROM host_snmp_cache'] = prov_cache(PROV_KEY_B, PROV_KEY_A); + prov()->provision(prov_node(), prov_device(), null); + + $GLOBALS['__gpu_db_rows']['FROM host_snmp_cache'] = prov_cache(PROV_KEY_A); + prov()->provision(prov_node(), prov_device(1), null); + + expect(array_filter($GLOBALS['__gpu_db_exec'], fn ($e) => str_starts_with($e['sql'], 'INSERT INTO plugin_gpu_reindex')))->toBe([]); +}); + +it('creates each graph type once for every present, cached GPU, and none for an absent one', function () { + $GLOBALS['__gpu_db_rows']['FROM graph_local'] = [['snmp_query_graph_id' => 12, 'snmp_index' => PROV_KEY_A]]; + + $result = prov()->provision(prov_node(), prov_device(), null); + $graphs = prov_calls('create_complete_graph_from_template'); + + expect($result['graphs'])->toBe(1) + ->and($graphs)->toHaveCount(1) + ->and($graphs[0][1])->toBe(343) + ->and($graphs[0][3])->toBe(['snmp_query_id' => 78, 'snmp_index_on' => 'gpuKey', 'snmp_query_graph_id' => 11, 'snmp_index' => PROV_KEY_A]) + ->and(prov_calls('push_out_host'))->toBe([['push_out_host', 40, 1]]); +}); + +it('does nothing when the templates are not installed', function () { + $GLOBALS['__gpu_db_rows']['FROM `snmp_query`'] = []; + + expect(prov()->provision(prov_node(), prov_device(), prov_request()))->toBe(['reindexed' => false, 'deferred' => false, 'graphs' => 0]) + ->and($GLOBALS['__gpu_cacti'])->toBe([]); +}); + +it('disables the nodes of deleted devices and keeps their records', function () { + expect((new NodeRepository(false, new FixedClock(5)))->disableForHosts([40, 41]))->toBe(1); + + $sql = $GLOBALS['__gpu_db_exec'][0]; + + expect($sql['sql'])->toStartWith("UPDATE plugin_gpu_node SET admin_state = 'disabled'") + ->and($sql['params'])->toBe([5, 40, 41]) + ->and(implode(' ', array_column($GLOBALS['__gpu_db_exec'], 'sql')))->not->toContain('DELETE'); +}); + +it('describes the latest collection without tool output', function () { + $page = new NodesPage(new NodeRepository(false, new FixedClock(0)), new GpuRepository(false), new NodeAccess(fn (int $id): bool => true), null, new FixedClock(1100)); + + $ok = CollectionStatus::fromRow(['node_id' => 3, 'state' => 'ok', 'finished_at' => 1000, 'gpus' => 8, 'new_gpus' => 1]); + $failed = CollectionStatus::fromRow(['node_id' => 3, 'state' => 'timed_out', 'detail' => 'The GPU metrics command exited with status 124', 'finished_at' => 1000, 'skipped' => 2]); + + expect($page->collection(null))->toBe('Not collected yet') + ->and($page->collection($ok))->toBe('Collected: 8 GPUs; 1 new GPUs recorded (100 s ago)') + ->and($page->collection($failed))->toBe('Timed out: The GPU metrics command exited with status 124 (100 s ago); 2 runs skipped while one was still running'); +}); + +it('offers only devices the acting user may see', function () { + $GLOBALS['__gpu_db_rows'] = ['FROM host AS h LEFT JOIN' => [['id' => '5', 'description' => 'visible'], ['id' => '6', 'description' => 'hidden']]]; + + $page = new NodesPage(new NodeRepository(false, new FixedClock(0)), new GpuRepository(false), new NodeAccess(fn (int $id): bool => $id === 5)); + + ob_start(); + $page->renderEdit(null); + $html = (string) ob_get_clean(); + + expect($html)->toContain('') + ->and($html)->not->toContain('value="6"'); +}); + +it('asks for a reindex when Cacti cached the same GPUs with an old index, name, or bus ID', function () { + $GLOBALS['__gpu_db_rows']['FROM host_snmp_cache'] = array_merge(prov_cache(PROV_KEY_B), prov_cache_with(['gpuName' => 'NVIDIA A40'], PROV_KEY_A)); + + prov()->provision(prov_node(), prov_device(), null); + + $request = array_values(array_filter($GLOBALS['__gpu_db_exec'], fn ($e) => str_starts_with($e['sql'], 'INSERT INTO plugin_gpu_reindex'))); + + expect($request)->toHaveCount(1) + ->and($request[0]['params'])->toBe([3, 1000, 'listing differs from the cache']); +}); + +it('keeps the request when the reindex left an old index, name, or bus ID in Cacti\'s cache', function () { + $GLOBALS['__gpu_db_rows']['FROM host_snmp_cache'] = array_merge(prov_cache(PROV_KEY_B), prov_cache_with(['gpuIndex' => '7'], PROV_KEY_A)); + + $result = prov()->provision(prov_node(), prov_device(), prov_request()); + $deferred = array_values(array_filter($GLOBALS['__gpu_db_exec'], fn ($e) => str_contains($e['sql'], 'attempts = attempts + 1'))); + + expect($result['deferred'])->toBeTrue() + ->and($deferred[0]['params'][1])->toBe('Cacti did not cache every GPU\'s current index, name, and bus ID; retried next cycle') + ->and(array_filter($GLOBALS['__gpu_db_exec'], fn ($e) => str_starts_with($e['sql'], 'DELETE FROM plugin_gpu_reindex')))->toBe([]); +}); + +it('keeps the request when the data sources of a cleared cache could not be marked orphaned', function () { + $GLOBALS['__gpu_db_rows']['LEFT JOIN plugin_gpu_retired'] = []; + $GLOBALS['__gpu_db_rows']['FROM host_snmp_cache'] = []; + $GLOBALS['__gpu_db_fail'] = ['UPDATE data_local SET orphan']; + + $result = prov()->provision(prov_node(), prov_device(), prov_request()); + + expect($result['deferred'])->toBeTrue() + ->and(array_filter($GLOBALS['__gpu_db_exec'], fn ($e) => str_starts_with($e['sql'], 'DELETE FROM plugin_gpu_reindex')))->toBe([]); +}); diff --git a/tests/Unit/RepositoryTest.php b/tests/Unit/RepositoryTest.php index e86970b..0520370 100644 --- a/tests/Unit/RepositoryTest.php +++ b/tests/Unit/RepositoryTest.php @@ -26,7 +26,9 @@ use Somethingwithproof\Gpu\IdentityReconciler; use Somethingwithproof\Gpu\Inventory; use Somethingwithproof\Gpu\InventoryExport; +use Somethingwithproof\Gpu\LockRepository; use Somethingwithproof\Gpu\Node; +use Somethingwithproof\Gpu\NodeDevice; use Somethingwithproof\Gpu\NodeRepository; use Somethingwithproof\Gpu\Presence; use Somethingwithproof\Gpu\Vendor; @@ -128,14 +130,17 @@ function repo_node(int $id = 1, AdminState $state = AdminState::Enabled): Node { it('confirms or rejects only a pending move, and reports whether one changed', function () { $gpus = new GpuRepository(false); - expect($gpus->confirmMove(5))->toBeTrue() + expect($gpus->confirmMove(5, 1, 2))->toBeTrue() ->and($GLOBALS['__gpu_db_exec'][0]['sql'])->toContain('SET node_id = pending_node_id') - ->and($GLOBALS['__gpu_db_exec'][0]['sql'])->toContain('AND pending_node_id > 0'); + ->and($GLOBALS['__gpu_db_exec'][0]['sql'])->toContain('AND node_id = ? AND pending_node_id = ? AND pending_node_id > 0') + // Only the move that was authorized: from node 1 to node 2. + ->and($GLOBALS['__gpu_db_exec'][0]['params'])->toBe([5, 1, 2]); $GLOBALS['__gpu_affected_rows'] = 0; - expect($gpus->confirmMove(5))->toBeFalse() - ->and($gpus->rejectMove(5))->toBeFalse(); + expect($gpus->confirmMove(5, 1, 2))->toBeFalse() + ->and($gpus->rejectMove(5, 1, 2))->toBeFalse() + ->and($GLOBALS['__gpu_db_exec'][2]['params'])->toBe([5, 1, 2]); }); it('deletes a node only in the statement that checks it owns no GPU', function () { @@ -188,3 +193,30 @@ function repo_node(int $id = 1, AdminState $state = AdminState::Enabled): Node { expect(stripos($json, 'toBeFalse() ->and($document['nodes'][0]['description'])->toBe(' rack 4'); }); + +it('hashes lock names to fit the server\'s 64-character limit, the same way for take and release', function () { + $seen = []; + $GLOBALS['__gpu_db_rows']['_LOCK('] = function ($sql) use (&$seen) { + $seen[] = $sql; + + return [['l' => 1]]; + }; + + $locks = new LockRepository(false); + + expect($locks->acquire('node_1'))->toBeTrue(); + $locks->release('node_1'); + + unset($GLOBALS['__gpu_db_rows']['_LOCK(']); + + expect($seen[0])->toBe("SELECT GET_LOCK(SHA2(CONCAT(DATABASE(), '.plugin_gpu.', ?), 256), 0)") + ->and($seen[1])->toBe("SELECT RELEASE_LOCK(SHA2(CONCAT(DATABASE(), '.plugin_gpu.', ?), 256))"); +}); + +it('keeps SNMPv3 passphrases exactly as Cacti stored them', function () { + $device = NodeDevice::fromRow(['id' => 4, 'hostname' => ' node ', 'snmp_password' => ' auth pass ', 'snmp_priv_passphrase' => 'priv ']); + + expect($device->snmpPassword)->toBe(' auth pass ') + ->and($device->snmpPrivPassphrase)->toBe('priv ') + ->and($device->hostname)->toBe('node'); +}); diff --git a/tests/Unit/ScriptServerTest.php b/tests/Unit/ScriptServerTest.php new file mode 100644 index 0000000..e0ca253 --- /dev/null +++ b/tests/Unit/ScriptServerTest.php @@ -0,0 +1,153 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu\CacheRepository; +use Somethingwithproof\Gpu\FixedClock; +use Somethingwithproof\Gpu\Freshness; +use Somethingwithproof\Gpu\ScriptServer; + +const SS_NOW = 1800000600; + +beforeEach(function () { + $GLOBALS['__gpu_db_exec'] = []; + $GLOBALS['__gpu_db_rows'] = []; + $GLOBALS['__gpu_log'] = []; +}); + +/** + * A GPU sampled 60 s ago by the node's latest, successful collection. + */ +function ss_row(array $override = []): array { + return array_merge([ + 'id' => 9, 'vendor' => 'nvidia', 'uuid' => 'GPU-00000000-0000-4000-8000-000000000001', 'gpu_index' => '0', 'name' => 'NVIDIA H100 80GB HBM3', + 'pci_bus_id' => '00000000:18:00.0', 'presence' => 'present', 'observed_at' => SS_NOW - 60, 'reported_at' => SS_NOW - 30, + 'collection_state' => 'ok', 'collection_finished_at' => SS_NOW - 30, 'util_gpu' => '37', 'mem_used' => '2147483648', 'power' => null, + 'temp_gpu' => '-5.5', 'thr_hw_slowdown' => '0', + ], $override); +} + +function ss(): ScriptServer { + return new ScriptServer(new CacheRepository(false), new FixedClock(SS_NOW), 600); +} + +it('prints a current value, and unknown for a missing one, never zero', function () { + expect(Freshness::format(Freshness::value('util_gpu', ss_row(), SS_NOW, 600)))->toBe('37') + ->and(Freshness::format(Freshness::value('mem_used', ss_row(), SS_NOW, 600)))->toBe('2147483648') + ->and(Freshness::format(Freshness::value('temp_gpu', ss_row(), SS_NOW, 600)))->toBe('-5.5') + ->and(Freshness::format(Freshness::value('thr_hw_slowdown', ss_row(), SS_NOW, 600)))->toBe('0') + ->and(Freshness::format(Freshness::value('power', ss_row(), SS_NOW, 600)))->toBe('U') + ->and(Freshness::format(Freshness::value('age', ss_row(), SS_NOW, 600)))->toBe('60') + ->and(Freshness::format(Freshness::value('no_such_field', ss_row(), SS_NOW, 600)))->toBe('U'); +}); + +it('prints unknown for stale, absent, unreported, failed, and never sampled GPUs, keeping age where a sample exists', function (array $row, string $value, string $age) { + expect(Freshness::format(Freshness::value('util_gpu', ss_row($row), SS_NOW, 600)))->toBe($value) + ->and(Freshness::format(Freshness::value('age', ss_row($row), SS_NOW, 600)))->toBe($age); +})->with([ + 'stale' => [['observed_at' => SS_NOW - 601], 'U', '601'], + 'at the limit' => [['observed_at' => SS_NOW - 600], '37', '600'], + 'absent' => [['presence' => 'absent'], 'U', '60'], + 'not in the latest result' => [['reported_at' => SS_NOW - 330], 'U', '60'], + 'latest collection failed' => [['collection_state' => 'timed_out'], 'U', '60'], + 'empty latest collection' => [['collection_state' => 'empty', 'reported_at' => SS_NOW - 330], 'U', '60'], + 'never collected' => [['collection_state' => null], 'U', '60'], + 'never sampled' => [['observed_at' => null, 'reported_at' => null], 'U', 'U'], + 'clock slightly ahead' => [['observed_at' => SS_NOW + 30], '37', '0'], + 'clock far ahead' => [['observed_at' => SS_NOW + 121], 'U', 'U'], +]); + +it('formats values as plain decimals RRDtool accepts', function () { + expect(Freshness::format(1e15))->toBe('1000000000000000') + ->and(Freshness::format(85899345920.0))->toBe('85899345920') + ->and(Freshness::format(0.000001))->toBe('0.000001') + ->and(Freshness::format(-0.0))->toBe('0') + ->and(Freshness::format(NAN))->toBe('U') + ->and(Freshness::format(INF))->toBe('U') + ->and(Freshness::format(null))->toBe('U'); +}); + +it('lists every GPU at the node by identity key, and counts them', function () { + $GLOBALS['__gpu_db_rows']['LEFT JOIN plugin_gpu_retired'] = [ss_row(), ss_row(['uuid' => 'GPU-00000000-0000-4000-8000-000000000002', 'gpu_index' => '1', 'presence' => 'absent'])]; + + expect(ss()->call('40', 'index'))->toBe("nvidia/GPU-00000000-0000-4000-8000-000000000001\nnvidia/GPU-00000000-0000-4000-8000-000000000002") + ->and(ss()->call('40', 'num_indexes'))->toBe('2') + ->and(ss()->call('40', 'query', 'index'))->toBe("nvidia/GPU-00000000-0000-4000-8000-000000000001!nvidia/GPU-00000000-0000-4000-8000-000000000001\nnvidia/GPU-00000000-0000-4000-8000-000000000002!nvidia/GPU-00000000-0000-4000-8000-000000000002") + ->and(ss()->call('40', 'query', 'gpu_index'))->toBe("nvidia/GPU-00000000-0000-4000-8000-000000000001!0\nnvidia/GPU-00000000-0000-4000-8000-000000000002!1") + ->and(ss()->call('40', 'query', 'util_gpu'))->toBe("nvidia/GPU-00000000-0000-4000-8000-000000000001!37\nnvidia/GPU-00000000-0000-4000-8000-000000000002!U") + ->and(ss()->call('40', 'get', 'name', 'nvidia/GPU-00000000-0000-4000-8000-000000000002'))->toBe('NVIDIA H100 80GB HBM3'); + + // Reads only. + expect($GLOBALS['__gpu_db_exec'])->toBe([]); +}); + +it('gets one value by identity key, with the key checked before any read', function () { + $GLOBALS['__gpu_db_rows']['LEFT JOIN plugin_gpu_retired'] = [ss_row()]; + + expect(ss()->call('40', 'get', 'util_gpu', 'nvidia/GPU-00000000-0000-4000-8000-000000000001'))->toBe('37') + ->and(ss()->call('40', 'get', 'age', 'nvidia/GPU-00000000-0000-4000-8000-000000000001'))->toBe('60'); + + $GLOBALS['__gpu_db_rows'] = []; + + expect(ss()->call('40', 'get', 'util_gpu', 'nvidia/GPU-00000000-0000-4000-8000-000000000009'))->toBe('U'); + + $GLOBALS['__gpu_db_rows']['LEFT JOIN plugin_gpu_retired'] = function () { + throw new LogicException('a malformed argument reached the database'); + }; + + foreach (['', 'GPU-1', 'amd/GPU-1', "nvidia/GPU-1' OR 1=1", 'nvidia/GPU-1/2'] as $index) { + expect(ss()->call('40', 'get', 'util_gpu', $index))->toBe('U', $index); + } + + foreach (['', '0', '-1', '4 OR 1', '1e3'] as $host) { + expect(ss()->call($host, 'get', 'util_gpu', 'nvidia/GPU-1'))->toBe('U', $host) + ->and(ss()->call($host, 'index'))->toBe('', $host); + } + + expect(ss()->call('40', 'get', 'no_such_field', 'nvidia/GPU-1'))->toBe('U') + ->and(ss()->call('40', 'drop', 'x'))->toBe(''); +}); + +it('prints an empty listing when the cache cannot be read', function () { + $GLOBALS['__gpu_db_rows']['LEFT JOIN plugin_gpu_retired'] = false; + + expect(ss()->call('40', 'index'))->toBe('') + ->and(ss()->call('40', 'num_indexes'))->toBe('') + ->and(ss()->call('40', 'query', 'util_gpu'))->toBe(''); +}); + +it('keeps a name with line breaks on one listing line', function () { + $GLOBALS['__gpu_db_rows']['LEFT JOIN plugin_gpu_retired'] = [ss_row(['name' => "NVIDIA\nnvidia/GPU-x!0"])]; + + expect(ss()->call('40', 'query', 'name'))->toBe('nvidia/GPU-00000000-0000-4000-8000-000000000001!NVIDIA nvidia/GPU-x!0'); +}); + +it('never throws from the script server entry point', function () { + // As Cacti's script server includes it. + $called_by_script_server = true; + + require_once dirname(__DIR__, 2) . '/ss_gpu.php'; + + $GLOBALS['__gpu_db_rows']['FROM settings'] = function () { + throw new RuntimeException('database gone'); + }; + + expect(ss_gpu('40', 'get', 'util_gpu', 'nvidia/GPU-1'))->toBe('U') + ->and(ss_gpu('40', 'index'))->toBe('') + ->and(end($GLOBALS['__gpu_log'])['message'])->toBe('ERROR: The GPU script server input failed: RuntimeException'); +}); diff --git a/tests/Unit/TemplateXmlTest.php b/tests/Unit/TemplateXmlTest.php new file mode 100644 index 0000000..4dab33a --- /dev/null +++ b/tests/Unit/TemplateXmlTest.php @@ -0,0 +1,180 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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\Gpu\MetricModel; +use Somethingwithproof\Gpu\TemplateXml; + +function tpl_root(): string { + return dirname(__DIR__, 2); +} + +it('ships exactly the XML the generator produces', function () { + expect((string) file_get_contents(tpl_root() . '/resource/script_server/' . TemplateXml::DATA_QUERY_FILE))->toBe(TemplateXml::dataQuery()) + ->and((string) file_get_contents(tpl_root() . '/templates/' . TemplateXml::TEMPLATE_FILE))->toBe(TemplateXml::templates()); +}); + +it('defines a script server data query keyed by GPU identity, with every call the input supports', function () { + $query = simplexml_load_string(TemplateXml::dataQuery()); + + expect((string) $query->script_function)->toBe('ss_gpu') + ->and((string) $query->script_path)->toBe('|path_cacti|/plugins/gpu/ss_gpu.php') + ->and((string) $query->arg_prepend)->toBe('|host_id|') + ->and((string) $query->arg_index)->toBe('index') + ->and((string) $query->arg_num_indexes)->toBe('num_indexes') + ->and((string) $query->arg_query)->toBe('query') + ->and((string) $query->arg_get)->toBe('get') + ->and((string) $query->fields->gpuKey->query_name)->toBe('index') + // Cacti re-maps data sources by the sort field at every reindex, so + // a positional field there would move history between cards. + ->and((string) $query->index_order)->toBe('gpuKey'); + + // Cacti splits each query line at the first delimiter, so the index + // (vendor/UUID) must never contain it. + expect(str_contains('nvidia/GPU-00000000-0000-4000-8000-000000000001', (string) $query->output_delimiter))->toBeFalse() + ->and((string) $query->output_delimiter)->toBe('!'); + + $outputs = []; + + foreach ($query->fields->children() as $name => $field) { + if ((string) $field->direction === 'output') { + $outputs[] = $name; + expect((string) $field->query_name)->toBe($name); + } + } + + expect($outputs)->toBe(MetricModel::names()); +}); + +it('uses valid Cacti 1.2 hashes, each defined once', function () { + $xml = TemplateXml::templates(); + + preg_match_all('/<(hash_[0-9a-z]+)>/', $xml, $opened); + + foreach ($opened[1] as $hash) { + expect($hash)->toMatch('/^hash_[0-9]{2}0103[0-9a-f]{32}$/'); + } + + expect($opened[1])->toBe(array_values(array_unique($opened[1]))); + expect(simplexml_load_string($xml))->not->toBeFalse(); +}); + +it('maps every model field in every data query graph, so one data source serves all of a GPU\'s graphs', function () { + $xml = simplexml_load_string(TemplateXml::templates()); + $dq = $xml->{TemplateXml::hash('04', TemplateXml::DATA_QUERY)}; + + expect((string) $dq->xml_path)->toBe('/resource/script_server/plugin_gpu.xml') + ->and((string) $dq->data_input_id)->toBe('hash_030103332111d8b54ac8ce939af87a7eac0c06') + ->and(count($dq->graphs->children()))->toBe(count(TemplateXml::graphs())); + + foreach ($dq->graphs->children() as $graph) { + $fields = []; + + foreach ($graph->rrd->children() as $item) { + $fields[] = (string) $item->snmp_field_name; + expect((string) $item->data_template_rrd_id)->toBe(TemplateXml::hash('08', (string) $item->snmp_field_name)); + } + + expect($fields)->toBe(MetricModel::names()) + ->and((string) $graph->sv_graph->children()[0]->text)->toContain('|query_gpuIndex| |query_gpuName|'); + } +}); + +it('draws only model fields, with no CDEF that could turn unknown into zero', function () { + $xml = simplexml_load_string(TemplateXml::templates()); + $names = MetricModel::names(); + + foreach (TemplateXml::graphs() as $name => $graph) { + $template = $xml->{TemplateXml::hash('00', $name)}; + + expect((string) $template->graph->title)->toBe(TemplateXml::title($name)) + ->and((string) $template->graph->t_title)->toBe('on'); + + foreach ($template->items->children() as $hash => $item) { + expect((string) $item->cdef_id)->toBe('0'); + + // Each input lists its items with the export's 00 type code. + $member = 'hash_00' . substr($hash, 7); + $found = false; + + foreach ($template->inputs->children() as $input) { + $found = $found || in_array($member, explode('|', (string) $input->items), true); + } + + expect($found)->toBeTrue($hash); + } + + foreach ($graph['items'] as [$metric]) { + expect($names)->toContain($metric); + } + } + + $covered = array_merge(...array_map(fn ($g) => array_column($g['items'], 0), array_values(TemplateXml::graphs()))); + + // Cacti stores only the fields some graph draws, so all must be drawn. + expect($covered)->toEqualCanonicalizing(MetricModel::names()); +}); + +it('defines one gauge per model field in the data template, with the model\'s range', function () { + $xml = simplexml_load_string(TemplateXml::templates()); + $template = $xml->{TemplateXml::hash('01', TemplateXml::DATA_TEMPLATE)}; + + expect(count($template->items->children()))->toBe(count(MetricModel::all())); + + foreach (MetricModel::all() as $metric) { + $item = $template->items->{TemplateXml::hash('08', $metric->name)}; + + expect((string) $item->data_source_name)->toBe($metric->name) + ->and((string) $item->data_source_type_id)->toBe('1') + ->and((string) $item->rrd_minimum)->toBe($metric->rrdMin()) + ->and((string) $item->rrd_maximum)->toBe($metric->rrdMax()); + } + + $host = $xml->{TemplateXml::hash('02', TemplateXml::DEVICE_TEMPLATE)}; + + expect((string) $host->data_queries)->toBe(TemplateXml::hash('04', TemplateXml::DATA_QUERY)) + ->and((string) $host->class)->toBe('hpc'); +}); + +it('does not count the templates as installed while Cacti\'s copy of the data query XML is missing or stale', function () { + $cacti = sys_get_temp_dir() . '/gpu-tpl-' . bin2hex(random_bytes(4)); + mkdir($cacti . '/resource/script_server', 0o700, true); + + // Every database object exists. + $GLOBALS['__gpu_db_rows']['SELECT id FROM'] = [['id' => 7]]; + + $installer = new \Somethingwithproof\Gpu\TemplateInstaller(new \Somethingwithproof\Gpu\CactiObjectRepository(false), new \Somethingwithproof\Gpu\LockRepository(false), tpl_root(), $cacti); + $target = $installer->dataQueryTarget(); + $missing = $installer->installed(); + + file_put_contents($target, 'stale'); + $stale = $installer->installed(); + + file_put_contents($target, (string) file_get_contents(tpl_root() . '/resource/script_server/' . TemplateXml::DATA_QUERY_FILE)); + $current = $installer->installed(); + + unlink($target); + rmdir($cacti . '/resource/script_server'); + rmdir($cacti . '/resource'); + rmdir($cacti); + unset($GLOBALS['__gpu_db_rows']['SELECT id FROM']); + + expect($missing)->toBeFalse() + ->and($stale)->toBeFalse() + ->and($current)->toBeTrue(); +}); diff --git a/tests/bin/e2e.php b/tests/bin/e2e.php new file mode 100644 index 0000000..e2850b6 --- /dev/null +++ b/tests/bin/e2e.php @@ -0,0 +1,451 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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. + */ + +/* + * End-to-end collection test against a real snmpd. Run from the Cacti root + * once the plugin is installed and enabled (tests/bin/php-guard-check.php): + * + * php plugins/gpu/tests/bin/e2e.php + * + * The agent is net-snmp's snmpd, configured by tests/bin/snmpd-conf.php + * from the extend lines in docs/node-setup.md, with tests/bin/fake-nvidia- + * smi installed as /usr/bin/nvidia-smi. Nothing in the SNMP path is + * stubbed: the plugin reads the agent over SNMPv3 with Cacti's own SNMP + * functions, and Cacti's poller reads the plugin's script server input and + * writes the RRD files. + * + * Environment: GPU_TEST_DATABASE=disposable; GPU_E2E_AGENT, the agent's + * host or host:port; GPU_E2E_SECRETS, the file snmpd-conf.php read; and + * GPU_E2E_FIXTURES, the directory the fake tool reads as /var/lib/gpu-e2e. + * + * snmpd caches each extend result for its -cacheTime, 30 seconds for the + * metrics, so each step that changes the tool's output waits that long. + */ + +chdir(dirname(__DIR__, 4)); + +require('./include/cli_check.php'); + +foreach (array('api_device', 'data_query', 'template', 'api_graph', 'api_data_source', 'utility', 'poller', 'rrd', 'snmp') as $library) { + require_once($config['library_path'] . '/' . $library . '.php'); +} + +require_once($config['base_path'] . '/plugins/gpu/setup.php'); + +if (getenv('GPU_TEST_DATABASE') !== 'disposable' || !gpu_boot()) { + fwrite(STDERR, "Set GPU_TEST_DATABASE=disposable and run on PHP 8.2 or later\n"); + exit(2); +} + +use Somethingwithproof\Gpu\MetricModel; +use Somethingwithproof\Gpu\TemplateXml; + +const E2E_CACHE_WAIT = 32; + +$e2e_per_gpu = count(TemplateXml::graphs()); + +$e2e_failures = 0; +$e2e_fixtures = rtrim((string) getenv('GPU_E2E_FIXTURES'), '/'); +$e2e_secrets = file((string) getenv('GPU_E2E_SECRETS'), FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); +$e2e_agent = explode(':', (string) getenv('GPU_E2E_AGENT')) + array(1 => '161'); +$e2e_changed = 0; + +if (!is_dir($e2e_fixtures) || !is_array($e2e_secrets) || count($e2e_secrets) < 2 || $e2e_agent[0] === '') { + fwrite(STDERR, "Set GPU_E2E_AGENT, GPU_E2E_SECRETS, and GPU_E2E_FIXTURES\n"); + exit(2); +} + +function e2e_check(bool $ok, string $what): void { + global $e2e_failures; + + print ($ok ? 'PASS ' : 'FAIL ') . $what . PHP_EOL; + + if (!$ok) { + $e2e_failures++; + } +} + +/** + * The fixture lines with GPU $n replaced, or removed when $line is null. + * + * @return list + */ +function e2e_fixture(string $name, string $part): array { + return explode("\n", rtrim((string) file_get_contents(dirname(__DIR__) . '/fixtures/nvidia-smi/' . $name . '.' . $part), "\n")); +} + +/** + * Give the fake tool new output, and wait out snmpd's cache of the old. + * + * @param list $metrics + * @param list $names + */ +function e2e_tool(array $metrics, array $names, int $status = 0): void { + global $e2e_fixtures, $e2e_changed; + + file_put_contents($e2e_fixtures . '/expected-query', implode(',', MetricModel::nvidiaFields())); + file_put_contents($e2e_fixtures . '/current.metrics', $metrics === array() ? '' : implode("\n", $metrics) . "\n"); + file_put_contents($e2e_fixtures . '/current.names', $names === array() ? '' : implode("\n", $names) . "\n"); + file_put_contents($e2e_fixtures . '/current.status', $status === 0 ? '' : (string) $status); + + if ($e2e_changed > 0) { + print 'wait ' . E2E_CACHE_WAIT . " s for snmpd's extend cache" . PHP_EOL; + sleep(E2E_CACHE_WAIT); + } + + $e2e_changed++; +} + +function e2e_wait_collector(): void { + for ($i = 0; $i < 90 && (int) db_fetch_cell("SELECT COUNT(*) FROM processes WHERE tasktype = 'gpu' AND taskname = 'collector'") > 0; $i++) { + sleep(1); + } +} + +/** + * One collector run, as poller_gpu.php does it, after any run that Cacti's + * poller_bottom hook started has finished. + * + * @return array + */ +function e2e_collect(): array { + e2e_wait_collector(); + + return gpu_poller()->run(gpu_settings(), 120); +} + +/** + * One Cacti poller cycle: it reads the script server input and updates the + * RRD files. + */ +function e2e_poll(): void { + global $config; + + $process = proc_open(array(PHP_BINARY, $config['base_path'] . '/poller.php', '--force'), array(1 => array('file', '/dev/null', 'w'), 2 => array('file', '/dev/null', 'w')), $pipes, $config['base_path']); + + if (is_resource($process)) { + proc_close($process); + } + + e2e_wait_collector(); +} + +function e2e_key(int $n): string { + return sprintf('nvidia/GPU-00000000-0000-4000-8000-%012x', $n); +} + +/** + * @return array + */ +function e2e_state(int $host): array { + global $e2e_node_id; + + $query = gpu_provisioner()->dataQueryId(); + + return array( + 'collection' => db_fetch_row_prepared('SELECT * FROM plugin_gpu_collection WHERE node_id = ?', array($e2e_node_id)), + 'presence' => array_column(db_fetch_assoc_prepared('SELECT uuid, presence FROM plugin_gpu_gpu WHERE node_id = ? ORDER BY uuid', array($e2e_node_id)), 'presence', 'uuid'), + 'cached' => array_column(db_fetch_assoc_prepared('SELECT DISTINCT snmp_index FROM host_snmp_cache WHERE host_id = ? AND snmp_query_id = ? ORDER BY snmp_index', array($host, $query)), 'snmp_index'), + 'graphs' => (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM graph_local WHERE host_id = ? AND snmp_query_id = ?', array($host, $query)), + 'sources' => array_column(db_fetch_assoc_prepared('SELECT id, snmp_index FROM data_local WHERE host_id = ? AND snmp_query_id = ? ORDER BY id', array($host, $query)), 'id', 'snmp_index'), + 'reindex' => db_fetch_row_prepared('SELECT * FROM plugin_gpu_reindex WHERE node_id = ?', array($e2e_node_id)), + ); +} + +function e2e_ss(int $host, string $command, string $field = '', string $index = ''): string { + return gpu_script_server()->call((string) $host, $command, $field, $index); +} + +/** + * The last values Cacti wrote to a GPU's RRD file. + * + * @return array + */ +function e2e_rrd(int $local_data_id): array { + $path = get_data_source_path($local_data_id, true); + + if (!is_file($path)) { + return array(); + } + + $lines = array(); + exec('rrdtool lastupdate ' . escapeshellarg($path), $lines); + + if (count($lines) < 3) { + return array(); + } + + $names = preg_split('/\s+/', trim($lines[0])); + $values = preg_split('/\s+/', trim(substr($lines[2], strpos($lines[2], ':') + 1))); + + return array('time' => (string) (int) $lines[2]) + array_combine($names, $values); +} + +/** + * A rendered graph: the templates ask for SVG; PNG is accepted too. + */ +function e2e_image($image): bool { + return is_string($image) && (substr($image, 0, 4) === "\x89PNG" || preg_match('/^(<\?xml[^>]*>\s*)?idByHash('host_template', TemplateXml::hash('02', TemplateXml::DEVICE_TEMPLATE)); + +e2e_check($e2e_template > 0, 'the GPU Node device template is installed'); + +// Cacti's SNMP availability check uses cacti_snmp_get(), which on Cacti +// 1.2.x (where snmp_format_agent() puts the target in brackets) cannot +// reach an IPv4 agent on a port other than 161, so cmd.php would hold the +// device down. Use the workaround docs/node-setup.md gives there: an +// availability method that does not use SNMP. +$e2e_avail = function_exists('snmp_format_agent') && (int) $e2e_agent[1] !== 161 ? AVAIL_NONE : AVAIL_SNMP; + +$e2e_host = (int) api_device_save(0, $e2e_template, 'gpu-node-e2e', $e2e_agent[0], '', 3, 'cactigpu', $e2e_secrets[0], (int) $e2e_agent[1], 1000, '', + $e2e_avail, 1, 23, 400, 1, '', 'SHA256', $e2e_secrets[1], 'AES128', '', '', 10, 1, 1, 0); + +e2e_check($e2e_host > 0, 'the node device was created through api_device_save()'); + +// Earlier CI steps leave nodes on unreachable test devices; only this +// test's node is collected, so the statistics below are its own. +db_execute("UPDATE plugin_gpu_node SET admin_state = 'disabled'"); + +$e2e_node_id = gpu_nodes()->save(0, $e2e_host, \Somethingwithproof\Gpu\AdminState::Enabled); +$e2e_node = gpu_nodes()->find($e2e_node_id); + +e2e_check($e2e_node !== null && gpu_provisioner()->attach($e2e_node), 'the GPU data query was attached with reindex method None'); +e2e_check((int) db_fetch_cell_prepared('SELECT reindex_method FROM host_snmp_query WHERE host_id = ? AND snmp_query_id = ?', array($e2e_host, gpu_provisioner()->dataQueryId())) === 0, 'the attachment keeps reindex method None'); + +// Wait, within a bound, until the agent answers over SNMPv3 with the +// device's own settings, so a slow agent start is not read as a failure. +// The read goes the way collection reads the device. +$e2e_device = $e2e_node !== null ? gpu_nodes()->device($e2e_node) : null; +$e2e_ready = false; + +for ($i = 0; $i < 30 && $e2e_device !== null && !$e2e_ready; $i++) { + $e2e_uptime = (new \Somethingwithproof\Gpu\SnmpExtendReader(0))->value($e2e_device, '.1.3.6.1.2.1.1.3.0', 1000); + $e2e_ready = $e2e_uptime !== '' && $e2e_uptime !== 'U'; + + if (!$e2e_ready) { + sleep(1); + } +} + +e2e_check($e2e_ready, 'the agent answers over SNMPv3'); + +if (!$e2e_ready) { + print "e2e: the agent never answered; see snmpd's log\n"; + exit(1); +} + +/* Boot: eight GPUs. */ + +$e2e_metrics = e2e_fixture('r580-8gpu', 'metrics'); +$e2e_names = e2e_fixture('r580-8gpu', 'names'); + +e2e_tool($e2e_metrics, $e2e_names); + +$e2e_stats = e2e_collect(); +$e2e_state = e2e_state($e2e_host); + +e2e_check($e2e_stats['ok'] === 1 && $e2e_state['collection']['state'] === 'ok' && (int) $e2e_state['collection']['gpus'] === 8, 'boot: the collection read eight GPUs over SNMPv3'); +e2e_check(count($e2e_state['presence']) === 8 && array_unique($e2e_state['presence']) === array('GPU-00000000-0000-4000-8000-000000000001' => 'present'), 'boot: eight GPU records, all present'); +e2e_check($e2e_stats['reindexed'] === 1 && count($e2e_state['cached']) === 8 && $e2e_state['reindex'] === array(), 'boot: the reindex listed the eight identity keys and its request was cleared'); +e2e_check($e2e_state['graphs'] === 8 * $e2e_per_gpu && count($e2e_state['sources']) === 8, "boot: $e2e_per_gpu graphs per GPU, sharing one data source each"); +e2e_check(e2e_ss($e2e_host, 'get', 'util_gpu', e2e_key(1)) === '30' && e2e_ss($e2e_host, 'get', 'mem_used', e2e_key(1)) === (string) (2048 * 1048576), 'boot: the script server input prints the cached values in model units'); + +// Cacti creates a new data source's RRD file in the first cycle that polls +// it and writes values from the next. +e2e_poll(); +e2e_poll(); + +$e2e_rrd = e2e_rrd((int) $e2e_state['sources'][e2e_key(2)]); +$e2e_first = $e2e_rrd; + +e2e_check(($e2e_rrd['util_gpu'] ?? '') === '31' && ($e2e_rrd['thr_sw_power_cap'] ?? '') === '1' && ($e2e_rrd['thr_hw_slowdown'] ?? '') === '0' && ($e2e_rrd['mem_total'] ?? '') === (string) (81559 * 1048576) && is_numeric($e2e_rrd['age'] ?? ''), 'boot: the Cacti poller wrote the GPU values to its RRD file'); +e2e_check(count($e2e_rrd) - 1 === count(MetricModel::names()), 'boot: the RRD file holds every model field'); + +if (count($e2e_rrd) - 1 !== count(MetricModel::names())) { + print ' RRD fields: ' . implode(' ', array_keys($e2e_rrd)) . PHP_EOL; +} + +foreach (TemplateXml::graphs() as $e2e_graph_name => $e2e_graph) { + $e2e_graph_id = (int) db_fetch_cell_prepared('SELECT gl.id FROM graph_local AS gl INNER JOIN graph_templates AS gt ON gt.id = gl.graph_template_id WHERE gl.host_id = ? AND gl.snmp_index = ? AND gt.name = ?', array($e2e_host, e2e_key(2), $e2e_graph_name)); + $e2e_meta = array(); + $e2e_image = rrdtool_function_graph($e2e_graph_id, 0, array('graph_start' => -3600, 'graph_end' => time()), false, $e2e_meta, 1); + + e2e_check(is_string($e2e_image) && e2e_image($e2e_image), "boot: '$e2e_graph_name' renders from the RRD file"); + + if (!e2e_image($e2e_image)) { + print ' output: ' . substr(preg_replace('/[^\x20-\x7E]/', '.', is_string($e2e_image) ? $e2e_image : var_export($e2e_image, true)), 0, 200) . PHP_EOL; + } +} + +e2e_check(e2e_title($e2e_host, e2e_key(1), 'GPU - Utilization') === 'gpu-node-e2e - GPU 0 NVIDIA H100 80GB HBM3 - Utilization', 'boot: the graph title names the GPU by index and name'); + +/* A tool failure stores nothing and marks no GPU absent. */ + +e2e_tool($e2e_metrics, $e2e_names, 9); +e2e_collect(); +$e2e_state = e2e_state($e2e_host); + +e2e_check($e2e_state['collection']['state'] === 'driver_not_loaded', 'tool failure: recorded as driver not loaded'); +e2e_check(array_unique($e2e_state['presence']) === array('GPU-00000000-0000-4000-8000-000000000001' => 'present'), 'tool failure: every GPU stays present'); +e2e_check(e2e_ss($e2e_host, 'get', 'util_gpu', e2e_key(1)) === 'U' && is_numeric(e2e_ss($e2e_host, 'get', 'age', e2e_key(1))), 'tool failure: values print U while age keeps counting'); + +/* Empty output succeeds and marks no GPU absent. */ + +e2e_tool(array(), array()); +e2e_collect(); +$e2e_state = e2e_state($e2e_host); + +e2e_check($e2e_state['collection']['state'] === 'empty', 'empty output: recorded as an empty collection'); +e2e_check(array_unique($e2e_state['presence']) === array('GPU-00000000-0000-4000-8000-000000000001' => 'present'), 'empty output: every GPU stays present'); +e2e_check(e2e_ss($e2e_host, 'get', 'util_gpu', e2e_key(1)) === 'U', 'empty output: values print U'); + +/* Remove GPU 8, then return it: one data source and RRD file throughout. */ + +$e2e_source8 = (int) $e2e_state['sources'][e2e_key(8)]; + +e2e_tool(array_slice($e2e_metrics, 0, 7), array_slice($e2e_names, 0, 7)); +e2e_collect(); +$e2e_state = e2e_state($e2e_host); + +e2e_check($e2e_state['presence']['GPU-00000000-0000-4000-8000-000000000008'] === 'absent', 'remove: the missing GPU is marked absent'); +e2e_check(in_array(e2e_key(8), explode("\n", e2e_ss($e2e_host, 'index')), true) && in_array(e2e_key(8), $e2e_state['cached'], true), 'remove: the absent GPU stays an index of the data query'); +e2e_check(e2e_ss($e2e_host, 'get', 'util_gpu', e2e_key(8)) === 'U' && (int) $e2e_state['sources'][e2e_key(8)] === $e2e_source8, 'remove: it prints U and keeps its data source'); + +$e2e_graph8 = (int) db_fetch_cell_prepared('SELECT id FROM graph_local WHERE host_id = ? AND snmp_index = ? LIMIT 1', array($e2e_host, e2e_key(8))); +$e2e_meta = array(); +$e2e_image = rrdtool_function_graph($e2e_graph8, 0, array('graph_start' => -3600, 'graph_end' => time()), false, $e2e_meta, 1); + +e2e_check(is_string($e2e_image) && e2e_image($e2e_image), 'remove: the absent GPU\'s graph still renders from its RRD file'); + +e2e_tool($e2e_metrics, $e2e_names); +e2e_collect(); +e2e_poll(); +$e2e_state = e2e_state($e2e_host); +$e2e_rrd = e2e_rrd($e2e_source8); + +e2e_check($e2e_state['presence']['GPU-00000000-0000-4000-8000-000000000008'] === 'present' && (int) $e2e_state['sources'][e2e_key(8)] === $e2e_source8, 're-add: the GPU is present again under the same data source'); +e2e_check(($e2e_rrd['util_gpu'] ?? '') === '37' && (int) ($e2e_rrd['time'] ?? 0) > (int) $e2e_first['time'], 're-add: history continues in the same RRD file'); + +/* A replacement card: same slot, new UUID. */ + +$e2e_replaced = $e2e_metrics; +$e2e_replaced[7] = str_replace('GPU-00000000-0000-4000-8000-000000000008', 'GPU-00000000-0000-4000-8000-000000000099', $e2e_replaced[7]); +$e2e_names2 = $e2e_names; +$e2e_names2[7] = str_replace('GPU-00000000-0000-4000-8000-000000000008', 'GPU-00000000-0000-4000-8000-000000000099', $e2e_names2[7]); + +e2e_tool($e2e_replaced, $e2e_names2); +e2e_collect(); +$e2e_state = e2e_state($e2e_host); + +e2e_check(($e2e_state['presence']['GPU-00000000-0000-4000-8000-000000000099'] ?? '') === 'present' && $e2e_state['presence']['GPU-00000000-0000-4000-8000-000000000008'] === 'absent', 'replacement: a new record for the new card, the old one absent'); +e2e_check(isset($e2e_state['sources'][e2e_key(0x99)]) && (int) $e2e_state['sources'][e2e_key(0x99)] !== $e2e_source8, 'replacement: the new card has its own data source'); +e2e_check((int) $e2e_state['sources'][e2e_key(8)] === $e2e_source8 && is_file(get_data_source_path($e2e_source8, true)), 'replacement: the old card\'s data source and RRD file are intact'); +e2e_check(count($e2e_state['cached']) === 9 && $e2e_state['graphs'] === 9 * $e2e_per_gpu, 'replacement: nine indexes, and graphs for the new card'); + +/* A reindex Cacti skips while the device is down runs once it is up. */ + +$e2e_swapped = $e2e_replaced; +$e2e_swapped[0] = preg_replace('/^([^,]*, [^,]*, )0,/', '${1}1,', $e2e_swapped[0]); +$e2e_swapped[1] = preg_replace('/^([^,]*, [^,]*, )1,/', '${1}0,', $e2e_swapped[1]); + +db_execute_prepared('UPDATE host SET status = 1 WHERE id = ?', array($e2e_host)); + +e2e_tool($e2e_swapped, $e2e_names2); +$e2e_stats = e2e_collect(); +$e2e_state = e2e_state($e2e_host); + +e2e_check($e2e_stats['deferred'] === 1 && (int) ($e2e_state['reindex']['attempts'] ?? 0) === 1, 'down: the reindex request is kept and its attempt recorded'); +e2e_check(e2e_title($e2e_host, e2e_key(1), 'GPU - Utilization') === 'gpu-node-e2e - GPU 0 NVIDIA H100 80GB HBM3 - Utilization', 'down: titles are unchanged while Cacti will not reindex'); + +db_execute_prepared('UPDATE host SET status = 3 WHERE id = ?', array($e2e_host)); + +$e2e_stats = e2e_collect(); +$e2e_state = e2e_state($e2e_host); + +e2e_check($e2e_stats['reindexed'] === 1 && $e2e_state['reindex'] === array(), 'up: the kept reindex ran and its request was cleared'); +e2e_check(e2e_title($e2e_host, e2e_key(1), 'GPU - Utilization') === 'gpu-node-e2e - GPU 1 NVIDIA H100 80GB HBM3 - Utilization', 'up: the new index is in the graph title'); + +/* Sixteen GPUs on a new driver line. */ + +e2e_tool(e2e_fixture('r620-16gpu', 'metrics'), e2e_fixture('r620-16gpu', 'names')); +e2e_collect(); +$e2e_state = e2e_state($e2e_host); + +e2e_check((int) $e2e_state['collection']['gpus'] === 16 && count(array_keys($e2e_state['presence'], 'present', true)) === 16, 'sixteen GPUs: all recorded present'); +e2e_check(count($e2e_state['cached']) === 17 && $e2e_state['graphs'] === 17 * $e2e_per_gpu, 'sixteen GPUs: seventeen indexes (the replaced card stays) and graphs for each present GPU'); + +/* One GPU on a newer driver that reports some fields as [N/A]. */ + +e2e_tool(e2e_fixture('r595-1gpu', 'metrics'), e2e_fixture('r595-1gpu', 'names')); +e2e_collect(); +$e2e_state = e2e_state($e2e_host); + +e2e_check($e2e_state['collection']['state'] === 'ok' && (int) $e2e_state['collection']['gpus'] === 1 && count(array_keys($e2e_state['presence'], 'present', true)) === 1, 'one GPU: collected, and the other records marked absent'); +e2e_check(e2e_ss($e2e_host, 'get', 'power', e2e_key(1)) === 'U' && e2e_ss($e2e_host, 'get', 'util_gpu', e2e_key(1)) === '30', 'one GPU: an [N/A] field prints U, the rest print values'); +e2e_check(count($e2e_state['cached']) === 17, 'one GPU: absent GPUs stay indexes'); + +/* REQ-SS-005: under 50 ms per call with 10,000 GPUs in the cache. */ + +$e2e_now = time(); + +for ($n = 0; $n < 625; $n++) { + db_execute_prepared("INSERT INTO plugin_gpu_node (host_id, admin_state) VALUES (?, 'enabled')", array(900000 + $n)); + $e2e_seed_node = (int) db_fetch_insert_id(); + + for ($g = 0; $g < 16; $g++) { + $e2e_uuid = sprintf('GPU-%08x-0000-4000-8000-%012x', 0x10000 + $n, $g); + db_execute_prepared("INSERT INTO plugin_gpu_gpu (vendor, uuid, node_id, gpu_index, pci_bus_id, name, presence) VALUES ('nvidia', ?, ?, ?, ?, 'seed', 'present')", array($e2e_uuid, $e2e_seed_node, $g, sprintf('00000000:%02X:00.0', $g))); + db_execute_prepared('INSERT INTO plugin_gpu_observation (gpu_id, node_id, observed_at, reported_at, util_gpu) VALUES (?, ?, ?, ?, 50)', array((int) db_fetch_insert_id(), $e2e_seed_node, $e2e_now, $e2e_now)); + } + + db_execute_prepared("INSERT INTO plugin_gpu_collection (node_id, state, finished_at) VALUES (?, 'ok', ?)", array($e2e_seed_node, $e2e_now)); +} + +e2e_check((int) db_fetch_cell('SELECT COUNT(*) FROM plugin_gpu_gpu') >= 10000, 'timing: 10,000 GPUs in the cache'); + +$e2e_slowest = 0.0; + +foreach (array(array('get', 'util_gpu', e2e_key(3)), array('get', 'age', e2e_key(3)), array('index', '', ''), array('num_indexes', '', ''), array('query', 'util_gpu', ''), array('query', 'name', '')) as $e2e_call) { + for ($i = 0; $i < 50; $i++) { + $e2e_start = microtime(true); + e2e_ss($e2e_host, $e2e_call[0], $e2e_call[1], $e2e_call[2]); + $e2e_slowest = max($e2e_slowest, microtime(true) - $e2e_start); + } +} + +e2e_check($e2e_slowest < 0.05, sprintf('timing: the slowest of 300 script server calls took %.1f ms', $e2e_slowest * 1000)); + +db_execute('DELETE o FROM plugin_gpu_observation AS o INNER JOIN plugin_gpu_node AS n ON n.id = o.node_id WHERE n.host_id >= 900000'); +db_execute('DELETE c FROM plugin_gpu_collection AS c INNER JOIN plugin_gpu_node AS n ON n.id = c.node_id WHERE n.host_id >= 900000'); +db_execute('DELETE g FROM plugin_gpu_gpu AS g INNER JOIN plugin_gpu_node AS n ON n.id = g.node_id WHERE n.host_id >= 900000'); +db_execute('DELETE FROM plugin_gpu_node WHERE host_id >= 900000'); + +print ($e2e_failures === 0 ? 'e2e ok' : "e2e: $e2e_failures failed") . PHP_EOL; + +exit($e2e_failures === 0 ? 0 : 1); diff --git a/tests/bin/fake-nvidia-smi b/tests/bin/fake-nvidia-smi new file mode 100755 index 0000000..5c37594 --- /dev/null +++ b/tests/bin/fake-nvidia-smi @@ -0,0 +1,49 @@ +#!/bin/sh +# SPDX-FileCopyrightText: 2026 Thomas Vincent +# SPDX-License-Identifier: GPL-2.0-or-later +# +# This file is part of plugin_gpu, a plugin for Cacti. +# https://github.com/somethingwithproof/plugin_gpu +# +# 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. + +# A stand-in for /usr/bin/nvidia-smi in the end-to-end test, run by snmpd +# through the documented extend lines (docs/node-setup.md). snmpd starts it +# with an empty environment, so its state lives in fixed files under +# /var/lib/gpu-e2e, which tests/bin/e2e.php writes: +# +# expected-query the metrics --query-gpu value the plugin's model asks for +# current.metrics fixture lines, with @NOW@ for the sample time +# current.names fixture lines for the names entry +# current.status optional: exit with this status and an NVML error on +# stderr, as a broken driver does +# +# It accepts only the two documented argument vectors, so a drift between +# the documentation and the plugin's field list fails the test. + +set -eu + +dir=/var/lib/gpu-e2e + +if [ -s "$dir/current.status" ]; then + echo 'Failed to initialize NVML: Driver/library version mismatch' >&2 + exit "$(cat "$dir/current.status")" +fi + +if [ "$#" -eq 2 ] && [ "$1" = "--query-gpu=$(cat "$dir/expected-query")" ] && [ "$2" = '--format=csv,noheader,nounits' ]; then + now=$(date -u '+%Y/%m/%d %H:%M:%S.000') + sed "s#@NOW@#$now#" "$dir/current.metrics" +elif [ "$#" -eq 2 ] && [ "$1" = '--query-gpu=uuid,name' ] && [ "$2" = '--format=csv,noheader' ]; then + cat "$dir/current.names" +else + echo "fake nvidia-smi: unexpected arguments: $*" >&2 + exit 2 +fi diff --git a/tests/bin/lifecycle.php b/tests/bin/lifecycle.php index 8a69a7b..4ad9efa 100644 --- a/tests/bin/lifecycle.php +++ b/tests/bin/lifecycle.php @@ -107,7 +107,9 @@ break; case 'drop_table': + // As if the table had never been created: no table, no tracking row. db_execute('DROP TABLE IF EXISTS `' . preg_replace('/[^a-z_]/', '', $argument) . '`'); + db_execute_prepared("DELETE FROM plugin_db_changes WHERE plugin = 'gpu' AND `table` = ?", array($argument)); break; case 'seed': @@ -158,11 +160,11 @@ $b = null; foreach ($gpus->pendingMoves() as $record) { - $b = $record->id; + $b = $record; } - $confirmed = $b !== null && $gpus->confirmMove($b); - $confirmedTwice = $b !== null && $gpus->confirmMove($b); + $confirmed = $b !== null && $gpus->confirmMove($b->id, $b->nodeId, $b->pendingNodeId); + $confirmedTwice = $b !== null && $gpus->confirmMove($b->id, $b->nodeId, $b->pendingNodeId); // A second record for a stored UUID must fail at the unique key. $copy = $snapshot(array(array($uuid('a1'), 3, '00000000:AF:00.0'))); @@ -247,4 +249,14 @@ 'admin' => (int) db_fetch_cell("SELECT COUNT(*) FROM user_auth_realm AS uar INNER JOIN plugin_realms AS pr ON pr.id + 100 = uar.realm_id WHERE pr.plugin = 'gpu' AND uar.user_id = 1"), 'tracked' => array_column(db_fetch_assoc("SELECT `table` FROM plugin_db_changes WHERE plugin = 'gpu' AND method = 'create' ORDER BY `table`"), 'table'), 'tables' => $tables, + // The shipped Cacti objects, by kind, so a test sees duplicates. + 'objects' => array( + 'data_query' => (int) db_fetch_cell("SELECT COUNT(*) FROM snmp_query WHERE name = 'GPU - Devices'"), + 'data_template' => (int) db_fetch_cell("SELECT COUNT(*) FROM data_template WHERE name = 'GPU - Metrics'"), + 'graph_templates' => (int) db_fetch_cell("SELECT COUNT(*) FROM graph_templates WHERE name LIKE 'GPU - %'"), + 'graph_items' => (int) db_fetch_cell("SELECT COUNT(*) FROM graph_templates_item AS i INNER JOIN graph_templates AS t ON t.id = i.graph_template_id WHERE t.name LIKE 'GPU - %' AND i.local_graph_id = 0"), + 'device_template' => (int) db_fetch_cell("SELECT COUNT(*) FROM host_template WHERE name = 'GPU Node'"), + 'dq_graphs' => (int) db_fetch_cell("SELECT COUNT(*) FROM snmp_query_graph AS g INNER JOIN snmp_query AS q ON q.id = g.snmp_query_id WHERE q.name = 'GPU - Devices'"), + 'dq_file' => is_file($config['base_path'] . '/resource/script_server/plugin_gpu.xml'), + ), ), JSON_PRETTY_PRINT) . PHP_EOL; diff --git a/tests/bin/page-permissions.php b/tests/bin/page-permissions.php index ec2988a..cf457a4 100644 --- a/tests/bin/page-permissions.php +++ b/tests/bin/page-permissions.php @@ -26,6 +26,9 @@ * viewer Console and GPU View: inventory loads, nodes is denied, and * GPUs of a device the viewer may not see are left out * norealm Console only: both pages are denied + * scoped Console and GPU Admin, granted only the first device: every + * node and GPU action on the second device is refused and + * writes nothing, and its records are not listed or exported * * Then shows that tool-reported strings and device descriptions are escaped, * that a delete or move confirmation sent as GET, or as POST without the @@ -50,7 +53,8 @@ $password = 'Gpu-' . bin2hex(random_bytes(8)); $failures = 0; -$view = (int) db_fetch_cell("SELECT id + 100 FROM plugin_realms WHERE plugin = 'gpu' AND file = 'gpu_inventory.php'"); +$view = (int) db_fetch_cell("SELECT id + 100 FROM plugin_realms WHERE plugin = 'gpu' AND file = 'gpu_inventory.php'"); +$admin = (int) db_fetch_cell("SELECT id + 100 FROM plugin_realms WHERE plugin = 'gpu' AND file = 'gpu_nodes.php'"); db_execute_prepared("UPDATE user_auth SET password = ?, must_change_password = '', password_change = '', enabled = 'on', locked = '', failed_attempts = 0 WHERE id = 1", array(password_hash($password, PASSWORD_DEFAULT))); @@ -60,8 +64,8 @@ // only the devices granted to it below are visible, as Cacti's permissive // model evaluates them; an allow policy with no tree exception is treated by // core as access to every device. -foreach (array('viewer' => array(8, $view), 'norealm' => array(8)) as $name => $realms) { - $policy = $name === 'viewer' ? 2 : 1; +foreach (array('viewer' => array(8, $view), 'norealm' => array(8), 'scoped' => array(8, $admin)) as $name => $realms) { + $policy = $name === 'norealm' ? 1 : 2; db_execute_prepared('DELETE FROM user_auth WHERE username = ?', array($name)); db_execute_prepared("INSERT INTO user_auth (username, password, realm, full_name, must_change_password, password_change, policy_graphs, policy_trees, policy_hosts, policy_graph_templates, enabled) VALUES (?, ?, 0, ?, '', '', ?, 1, ?, ?, 'on')", array($name, password_hash($password, PASSWORD_DEFAULT), $name, $policy, $policy, $policy)); @@ -85,6 +89,7 @@ } db_execute_prepared('INSERT INTO user_auth_perms (user_id, item_id, type) VALUES (?, ?, 3)', array($users['viewer'], $devices['open'])); +db_execute_prepared('INSERT INTO user_auth_perms (user_id, item_id, type) VALUES (?, ?, 3)', array($users['scoped'], $devices['open'])); $open = 'GPU-00000000-0000-4000-8000-0000000000a1'; $hidden = 'GPU-00000000-0000-4000-8000-0000000000b2'; @@ -228,6 +233,96 @@ function perm_login($user) { unlink($jar); +// A GPU Admin restricted to the first device acts on the second one. Each +// attempt must be refused and leave every plugin table and the device's +// data query attachment as they were. +db_execute_prepared("INSERT INTO plugin_gpu_gpu (vendor, uuid, node_id, pci_bus_id, name, presence) VALUES ('nvidia', 'GPU-00000000-0000-4000-8000-0000000000c3', ?, '00000000:3D:00.0', 'Absent hidden GPU', 'absent')", array($nodes['hidden'])); +$absentHidden = (int) db_fetch_insert_id(); +db_execute_prepared("INSERT INTO plugin_gpu_gpu (vendor, uuid, node_id, pci_bus_id, name, pending_node_id, pending_since) VALUES ('nvidia', 'GPU-00000000-0000-4000-8000-0000000000d4', ?, '00000000:3E:00.0', 'Hidden to open', ?, 1)", array($nodes['hidden'], $nodes['open'])); +$intoOpen = (int) db_fetch_insert_id(); +db_execute_prepared("INSERT INTO plugin_gpu_gpu (vendor, uuid, node_id, pci_bus_id, name, pending_node_id, pending_since) VALUES ('nvidia', 'GPU-00000000-0000-4000-8000-0000000000e5', ?, '00000000:3F:00.0', 'Open to hidden', ?, 1)", array($nodes['open'], $nodes['hidden'])); +$intoHidden = (int) db_fetch_insert_id(); +db_execute_prepared("INSERT INTO host (description, hostname) VALUES ('Hidden empty node', 'hidden-empty.invalid')"); +$hiddenEmptyDevice = (int) db_fetch_insert_id(); +db_execute_prepared("INSERT INTO plugin_gpu_node (host_id, admin_state) VALUES (?, 'enabled')", array($hiddenEmptyDevice)); +$hiddenEmpty = (int) db_fetch_insert_id(); +db_execute_prepared("INSERT INTO host (description, hostname) VALUES ('Unregistered hidden', 'unregistered.invalid')"); +$unregistered = (int) db_fetch_insert_id(); + +$state = function () { + $tables = array(); + + foreach (array('plugin_gpu_node', 'plugin_gpu_gpu', 'plugin_gpu_retired', 'plugin_gpu_reindex', 'host_snmp_query', 'host') as $table) { + $tables[$table] = db_fetch_assoc('SELECT * FROM `' . $table . '` ORDER BY 1, 2'); + } + + return md5(serialize($tables)); +}; + +$before = $state(); +$jar = perm_login('scoped'); + +list(, $list) = perm_http($base . 'gpu_nodes.php', $jar); +$token = perm_token($list); + +perm_expect(strpos($list, 'Export Records') !== false && strpos($list, 'Hidden node') === false && strpos($list, 'Hidden empty node') === false, 'scoped GPU Admin lists only the nodes of devices it may see'); +perm_expect(strpos($list, '0000000000d4') === false && strpos($list, '0000000000e5') === false, 'scoped GPU Admin is not offered moves that involve a device it may not see'); + +list(, $edit) = perm_http($base . 'gpu_nodes.php?action=edit&id=' . $nodes['hidden'], $jar); +perm_expect(strpos($edit, 'do not have access') !== false && strpos($edit, 'Absent hidden GPU') === false, 'scoped GPU Admin cannot open a node on a device it may not see'); + +list(, $edit) = perm_http($base . 'gpu_nodes.php?action=edit', $jar); +perm_expect(strpos($edit, 'Unregistered hidden') === false && strpos($edit, 'Hidden empty node') === false, 'scoped GPU Admin is offered only devices it may see'); + +$attempts = array( + 'disable a hidden node, keeping its device' => array('action' => 'save', 'id' => $nodes['hidden'], 'host_id' => $devices['hidden']), + 'enable a hidden node, keeping its device' => array('action' => 'save', 'id' => $nodes['hidden'], 'host_id' => $devices['hidden'], 'enabled' => 'on'), + 'move its own node to a hidden device' => array('action' => 'save', 'id' => $nodes['open'], 'host_id' => $unregistered, 'enabled' => 'on'), + 'register a hidden device as a node' => array('action' => 'save', 'id' => 0, 'host_id' => $unregistered, 'enabled' => 'on'), + 'delete a hidden node' => array('action' => 'delete', 'id' => $hiddenEmpty), + 'retire a hidden absent GPU' => array('action' => 'retire', 'id' => $absentHidden), + 'confirm a move from a hidden node' => array('action' => 'confirm_move', 'id' => $intoOpen), + 'reject a move from a hidden node' => array('action' => 'reject_move', 'id' => $intoOpen), + 'confirm a move to a hidden node' => array('action' => 'confirm_move', 'id' => $intoHidden), + 'reject a move to a hidden node' => array('action' => 'reject_move', 'id' => $intoHidden), + 'create a device without device management' => array('action' => 'create_device', 'description' => 'Created', 'hostname' => 'created.invalid'), +); + +foreach ($attempts as $what => $post) { + perm_http($base . 'gpu_nodes.php', $jar, array('__csrf_magic' => $token) + $post); + perm_expect($state() === $before, "scoped GPU Admin cannot $what: nothing is written"); +} + +list(, $export) = perm_http($base . 'gpu_nodes.php?action=export', $jar); +$document = json_decode($export, true); +$exportedGpus = is_array($document) ? array_column($document['gpus'], 'node_id') : array(-1); +perm_expect(is_array($document) && array_column($document['nodes'], 'id') === array($nodes['open']) && array_unique($exportedGpus) === array($nodes['open']) && strpos($export, '0000000000c3') === false && strpos($export, '0000000000d4') === false, 'scoped GPU Admin exports only the records of devices it may see'); + +// The controls: the same user can act on its own device, and may disable, +// but not re-enable, a node whose device was deleted. +perm_http($base . 'gpu_nodes.php', $jar, array('__csrf_magic' => $token, 'action' => 'save', 'id' => $nodes['open'], 'host_id' => $devices['open'])); +perm_expect(db_fetch_cell_prepared('SELECT admin_state FROM plugin_gpu_node WHERE id = ?', array($nodes['open'])) === 'disabled', 'scoped GPU Admin can disable the node of a device it may see'); + +db_execute_prepared("INSERT INTO plugin_gpu_node (host_id, admin_state) VALUES (999999, 'enabled')"); +$orphan = (int) db_fetch_insert_id(); +$orphanState = function () use ($orphan) { + return db_fetch_cell_prepared('SELECT admin_state FROM plugin_gpu_node WHERE id = ?', array($orphan)); +}; + +perm_http($base . 'gpu_nodes.php', $jar, array('__csrf_magic' => $token, 'action' => 'save', 'id' => $orphan, 'host_id' => $devices['open'], 'enabled' => 'on')); +perm_expect($orphanState() === 'enabled' && (int) db_fetch_cell_prepared('SELECT host_id FROM plugin_gpu_node WHERE id = ?', array($orphan)) === 999999, 'a node whose device was deleted cannot be moved to another device'); + +perm_http($base . 'gpu_nodes.php', $jar, array('__csrf_magic' => $token, 'action' => 'save', 'id' => $orphan, 'host_id' => 999999)); +perm_expect($orphanState() === 'disabled', 'a node whose device was deleted can be disabled'); + +perm_http($base . 'gpu_nodes.php', $jar, array('__csrf_magic' => $token, 'action' => 'save', 'id' => $orphan, 'host_id' => 999999, 'enabled' => 'on')); +perm_expect($orphanState() === 'disabled', 'a node whose device was deleted cannot be enabled again'); + +perm_http($base . 'gpu_nodes.php', $jar, array('__csrf_magic' => $token, 'action' => 'delete', 'id' => $orphan)); +perm_expect($orphanState() === 'disabled', 'a node whose device was deleted is not deleted by a scoped GPU Admin'); + +unlink($jar); + $jar = perm_login('viewer'); list(, $export) = perm_http($base . 'gpu_nodes.php?action=export', $jar); perm_expect(strpos($export, $open) === false, 'a GPU View user cannot download the export'); diff --git a/tests/bin/php-guard-check.php b/tests/bin/php-guard-check.php index d9ed4b2..ffd7ee4 100644 --- a/tests/bin/php-guard-check.php +++ b/tests/bin/php-guard-check.php @@ -108,8 +108,8 @@ function guard_call_shims() { if ($supported) { guard_expect($state['status'] == 1, 'install and enable succeed (status ' . $state['status'] . ')'); - guard_expect($state['tables'] === 2, 'both plugin tables exist (' . $state['tables'] . ')'); - guard_expect($state['hooks'] === 3 && $state['realms'] === 2, 'hooks and realms are registered'); + guard_expect($state['tables'] === 6, 'every plugin table exists (' . $state['tables'] . ')'); + guard_expect($state['hooks'] === 6 && $state['realms'] === 2, 'hooks and realms are registered'); } else { guard_expect($state['status'] == 2, 'plugin is left as needing configuration, not enabled (status ' . $state['status'] . ')'); guard_expect($state['tables'] === 0 && $state['hooks'] === 0 && $state['realms'] === 0, 'no tables, hooks, or realms were created'); diff --git a/tests/bin/snmpd-conf.php b/tests/bin/snmpd-conf.php new file mode 100644 index 0000000..6abec9c --- /dev/null +++ b/tests/bin/snmpd-conf.php @@ -0,0 +1,56 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * 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. + */ + +/* + * Print the snmpd.conf the end-to-end test runs the agent with: + * + * php tests/bin/snmpd-conf.php [agent address] + * + * The extend lines are taken from docs/node-setup.md as written, so the test + * exercises what an administrator installs. The rest follows the same page: + * an unprivileged agentuser, and an SNMPv3 authPriv user limited to the + * system group and the extend tables. The createUser line goes in this file + * rather than the persistent one, which net-snmp also accepts, because the + * test agent starts from nothing each run. The secrets file holds the + * authentication and privacy passphrases, one per line; they never appear on + * a command line. + */ + +$doc = (string) file_get_contents(dirname(__DIR__, 2) . '/docs/node-setup.md'); + +if (preg_match('/\n```\n(.*)\n```\n/s', $doc, $match) !== 1) { + fwrite(STDERR, "docs/node-setup.md has no extend lines block\n"); + exit(1); +} + +$secrets = file((string) ($argv[1] ?? ''), FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); + +if (!is_array($secrets) || count($secrets) < 2 || preg_match('/^[A-Za-z0-9]{16,64}$/', $secrets[0]) !== 1 || preg_match('/^[A-Za-z0-9]{16,64}$/', $secrets[1]) !== 1) { + fwrite(STDERR, "usage: snmpd-conf.php [agent address]\n"); + exit(2); +} + +print 'agentaddress ' . ($argv[2] ?? 'udp:161') . "\n" + . "agentuser Debian-snmp\n" + . "dontLogTCPWrappersConnects yes\n" + . "view cactigpu included .1.3.6.1.2.1.1\n" + . "view cactigpu included .1.3.6.1.4.1.8072.1.3.2\n" + . "rouser -s usm cactigpu priv -V cactigpu\n" + . "createUser cactigpu SHA-256 {$secrets[0]} AES {$secrets[1]}\n" + . $match[1] . "\n"; diff --git a/tests/bootstrap-unit.php b/tests/bootstrap-unit.php index dcacb23..ccccb3f 100644 --- a/tests/bootstrap-unit.php +++ b/tests/bootstrap-unit.php @@ -76,10 +76,12 @@ function read_config_option($config_name, $force = false) { $GLOBALS['__gpu_db_exec'] = []; $GLOBALS['__gpu_db_rows'] = []; -function gpu_test_rows(string $sql): mixed { +function gpu_test_rows(string $sql, array $params = []): mixed { foreach ($GLOBALS['__gpu_db_rows'] as $needle => $rows) { if (str_contains($sql, $needle)) { - return $rows; + // A closure answers each query in turn, for a test that needs a + // table to change between two reads. + return $rows instanceof Closure ? $rows($sql, $params) : $rows; } } @@ -90,19 +92,26 @@ function gpu_test_rows(string $sql): mixed { function db_execute_prepared($sql, $params = [], $log = true, $db_conn = false, $log_function = null) { $GLOBALS['__gpu_db_exec'][] = ['sql' => $sql, 'params' => $params]; + // A test makes a write fail by naming a fragment of its statement. + foreach ($GLOBALS['__gpu_db_fail'] ?? [] as $fragment) { + if (str_contains($sql, $fragment)) { + return false; + } + } + return true; } } if (!function_exists('db_fetch_assoc_prepared')) { function db_fetch_assoc_prepared($sql, $params = [], $log = true, $db_conn = false, $log_function = null) { - return gpu_test_rows($sql); + return gpu_test_rows($sql, $params); } } if (!function_exists('db_fetch_row_prepared')) { function db_fetch_row_prepared($sql, $params = [], $log = true, $db_conn = false, $log_function = null) { - $rows = gpu_test_rows($sql); + $rows = gpu_test_rows($sql, $params); return is_array($rows) && isset($rows[0]) ? $rows[0] : []; } @@ -139,7 +148,7 @@ function db_fetch_cell_prepared($sql, $params = [], $col_name = '', $log = true, return $GLOBALS['__gpu_in_tx'] === [] ? 1 : array_shift($GLOBALS['__gpu_in_tx']); } - $rows = gpu_test_rows($sql); + $rows = gpu_test_rows($sql, $params); return is_array($rows) && isset($rows[0]) ? reset($rows[0]) : 0; } @@ -151,6 +160,61 @@ function db_fetch_insert_id($db_conn = false) { } } +// An SNMP agent: $GLOBALS['__gpu_snmp'] maps numeric OIDs (no leading dot) +// to values, or to closures called on each get. A get of a missing OID +// answers like Cacti does for no answer. Each get is recorded with its +// timeout in $GLOBALS['__gpu_snmp_gets']. Each session is recorded in +// $GLOBALS['__gpu_snmp_sessions'] with the target it was given; setting +// $GLOBALS['__gpu_snmp_session'] to false or a Throwable makes +// cacti_snmp_session() return false or throw it, and each get through +// cacti_snmp_get() is then recorded as well in $GLOBALS['__gpu_snmp_direct']. +$GLOBALS['__gpu_snmp'] = []; +$GLOBALS['__gpu_snmp_gets'] = []; +$GLOBALS['__gpu_snmp_sessions'] = []; +$GLOBALS['__gpu_snmp_session'] = true; +$GLOBALS['__gpu_snmp_direct'] = []; + +if (!function_exists('cacti_snmp_session')) { + function cacti_snmp_session($hostname, $community, $version, $auth_user = '', $auth_pass = '', $auth_proto = '', $priv_pass = '', $priv_proto = '', $context = '', $engineid = '', $port = 161, $timeout_ms = 500, $retries = 0, $max_oids = 10, $bulk_walk_size = 10) { + $GLOBALS['__gpu_snmp_sessions'][] = [$hostname, $port, $timeout_ms]; + + if ($GLOBALS['__gpu_snmp_session'] instanceof Throwable) { + throw $GLOBALS['__gpu_snmp_session']; + } + + return $GLOBALS['__gpu_snmp_session'] === false ? false : (object) ['timeout' => $timeout_ms]; + } + + function cacti_snmp_session_get($session, $oid, $strip_alpha = false) { + $GLOBALS['__gpu_snmp_gets'][] = [ltrim($oid, '.'), $session->timeout]; + $value = $GLOBALS['__gpu_snmp'][ltrim($oid, '.')] ?? false; + + return $value instanceof Closure ? $value() : $value; + } +} + +if (!function_exists('cacti_snmp_get')) { + function cacti_snmp_get($hostname, $community, $oid, $version, $auth_user = '', $auth_pass = '', $auth_proto = '', $priv_pass = '', $priv_proto = '', $context = '', $port = 161, $timeout_ms = 500, $retries = 0, $environ = 'SNMP', $engineid = '', $value_output_format = 1) { + $GLOBALS['__gpu_snmp_gets'][] = [ltrim($oid, '.'), $timeout_ms]; + $GLOBALS['__gpu_snmp_direct'][] = [$hostname, $port]; + $value = $GLOBALS['__gpu_snmp'][ltrim($oid, '.')] ?? 'U'; + + return $value instanceof Closure ? $value() : $value; + } + + function cacti_snmp_walk($hostname, $community, $oid, $version, $auth_user = '', $auth_pass = '', $auth_proto = '', $priv_pass = '', $priv_proto = '', $context = '', $port = 161, $timeout_ms = 500, $retries = 0, $bulk_walk_size = 10, $environ = 'SNMP', $engineid = '', $value_output_format = 1) { + $out = []; + + foreach ($GLOBALS['__gpu_snmp'] as $key => $value) { + if (str_starts_with($key, ltrim($oid, '.') . '.')) { + $out[] = ['oid' => '.' . $key, 'value' => $value]; + } + } + + return $out; + } +} + // Enough of Cacti's HTML helpers for a page class to render into a buffer. if (!function_exists('html_escape')) { function html_escape($string) { @@ -187,3 +251,30 @@ function db_affected_rows($db_conn = false) { require_once dirname(__DIR__) . '/setup.php'; require_once dirname(__DIR__) . '/include/autoload.php'; + +// Cacti's device, data query, and graph APIs. Each call is recorded in +// $GLOBALS['__gpu_cacti']; a test sets what they return. +$GLOBALS['__gpu_cacti'] = []; +$GLOBALS['__gpu_cacti_graph'] = ['local_graph_id' => 1, 'local_data_id' => [1]]; + +if (!function_exists('api_device_dq_add')) { + function api_device_dq_add($device_id, $data_query_id, $reindex_method) { + $GLOBALS['__gpu_cacti'][] = ['api_device_dq_add', $device_id, $data_query_id, $reindex_method]; + } + + function run_data_query($host_id, $snmp_query_id, $automation = false, $force = false) { + $GLOBALS['__gpu_cacti'][] = ['run_data_query', $host_id, $snmp_query_id, $force]; + + return true; + } + + function create_complete_graph_from_template($graph_template_id, $host_id, $snmp_query_array, &$suggested_vals) { + $GLOBALS['__gpu_cacti'][] = ['create_complete_graph_from_template', $graph_template_id, $host_id, $snmp_query_array]; + + return $GLOBALS['__gpu_cacti_graph']; + } + + function push_out_host($host_id, $local_data_id = 0, $data_template_id = 0) { + $GLOBALS['__gpu_cacti'][] = ['push_out_host', $host_id, $local_data_id]; + } +} diff --git a/tests/fixtures/nvidia-smi/r580-8gpu.metrics b/tests/fixtures/nvidia-smi/r580-8gpu.metrics new file mode 100644 index 0000000..8dc9e2f --- /dev/null +++ b/tests/fixtures/nvidia-smi/r580-8gpu.metrics @@ -0,0 +1,8 @@ +@NOW@, GPU-00000000-0000-4000-8000-000000000001, 0, 00000000:18:00.0, 580.95.05, 30, 10, 2048, 81559, 40, 100.50, 700.00, 1410, 1593, 0, 0, No, 0x0000000000000001 +@NOW@, GPU-00000000-0000-4000-8000-000000000002, 1, 00000000:28:00.0, 580.95.05, 31, 11, 2049, 81559, 41, 101.50, 700.00, 1411, 1593, 0, 0, No, 0x0000000000000004 +@NOW@, GPU-00000000-0000-4000-8000-000000000003, 2, 00000000:38:00.0, 580.95.05, 32, 12, 2050, 81559, 42, 102.50, 700.00, 1412, 1593, 0, 0, No, 0x0000000000000001 +@NOW@, GPU-00000000-0000-4000-8000-000000000004, 3, 00000000:48:00.0, 580.95.05, 33, 13, 2051, 81559, 43, 103.50, 700.00, 1413, 1593, 0, 0, No, 0x0000000000000001 +@NOW@, GPU-00000000-0000-4000-8000-000000000005, 4, 00000000:58:00.0, 580.95.05, 34, 14, 2052, 81559, 44, 104.50, 700.00, 1414, 1593, 0, 0, No, 0x0000000000000001 +@NOW@, GPU-00000000-0000-4000-8000-000000000006, 5, 00000000:68:00.0, 580.95.05, 35, 15, 2053, 81559, 45, 105.50, 700.00, 1415, 1593, 0, 0, No, 0x0000000000000001 +@NOW@, GPU-00000000-0000-4000-8000-000000000007, 6, 00000000:78:00.0, 580.95.05, 36, 16, 2054, 81559, 46, 106.50, 700.00, 1416, 1593, 0, 0, No, 0x0000000000000001 +@NOW@, GPU-00000000-0000-4000-8000-000000000008, 7, 00000000:88:00.0, 580.95.05, 37, 17, 2055, 81559, 47, 107.50, 700.00, 1417, 1593, 0, 0, No, 0x0000000000000001 diff --git a/tests/fixtures/nvidia-smi/r580-8gpu.names b/tests/fixtures/nvidia-smi/r580-8gpu.names new file mode 100644 index 0000000..6043ac6 --- /dev/null +++ b/tests/fixtures/nvidia-smi/r580-8gpu.names @@ -0,0 +1,8 @@ +GPU-00000000-0000-4000-8000-000000000001, NVIDIA H100 80GB HBM3 +GPU-00000000-0000-4000-8000-000000000002, NVIDIA H100 80GB HBM3 +GPU-00000000-0000-4000-8000-000000000003, NVIDIA H100 80GB HBM3 +GPU-00000000-0000-4000-8000-000000000004, NVIDIA H100 80GB HBM3 +GPU-00000000-0000-4000-8000-000000000005, NVIDIA H100 80GB HBM3 +GPU-00000000-0000-4000-8000-000000000006, NVIDIA H100 80GB HBM3 +GPU-00000000-0000-4000-8000-000000000007, NVIDIA H100 80GB HBM3 +GPU-00000000-0000-4000-8000-000000000008, NVIDIA H100 80GB HBM3 diff --git a/tests/fixtures/nvidia-smi/r595-1gpu.metrics b/tests/fixtures/nvidia-smi/r595-1gpu.metrics new file mode 100644 index 0000000..9e6786b --- /dev/null +++ b/tests/fixtures/nvidia-smi/r595-1gpu.metrics @@ -0,0 +1 @@ +@NOW@, GPU-00000000-0000-4000-8000-000000000001, 0, 00000000:18:00.0, 595.45.04, 30, 10, 2048, 81559, 40, [N/A], [N/A], 1410, 1593, [N/A], [N/A], [N/A], 0 diff --git a/tests/fixtures/nvidia-smi/r595-1gpu.names b/tests/fixtures/nvidia-smi/r595-1gpu.names new file mode 100644 index 0000000..a12c819 --- /dev/null +++ b/tests/fixtures/nvidia-smi/r595-1gpu.names @@ -0,0 +1 @@ +GPU-00000000-0000-4000-8000-000000000001, NVIDIA H100 80GB HBM3 diff --git a/tests/fixtures/nvidia-smi/r620-16gpu.metrics b/tests/fixtures/nvidia-smi/r620-16gpu.metrics new file mode 100644 index 0000000..79bd71e --- /dev/null +++ b/tests/fixtures/nvidia-smi/r620-16gpu.metrics @@ -0,0 +1,16 @@ +@NOW@, GPU-00000000-0000-4000-8000-000000000001, 0, 00000000:18:00.0, 620.70.06, 30, 10, 2048, 81559, 40, 100.50, 700.00, 1410, 1593, 0, 0, No, 0x0000000000000000 +@NOW@, GPU-00000000-0000-4000-8000-000000000002, 1, 00000000:28:00.0, 620.70.06, 31, 11, 2049, 81559, 41, 101.50, 700.00, 1411, 1593, 0, 0, No, 0x0000000000000000 +@NOW@, GPU-00000000-0000-4000-8000-000000000003, 2, 00000000:38:00.0, 620.70.06, 32, 12, 2050, 81559, 42, 102.50, 700.00, 1412, 1593, 0, 0, No, 0x0000000000000000 +@NOW@, GPU-00000000-0000-4000-8000-000000000004, 3, 00000000:48:00.0, 620.70.06, 33, 13, 2051, 81559, 43, 103.50, 700.00, 1413, 1593, 0, 0, No, 0x0000000000000048 +@NOW@, GPU-00000000-0000-4000-8000-000000000005, 4, 00000000:58:00.0, 620.70.06, 34, 14, 2052, 81559, 44, 104.50, 700.00, 1414, 1593, 0, 0, No, 0x0000000000000000 +@NOW@, GPU-00000000-0000-4000-8000-000000000006, 5, 00000000:68:00.0, 620.70.06, 35, 15, 2053, 81559, 45, 105.50, 700.00, 1415, 1593, 0, 0, No, 0x0000000000000000 +@NOW@, GPU-00000000-0000-4000-8000-000000000007, 6, 00000000:78:00.0, 620.70.06, 36, 16, 2054, 81559, 46, 106.50, 700.00, 1416, 1593, 0, 0, No, 0x0000000000000000 +@NOW@, GPU-00000000-0000-4000-8000-000000000008, 7, 00000000:88:00.0, 620.70.06, 37, 17, 2055, 81559, 47, 107.50, 700.00, 1417, 1593, 0, 0, No, 0x0000000000000000 +@NOW@, GPU-00000000-0000-4000-8000-000000000009, 8, 00000000:98:00.0, 620.70.06, 38, 18, 2056, 81559, 48, 108.50, 700.00, 1418, 1593, 0, 0, No, 0x0000000000000000 +@NOW@, GPU-00000000-0000-4000-8000-00000000000a, 9, 00000000:A8:00.0, 620.70.06, 39, 19, 2057, 81559, 49, 109.50, 700.00, 1419, 1593, 0, 0, No, 0x0000000000000000 +@NOW@, GPU-00000000-0000-4000-8000-00000000000b, 10, 00000000:B8:00.0, 620.70.06, 40, 20, 2058, 81559, 50, 110.50, 700.00, 1420, 1593, 0, 0, No, 0x0000000000000000 +@NOW@, GPU-00000000-0000-4000-8000-00000000000c, 11, 00000000:C8:00.0, 620.70.06, 41, 21, 2059, 81559, 51, 111.50, 700.00, 1421, 1593, 0, 0, No, 0x0000000000000000 +@NOW@, GPU-00000000-0000-4000-8000-00000000000d, 12, 00000000:D8:00.0, 620.70.06, 42, 22, 2060, 81559, 52, 112.50, 700.00, 1422, 1593, 0, 0, No, 0x0000000000000000 +@NOW@, GPU-00000000-0000-4000-8000-00000000000e, 13, 00000000:E8:00.0, 620.70.06, 43, 23, 2061, 81559, 53, 113.50, 700.00, 1423, 1593, 0, 0, No, 0x0000000000000000 +@NOW@, GPU-00000000-0000-4000-8000-00000000000f, 14, 00000000:FE:00.0, 620.70.06, 44, 24, 2062, 81559, 54, 114.50, 700.00, 1424, 1593, 0, 0, No, 0x0000000000000000 +@NOW@, GPU-00000000-0000-4000-8000-000000000010, 15, 00000000:FF:00.0, 620.70.06, 45, 25, 2063, 81559, 55, 115.50, 700.00, 1425, 1593, 0, 0, No, 0x0000000000000000 diff --git a/tests/fixtures/nvidia-smi/r620-16gpu.names b/tests/fixtures/nvidia-smi/r620-16gpu.names new file mode 100644 index 0000000..9c51f7e --- /dev/null +++ b/tests/fixtures/nvidia-smi/r620-16gpu.names @@ -0,0 +1,16 @@ +GPU-00000000-0000-4000-8000-000000000001, NVIDIA H100 80GB HBM3 +GPU-00000000-0000-4000-8000-000000000002, NVIDIA H100 80GB HBM3 +GPU-00000000-0000-4000-8000-000000000003, NVIDIA H100 80GB HBM3 +GPU-00000000-0000-4000-8000-000000000004, NVIDIA H100 80GB HBM3 +GPU-00000000-0000-4000-8000-000000000005, NVIDIA H100 80GB HBM3 +GPU-00000000-0000-4000-8000-000000000006, NVIDIA H100 80GB HBM3 +GPU-00000000-0000-4000-8000-000000000007, NVIDIA H100 80GB HBM3 +GPU-00000000-0000-4000-8000-000000000008, NVIDIA H100 80GB HBM3 +GPU-00000000-0000-4000-8000-000000000009, NVIDIA H100 80GB HBM3 +GPU-00000000-0000-4000-8000-00000000000a, NVIDIA H100 80GB HBM3 +GPU-00000000-0000-4000-8000-00000000000b, NVIDIA H100 80GB HBM3 +GPU-00000000-0000-4000-8000-00000000000c, NVIDIA H100 80GB HBM3 +GPU-00000000-0000-4000-8000-00000000000d, NVIDIA H100 80GB HBM3 +GPU-00000000-0000-4000-8000-00000000000e, NVIDIA H100 80GB HBM3 +GPU-00000000-0000-4000-8000-00000000000f, NVIDIA H100 80GB HBM3 +GPU-00000000-0000-4000-8000-000000000010, NVIDIA H100 80GB HBM3