From f56b584a29ddcdb778f2b7265fbb03ff10c8f149 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 08:21:17 -0800 Subject: [PATCH 01/18] fix(nodes): settle removal of orphan nodes and invisible created devices A GPU Admin may now disable or delete a node whose device was deleted, since no device permission can apply to it; such nodes stay out of the export. When an account creates a device it then cannot see, the device is removed again through api_device_remove() in the same request and an error is shown. The permission suite covers both, and PLAN records the decisions. Signed-off-by: Thomas Vincent --- docs/PLAN.md | 2 ++ gpu_nodes.php | 19 +++++++++++++++++-- lib/NodeAccess.php | 18 ++++++++++++++---- setup.php | 12 ++++++++++++ tests/Unit/NodeAccessTest.php | 7 +++++++ tests/bin/page-permissions.php | 23 ++++++++++++++++++++++- 6 files changed, 74 insertions(+), 7 deletions(-) diff --git a/docs/PLAN.md b/docs/PLAN.md index 1c117d9..7ffd6a1 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -438,6 +438,8 @@ Milestone size estimates (ranges from measured reference plugins, no durations) | 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 | +| Nodes on deleted devices | Decided for milestone 4: a GPU Admin may disable or delete a node whose device no longer exists, since no device permission can apply to it; such nodes are left out of the export (`NodeAccess`) | Milestone 4 | Owner | +| A created device its creator cannot see | Decided for milestone 4: the device is removed again through `api_device_remove()` in the same request and an error is shown, so no node points at a device its creator cannot manage (`gpu_nodes.php`) | Milestone 4 | Owner | ## Risks diff --git a/gpu_nodes.php b/gpu_nodes.php index 958f835..5e0ea85 100644 --- a/gpu_nodes.php +++ b/gpu_nodes.php @@ -146,7 +146,9 @@ function gpu_nodes_attach(\Somethingwithproof\Gpu\Node $node): void { case 'delete': $gpu_node = $gpu_nodes->find((int) get_filter_request_var('id')); - if (!$gpu_access->canManage($gpu_node)) { + // A node whose device was deleted may be deleted too, by any GPU + // Admin; see NodeAccess. + if (!$gpu_access->canRemove($gpu_node)) { gpu_nodes_refuse(); } @@ -211,9 +213,22 @@ function gpu_nodes_attach(\Somethingwithproof\Gpu\Node $node): void { 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; + // Such a device is removed again through Cacti's API in the same + // request, so the user does not leave behind a device they cannot + // see or manage (owner decision for milestone 4). + if ($gpu_host > 0 && !$gpu_access->deviceAllowed($gpu_host)) { + gpu_remove_device($gpu_host); + + raise_message('gpu_device', __('The device was not kept: your account may not see devices it creates. Ask an administrator to create it.', 'gpu'), MESSAGE_LEVEL_ERROR); + + header('Location: gpu_nodes.php'); + exit; + } + + $gpu_id = $gpu_host > 0 && !$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)) { diff --git a/lib/NodeAccess.php b/lib/NodeAccess.php index 7bd2464..3758d2e 100644 --- a/lib/NodeAccess.php +++ b/lib/NodeAccess.php @@ -23,10 +23,12 @@ * 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. + * One exemption: a node whose device was deleted is visible to every GPU + * Admin, and may only be disabled or deleted, so a stale node can be stopped + * or cleared away (owner decision for milestone 4). No device permission can + * be checked for it, so nothing else is allowed on it, and it and its GPU + * records are left out of the export, which carries only what the user may + * manage. */ final class NodeAccess { /** @@ -47,6 +49,14 @@ public function canSee(?Node $node): bool { return $node !== null && (!$node->deviceExists || $this->canManage($node)); } + /** + * Whether the user may delete the node: a node they may manage, or one + * whose device was deleted. + */ + public function canRemove(?Node $node): bool { + return $node !== null && (!$node->deviceExists || $this->canManage($node)); + } + /** * @param array $nodes by id */ diff --git a/setup.php b/setup.php index 6172f48..e458144 100644 --- a/setup.php +++ b/setup.php @@ -338,6 +338,18 @@ function gpu_create_device(string $description, string $hostname, int $template) return is_numeric($id) ? (int) $id : 0; } +/** + * Remove a device through Cacti's API, which also calls the device_remove + * hooks. + */ +function gpu_remove_device(int $id): void { + global $config; + + include_once($config['library_path'] . '/api_device.php'); + + api_device_remove($id); +} + /** * poller_bottom hook: start the collector in the background once the * poller cycle has finished. The collector reads the GPU nodes; the poller diff --git a/tests/Unit/NodeAccessTest.php b/tests/Unit/NodeAccessTest.php index 8960de0..95acc6a 100644 --- a/tests/Unit/NodeAccessTest.php +++ b/tests/Unit/NodeAccessTest.php @@ -50,6 +50,13 @@ function access(): NodeAccess { ->and(access()->canSee(access_node(2, 20)))->toBeFalse(); }); +it('lets a node be deleted on a device the user may see, or whose device was deleted', function () { + expect(access()->canRemove(access_node(1, 10)))->toBeTrue() + ->and(access()->canRemove(access_node(3, 20, false)))->toBeTrue() + ->and(access()->canRemove(access_node(2, 20)))->toBeFalse() + ->and(access()->canRemove(null))->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)]; diff --git a/tests/bin/page-permissions.php b/tests/bin/page-permissions.php index cf457a4..1bcabe4 100644 --- a/tests/bin/page-permissions.php +++ b/tests/bin/page-permissions.php @@ -318,8 +318,29 @@ function perm_login($user) { 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'); +list(, $export) = perm_http($base . 'gpu_nodes.php?action=export', $jar); +$document = json_decode($export, true); +perm_expect(is_array($document) && !in_array($orphan, array_column($document['nodes'], 'id'), true), 'a node whose device was deleted is left out of the export'); + +// One with GPU records stays, as any node with records does; an empty one +// may be deleted by any GPU Admin, since no device permission applies. +db_execute_prepared("INSERT INTO plugin_gpu_node (host_id, admin_state) VALUES (999998, 'disabled')"); +$orphanWithGpu = (int) db_fetch_insert_id(); +db_execute_prepared("INSERT INTO plugin_gpu_gpu (vendor, uuid, node_id, pci_bus_id, name, presence) VALUES ('nvidia', 'GPU-00000000-0000-4000-8000-0000000000f6', ?, '00000000:40:00.0', 'Orphaned GPU', 'absent')", array($orphanWithGpu)); + +perm_http($base . 'gpu_nodes.php', $jar, array('__csrf_magic' => $token, 'action' => 'delete', 'id' => $orphanWithGpu)); +perm_expect((int) db_fetch_cell_prepared('SELECT COUNT(*) FROM plugin_gpu_node WHERE id = ?', array($orphanWithGpu)) === 1, 'a node whose device was deleted is kept while GPU records belong to it'); + 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'); +perm_expect((int) db_fetch_cell_prepared('SELECT COUNT(*) FROM plugin_gpu_node WHERE id = ?', array($orphan)) === 0, 'an empty node whose device was deleted is deleted by a scoped GPU Admin'); + +// With Cacti's device management, a device this user would not be allowed +// to see is removed again in the same request, and no node is made for it. +db_execute_prepared('INSERT INTO user_auth_realm (realm_id, user_id) VALUES (3, ?)', array($users['scoped'])); +list(, $form) = perm_http($base . 'gpu_nodes.php?action=edit', $jar); +list(, $result) = perm_http($base . 'gpu_nodes.php', $jar, array('__csrf_magic' => perm_token($form), 'action' => 'create_device', 'description' => 'Invisible created', 'hostname' => 'invisible.invalid')); +perm_expect((int) db_fetch_cell("SELECT COUNT(*) FROM host WHERE hostname = 'invisible.invalid'") === 0 && (int) db_fetch_cell('SELECT COUNT(*) FROM plugin_gpu_node WHERE host_id NOT IN (SELECT id FROM host) AND host_id NOT IN (999998)') === 0 && strpos($result, 'was not kept') !== false, 'a created device the creator may not see is removed again, with an error'); +db_execute_prepared('DELETE FROM user_auth_realm WHERE realm_id = 3 AND user_id = ?', array($users['scoped'])); unlink($jar); From ecef1c72f84aa1a70e362037390dce524c87ddaa Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 08:22:53 -0800 Subject: [PATCH 02/18] feat(metrics): add ECC deltas, retired pages, and ECC mode (#45) The collector now computes new corrected and uncorrected ECC errors since the previous sample from consecutive volatile totals. A first sample, a missed read, or a total that went down stores unknown, never a negative or zero. Both deltas are gauges, so Thold never computes a rate from an unknown value. The model also reads retired single-bit and double-bit page counts and the current ECC mode, which explains why ECC values are unknown. A new graph draws the deltas and another the retired pages, so Cacti stores them. Schema version 3 adds the columns. The vendor command rule now also refuses ECC counter clears and drains. XID stays out: no source fits the fixed nvidia-smi commands, so it is blocked on #8. Signed-off-by: Thomas Vincent --- docs/metrics.md | 11 +- docs/node-setup.md | 2 +- lib/CacheRepository.php | 2 +- lib/EccMode.php | 56 + lib/Freshness.php | 2 +- lib/MetricModel.php | 21 +- lib/NvidiaSmiParser.php | 2 +- lib/ObservationRepository.php | 24 +- lib/Reading.php | 2 + lib/Schema.php | 47 +- lib/TemplateXml.php | 8 + resource/script_server/plugin_gpu.xml | 20 + templates/gpu_templates.xml | 1272 +++++++++++++++--- tests/Integration/LifecycleTest.php | 2 +- tests/Security/SourceRulesTest.php | 8 +- tests/Unit/CollectorTest.php | 19 +- tests/Unit/NvidiaSmiParserTest.php | 34 +- tests/fixtures/nvidia-smi/r580-8gpu.metrics | 16 +- tests/fixtures/nvidia-smi/r595-1gpu.metrics | 2 +- tests/fixtures/nvidia-smi/r620-16gpu.metrics | 32 +- 20 files changed, 1373 insertions(+), 209 deletions(-) create mode 100644 lib/EccMode.php diff --git a/docs/metrics.md b/docs/metrics.md index 7fbbcf9..a249b71 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -18,7 +18,11 @@ Milestone 3 implements the nvidia-smi column. The DCGM and AMD columns record th | `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` | +| `ecc_corr_new` | Corrected ECC errors since the previous sample | count | gauge | 0 to U | computed from consecutive `ecc_corr` samples | computed from consecutive `ecc_corr` samples | computed from consecutive `ecc_corr` samples | +| `ecc_uncorr_new` | Uncorrected ECC errors since the previous sample | count | gauge | 0 to U | computed from consecutive `ecc_uncorr` samples | computed from consecutive `ecc_uncorr` samples | computed from consecutive `ecc_uncorr` samples | | `retired_pending` | Page retirement pending | 0 or 1 | indicator | 0 to 1 | `retired_pages.pending` | 392 | #18 | +| `retired_sbe` | Pages retired after single-bit ECC errors | pages | gauge | 0 to U | `retired_pages.sbe` | 390 (`DCGM_FI_DEV_RETIRED_SBE`, unconfirmed, #15) | #18 | +| `retired_dbe` | Pages retired after a double-bit ECC error | pages | gauge | 0 to U | `retired_pages.dbe` | 391 (`DCGM_FI_DEV_RETIRED_DBE`, unconfirmed, #15) | #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) | @@ -32,7 +36,12 @@ Milestone 3 implements the nvidia-smi column. The DCGM and AMD columns record th - 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. +- ECC values are gauges of the reported total since the driver was loaded (REQ-METRIC-005). They are volatile counts, not lifetime totals (REQ-ERR-003): A driver reload resets them to 0, so a threshold on the total can clear after a reboot without the cause being fixed. +- `ecc_corr_new` and `ecc_uncorr_new` are the errors counted since the previous sample, which the plugin computes from two consecutive totals of the same GPU. They are unknown for a GPU's first sample, after a missed or unknown read, and when the total went down (a driver reload). They are gauges, never Cacti or RRD counters: Thold 1.8.2 throws a PHP `TypeError` when a thresholded DERIVE or COUNTER data source reads `U`, and Cacti then disables Thold. Alert on these, not on the totals. +- `retired_sbe`, `retired_dbe`, and `retired_pending` are the GPU's retired page counts and pending flag. They persist across driver loads. +- A GPU without ECC, or with ECC turned off, reports `U` for every ECC value, never 0 (REQ-ERR-002). The plugin also stores `ecc.mode.current`, and the health page shows the reason: ECC disabled, or not supported. +- There is no XID field. No XID source fits the fixed `nvidia-smi` commands ADR 0008 allows: `--query-gpu` has no XID field (checked against a published `--help-query-gpu` list; confirming it on current drivers is part of #14), `nvidia-smi event-log` is not documented to report XIDs, and the kernel log is outside those commands. Decision #8 picks the source ([research/xid.md](research/xid.md)). +- No error value causes a reset, drain, ECC counter clear, or page retirement (REQ-ERR-006). The plugin only reads. - 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. diff --git a/docs/node-setup.md b/docs/node-setup.md index 060e96c..dfa8241 100644 --- a/docs/node-setup.md +++ b/docs/node-setup.md @@ -8,7 +8,7 @@ Add these lines exactly as shown. The entry names, the field list, and its order ``` -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 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,ecc.mode.current,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,retired_pages.sbe,retired_pages.dbe,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 ``` diff --git a/lib/CacheRepository.php b/lib/CacheRepository.php index 030df80..a5068cd 100644 --- a/lib/CacheRepository.php +++ b/lib/CacheRepository.php @@ -77,7 +77,7 @@ public function sample(int $hostId, Vendor $vendor, string $uuid): ?array { } private static function sampleSelect(): string { - return 'SELECT ' . self::COLUMNS . ', o.observed_at, o.reported_at, o.' . implode(', o.', Schema::OBSERVATION_METRICS) . ', + return 'SELECT ' . self::COLUMNS . ', o.observed_at, o.reported_at, o.' . implode(', o.', Schema::observationMetrics()) . ', 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 diff --git a/lib/EccMode.php b/lib/EccMode.php new file mode 100644 index 0000000..d42a9d5 --- /dev/null +++ b/lib/EccMode.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. + */ + +namespace Somethingwithproof\Gpu; + +/** + * Whether a GPU's ECC is on, so the health page can say why its ECC values + * are unknown (REQ-ERR-002). Stored as the value; '' is not reported. + */ +enum EccMode: string { + case Enabled = 'enabled'; + case Disabled = 'disabled'; + case Unavailable = 'unavailable'; + case Unknown = ''; + + /** + * nvidia-smi's ecc.mode.current: "Enabled", "Disabled", or a bracketed + * placeholder such as "[N/A]" on a GPU without ECC. + */ + public static function fromNvidia(string $raw): self { + return match (strtolower(trim($raw))) { + 'enabled' => self::Enabled, + 'disabled' => self::Disabled, + '[n/a]', 'n/a', '[not supported]' => self::Unavailable, + default => self::Unknown, + }; + } + + /** + * Why the GPU's ECC values are unknown, or '' when ECC is on. + */ + public function reason(): string { + return match ($this) { + self::Enabled => '', + self::Disabled => __('ECC is disabled on this GPU', 'gpu'), + self::Unavailable => __('This GPU does not report ECC', 'gpu'), + self::Unknown => __('ECC mode not reported', 'gpu'), + }; + } +} diff --git a/lib/Freshness.php b/lib/Freshness.php index 87e00be..347bf23 100644 --- a/lib/Freshness.php +++ b/lib/Freshness.php @@ -77,7 +77,7 @@ public static function value(string $field, array $row, int $now, int $staleAfte return null; } - return in_array($field, Schema::OBSERVATION_METRICS, true) ? Row::float($row, $field) : null; + return in_array($field, Schema::observationMetrics(), true) ? Row::float($row, $field) : null; } /** diff --git a/lib/MetricModel.php b/lib/MetricModel.php index ae59f70..7c45e2d 100644 --- a/lib/MetricModel.php +++ b/lib/MetricModel.php @@ -40,6 +40,16 @@ final class MetricModel { // bitmask in the same position, so the parser accepts either. public const MASK_FIELD = 'clocks_throttle_reasons.active'; + // Whether ECC is on, so the health page can say why an ECC value is + // unknown (REQ-ERR-002). Not a model field: it is stored as text. + public const ECC_MODE_FIELD = 'ecc.mode.current'; + + /** + * Fields the plugin computes from two consecutive samples of a total: + * delta => total. They are stored as gauges (see all()). + */ + public const DELTAS = ['ecc_corr_new' => 'ecc_corr', 'ecc_uncorr_new' => 'ecc_uncorr']; + // 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. @@ -70,7 +80,15 @@ public static function all(): array { 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`'), + // Each alertable value is a gauge (ADR 0002): Thold 1.8.2 fails on + // a DERIVE or COUNTER data source that reads U, so the plugin + // computes the new errors itself from consecutive samples, and a + // reset at driver load, or a missing value, is unknown. + new Metric('ecc_corr_new', 'Corrected ECC errors since the previous sample', 'count', $gauge, 0.0, null, null, 1.0, null, 'computed from consecutive `ecc_corr` samples', 1.0, 'computed from consecutive `ecc_corr` samples'), + new Metric('ecc_uncorr_new', 'Uncorrected ECC errors since the previous sample', 'count', $gauge, 0.0, null, null, 1.0, null, 'computed from consecutive `ecc_uncorr` samples', 1.0, 'computed from consecutive `ecc_uncorr` samples'), 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('retired_sbe', 'Pages retired after single-bit ECC errors', 'pages', $gauge, 0.0, null, 'retired_pages.sbe', 1.0, null, '390 (`DCGM_FI_DEV_RETIRED_SBE`, unconfirmed, #15)', 1.0, '#18'), + new Metric('retired_dbe', 'Pages retired after a double-bit ECC error', 'pages', $gauge, 0.0, null, 'retired_pages.dbe', 1.0, null, '391 (`DCGM_FI_DEV_RETIRED_DBE`, unconfirmed, #15)', 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)'), @@ -107,7 +125,7 @@ public static function names(): array { * @return list */ public static function nvidiaFields(): array { - $fields = ['timestamp', 'uuid', 'index', 'pci.bus_id', 'driver_version']; + $fields = ['timestamp', 'uuid', 'index', 'pci.bus_id', 'driver_version', self::ECC_MODE_FIELD]; foreach (self::all() as $metric) { if ($metric->nvidiaField !== null) { @@ -138,6 +156,7 @@ public static function table(): string { $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), + isset(self::DELTAS[$metric->name]) => sprintf('computed from consecutive `%s` samples', self::DELTAS[$metric->name]), default => 'computed from `timestamp`', }; diff --git a/lib/NvidiaSmiParser.php b/lib/NvidiaSmiParser.php index 0de658d..cee1e93 100644 --- a/lib/NvidiaSmiParser.php +++ b/lib/NvidiaSmiParser.php @@ -102,7 +102,7 @@ public function parse(ExtendOutput $metrics, ExtendOutput $names): Collection { $version = $version === '' ? $report->driverVersion : $version; $reports[] = $report; - $readings[] = new Reading($report, $observed, $read, $mask); + $readings[] = new Reading($report, $observed, $read, $mask, EccMode::fromNvidia($values[$position[MetricModel::ECC_MODE_FIELD]])->value); } try { diff --git a/lib/ObservationRepository.php b/lib/ObservationRepository.php index f9db9ca..9ee9319 100644 --- a/lib/ObservationRepository.php +++ b/lib/ObservationRepository.php @@ -32,22 +32,34 @@ public function __construct(private readonly \PDO|false $connection) { * 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. + * + * The new ECC errors are computed here, against the stored sample, in + * the same statement: the new total minus the stored one. The result is + * unknown when either total is unknown, and when the new total is lower, + * which is a reset at driver load (REQ-ERR-003), so a reset is never + * read as a negative count or as zero. */ public function store(int $gpuId, int $nodeId, Reading $reading, string $backend, string $toolVersion, int $now): bool { - $columns = Schema::OBSERVATION_METRICS; + $columns = array_values(array_diff(Schema::observationMetrics(), array_keys(MetricModel::DELTAS))); $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']); + $all = array_merge(['gpu_id', 'node_id', 'observed_at', 'ingested_at', 'reported_at', 'backend', 'tool_version'], $columns, ['thr_mask', 'ecc_mode']); $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) { + // MySQL applies the assignments in order, and a later one sees the + // columns earlier ones set. The deltas are assigned before the totals + // change, and observed_at last, so every other column still compares + // against the stored sample. + foreach (MetricModel::DELTAS as $delta => $total) { + $update[] = "$delta = IF($newer, IF(VALUES($total) >= $total, VALUES($total) - $total, NULL), $delta)"; + } + + foreach (array_merge(['ingested_at', 'backend', 'tool_version'], $columns, ['thr_mask', 'ecc_mode']) as $column) { $update[] = "$column = IF($newer, VALUES($column), $column)"; } @@ -56,6 +68,6 @@ public function store(int $gpuId, int $nodeId, Reading $reading, string $backend $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); + return (bool) db_execute_prepared($sql, array_merge([$gpuId, $nodeId, $reading->observedAt, $now, $now, $backend, $toolVersion], $values, [$reading->mask, $reading->eccMode]), true, $this->connection); } } diff --git a/lib/Reading.php b/lib/Reading.php index 390719f..1af6609 100644 --- a/lib/Reading.php +++ b/lib/Reading.php @@ -33,6 +33,8 @@ public function __construct( public int $observedAt, public array $values, public ?int $mask, + // EccMode value, or '' when the backend does not report it. + public string $eccMode = '', ) { } } diff --git a/lib/Schema.php b/lib/Schema.php index 3cd3ea3..8917c83 100644 --- a/lib/Schema.php +++ b/lib/Schema.php @@ -35,7 +35,7 @@ * RRD file, or contacts a GPU node (REQ-LIFE-003, REQ-LIFE-005). */ final class Schema { - public const VERSION = 2; + public const VERSION = 3; public const HOOKS = [ 'config_arrays' => 'gpu_config_arrays', @@ -55,6 +55,11 @@ final class Schema { 'thr_sw_power_cap', 'thr_hw_slowdown', 'thr_sw_thermal', 'thr_hw_thermal', 'thr_hw_power_brake', ]; + // The metric columns migration 3 added. The two _new columns are + // computed by ObservationRepository from consecutive samples + // (MetricModel::DELTAS). + public const OBSERVATION_METRICS_3 = ['ecc_corr_new', 'ecc_uncorr_new', 'retired_sbe', 'retired_dbe']; + private const PLUGIN = 'gpu'; private const SETTING = 'gpu_schema_version'; @@ -151,9 +156,48 @@ private function migrations(): array { return [ 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']))), + // ECC delta, retired-page, and ECC mode columns (#45). A fresh + // install created them in migration 2, from the current table. + 3 => fn (): bool => $this->addColumns('plugin_gpu_observation', self::observationColumns3()), ]; } + /** + * Every metric column of plugin_gpu_observation. + * + * @return list + */ + public static function observationMetrics(): array { + return array_merge(self::OBSERVATION_METRICS, self::OBSERVATION_METRICS_3); + } + + /** + * @return list> + */ + private static function observationColumns3(): array { + return array_merge( + array_map(static fn (string $name): array => ['name' => $name, 'type' => 'double', 'NULL' => true], self::OBSERVATION_METRICS_3), + [['name' => 'ecc_mode', 'type' => 'varchar(16)', 'NULL' => false, 'default' => '']], + ); + } + + /** + * @param list> $columns + */ + private function addColumns(string $table, array $columns): bool { + foreach ($columns as $column) { + db_add_column($table, $column, true, $this->connection); + + if (db_fetch_cell_prepared('SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?', [$table, $column['name']], '', true, $this->connection) < 1) { + Log::error(sprintf('Unable to add column %s to %s', Row::string($column, 'name'), $table)); + + return false; + } + } + + return true; + } + /** * Track every existing plugin table for uninstall again. * @@ -281,6 +325,7 @@ public static function tables(): array { // 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]], + self::observationColumns3(), ), 'primary' => 'gpu_id', 'keys' => [['name' => 'node_id', 'columns' => ['node_id']]], diff --git a/lib/TemplateXml.php b/lib/TemplateXml.php index 38797af..103223d 100644 --- a/lib/TemplateXml.php +++ b/lib/TemplateXml.php @@ -122,6 +122,14 @@ public static function graphs(): array { ['ecc_corr', self::LINE1, '0072C6', 'Corrected'], ['ecc_uncorr', self::LINE2, 'B00020', 'Uncorrected'], ]], + 'GPU - New ECC Errors' => ['label' => 'errors since the previous sample', 'base' => 1000, 'upper' => '0', 'items' => [ + ['ecc_corr_new', self::LINE1, '0072C6', 'Corrected'], + ['ecc_uncorr_new', self::LINE2, 'B00020', 'Uncorrected'], + ]], + 'GPU - Retired Pages' => ['label' => 'pages', 'base' => 1000, 'upper' => '0', 'items' => [ + ['retired_sbe', self::LINE1, '0072C6', 'Single-bit errors'], + ['retired_dbe', self::LINE2, 'B00020', 'Double-bit error'], + ]], 'GPU - Sample Age' => ['label' => 'seconds', 'base' => 1000, 'upper' => '0', 'items' => [ ['age', self::LINE1, '555555', 'Age of the latest sample'], ]], diff --git a/resource/script_server/plugin_gpu.xml b/resource/script_server/plugin_gpu.xml index 4bdee05..0c9dd62 100644 --- a/resource/script_server/plugin_gpu.xml +++ b/resource/script_server/plugin_gpu.xml @@ -89,11 +89,31 @@ output ecc_uncorr + + Corrected ECC errors since the previous sample + output + ecc_corr_new + + + Uncorrected ECC errors since the previous sample + output + ecc_uncorr_new + Page retirement pending output retired_pending + + Pages retired after single-bit ECC errors + output + retired_sbe + + + Pages retired after a double-bit ECC error + output + retired_dbe + Clocks held by the software power cap output diff --git a/templates/gpu_templates.xml b/templates/gpu_templates.xml index 83d663c..6696741 100644 --- a/templates/gpu_templates.xml +++ b/templates/gpu_templates.xml @@ -1896,6 +1896,476 @@ + + GPU - New ECC Errors + + + + on + |host_description| - GPU |query_gpuIndex| |query_gpuName| - New ECC Errors + + errors since the previous sample + + 3 + + 200 + + 700 + + 1000 + + on + + on + + 2 + + + + + + + + 0 + + 0 + + + + + + + + + + + + + + + + 0 + + 0 + + 0 + + on + + + + + + + + 0 + + 0 + + + + 4 + hash_0801031ba5b836a0ff7ecfa9feba3d334fbc0a + 0072C6 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Corrected + + 1.00 + + 0 + 1 + + + 9 + hash_0801031ba5b836a0ff7ecfa9feba3d334fbc0a + 0 + FF + 4 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Current: + + 1.00 + + 0 + 2 + + + 9 + hash_0801031ba5b836a0ff7ecfa9feba3d334fbc0a + 0 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Average: + + 1.00 + + 0 + 3 + + + 9 + hash_0801031ba5b836a0ff7ecfa9feba3d334fbc0a + 0 + FF + 3 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Maximum: + on + 1.00 + + 0 + 4 + + + 5 + hash_080103c46dce5c285e4686088f1b510da6e966 + B00020 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Uncorrected + + 2.00 + + 0 + 5 + + + 9 + hash_080103c46dce5c285e4686088f1b510da6e966 + 0 + FF + 4 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Current: + + 1.00 + + 0 + 6 + + + 9 + hash_080103c46dce5c285e4686088f1b510da6e966 + 0 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Average: + + 1.00 + + 0 + 7 + + + 9 + hash_080103c46dce5c285e4686088f1b510da6e966 + 0 + FF + 3 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Maximum: + on + 1.00 + + 0 + 8 + + + + + Data Source [ecc_corr_new] + + task_item_id + hash_000103f1cf7206265c8b838bbb7e571dcde2c0|hash_00010354ea49d2dd05855236b68e11694ea7cd|hash_000103e5b6d1c9b42f3cd8a3021d4cd3a119fe|hash_000103e33a216be96c01c918d48717604f347e + + + Data Source [ecc_uncorr_new] + + task_item_id + hash_00010375835668cb37781c565a2bccf6737183|hash_000103c28ee6c6feea444b9be37f3d4deadb16|hash_00010370b991cf83afc4fe1cd0d7cf61085b88|hash_000103a35b2ec748bce481ff6887343bb0ba6a + + + + + GPU - Retired Pages + + + + on + |host_description| - GPU |query_gpuIndex| |query_gpuName| - Retired Pages + + pages + + 3 + + 200 + + 700 + + 1000 + + on + + on + + 2 + + + + + + + + 0 + + 0 + + + + + + + + + + + + + + + + 0 + + 0 + + 0 + + on + + + + + + + + 0 + + 0 + + + + 4 + hash_080103c2afb6ee87f53f498a736738e5bd0113 + 0072C6 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Single-bit errors + + 1.00 + + 0 + 1 + + + 9 + hash_080103c2afb6ee87f53f498a736738e5bd0113 + 0 + FF + 4 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Current: + + 1.00 + + 0 + 2 + + + 9 + hash_080103c2afb6ee87f53f498a736738e5bd0113 + 0 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Average: + + 1.00 + + 0 + 3 + + + 9 + hash_080103c2afb6ee87f53f498a736738e5bd0113 + 0 + FF + 3 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Maximum: + on + 1.00 + + 0 + 4 + + + 5 + hash_08010378bed9f1d5da131bc2e3939e967fb9df + B00020 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Double-bit error + + 2.00 + + 0 + 5 + + + 9 + hash_08010378bed9f1d5da131bc2e3939e967fb9df + 0 + FF + 4 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Current: + + 1.00 + + 0 + 6 + + + 9 + hash_08010378bed9f1d5da131bc2e3939e967fb9df + 0 + FF + 1 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Average: + + 1.00 + + 0 + 7 + + + 9 + hash_08010378bed9f1d5da131bc2e3939e967fb9df + 0 + FF + 3 + 0 + 0 + + + hash_060103e9c43831e54eca8069317a2ce8c6f751 + + Maximum: + on + 1.00 + + 0 + 8 + + + + + Data Source [retired_sbe] + + task_item_id + hash_0001034dbf96ada28133710d9ce1078a19090c|hash_000103d49d2a851f27c33178f55c68f49c5f62|hash_000103c36c45df896aa444a2d19d61479104c6|hash_0001030eb80680e82d0f04c6b416819aaec19e + + + Data Source [retired_dbe] + + task_item_id + hash_000103047232c42e699e73e9bc6b8ee5c148f8|hash_000103cefd141dddd304d40376cc512bb5f53e|hash_0001037b12d3ce249a2df6b77964181b42ccd7|hash_00010351eb073acb90a08214ed3083a7211d13 + + + GPU - Sample Age @@ -2218,6 +2688,34 @@ 0 + + + ecc_corr_new + + 0 + + U + + 1 + + 600 + + 0 + + + + ecc_uncorr_new + + 0 + + U + + 1 + + 600 + + 0 + retired_pending @@ -2232,6 +2730,34 @@ 0 + + + retired_sbe + + 0 + + U + + 1 + + 600 + + 0 + + + + retired_dbe + + 0 + + U + + 1 + + 600 + + 0 + thr_sw_power_cap @@ -2401,60 +2927,211 @@ hash_0801031ad88ffa3dd274846760a8d68f2a0a60 - retired_pending + ecc_corr_new + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801031ba5b836a0ff7ecfa9feba3d334fbc0a + + + ecc_uncorr_new + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103c46dce5c285e4686088f1b510da6e966 + + + retired_pending + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103db6f1d51fd093d2d28b0cab3c1bd19a0 + + + retired_sbe + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103c2afb6ee87f53f498a736738e5bd0113 + + + retired_dbe + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010378bed9f1d5da131bc2e3939e967fb9df + + + 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 + + + ecc_corr_new hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_080103db6f1d51fd093d2d28b0cab3c1bd19a0 + hash_0801031ba5b836a0ff7ecfa9feba3d334fbc0a - thr_sw_power_cap + ecc_uncorr_new hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_080103e2d56f87cdaca55a819207fe6a19cd9d + hash_080103c46dce5c285e4686088f1b510da6e966 - thr_hw_slowdown + retired_pending hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_08010315564beb5b304bad49dbca0cb469bb2f + hash_080103db6f1d51fd093d2d28b0cab3c1bd19a0 - thr_sw_thermal + retired_sbe hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_080103684afab926b998321a7a6fac6f5a393b + hash_080103c2afb6ee87f53f498a736738e5bd0113 - thr_hw_thermal + retired_dbe hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_0801035f35b5a45efe842fa4a8dec1cdac348e + hash_08010378bed9f1d5da131bc2e3939e967fb9df - thr_hw_power_brake + thr_sw_power_cap hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_08010340894c404284f5ad11902bd285da8568 + 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 - + |host_description| - GPU |query_gpuIndex| |query_gpuName| - Memory + - + name hash_0101037f7ae72a8e79a16815acaea47b35ab66 1 |host_description| - GPU |query_gpuIndex| |query_gpuName| - + - - - hash_0001031f7fc035100b6ccfacb4cada93f8267a - GPU - Memory + + + hash_000103a5a788934a0519975f187c376bce7d4e + GPU - Temperature util_gpu @@ -2512,60 +3189,211 @@ hash_0801031ad88ffa3dd274846760a8d68f2a0a60 - retired_pending + ecc_corr_new hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_080103db6f1d51fd093d2d28b0cab3c1bd19a0 + hash_0801031ba5b836a0ff7ecfa9feba3d334fbc0a - thr_sw_power_cap + ecc_uncorr_new hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_080103e2d56f87cdaca55a819207fe6a19cd9d + hash_080103c46dce5c285e4686088f1b510da6e966 - thr_hw_slowdown + retired_pending hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_08010315564beb5b304bad49dbca0cb469bb2f + hash_080103db6f1d51fd093d2d28b0cab3c1bd19a0 - thr_sw_thermal + retired_sbe hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_080103684afab926b998321a7a6fac6f5a393b + hash_080103c2afb6ee87f53f498a736738e5bd0113 - thr_hw_thermal + retired_dbe hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_0801035f35b5a45efe842fa4a8dec1cdac348e + hash_08010378bed9f1d5da131bc2e3939e967fb9df + 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 + + + ecc_corr_new + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_0801031ba5b836a0ff7ecfa9feba3d334fbc0a + + + ecc_uncorr_new + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103c46dce5c285e4686088f1b510da6e966 + + + retired_pending + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103db6f1d51fd093d2d28b0cab3c1bd19a0 + + + retired_sbe + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_080103c2afb6ee87f53f498a736738e5bd0113 + + + retired_dbe + hash_0101037f7ae72a8e79a16815acaea47b35ab66 + hash_08010378bed9f1d5da131bc2e3939e967fb9df + + + 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 - + |host_description| - GPU |query_gpuIndex| |query_gpuName| - Power + - + name hash_0101037f7ae72a8e79a16815acaea47b35ab66 1 |host_description| - GPU |query_gpuIndex| |query_gpuName| - + - - - hash_000103a5a788934a0519975f187c376bce7d4e - GPU - Temperature + + + hash_0001039731ead9f1bdb18ff2a968a804253ba0 + GPU - Clocks util_gpu @@ -2623,60 +3451,80 @@ hash_0801031ad88ffa3dd274846760a8d68f2a0a60 - retired_pending + ecc_corr_new hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_080103db6f1d51fd093d2d28b0cab3c1bd19a0 + hash_0801031ba5b836a0ff7ecfa9feba3d334fbc0a - thr_sw_power_cap + ecc_uncorr_new hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_080103e2d56f87cdaca55a819207fe6a19cd9d + hash_080103c46dce5c285e4686088f1b510da6e966 - thr_hw_slowdown + retired_pending hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_08010315564beb5b304bad49dbca0cb469bb2f + hash_080103db6f1d51fd093d2d28b0cab3c1bd19a0 - thr_sw_thermal + retired_sbe hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_080103684afab926b998321a7a6fac6f5a393b + hash_080103c2afb6ee87f53f498a736738e5bd0113 - thr_hw_thermal + retired_dbe hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_0801035f35b5a45efe842fa4a8dec1cdac348e + hash_08010378bed9f1d5da131bc2e3939e967fb9df - thr_hw_power_brake + thr_sw_power_cap hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_08010340894c404284f5ad11902bd285da8568 + 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 - + |host_description| - GPU |query_gpuIndex| |query_gpuName| - Clocks + - + name hash_0101037f7ae72a8e79a16815acaea47b35ab66 1 |host_description| - GPU |query_gpuIndex| |query_gpuName| - + - - - hash_000103457ae08592c3f41860e35b5f466a1274 - GPU - Power + + + hash_000103a3b2a1e103b387430075b176c004c97d + GPU - Throttle util_gpu @@ -2734,60 +3582,80 @@ hash_0801031ad88ffa3dd274846760a8d68f2a0a60 - retired_pending + ecc_corr_new hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_080103db6f1d51fd093d2d28b0cab3c1bd19a0 + hash_0801031ba5b836a0ff7ecfa9feba3d334fbc0a - thr_sw_power_cap + ecc_uncorr_new hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_080103e2d56f87cdaca55a819207fe6a19cd9d + hash_080103c46dce5c285e4686088f1b510da6e966 - thr_hw_slowdown + retired_pending hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_08010315564beb5b304bad49dbca0cb469bb2f + hash_080103db6f1d51fd093d2d28b0cab3c1bd19a0 - thr_sw_thermal + retired_sbe hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_080103684afab926b998321a7a6fac6f5a393b + hash_080103c2afb6ee87f53f498a736738e5bd0113 - thr_hw_thermal + retired_dbe hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_0801035f35b5a45efe842fa4a8dec1cdac348e + hash_08010378bed9f1d5da131bc2e3939e967fb9df - thr_hw_power_brake + thr_sw_power_cap hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_08010340894c404284f5ad11902bd285da8568 + 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 - + |host_description| - GPU |query_gpuIndex| |query_gpuName| - Throttle + - + name hash_0101037f7ae72a8e79a16815acaea47b35ab66 1 |host_description| - GPU |query_gpuIndex| |query_gpuName| - + - - - hash_0001039731ead9f1bdb18ff2a968a804253ba0 - GPU - Clocks + + + hash_000103a74a22a26e30e91efb4e805bff01e83b + GPU - ECC Errors util_gpu @@ -2845,60 +3713,80 @@ hash_0801031ad88ffa3dd274846760a8d68f2a0a60 - retired_pending + ecc_corr_new hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_080103db6f1d51fd093d2d28b0cab3c1bd19a0 + hash_0801031ba5b836a0ff7ecfa9feba3d334fbc0a - thr_sw_power_cap + ecc_uncorr_new hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_080103e2d56f87cdaca55a819207fe6a19cd9d + hash_080103c46dce5c285e4686088f1b510da6e966 - thr_hw_slowdown + retired_pending hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_08010315564beb5b304bad49dbca0cb469bb2f + hash_080103db6f1d51fd093d2d28b0cab3c1bd19a0 - thr_sw_thermal + retired_sbe hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_080103684afab926b998321a7a6fac6f5a393b + hash_080103c2afb6ee87f53f498a736738e5bd0113 - thr_hw_thermal + retired_dbe hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_0801035f35b5a45efe842fa4a8dec1cdac348e + hash_08010378bed9f1d5da131bc2e3939e967fb9df - thr_hw_power_brake + thr_sw_power_cap hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_08010340894c404284f5ad11902bd285da8568 + 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 - + |host_description| - GPU |query_gpuIndex| |query_gpuName| - ECC Errors + - + name hash_0101037f7ae72a8e79a16815acaea47b35ab66 1 |host_description| - GPU |query_gpuIndex| |query_gpuName| - + - - - hash_000103a3b2a1e103b387430075b176c004c97d - GPU - Throttle + + + hash_00010377a7e64e0140f9f50eda31b194c57dbe + GPU - New ECC Errors util_gpu @@ -2956,60 +3844,80 @@ hash_0801031ad88ffa3dd274846760a8d68f2a0a60 - retired_pending + ecc_corr_new hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_080103db6f1d51fd093d2d28b0cab3c1bd19a0 + hash_0801031ba5b836a0ff7ecfa9feba3d334fbc0a - thr_sw_power_cap + ecc_uncorr_new hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_080103e2d56f87cdaca55a819207fe6a19cd9d + hash_080103c46dce5c285e4686088f1b510da6e966 - thr_hw_slowdown + retired_pending hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_08010315564beb5b304bad49dbca0cb469bb2f + hash_080103db6f1d51fd093d2d28b0cab3c1bd19a0 - thr_sw_thermal + retired_sbe hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_080103684afab926b998321a7a6fac6f5a393b + hash_080103c2afb6ee87f53f498a736738e5bd0113 - thr_hw_thermal + retired_dbe hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_0801035f35b5a45efe842fa4a8dec1cdac348e + hash_08010378bed9f1d5da131bc2e3939e967fb9df - thr_hw_power_brake + thr_sw_power_cap hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_08010340894c404284f5ad11902bd285da8568 + 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 - + |host_description| - GPU |query_gpuIndex| |query_gpuName| - New ECC Errors + - + name hash_0101037f7ae72a8e79a16815acaea47b35ab66 1 |host_description| - GPU |query_gpuIndex| |query_gpuName| - + - - - hash_000103a74a22a26e30e91efb4e805bff01e83b - GPU - ECC Errors + + + hash_000103847b4bc7d3af133d9c40ac28658b3a18 + GPU - Retired Pages util_gpu @@ -3067,57 +3975,77 @@ hash_0801031ad88ffa3dd274846760a8d68f2a0a60 - retired_pending + ecc_corr_new hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_080103db6f1d51fd093d2d28b0cab3c1bd19a0 + hash_0801031ba5b836a0ff7ecfa9feba3d334fbc0a - thr_sw_power_cap + ecc_uncorr_new hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_080103e2d56f87cdaca55a819207fe6a19cd9d + hash_080103c46dce5c285e4686088f1b510da6e966 - thr_hw_slowdown + retired_pending hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_08010315564beb5b304bad49dbca0cb469bb2f + hash_080103db6f1d51fd093d2d28b0cab3c1bd19a0 - thr_sw_thermal + retired_sbe hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_080103684afab926b998321a7a6fac6f5a393b + hash_080103c2afb6ee87f53f498a736738e5bd0113 - thr_hw_thermal + retired_dbe hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_0801035f35b5a45efe842fa4a8dec1cdac348e + hash_08010378bed9f1d5da131bc2e3939e967fb9df - thr_hw_power_brake + thr_sw_power_cap hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_08010340894c404284f5ad11902bd285da8568 + 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 - + |host_description| - GPU |query_gpuIndex| |query_gpuName| - Retired Pages + - + name hash_0101037f7ae72a8e79a16815acaea47b35ab66 1 |host_description| - GPU |query_gpuIndex| |query_gpuName| - + - + hash_0001039f12a36681425f2d9faa64323165254c GPU - Sample Age @@ -3178,40 +4106,60 @@ hash_0801031ad88ffa3dd274846760a8d68f2a0a60 - retired_pending + ecc_corr_new hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_080103db6f1d51fd093d2d28b0cab3c1bd19a0 + hash_0801031ba5b836a0ff7ecfa9feba3d334fbc0a - thr_sw_power_cap + ecc_uncorr_new hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_080103e2d56f87cdaca55a819207fe6a19cd9d + hash_080103c46dce5c285e4686088f1b510da6e966 - thr_hw_slowdown + retired_pending hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_08010315564beb5b304bad49dbca0cb469bb2f + hash_080103db6f1d51fd093d2d28b0cab3c1bd19a0 - thr_sw_thermal + retired_sbe hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_080103684afab926b998321a7a6fac6f5a393b + hash_080103c2afb6ee87f53f498a736738e5bd0113 - thr_hw_thermal + retired_dbe hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_0801035f35b5a45efe842fa4a8dec1cdac348e + hash_08010378bed9f1d5da131bc2e3939e967fb9df - thr_hw_power_brake + thr_sw_power_cap hash_0101037f7ae72a8e79a16815acaea47b35ab66 - hash_08010340894c404284f5ad11902bd285da8568 + 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 - + diff --git a/tests/Integration/LifecycleTest.php b/tests/Integration/LifecycleTest.php index dfff7a4..972fc69 100644 --- a/tests/Integration/LifecycleTest.php +++ b/tests/Integration/LifecycleTest.php @@ -86,7 +86,7 @@ }); 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]; + $objects = ['data_query' => 1, 'data_template' => 1, 'graph_templates' => 10, 'graph_items' => 88, 'device_template' => 1, 'dq_graphs' => 10, 'dq_file' => true]; expect(lifecycle('install')['objects'])->toBe($objects); diff --git a/tests/Security/SourceRulesTest.php b/tests/Security/SourceRulesTest.php index 4998965..8a4fb87 100644 --- a/tests/Security/SourceRulesTest.php +++ b/tests/Security/SourceRulesTest.php @@ -291,9 +291,10 @@ function gpu_entry_points(): array { it('names no state-changing vendor command anywhere', function () { // REQ-LIFE-005: clocks, power limits, persistence mode, resets, MIG - // layout, and amd-smi set or reset are never invoked. A string that + // layout, ECC counter clears, drains, and amd-smi set or reset are never + // invoked, whatever an error value reads (REQ-ERR-006). A string that // pairs a vendor tool with one of these is refused wherever it appears. - $mutating = '/\b(nvidia-smi|dcgmi|amd-smi|rocm-smi)\b.*(\s-(pm|pl|ac|rac|lgc|rgc|lmc|rmc|r|e|c|mig|cgi|cci|dgi|dci)\b|--(persistence-mode|power-limit|applications-clocks|reset-applications-clocks|lock-gpu-clocks|reset-gpu-clocks|lock-memory-clocks|reset-memory-clocks|gpu-reset|ecc-config|compute-mode|multi-instance-gpu)\b|\s(mig|set|reset|config)\s)/i'; + $mutating = '/\b(nvidia-smi|dcgmi|amd-smi|rocm-smi)\b.*(\s-(pm|pl|ac|rac|lgc|rgc|lmc|rmc|r|e|p|c|mig|cgi|cci|dgi|dci)\b|--(persistence-mode|power-limit|applications-clocks|reset-applications-clocks|lock-gpu-clocks|reset-gpu-clocks|lock-memory-clocks|reset-memory-clocks|gpu-reset|reset-ecc-errors|ecc-config|compute-mode|multi-instance-gpu)\b|\s(mig|set|reset|config|drain)\s)/i'; foreach (gpu_sources() as $file) { foreach (PhpToken::tokenize((string) file_get_contents(gpu_root() . '/' . $file)) as $token) { @@ -306,5 +307,8 @@ function gpu_entry_points(): array { expect(preg_match($mutating, "'nvidia-smi -pl 200'"))->toBe(1) ->and(preg_match($mutating, "'nvidia-smi --gpu-reset -i 0'"))->toBe(1) ->and(preg_match($mutating, "'amd-smi set --power-cap 100'"))->toBe(1) + ->and(preg_match($mutating, "'nvidia-smi -p 0 -i 0'"))->toBe(1) + ->and(preg_match($mutating, "'nvidia-smi --reset-ecc-errors=1'"))->toBe(1) + ->and(preg_match($mutating, "'nvidia-smi drain -p 0000:01:00.0 -m 1'"))->toBe(1) ->and(preg_match($mutating, "'nvidia-smi --query-gpu=uuid,index --format=csv'"))->toBe(0); }); diff --git a/tests/Unit/CollectorTest.php b/tests/Unit/CollectorTest.php index 10d85c5..7c4a8a7 100644 --- a/tests/Unit/CollectorTest.php +++ b/tests/Unit/CollectorTest.php @@ -29,6 +29,7 @@ use Somethingwithproof\Gpu\GpuRepository; use Somethingwithproof\Gpu\IdentityReconciler; use Somethingwithproof\Gpu\Inventory; +use Somethingwithproof\Gpu\MetricModel; use Somethingwithproof\Gpu\LockRepository; use Somethingwithproof\Gpu\Node; use Somethingwithproof\Gpu\NodeDevice; @@ -155,7 +156,7 @@ function collect_known(int $node = 3): array { ->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']); + $named = array_combine(array_merge(['gpu_id', 'node_id', 'observed_at', 'ingested_at', 'reported_at', 'backend', 'tool_version'], array_values(array_diff(Schema::observationMetrics(), array_keys(MetricModel::DELTAS))), ['thr_mask', 'ecc_mode']), $store['params']); expect($named['gpu_id'])->toBe(9) ->and($named['node_id'])->toBe(3) @@ -165,6 +166,8 @@ function collect_known(int $node = 3): array { ->and($named['util_gpu'])->toBe(30.0) ->and($named['power'])->toBeNull() ->and($named['thr_mask'])->toBe(0) + ->and($named['ecc_mode'])->toBe('unavailable') + ->and($named)->not->toHaveKey('ecc_corr_new') ->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(')); @@ -262,5 +265,17 @@ function collect_known(int $node = 3): array { ]); it('keeps one observation column per stored model field', function () { - expect(Schema::OBSERVATION_METRICS)->toBe(array_values(array_diff(\Somethingwithproof\Gpu\MetricModel::names(), ['age']))); + expect(Schema::observationMetrics())->toEqualCanonicalizing(array_values(array_diff(\Somethingwithproof\Gpu\MetricModel::names(), ['age']))); +}); + +it('computes new ECC errors from the stored total, as unknown across a reset or a missing total', function () { + (new \Somethingwithproof\Gpu\ObservationRepository(false))->store(9, 3, smi_parse('r580-8gpu')->readings[0], 'nvidia-smi', '580.95.05', COLLECT_NOW); + + $sql = $GLOBALS['__gpu_db_exec'][0]['sql']; + + // Before the totals are replaced, and only for a newer sample. + expect($sql)->toContain('ecc_corr_new = IF(VALUES(observed_at) > observed_at, IF(VALUES(ecc_corr) >= ecc_corr, VALUES(ecc_corr) - ecc_corr, NULL), ecc_corr_new)') + ->and($sql)->toContain('ecc_uncorr_new = IF(VALUES(observed_at) > observed_at, IF(VALUES(ecc_uncorr) >= ecc_uncorr, VALUES(ecc_uncorr) - ecc_uncorr, NULL), ecc_uncorr_new)') + ->and(strpos($sql, 'ecc_corr_new = IF('))->toBeLessThan(strpos($sql, 'ecc_corr = IF(')) + ->and(strpos($sql, 'ecc_uncorr_new = IF('))->toBeLessThan(strpos($sql, 'ecc_uncorr = IF(')); }); diff --git a/tests/Unit/NvidiaSmiParserTest.php b/tests/Unit/NvidiaSmiParserTest.php index a1c96a4..549b301 100644 --- a/tests/Unit/NvidiaSmiParserTest.php +++ b/tests/Unit/NvidiaSmiParserTest.php @@ -77,7 +77,7 @@ function smi_error(ExtendOutput $metrics, ?ExtendOutput $names = null): Collecti ->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']))); + ->and(array_keys($first->values))->toEqualCanonicalizing(array_values(array_diff(MetricModel::names(), ['age'], array_keys(MetricModel::DELTAS)))); })->with([ ['r580-8gpu', 8, '580.95.05'], ['r595-1gpu', 1, '595.45.04'], @@ -143,9 +143,9 @@ function smi_error(ExtendOutput $metrics, ?ExtendOutput $names = null): Collecti $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->getMessage())->toBe('GPU metrics line 1 has 20 fields where 21 were requested') ->and($short->rejectedLines)->toBe(1) - ->and($extra->getMessage())->toBe('GPU metrics line 1 has 19 fields where 18 were requested'); + ->and($extra->getMessage())->toBe('GPU metrics line 1 has 22 fields where 21 were requested'); }); it('rejects stderr text that snmpd merged into the output', function () { @@ -155,7 +155,7 @@ function smi_error(ExtendOutput $metrics, ?ExtendOutput $names = null): Collecti $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())->toBe('GPU metrics line 3 has 1 fields where 21 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()) @@ -357,3 +357,29 @@ function smi_device(): \Somethingwithproof\Gpu\NodeDevice { 'PHP\'s SNMP class missing' => [new \Error('Class "SNMP" not found')], 'an SNMPv3 protocol refused' => [new \ValueError('Authentication protocol must be "SHA" or "MD5"')], ]); + +it('reads retired pages and the ECC mode, and a GPU without ECC as unknown', function () { + $with = smi_parse('r580-8gpu')->readings[0]; + $without = smi_parse('r595-1gpu')->readings[0]; + + expect($with->values['retired_sbe'])->toBe(0.0) + ->and($with->values['retired_dbe'])->toBe(0.0) + ->and($with->eccMode)->toBe('enabled') + ->and($without->values['ecc_corr'])->toBeNull() + ->and($without->values['retired_sbe'])->toBeNull() + ->and($without->values['retired_dbe'])->toBeNull() + ->and($without->eccMode)->toBe('unavailable'); +}); + +it('names the reason an ECC value is unknown', function (string $raw, \Somethingwithproof\Gpu\EccMode $mode, bool $reason) { + $parsed = \Somethingwithproof\Gpu\EccMode::fromNvidia($raw); + + expect($parsed)->toBe($mode) + ->and($parsed->reason() !== '')->toBe($reason); +})->with([ + ['Enabled', \Somethingwithproof\Gpu\EccMode::Enabled, false], + ['Disabled', \Somethingwithproof\Gpu\EccMode::Disabled, true], + ['[N/A]', \Somethingwithproof\Gpu\EccMode::Unavailable, true], + ['[Not Supported]', \Somethingwithproof\Gpu\EccMode::Unavailable, true], + ['Pending', \Somethingwithproof\Gpu\EccMode::Unknown, true], +]); diff --git a/tests/fixtures/nvidia-smi/r580-8gpu.metrics b/tests/fixtures/nvidia-smi/r580-8gpu.metrics index 8dc9e2f..e15a89f 100644 --- a/tests/fixtures/nvidia-smi/r580-8gpu.metrics +++ b/tests/fixtures/nvidia-smi/r580-8gpu.metrics @@ -1,8 +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 +@NOW@, GPU-00000000-0000-4000-8000-000000000001, 0, 00000000:18:00.0, 580.95.05, Enabled, 30, 10, 2048, 81559, 40, 100.50, 700.00, 1410, 1593, 0, 0, No, 0, 0, 0x0000000000000001 +@NOW@, GPU-00000000-0000-4000-8000-000000000002, 1, 00000000:28:00.0, 580.95.05, Enabled, 31, 11, 2049, 81559, 41, 101.50, 700.00, 1411, 1593, 0, 0, No, 0, 0, 0x0000000000000004 +@NOW@, GPU-00000000-0000-4000-8000-000000000003, 2, 00000000:38:00.0, 580.95.05, Enabled, 32, 12, 2050, 81559, 42, 102.50, 700.00, 1412, 1593, 0, 0, No, 0, 0, 0x0000000000000001 +@NOW@, GPU-00000000-0000-4000-8000-000000000004, 3, 00000000:48:00.0, 580.95.05, Enabled, 33, 13, 2051, 81559, 43, 103.50, 700.00, 1413, 1593, 0, 0, No, 0, 0, 0x0000000000000001 +@NOW@, GPU-00000000-0000-4000-8000-000000000005, 4, 00000000:58:00.0, 580.95.05, Enabled, 34, 14, 2052, 81559, 44, 104.50, 700.00, 1414, 1593, 0, 0, No, 0, 0, 0x0000000000000001 +@NOW@, GPU-00000000-0000-4000-8000-000000000006, 5, 00000000:68:00.0, 580.95.05, Enabled, 35, 15, 2053, 81559, 45, 105.50, 700.00, 1415, 1593, 0, 0, No, 0, 0, 0x0000000000000001 +@NOW@, GPU-00000000-0000-4000-8000-000000000007, 6, 00000000:78:00.0, 580.95.05, Enabled, 36, 16, 2054, 81559, 46, 106.50, 700.00, 1416, 1593, 0, 0, No, 0, 0, 0x0000000000000001 +@NOW@, GPU-00000000-0000-4000-8000-000000000008, 7, 00000000:88:00.0, 580.95.05, Enabled, 37, 17, 2055, 81559, 47, 107.50, 700.00, 1417, 1593, 0, 0, No, 0, 0, 0x0000000000000001 diff --git a/tests/fixtures/nvidia-smi/r595-1gpu.metrics b/tests/fixtures/nvidia-smi/r595-1gpu.metrics index 9e6786b..3adacd1 100644 --- a/tests/fixtures/nvidia-smi/r595-1gpu.metrics +++ b/tests/fixtures/nvidia-smi/r595-1gpu.metrics @@ -1 +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 +@NOW@, GPU-00000000-0000-4000-8000-000000000001, 0, 00000000:18:00.0, 595.45.04, [N/A], 30, 10, 2048, 81559, 40, [N/A], [N/A], 1410, 1593, [N/A], [N/A], [N/A], [N/A], [N/A], 0 diff --git a/tests/fixtures/nvidia-smi/r620-16gpu.metrics b/tests/fixtures/nvidia-smi/r620-16gpu.metrics index 79bd71e..c803bb1 100644 --- a/tests/fixtures/nvidia-smi/r620-16gpu.metrics +++ b/tests/fixtures/nvidia-smi/r620-16gpu.metrics @@ -1,16 +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 +@NOW@, GPU-00000000-0000-4000-8000-000000000001, 0, 00000000:18:00.0, 620.70.06, Enabled, 30, 10, 2048, 81559, 40, 100.50, 700.00, 1410, 1593, 0, 0, No, 0, 0, 0x0000000000000000 +@NOW@, GPU-00000000-0000-4000-8000-000000000002, 1, 00000000:28:00.0, 620.70.06, Enabled, 31, 11, 2049, 81559, 41, 101.50, 700.00, 1411, 1593, 0, 0, No, 0, 0, 0x0000000000000000 +@NOW@, GPU-00000000-0000-4000-8000-000000000003, 2, 00000000:38:00.0, 620.70.06, Enabled, 32, 12, 2050, 81559, 42, 102.50, 700.00, 1412, 1593, 0, 0, No, 0, 0, 0x0000000000000000 +@NOW@, GPU-00000000-0000-4000-8000-000000000004, 3, 00000000:48:00.0, 620.70.06, Enabled, 33, 13, 2051, 81559, 43, 103.50, 700.00, 1413, 1593, 0, 0, No, 0, 0, 0x0000000000000048 +@NOW@, GPU-00000000-0000-4000-8000-000000000005, 4, 00000000:58:00.0, 620.70.06, Enabled, 34, 14, 2052, 81559, 44, 104.50, 700.00, 1414, 1593, 0, 0, No, 0, 0, 0x0000000000000000 +@NOW@, GPU-00000000-0000-4000-8000-000000000006, 5, 00000000:68:00.0, 620.70.06, Enabled, 35, 15, 2053, 81559, 45, 105.50, 700.00, 1415, 1593, 0, 0, No, 0, 0, 0x0000000000000000 +@NOW@, GPU-00000000-0000-4000-8000-000000000007, 6, 00000000:78:00.0, 620.70.06, Enabled, 36, 16, 2054, 81559, 46, 106.50, 700.00, 1416, 1593, 0, 0, No, 0, 0, 0x0000000000000000 +@NOW@, GPU-00000000-0000-4000-8000-000000000008, 7, 00000000:88:00.0, 620.70.06, Enabled, 37, 17, 2055, 81559, 47, 107.50, 700.00, 1417, 1593, 0, 0, No, 0, 0, 0x0000000000000000 +@NOW@, GPU-00000000-0000-4000-8000-000000000009, 8, 00000000:98:00.0, 620.70.06, Enabled, 38, 18, 2056, 81559, 48, 108.50, 700.00, 1418, 1593, 0, 0, No, 0, 0, 0x0000000000000000 +@NOW@, GPU-00000000-0000-4000-8000-00000000000a, 9, 00000000:A8:00.0, 620.70.06, Enabled, 39, 19, 2057, 81559, 49, 109.50, 700.00, 1419, 1593, 0, 0, No, 0, 0, 0x0000000000000000 +@NOW@, GPU-00000000-0000-4000-8000-00000000000b, 10, 00000000:B8:00.0, 620.70.06, Enabled, 40, 20, 2058, 81559, 50, 110.50, 700.00, 1420, 1593, 0, 0, No, 0, 0, 0x0000000000000000 +@NOW@, GPU-00000000-0000-4000-8000-00000000000c, 11, 00000000:C8:00.0, 620.70.06, Enabled, 41, 21, 2059, 81559, 51, 111.50, 700.00, 1421, 1593, 0, 0, No, 0, 0, 0x0000000000000000 +@NOW@, GPU-00000000-0000-4000-8000-00000000000d, 12, 00000000:D8:00.0, 620.70.06, Enabled, 42, 22, 2060, 81559, 52, 112.50, 700.00, 1422, 1593, 0, 0, No, 0, 0, 0x0000000000000000 +@NOW@, GPU-00000000-0000-4000-8000-00000000000e, 13, 00000000:E8:00.0, 620.70.06, Enabled, 43, 23, 2061, 81559, 53, 113.50, 700.00, 1423, 1593, 0, 0, No, 0, 0, 0x0000000000000000 +@NOW@, GPU-00000000-0000-4000-8000-00000000000f, 14, 00000000:FE:00.0, 620.70.06, Enabled, 44, 24, 2062, 81559, 54, 114.50, 700.00, 1424, 1593, 0, 0, No, 0, 0, 0x0000000000000000 +@NOW@, GPU-00000000-0000-4000-8000-000000000010, 15, 00000000:FF:00.0, 620.70.06, Enabled, 45, 25, 2063, 81559, 55, 115.50, 700.00, 1425, 1593, 0, 0, No, 0, 0, 0x0000000000000000 From 07c6bdb4a289dc12a5245cc45c621249c7ae96d8 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 12:29:32 -0800 Subject: [PATCH 03/18] feat(alerting): ship Thold templates and an end-to-end alert test (#44, #46) templates/gpu_thold_templates.xml holds nine Thold threshold templates, generated from lib/TholdTemplateXml.php: temperature, power against its limit, the hardware and thermal throttle indicators, new uncorrected ECC errors, pending page retirement, and sample age. Each names only columns Thold 1.8.2 imports, and each is a high threshold on a gauge, because Thold 1.8.2 fails on an unknown value of a thresholded counter. A unit test keeps the shipped file equal to the generator. tests/bin/alert-flow.php imports the templates with Thold's own import, links them to the GPU Node device template, and lets Thold create the thresholds as the plugin creates the graphs. Against a real snmpd and the fake nvidia-smi it shows each threshold fire and restore, an ECC reset reading U without breaching or a TypeError, a failed collection alerting only on age, and a Maint schedule suppressing a breach the RRD file still records. Thold and Maint run unchanged. The shared end-to-end helpers move to tests/bin/e2e-lib.php, so the new flows reuse them. Signed-off-by: Thomas Vincent --- lib/TholdTemplateXml.php | 129 ++++++++++ locales/po/cacti.pot | 16 ++ templates/gpu_thold_templates.xml | 164 +++++++++++++ tests/Unit/TholdTemplateXmlTest.php | 92 +++++++ tests/bin/alert-flow.php | 363 ++++++++++++++++++++++++++++ tests/bin/e2e-lib.php | 242 +++++++++++++++++++ tests/bin/e2e.php | 195 +-------------- 7 files changed, 1008 insertions(+), 193 deletions(-) create mode 100644 lib/TholdTemplateXml.php create mode 100644 templates/gpu_thold_templates.xml create mode 100644 tests/Unit/TholdTemplateXmlTest.php create mode 100644 tests/bin/alert-flow.php create mode 100644 tests/bin/e2e-lib.php diff --git a/lib/TholdTemplateXml.php b/lib/TholdTemplateXml.php new file mode 100644 index 0000000..22d6149 --- /dev/null +++ b/lib/TholdTemplateXml.php @@ -0,0 +1,129 @@ + + * 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; + +/** + * Default Thold threshold templates for the GPU data source (REQ-ALERT-001, + * ADR 0002), in the XML that Thold's Threshold Templates import reads. + * + * The plugin never loads Thold. An operator imports templates/ + * gpu_thold_templates.xml on Thold's Threshold Templates page and links the + * templates to the GPU Node device template; Thold then creates thresholds + * for each GPU's data source. docs/alerting.md describes the steps. + * + * Each template names only columns of Thold 1.8.2's thold_template table, + * because its import refuses a template with any column the table lacks. + * Every threshold is a high threshold on a gauge: no template uses a + * counter, so Thold's rate calculation never sees an unknown value. + * + * Not templated, on purpose: the software power cap (normal under load), + * Idle and the other mask bits without an indicator (REQ-THR-002), the + * volatile ECC totals (they fall at driver load, so a threshold on them + * clears without a fix), and new corrected ECC errors (occasional ones are + * normal, and no default rate is known). + */ +final class TholdTemplateXml { + public const FILE = 'gpu_thold_templates.xml'; + + // Thold's thold_type 0 is High / Low; data_type 0 is the exact value + // and 2 is a percentage of another data source item. + private const HIGH_LOW = 0; + private const EXACT = 0; + private const PERCENTAGE = 2; + + /** + * name => [data source item, high threshold, fail trigger in polls, + * percentage of this item, or '']. + * + * A fail trigger counts Cacti polls; the collector reads each node once + * per poller cycle, so one poll is one collection interval + * (REQ-ALERT-004). + * + * @return array + */ + public static function templates(): array { + return [ + 'GPU - Temperature High' => ['temp_gpu', '85', 2, ''], + 'GPU - Power Above Limit' => ['power', '100', 2, 'power_limit'], + 'GPU - Software Thermal Slowdown' => ['thr_sw_thermal', '0.5', 1, ''], + 'GPU - Hardware Thermal Slowdown' => ['thr_hw_thermal', '0.5', 1, ''], + 'GPU - Hardware Power Brake' => ['thr_hw_power_brake', '0.5', 1, ''], + 'GPU - Hardware Slowdown' => ['thr_hw_slowdown', '0.5', 1, ''], + 'GPU - New Uncorrected ECC Errors' => ['ecc_uncorr_new', '0.5', 1, ''], + 'GPU - Page Retirement Pending' => ['retired_pending', '0.5', 1, ''], + // Three default poller cycles: age stays numeric while a sample + // exists, so this fires when collection stops (REQ-ALERT-002). + 'GPU - Sample Too Old' => ['age', '900', 1, ''], + ]; + } + + /** + * The Thold template hash: 32 hex digits, fixed per template name. + */ + public static function hash(string $name): string { + return md5('plugin_gpu:thold_template:' . $name); + } + + /** + * The file Thold's import reads, in the shape Thold's own export writes. + */ + public static function xml(): string { + $out = "\n"; + $sequence = 1; + + foreach (self::templates() as $name => [$item, $high, $trigger, $percentOf]) { + $metric = MetricModel::find($item); + + if ($metric === null) { + throw new \LogicException("No model field $item"); + } + + $columns = [ + 'hash' => self::hash($name), + 'name' => $name, + 'data_template_id' => substr(TemplateXml::hash('01', TemplateXml::DATA_TEMPLATE), -32), + 'data_template_name' => TemplateXml::DATA_TEMPLATE, + 'data_source_id' => substr(TemplateXml::hash('08', $item), -32), + 'data_source_name' => $item, + 'data_source_friendly' => $metric->label, + 'thold_enabled' => 'on', + 'thold_type' => (string) self::HIGH_LOW, + 'thold_hi' => $high, + 'thold_low' => '', + 'thold_fail_trigger' => (string) $trigger, + 'data_type' => (string) ($percentOf === '' ? self::EXACT : self::PERCENTAGE), + 'percent_ds' => $percentOf, + 'repeat_alert' => '0', + 'restored_alert' => '', + ]; + + $out .= "\n"; + + foreach ($columns as $column => $value) { + $out .= "\t<$column>" . htmlspecialchars($value, ENT_QUOTES | ENT_XML1, 'UTF-8') . "\n"; + } + + $out .= "\n"; + $sequence++; + } + + return $out . "\n"; + } +} diff --git a/locales/po/cacti.pot b/locales/po/cacti.pot index 13e31c2..883e812 100644 --- a/locales/po/cacti.pot +++ b/locales/po/cacti.pot @@ -84,6 +84,10 @@ msgstr "" msgid "The GPU Node device template is not installed." msgstr "" +#: gpu_nodes.php +msgid "The device was not kept: your account may not see devices it creates. Ask an administrator to create it." +msgstr "" + #: gpu_nodes.php msgid "The device and its GPU node were created. Set the device's SNMP settings on its device page." msgstr "" @@ -92,6 +96,18 @@ msgstr "" msgid "The device could not be created; see the Cacti log." msgstr "" +#: lib/EccMode.php +msgid "ECC is disabled on this GPU" +msgstr "" + +#: lib/EccMode.php +msgid "This GPU does not report ECC" +msgstr "" + +#: lib/EccMode.php +msgid "ECC mode not reported" +msgstr "" + #: lib/ExecutionState.php msgid "Collected" msgstr "" diff --git a/templates/gpu_thold_templates.xml b/templates/gpu_thold_templates.xml new file mode 100644 index 0000000..6c9aec1 --- /dev/null +++ b/templates/gpu_thold_templates.xml @@ -0,0 +1,164 @@ + + + c7ba1c5a38424906e68e301d84752ae3 + GPU - Temperature High + 7f7ae72a8e79a16815acaea47b35ab66 + GPU - Metrics + a269082db3ee8d772f5f44f27b3f7a23 + temp_gpu + GPU temperature + on + 0 + 85 + + 2 + 0 + + 0 + + + + 317eaf729f39a855be0301d2c7e656c7 + GPU - Power Above Limit + 7f7ae72a8e79a16815acaea47b35ab66 + GPU - Metrics + 8cbec3da5106f36e5d6c2394eb3ec1a2 + power + Board power draw + on + 0 + 100 + + 2 + 2 + power_limit + 0 + + + + c1cff81c23bcd50f2a2c931dcdcb1bdd + GPU - Software Thermal Slowdown + 7f7ae72a8e79a16815acaea47b35ab66 + GPU - Metrics + 684afab926b998321a7a6fac6f5a393b + thr_sw_thermal + Software thermal slowdown + on + 0 + 0.5 + + 1 + 0 + + 0 + + + + 44590c3b6d62306a7561417f3d656a21 + GPU - Hardware Thermal Slowdown + 7f7ae72a8e79a16815acaea47b35ab66 + GPU - Metrics + 5f35b5a45efe842fa4a8dec1cdac348e + thr_hw_thermal + Hardware thermal slowdown + on + 0 + 0.5 + + 1 + 0 + + 0 + + + + 62c8674a7772d1f52ce82bd993de9ecb + GPU - Hardware Power Brake + 7f7ae72a8e79a16815acaea47b35ab66 + GPU - Metrics + 40894c404284f5ad11902bd285da8568 + thr_hw_power_brake + Hardware power brake + on + 0 + 0.5 + + 1 + 0 + + 0 + + + + 7646a917fad9fe450b54354877d31411 + GPU - Hardware Slowdown + 7f7ae72a8e79a16815acaea47b35ab66 + GPU - Metrics + 15564beb5b304bad49dbca0cb469bb2f + thr_hw_slowdown + Hardware slowdown + on + 0 + 0.5 + + 1 + 0 + + 0 + + + + 70f540176d91463cd62f1ac8d287f405 + GPU - New Uncorrected ECC Errors + 7f7ae72a8e79a16815acaea47b35ab66 + GPU - Metrics + c46dce5c285e4686088f1b510da6e966 + ecc_uncorr_new + Uncorrected ECC errors since the previous sample + on + 0 + 0.5 + + 1 + 0 + + 0 + + + + f7d369b0ca08b1d3ac976d91d46b2753 + GPU - Page Retirement Pending + 7f7ae72a8e79a16815acaea47b35ab66 + GPU - Metrics + db6f1d51fd093d2d28b0cab3c1bd19a0 + retired_pending + Page retirement pending + on + 0 + 0.5 + + 1 + 0 + + 0 + + + + 88216ef9fd56a46ad04b86e95a7e8b8c + GPU - Sample Too Old + 7f7ae72a8e79a16815acaea47b35ab66 + GPU - Metrics + 91f7fdb74f0d794e1fbe5e362a45dd1f + age + Seconds since the tool took the sample + on + 0 + 900 + + 1 + 0 + + 0 + + + diff --git a/tests/Unit/TholdTemplateXmlTest.php b/tests/Unit/TholdTemplateXmlTest.php new file mode 100644 index 0000000..cfa37ea --- /dev/null +++ b/tests/Unit/TholdTemplateXmlTest.php @@ -0,0 +1,92 @@ + + * 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; +use Somethingwithproof\Gpu\TemplateXml; +use Somethingwithproof\Gpu\TholdTemplateXml; + +// The thold_template columns of Thold v1.8.2 other than id +// (includes/database.php at 1eb406bd); its import refuses a template with +// any other column. +const THOLD_182_COLUMNS = ['hash', 'name', 'suggested_name', 'data_template_id', 'data_template_hash', 'data_template_name', 'data_source_id', 'data_source_name', 'data_source_friendly', 'thold_hi', 'thold_low', 'thold_fail_trigger', 'time_hi', 'time_low', 'time_fail_trigger', 'time_fail_length', 'thold_warning_hi', 'thold_warning_low', 'thold_warning_fail_trigger', 'thold_warning_fail_count', 'time_warning_hi', 'time_warning_low', 'time_warning_fail_trigger', 'time_warning_fail_length', 'thold_enabled', 'thold_type', 'bl_ref_time_range', 'bl_type', 'bl_pct_down', 'bl_pct_up', 'bl_fail_trigger', 'bl_fail_count', 'bl_alert', 'bl_cf', 'repeat_alert', 'notify_extra', 'notify_warning_extra', 'notify_templated', 'notify_warning', 'notify_alert', 'snmp_event_category', 'snmp_event_description', 'snmp_event_severity', 'snmp_event_warning_severity', 'data_type', 'show_units', 'units_suffix', 'decimals', 'cdef', 'percent_ds', 'expression', 'upper_ds', 'exempt', 'thold_hrule_alert', 'thold_hrule_warning', 'skipscale', 'restored_alert', 'reset_ack', 'persist_ack', 'email_subject', 'email_subject_warn', 'email_subject_restoral', 'email_body', 'email_body_warn', 'email_body_restoral', 'trigger_cmd_high', 'trigger_cmd_low', 'trigger_cmd_norm', 'syslog_priority', 'syslog_facility', 'syslog_enabled', 'notes', 'external_id', 'format_file', 'graph_timespan']; + +it('ships exactly the Thold templates the generator produces', function () { + expect((string) file_get_contents(dirname(__DIR__, 2) . '/templates/' . TholdTemplateXml::FILE))->toBe(TholdTemplateXml::xml()); +}); + +it('writes only columns Thold 1.8.2 imports, and points at the GPU data template', function () { + $xml = simplexml_load_string(TholdTemplateXml::xml()); + + expect($xml)->not->toBeFalse() + ->and(count($xml->children()))->toBe(count(TholdTemplateXml::templates())); + + foreach ($xml->children() as $template) { + foreach ($template->children() as $column) { + expect(THOLD_182_COLUMNS)->toContain($column->getName()); + } + + expect((string) $template->data_template_id)->toBe(substr(TemplateXml::hash('01', TemplateXml::DATA_TEMPLATE), -32)) + ->and((string) $template->data_source_id)->toBe(substr(TemplateXml::hash('08', (string) $template->data_source_name), -32)) + ->and((string) $template->hash)->toMatch('/^[0-9a-f]{32}$/'); + } +}); + +it('thresholds only drawn gauges, never a counter, Idle, or the volatile ECC totals', function () { + $drawn = []; + + foreach (TemplateXml::graphs() as $graph) { + foreach ($graph['items'] as $item) { + $drawn[] = $item[0]; + } + } + + foreach (TholdTemplateXml::templates() as $name => [$item, $high, $trigger, $percentOf]) { + $metric = MetricModel::find($item); + + expect($metric)->not->toBeNull() + ->and(in_array($metric->kind, [Metric::GAUGE, Metric::INDICATOR], true))->toBeTrue() + ->and($drawn)->toContain($item) + ->and(is_numeric($high))->toBeTrue() + ->and($trigger)->toBeGreaterThanOrEqual(1); + + if ($percentOf !== '') { + expect($drawn)->toContain($percentOf); + } + } + + $items = array_column(TholdTemplateXml::templates(), 0); + + expect($items)->not->toContain('ecc_corr') + ->and($items)->not->toContain('ecc_uncorr') + ->and($items)->not->toContain('thr_sw_power_cap') + ->and($items)->toContain('age') + ->and($items)->toContain('ecc_uncorr_new') + ->and($items)->toContain('thr_hw_thermal'); +}); + +it('stores every data source as a gauge, so Thold never computes a rate from an unknown value', function () { + $xml = TemplateXml::templates(); + + // data_source_type_id 1 is GAUGE; 2 COUNTER, 3 DERIVE, 4 ABSOLUTE. + preg_match_all('/(\d+)<\/data_source_type_id>/', $xml, $types); + + expect($types[1])->not->toBe([]) + ->and(array_unique($types[1]))->toBe(['1']); +}); diff --git a/tests/bin/alert-flow.php b/tests/bin/alert-flow.php new file mode 100644 index 0000000..ececb35 --- /dev/null +++ b/tests/bin/alert-flow.php @@ -0,0 +1,363 @@ + + * 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. + */ + +/* + * Thold alerting and Maint suppression on the GPU data source, end to end + * (#46, REQ-ALERT-001 to REQ-ALERT-005), with Thold v1.8.2 and Maint v1.3 + * installed unchanged at plugins/thold and plugins/maint. Run from the + * Cacti root once the plugin, Thold, and Maint are installed and enabled, + * with the same agent and environment as tests/bin/e2e.php: + * + * php plugins/gpu/tests/bin/alert-flow.php + * + * The thresholds are the shipped templates (templates/gpu_thold_templates. + * xml), imported with Thold's own import and linked to the GPU Node device + * template, so Thold creates them itself when the plugin creates the + * graphs. Each round gives the fake nvidia-smi new output for GPU 0, + * collects over SNMPv3, runs Cacti's poller, and runs Thold's check; the + * round then checks what Thold logged. The maintenance schedule is the two + * rows Maint's schedule page saves. + * + * Every check prints PASS or FAIL; EVIDENCE lines show the Thold state and + * log rows each check relied on. Must parse on PHP 8.0. + */ + +require(__DIR__ . '/e2e-lib.php'); + +use Somethingwithproof\Gpu\MetricModel; +use Somethingwithproof\Gpu\TemplateXml; +use Somethingwithproof\Gpu\TholdTemplateXml; + +if (!api_plugin_is_enabled('thold') || !api_plugin_is_enabled('maint')) { + fwrite(STDERR, "Install and enable Thold and Maint first\n"); + exit(2); +} + +require_once($config['base_path'] . '/plugins/thold/thold_functions.php'); +require_once($config['base_path'] . '/plugins/maint/functions.php'); + +// Thold's log statuses (plugins/thold/includes/arrays.php). +const ALERT_NOTIFY = 4; +const ALERT_RESTORE = 5; + +// The age threshold this test sets on GPU 0, in seconds: low enough that a +// round without a sample passes it, above the age a fresh sample has. +const ALERT_AGE = 45; + +$alert_log = 0; + +/** + * The 8-GPU fixture with GPU 0's fields changed, by nvidia-smi field name. + * + * @param array $change + * @return list + */ +function alert_metrics(array $change): array { + $fields = MetricModel::nvidiaFields(); + $lines = e2e_fixture('r580-8gpu', 'metrics'); + $values = array_map('trim', explode(',', $lines[0])); + + foreach ($change as $field => $value) { + $values[array_search($field, $fields, true)] = $value; + } + + $lines[0] = implode(', ', $values); + + return $lines; +} + +/** + * Thold's threshold on one of GPU 0's data source items. + * + * @return array + */ +function alert_thold(string $item): array { + global $e2e_host; + + $row = db_fetch_row_prepared('SELECT td.id, td.thold_alert, td.thold_fail_count, td.lastread, td.thold_hi, td.thold_enabled, td.data_type, td.percent_ds + FROM thold_data AS td + INNER JOIN data_local AS dl ON dl.id = td.local_data_id + WHERE td.host_id = ? AND dl.snmp_index = ? AND td.data_source_name = ?', array($e2e_host, e2e_key(1), $item)); + + return is_array($row) ? $row : array(); +} + +/** + * Thold log rows since the round began: data source item => statuses, for + * every threshold on the node. + * + * @return array> + */ +function alert_logged(): array { + global $alert_log, $e2e_host; + + $out = array(); + + foreach (db_fetch_assoc_prepared('SELECT l.id, l.status, l.current, td.data_source_name, dl.snmp_index + FROM plugin_thold_log AS l + INNER JOIN thold_data AS td ON td.id = l.threshold_id + INNER JOIN data_local AS dl ON dl.id = td.local_data_id + WHERE l.id > ? AND td.host_id = ? ORDER BY l.id', array($alert_log, $e2e_host)) as $row) { + print 'EVIDENCE log id=' . $row['id'] . ' ' . $row['snmp_index'] . ' ' . $row['data_source_name'] . ' status=' . $row['status'] . " current='" . $row['current'] . "'" . PHP_EOL; + + $key = ($row['snmp_index'] === e2e_key(1) ? '' : $row['snmp_index'] . ' ') . $row['data_source_name']; + $out[$key][] = (int) $row['status']; + } + + return $out; +} + +/** + * Run a program from the Cacti root, with its output in a file. + * + * @param list $argv + */ +function alert_run(array $argv, string $output): int { + global $config; + + $process = proc_open($argv, array(1 => array('file', $output, 'w'), 2 => array('file', $output, 'a')), $pipes, $config['base_path']); + + return is_resource($process) ? proc_close($process) : -1; +} + +/** + * One round: new tool output for GPU 0, a collection, a Cacti poll, and a + * Thold check. Returns the Thold log rows the round added. + * + * @param array $change + * @return array> + */ +function alert_round(string $round, array $change, int $status = 0, int $extraWait = 0): array { + global $config, $alert_log; + + print "== round $round" . PHP_EOL; + + $alert_log = (int) db_fetch_cell('SELECT COALESCE(MAX(id), 0) FROM plugin_thold_log'); + + e2e_tool(alert_metrics($change), e2e_fixture('r580-8gpu', 'names'), $status); + + if ($extraWait > 0) { + sleep($extraWait); + } + + e2e_collect(); + + // RRDtool refuses a second update in the same second. + sleep(1); + e2e_poll(); + + // poller_bottom starts poller_thold.php in the background. Wait for it, + // then run it in the foreground: a run that finds nothing new to check + // changes nothing. + for ($i = 0; $i < 60 && (int) db_fetch_cell("SELECT COUNT(*) FROM processes WHERE tasktype = 'thold'") > 0; $i++) { + sleep(1); + } + + $output = $config['base_path'] . '/log/gpu-alert-thold.txt'; + $rc = alert_run(array(PHP_BINARY, $config['base_path'] . '/plugins/thold/poller_thold.php'), $output); + $text = (string) file_get_contents($output); + + e2e_check($rc === 0 && stripos($text, 'TypeError') === false && stripos($text, 'Fatal') === false, "$round: Thold's check ran without an error (exit $rc)"); + + if ($rc !== 0 || stripos($text, 'error') !== false) { + print ' poller_thold.php: ' . substr(preg_replace('/\s+/', ' ', $text), 0, 400) . PHP_EOL; + } + + foreach (TholdTemplateXml::templates() as $spec) { + $t = alert_thold($spec[0]); + + if ($t !== array()) { + print "EVIDENCE $round " . $spec[0] . ' alert=' . $t['thold_alert'] . ' fail_count=' . $t['thold_fail_count'] . " lastread='" . $t['lastread'] . "'" . PHP_EOL; + } + } + + return alert_logged(); +} + +/** + * Check a round: $expect is item => [breached now, statuses logged]; every + * other threshold on the node must have logged nothing. + * + * @param array> $logged + * @param array}> $expect + */ +function alert_expect(string $round, array $logged, array $expect): void { + foreach ($expect as $item => $want) { + $t = alert_thold($item); + $got = $logged[$item] ?? array(); + + e2e_check($t !== array() && ((int) $t['thold_alert'] !== 0) === $want[0] && $got === $want[1], "$round: $item " . ($want[0] ? 'breached' : 'normal') . ' with log ' . json_encode($want[1]) . ' (alert=' . ($t['thold_alert'] ?? '?') . ', fail_count=' . ($t['thold_fail_count'] ?? '?') . ', log ' . json_encode($got) . ')'); + } + + $other = array_diff_key($logged, $expect); + + e2e_check($other === array(), "$round: no other threshold logged anything" . ($other === array() ? '' : ' (' . json_encode($other) . ')')); +} + +function alert_thold_enabled(string $round): void { + // Cacti disables a plugin whose hook throws; Thold must still be on. + e2e_check(api_plugin_is_enabled('thold') && (int) db_fetch_cell("SELECT status FROM plugin_config WHERE directory = 'thold'") === 1, "$round: Thold is still enabled"); +} + +$quiet = array(); + +foreach (TholdTemplateXml::templates() as $spec) { + $quiet[$spec[0]] = array(false, array()); +} + +$mask = MetricModel::MASK_FIELD; +$uncorr = 'ecc.errors.uncorrected.volatile.total'; +$hot = array('temperature.gpu' => '95', $mask => '0x0000000000000048', $uncorr => '3', 'retired_pages.pending' => 'Yes'); + +/* Setup: the shipped Thold templates, linked to the GPU Node template. */ + +$alert_result = thold_template_import((string) file_get_contents($config['base_path'] . '/plugins/gpu/templates/' . TholdTemplateXml::FILE)); + +e2e_check(count($alert_result['success'] ?? array()) === count(TholdTemplateXml::templates()) && empty($alert_result['errors']) && empty($alert_result['failure']), 'setup: Thold imported every shipped template (' . json_encode($alert_result) . ')'); + +$alert_host_template = (new \Somethingwithproof\Gpu\CactiObjectRepository(false))->idByHash('host_template', TemplateXml::hash('02', TemplateXml::DEVICE_TEMPLATE)); + +// As Thold's Device Template page links a template (item_add_tt), with +// Thold's own setting to create thresholds for new graphs. +foreach (TholdTemplateXml::templates() as $alert_name => $spec) { + db_execute_prepared('REPLACE INTO plugin_thold_host_template (host_template_id, thold_template_id) SELECT ?, id FROM thold_template WHERE hash = ?', array($alert_host_template, TholdTemplateXml::hash($alert_name))); +} + +db_execute("REPLACE INTO settings (name, value) VALUES ('thold_autocreate', 'on')"); + +list($e2e_host, $e2e_node_id) = e2e_node('gpu-node-alert'); + +e2e_tool(alert_metrics(array()), e2e_fixture('r580-8gpu', 'names')); +e2e_collect(); + +$alert_count = (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM thold_data WHERE host_id = ?', array($e2e_host)); + +e2e_check($alert_count === 8 * count(TholdTemplateXml::templates()), "setup: Thold created the templated thresholds for each GPU's graphs ($alert_count)"); + +foreach (TholdTemplateXml::templates() as $alert_name => $spec) { + $t = alert_thold($spec[0]); + + e2e_check(($t['thold_hi'] ?? '') === $spec[1] && ($t['thold_enabled'] ?? '') === 'on' && (int) ($t['data_type'] ?? -1) === ($spec[3] === '' ? 0 : 2) && ($t['percent_ds'] ?? '') === $spec[3], "setup: '$alert_name' is on GPU 0 above " . $spec[1]); +} + +// A low staleness threshold for this test only (the template's is 900 s). +db_execute_prepared('UPDATE thold_data SET thold_hi = ? WHERE id = ?', array((string) ALERT_AGE, (int) (alert_thold('age')['id'] ?? 0))); + +// Cacti creates the RRD files in the first cycle and writes from the next. +e2e_poll(); +e2e_poll(); + +e2e_check((int) db_fetch_cell_prepared('SELECT status FROM host WHERE id = ?', array($e2e_host)) === 3, 'setup: the node device is up, so Thold checks its thresholds'); + +/* Normal values: nothing breaches, and the values Thold reads are numbers. */ + +$logged = alert_round('baseline', array()); +alert_expect('baseline', $logged, $quiet); +e2e_check(is_numeric(alert_thold('temp_gpu')['lastread'] ?? '') && is_numeric(alert_thold('age')['lastread'] ?? '') && (alert_thold('ecc_uncorr_new')['lastread'] ?? '') === '0', 'baseline: Thold read temperature, age, and zero new ECC errors'); + +/* A fault: hot, throttled by hardware, new uncorrected errors, a page pending. */ + +$logged = alert_round('fault', $hot); +alert_expect('fault', $logged, array( + 'temp_gpu' => array(true, array()), + 'thr_hw_thermal' => array(true, array(ALERT_NOTIFY)), + 'thr_hw_slowdown' => array(true, array(ALERT_NOTIFY)), + 'ecc_uncorr_new' => array(true, array(ALERT_NOTIFY)), + 'retired_pending' => array(true, array(ALERT_NOTIFY)), +) + $quiet); +e2e_check((int) (alert_thold('temp_gpu')['thold_fail_count'] ?? 0) === 1, 'fault: the temperature breach waits for its second poll'); + +/* The fault holds; no new errors, so the ECC alert recovers. */ + +$logged = alert_round('fault2', $hot); +alert_expect('fault2', $logged, array( + 'temp_gpu' => array(true, array(ALERT_NOTIFY)), + 'thr_hw_thermal' => array(true, array()), + 'thr_hw_slowdown' => array(true, array()), + 'ecc_uncorr_new' => array(false, array(ALERT_RESTORE)), + 'retired_pending' => array(true, array()), +) + $quiet); + +/* Driver reload: the volatile total falls to 0, so the delta is unknown. */ + +$logged = alert_round('reset', array($uncorr => '0')); +alert_expect('reset', $logged, array( + 'temp_gpu' => array(false, array(ALERT_RESTORE)), + 'thr_hw_thermal' => array(false, array(ALERT_RESTORE)), + 'thr_hw_slowdown' => array(false, array(ALERT_RESTORE)), + 'retired_pending' => array(false, array(ALERT_RESTORE)), +) + $quiet); +e2e_check(!is_numeric(alert_thold('ecc_uncorr_new')['lastread'] ?? '0') && e2e_ss($e2e_host, 'get', 'ecc_uncorr_new', e2e_key(1)) === 'U', 'reset: the new-error count is unknown after the total fell, and Thold reads no number'); +alert_thold_enabled('reset'); + +/* New errors after the reset fire again, and recover. */ + +$logged = alert_round('after reset', array($uncorr => '2')); +alert_expect('after reset', $logged, array('ecc_uncorr_new' => array(true, array(ALERT_NOTIFY))) + $quiet); +e2e_check((alert_thold('ecc_uncorr_new')['lastread'] ?? '') === '2', 'after reset: Thold read the two errors counted since the reset'); + +$logged = alert_round('recovered', array($uncorr => '2')); +alert_expect('recovered', $logged, array('ecc_uncorr_new' => array(false, array(ALERT_RESTORE))) + $quiet); +alert_thold_enabled('recovered'); + +/* The tool fails: every value is unknown and breaches nothing; age alerts. */ + +$logged = alert_round('silent', array(), 9, 15); +alert_expect('silent', $logged, array('age' => array(true, array(ALERT_NOTIFY))) + $quiet); +e2e_check(is_numeric(alert_thold('age')['lastread'] ?? '') && !is_numeric(alert_thold('temp_gpu')['lastread'] ?? '0'), 'silent: age stays numeric while every other value is unknown (REQ-ALERT-002)'); + +$logged = alert_round('answering', array()); +alert_expect('answering', $logged, array('age' => array(false, array(ALERT_RESTORE))) + $quiet); + +/* Maint: a one-off schedule on the node's device, as Maint's page saves it. */ + +db_execute_prepared("INSERT INTO plugin_maint_schedules (enabled, name, mtype, stime, etime, minterval) VALUES ('on', 'gpu alert test', 1, ?, ?, 0)", array(time() - 60, time() + 3600)); +$alert_schedule = (int) db_fetch_insert_id(); +db_execute_prepared('INSERT INTO plugin_maint_hosts (type, host, schedule) VALUES (1, ?, ?)', array($e2e_host, $alert_schedule)); + +e2e_check(plugin_maint_check_cacti_host($e2e_host), 'maint: Maint reports the node device in maintenance'); + +foreach (array('maint', 'maint2') as $alert_round_name) { + $logged = alert_round($alert_round_name, array('temperature.gpu' => '95')); + $t = alert_thold('temp_gpu'); + $rrd = e2e_rrd((int) db_fetch_cell_prepared('SELECT local_data_id FROM thold_data WHERE id = ?', array((int) ($t['id'] ?? 0)))); + + e2e_check((int) ($t['thold_fail_count'] ?? -1) === 0 && ($logged['temp_gpu'] ?? array()) === array() && ($rrd['temp_gpu'] ?? '') === '95', "$alert_round_name: in maintenance the breach is neither counted nor notified, while the RRD file records 95 (fail_count=" . ($t['thold_fail_count'] ?? '?') . ')'); + alert_expect($alert_round_name, $logged, array('temp_gpu' => array(true, array())) + $quiet); +} + +db_execute_prepared('DELETE FROM plugin_maint_hosts WHERE schedule = ?', array($alert_schedule)); +db_execute_prepared('DELETE FROM plugin_maint_schedules WHERE id = ?', array($alert_schedule)); + +e2e_check(!plugin_maint_check_cacti_host($e2e_host), 'unmaint: the node device is out of maintenance'); + +$logged = alert_round('unmaint', array('temperature.gpu' => '95')); +alert_expect('unmaint', $logged, array('temp_gpu' => array(true, array())) + $quiet); +e2e_check((int) (alert_thold('temp_gpu')['thold_fail_count'] ?? 0) === 1, 'unmaint: out of maintenance the breach counts again'); + +$logged = alert_round('unmaint2', array('temperature.gpu' => '95')); +alert_expect('unmaint2', $logged, array('temp_gpu' => array(true, array(ALERT_NOTIFY))) + $quiet); + +$logged = alert_round('final', array()); +alert_expect('final', $logged, array('temp_gpu' => array(false, array(ALERT_RESTORE))) + $quiet); +alert_thold_enabled('final'); + +print ($e2e_failures === 0 ? 'alert flow ok' : "alert flow: $e2e_failures failed") . PHP_EOL; + +exit($e2e_failures === 0 ? 0 : 1); diff --git a/tests/bin/e2e-lib.php b/tests/bin/e2e-lib.php new file mode 100644 index 0000000..369778c --- /dev/null +++ b/tests/bin/e2e-lib.php @@ -0,0 +1,242 @@ + + * 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. + */ + +/* + * Helpers shared by the end-to-end runs against a real snmpd (e2e.php, + * alert-flow.php, failure-flow.php, restore-flow.php, scale-flow.php). Each + * run includes this file from the Cacti root; see e2e.php for the + * environment. Must parse on PHP 8.0. + */ + +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); +} + +const E2E_CACHE_WAIT = 32; + +$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(',', \Somethingwithproof\Gpu\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); +} + +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 { + return e2e_rrd_file((string) get_data_source_path($local_data_id, true)); +} + +/** + * The last values written to an RRD file, by path. + * + * @return array + */ +function e2e_rrd_file(string $path): array { + + 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', \Somethingwithproof\Gpu\TemplateXml::hash('02', \Somethingwithproof\Gpu\TemplateXml::DEVICE_TEMPLATE)); + + e2e_check($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. + $avail = function_exists('snmp_format_agent') && (int) $e2e_agent[1] !== 161 ? AVAIL_NONE : AVAIL_SNMP; + + $host = (int) api_device_save(0, $template, $description, $e2e_agent[0], '', 3, 'cactigpu', $e2e_secrets[0], (int) $e2e_agent[1], 1000, '', + $avail, 1, 23, 400, 1, '', 'SHA256', $e2e_secrets[1], 'AES128', '', '', 10, 1, 1, 0); + + e2e_check($host > 0, 'the node device was created through api_device_save()'); + + // Earlier CI steps leave nodes on unreachable test devices; only this + // run's node is collected, so the statistics are its own. + db_execute("UPDATE plugin_gpu_node SET admin_state = 'disabled'"); + + $nodeId = gpu_nodes()->save(0, $host, \Somethingwithproof\Gpu\AdminState::Enabled); + $node = gpu_nodes()->find($nodeId); + + e2e_check($node !== null && gpu_provisioner()->attach($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($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. + $device = $node !== null ? gpu_nodes()->device($node) : null; + $ready = false; + + for ($i = 0; $i < 30 && $device !== null && !$ready; $i++) { + $uptime = (new \Somethingwithproof\Gpu\SnmpExtendReader(0))->value($device, '.1.3.6.1.2.1.1.3.0', 1000); + $ready = $uptime !== '' && $uptime !== 'U'; + + if (!$ready) { + sleep(1); + } + } + + e2e_check($ready, 'the agent answers over SNMPv3'); + + if (!$ready) { + print "e2e: the agent never answered; see snmpd's log\n"; + exit(1); + } + + return array($host, $nodeId); +} diff --git a/tests/bin/e2e.php b/tests/bin/e2e.php index e2850b6..58877b9 100644 --- a/tests/bin/e2e.php +++ b/tests/bin/e2e.php @@ -38,118 +38,13 @@ * 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); -} +require(__DIR__ . '/e2e-lib.php'); 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 */ @@ -168,97 +63,11 @@ function e2e_state(int $host): array { ); } -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); -} +list($e2e_host, $e2e_node_id) = e2e_node('gpu-node-e2e'); /* Boot: eight GPUs. */ From 1e782458898f555994cfa9860f5cfe2365be91d8 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 12:30:37 -0800 Subject: [PATCH 04/18] feat(health): add the GPU Health page and widen the permission suite (#47, #48) GPU Health, under the GPU View realm, lists each node a viewer may see: freshness of its newest sample against the poller interval, how its latest collection ended (completed, tool error, permission denied, timed out, or unknown, with the stored detail bounded and stripped of control characters), runs skipped while another run held the node, whether Maint holds its device, its backend, tool, and driver versions, and its GPU counts. Each GPU row shows presence, sample freshness, the ECC state or the reason ECC values are unknown, and the raw clock event mask with any bits that have no indicator. A sample stamped further ahead of Cacti's clock than skew explains reads as ahead, not current. The page reads stored records only; a source rule keeps SNMP, collectors, and sleeps out of it, and another keeps any outbound notification out of the plugin. The permission suite covers the new page for every user, revocation of a device or of the realm on the next request, refusals that name nothing about a hidden node, and escaping on both View pages. The lifecycle test reads the schema version from the code and covers the version 2 upgrade. Signed-off-by: Thomas Vincent --- gpu_health.php | 50 +++++ lib/ExecutionState.php | 16 ++ lib/FreshnessState.php | 64 +++++++ lib/HealthPage.php | 275 ++++++++++++++++++++++++++++ lib/ObservationRepository.php | 18 ++ lib/Pages.php | 3 +- lib/ThrottleMask.php | 16 ++ locales/po/cacti.pot | 219 ++++++++++++++++------ setup.php | 17 ++ tests/Integration/LifecycleTest.php | 32 +++- tests/Security/SourceRulesTest.php | 32 ++++ tests/Unit/HealthPageTest.php | 159 ++++++++++++++++ tests/bin/lifecycle.php | 13 ++ tests/bin/page-permissions.php | 58 ++++-- 14 files changed, 904 insertions(+), 68 deletions(-) create mode 100644 gpu_health.php create mode 100644 lib/FreshnessState.php create mode 100644 lib/HealthPage.php create mode 100644 tests/Unit/HealthPageTest.php diff --git a/gpu_health.php b/gpu_health.php new file mode 100644 index 0000000..840aad4 --- /dev/null +++ b/gpu_health.php @@ -0,0 +1,50 @@ + + * 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. + */ + +/* + * GPU Health (GPU View realm). Parses on PHP 8.0; gpu_page_start() + * refuses an unsupported runtime before any plugin class loads. The page + * reads stored records only and never contacts a node. + */ + +chdir('../../'); +include('./include/auth.php'); +include_once('./plugins/gpu/setup.php'); + +if (!gpu_page_start()) { + exit; +} + +$gpu_page = new \Somethingwithproof\Gpu\HealthPage( + gpu_nodes(), + gpu_gpus(), + new \Somethingwithproof\Gpu\CollectionRepository(false), + new \Somethingwithproof\Gpu\ObservationRepository(false), + function ($host_id) { + return is_device_allowed($host_id); + }, + Closure::fromCallable('gpu_in_maintenance'), + new \Somethingwithproof\Gpu\SystemClock(), + max(10, (int) read_config_option('poller_interval')), + gpu_settings()->staleAfter +); + +top_header(); +$gpu_page->render(); +bottom_footer(); diff --git a/lib/ExecutionState.php b/lib/ExecutionState.php index 20869a3..e65f6be 100644 --- a/lib/ExecutionState.php +++ b/lib/ExecutionState.php @@ -65,6 +65,22 @@ public static function fromExitStatus(int $status): self { }; } + /** + * The outcome the health page names (REQ-HEALTH-002): completed, tool + * error, permission denied, timed out, or unknown. Every failure that is + * not a permission or a timeout is a tool error, with label() saying + * which; a skipped run says nothing about the node, so it is unknown. + */ + public function outcome(): string { + return match ($this) { + self::Ok, self::Empty => __('Completed', 'gpu'), + self::PermissionDenied => __('Permission denied', 'gpu'), + self::TimedOut => __('Timed out', 'gpu'), + self::Skipped => __('Unknown', 'gpu'), + default => __('Tool error', 'gpu'), + }; + } + public function label(): string { return match ($this) { self::Ok => __('Collected', 'gpu'), diff --git a/lib/FreshnessState.php b/lib/FreshnessState.php new file mode 100644 index 0000000..080fd8f --- /dev/null +++ b/lib/FreshnessState.php @@ -0,0 +1,64 @@ + + * 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 recent a node's or GPU's newest sample is, against the interval it + * is expected at (REQ-HEALTH-001). The page refresh time never counts. + */ +enum FreshnessState: string { + case Current = 'current'; + case Delayed = 'delayed'; + case Stale = 'stale'; + case Never = 'never'; + case Ahead = 'ahead'; + + /** + * Current while the sample is at most one and a half intervals old (one + * interval plus the drift between Cacti's poll and the collection), + * delayed after that, and stale once it is too old to graph, which is + * when the script server input starts printing U (Freshness). A sample + * stamped further ahead of Cacti's clock than skew explains is ahead: + * its values print U, so it must not read as current. + */ + public static function of(int $observedAt, int $now, int $interval, int $staleAfter): self { + if ($observedAt <= 0) { + return self::Never; + } + + $age = $now - $observedAt; + + return match (true) { + $age < -Freshness::SKEW_ALLOWANCE => self::Ahead, + $age <= min(intdiv(max(1, $interval) * 3, 2), $staleAfter) => self::Current, + $age <= $staleAfter => self::Delayed, + default => self::Stale, + }; + } + + public function label(): string { + return match ($this) { + self::Current => __('Current', 'gpu'), + self::Delayed => __('Delayed', 'gpu'), + self::Stale => __('Stale', 'gpu'), + self::Never => __('Never observed', 'gpu'), + self::Ahead => __('Ahead of the Cacti server\'s clock', 'gpu'), + }; + } +} diff --git a/lib/HealthPage.php b/lib/HealthPage.php new file mode 100644 index 0000000..cf6000d --- /dev/null +++ b/lib/HealthPage.php @@ -0,0 +1,275 @@ + + * 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 Health page (GPU View): the measurement state of each node and + * GPU the viewer may see (PLAN, Measurement state; REQ-HEALTH-001 to + * REQ-HEALTH-005). + * + * It reads stored records only. Rendering it never runs a tool, contacts a + * node, or waits for one (REQ-HEALTH-003, REQ-PERF-002); a static rule in + * tests/Security keeps it that way. Every stored string is escaped where it + * is printed, and the collection detail is bounded and stripped of control + * characters first, although it never holds tool output (CollectionError). + */ +final class HealthPage { + public const FILE = 'gpu_health.php'; + + // The longest collection detail the page prints, in characters. + public const DETAIL_LIMIT = 200; + + /** + * @param \Closure(int): bool $deviceAllowed Cacti's device permission check for the viewer + * @param \Closure(int): ?bool $inMaintenance whether Maint holds a device in maintenance, null without Maint + * @param int $interval the expected collection interval in seconds (Cacti's poller interval) + */ + public function __construct( + private readonly NodeRepository $nodes, + private readonly GpuRepository $gpus, + private readonly CollectionRepository $collections, + private readonly ObservationRepository $observations, + private readonly \Closure $deviceAllowed, + private readonly \Closure $inMaintenance, + private readonly Clock $clock, + private readonly int $interval, + private readonly int $staleAfter, + ) { + } + + public function render(): void { + $nodes = []; + + foreach ($this->nodes->all() as $node) { + if (($this->deviceAllowed)($node->hostId)) { + $nodes[$node->id] = $node; + } + } + + $retired = array_flip($this->gpus->retiredIds()); + $byNode = []; + + foreach ($this->gpus->all() as $gpu) { + if (isset($nodes[$gpu->nodeId]) && !isset($retired[$gpu->id])) { + $byNode[$gpu->nodeId][] = $gpu; + } + } + + $samples = $nodes === [] ? [] : $this->observations->summaries(); + + $headers = [__('Node', 'gpu'), __('Admin State', 'gpu'), __('Freshness', 'gpu'), __('Last Collection', 'gpu'), __('Maintenance', 'gpu'), __('Backend', 'gpu'), __('Tool', 'gpu'), __('Driver', 'gpu'), __('GPUs', 'gpu')]; + + html_start_box(__('GPU Node Health', 'gpu'), '100%', '', '3', 'center', ''); + print $this->header($headers); + + foreach ($nodes as $node) { + print $this->line($this->nodeRow($node, $this->collections->find($node->id), $byNode[$node->id] ?? [], $samples)); + } + + if ($nodes === []) { + print $this->empty(count($headers), __('No GPU nodes you may see.', 'gpu')); + } + + html_end_box(); + + $headers = [__('Node', 'gpu'), __('Index', 'gpu'), __('Name', 'gpu'), __('UUID', 'gpu'), __('State', 'gpu'), __('Sample', 'gpu'), __('ECC', 'gpu'), __('Clock Event Reasons', 'gpu')]; + + html_start_box(__('GPU Health', 'gpu'), '100%', '', '3', 'center', ''); + print $this->header($headers); + + $shown = 0; + + foreach ($byNode as $nodeId => $gpus) { + foreach ($gpus as $gpu) { + print $this->line($this->gpuRow($gpu, $nodes[$nodeId], $samples[$gpu->id] ?? null)); + $shown++; + } + } + + if ($shown === 0) { + print $this->empty(count($headers), __('No GPUs recorded yet. GPUs appear here once a node\'s collection reports them.', 'gpu')); + } + + html_end_box(); + } + + /** + * One node's cells, as plain text. + * + * @param list $gpus the node's GPU records, retired ones left out + * @param array> $samples ObservationRepository::summaries() + * @return list + */ + public function nodeRow(Node $node, ?CollectionStatus $status, array $gpus, array $samples): array { + $present = 0; + $replaced = 0; + $backends = []; + $newest = $status === null ? 0 : $status->observedAt; + + foreach ($gpus as $gpu) { + $present += $gpu->presence === Presence::Present ? 1 : 0; + $replaced += $gpu->possibleReplacement() ? 1 : 0; + $sample = $samples[$gpu->id] ?? null; + + if ($sample !== null) { + $backends[] = Row::string($sample, 'backend'); + $newest = max($newest, Row::int($sample, 'observed_at', 0, 0)); + } + } + + $maintenance = ($this->inMaintenance)($node->hostId); + + return [ + $node->description, + $node->enabled() ? __('Enabled', 'gpu') : __('Disabled', 'gpu'), + $this->freshness($newest), + $this->collection($status), + $maintenance === null ? __('Maint not installed', 'gpu') : ($maintenance ? __('In maintenance', 'gpu') : __('Not in maintenance', 'gpu')), + self::distinct($backends), + self::distinct(array_map(static fn (GpuRecord $gpu): string => trim($gpu->tool . ' ' . $gpu->toolVersion), $gpus)), + self::distinct(array_map(static fn (GpuRecord $gpu): string => $gpu->driverVersion, $gpus)), + __('%d present, %d absent, %d possible replacements', $present, count($gpus) - $present, $replaced, 'gpu'), + ]; + } + + /** + * One GPU's cells, as plain text. + * + * @param array|null $sample its row of ObservationRepository::summaries() + * @return list + */ + public function gpuRow(GpuRecord $gpu, Node $node, ?array $sample): array { + $state = [$gpu->presence === Presence::Present ? __('Present', 'gpu') : __('Absent', 'gpu')]; + + if ($gpu->possibleReplacement()) { + $state[] = __('possible replacement of GPU record %d', $gpu->replacesGpuId, 'gpu'); + } + + if ($sample === null) { + return [$node->description, self::index($gpu), $gpu->name, $gpu->uuid, implode('; ', $state), FreshnessState::Never->label(), '-', '-']; + } + + $ecc = EccMode::tryFrom(Row::string($sample, 'ecc_mode')) ?? EccMode::Unknown; + $mask = $sample['thr_mask'] ?? null; + + return [ + $node->description, + self::index($gpu), + $gpu->name, + $gpu->uuid, + implode('; ', $state), + $this->freshness(Row::int($sample, 'observed_at', 0, 0)), + $ecc === EccMode::Enabled ? __('Enabled', 'gpu') : $ecc->reason(), + ThrottleMask::describe($mask === null || $mask === '' ? null : Row::int($sample, 'thr_mask', 0, 0)), + ]; + } + + /** + * How the node's latest collection ended (REQ-HEALTH-002): one of + * completed, tool error, permission denied, timed out, or unknown, then + * the state and its bounded detail. + */ + public function collection(?CollectionStatus $status): string { + if ($status === null || $status->state === null) { + return __('Unknown: not collected yet', 'gpu'); + } + + $outcome = $status->state->outcome(); + $label = $status->state->label(); + $text = $outcome === $label ? $outcome : $outcome . ': ' . $label; + + if ($status->succeeded()) { + $text .= ', ' . __('%d GPUs', $status->gpus, 'gpu'); + } elseif ($status->detail !== '') { + $text .= ': ' . self::detail($status->detail); + } + + if ($status->finishedAt > 0) { + $text .= ' (' . self::ago(max(0, $this->clock->now() - $status->finishedAt)) . ')'; + } + + if (!$status->succeeded() && $status->lastOkAt > 0) { + $text .= '; ' . __('last completed %s', self::ago(max(0, $this->clock->now() - $status->lastOkAt)), 'gpu'); + } + + // A run that finds the node held by another run skips it and records + // nothing else, so this count is the only trace (REQ-PERF-003). + if ($status->skipped > 0) { + $text .= '; ' . __('%d later runs skipped while another run held the node', $status->skipped, 'gpu'); + } + + return $text; + } + + /** + * Detail text made safe to print: control characters become spaces and + * the text is cut at DETAIL_LIMIT characters. + */ + public static function detail(string $text): string { + $text = trim((string) preg_replace('/[\x00-\x1F\x7F]+/u', ' ', $text)); + + return mb_strlen($text) > self::DETAIL_LIMIT ? mb_substr($text, 0, self::DETAIL_LIMIT - 3) . '...' : $text; + } + + private function freshness(int $observedAt): string { + $state = FreshnessState::of($observedAt, $this->clock->now(), $this->interval, $this->staleAfter); + + return $state === FreshnessState::Never || $state === FreshnessState::Ahead ? $state->label() : $state->label() . ' (' . self::ago(max(0, $this->clock->now() - $observedAt)) . ')'; + } + + private static function ago(int $seconds): string { + return match (true) { + $seconds < 120 => __('%d seconds ago', $seconds, 'gpu'), + $seconds < 7200 => __('%d minutes ago', intdiv($seconds, 60), 'gpu'), + $seconds < 172800 => __('%d hours ago', intdiv($seconds, 3600), 'gpu'), + default => __('%d days ago', intdiv($seconds, 86400), 'gpu'), + }; + } + + private static function index(GpuRecord $gpu): string { + return $gpu->index === null ? '-' : (string) $gpu->index; + } + + /** + * @param list $values + */ + private static function distinct(array $values): string { + $values = array_values(array_unique(array_filter($values, static fn (string $value): bool => $value !== ''))); + + return $values === [] ? '-' : implode(', ', $values); + } + + /** + * @param list $cells + */ + private function header(array $cells): string { + return '
' . implode('', array_map('html_escape', $cells)) . '
'; + } + + /** + * @param list $cells + */ + private function line(array $cells): string { + return '
' . implode('', array_map('html_escape', $cells)) . '
'; + } + + private function empty(int $columns, string $text): string { + return '
' . html_escape($text) . ''; + } +} diff --git a/lib/ObservationRepository.php b/lib/ObservationRepository.php index 9ee9319..4e49738 100644 --- a/lib/ObservationRepository.php +++ b/lib/ObservationRepository.php @@ -26,6 +26,24 @@ final class ObservationRepository { public function __construct(private readonly \PDO|false $connection) { } + /** + * What the health page shows of each GPU's latest sample, by GPU record + * id: when it was taken, by which backend and tool version, the raw + * clock event mask, and the ECC mode. One query for every GPU. + * + * @return array> + */ + public function summaries(): array { + $rows = db_fetch_assoc_prepared('SELECT gpu_id, observed_at, backend, tool_version, thr_mask, ecc_mode FROM plugin_gpu_observation', [], true, $this->connection); + $out = []; + + foreach (is_array($rows) ? Row::rows($rows) : [] as $row) { + $out[Row::int($row, 'gpu_id')] = $row; + } + + return $out; + } + /** * 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 diff --git a/lib/Pages.php b/lib/Pages.php index 8a8cc44..718ceb4 100644 --- a/lib/Pages.php +++ b/lib/Pages.php @@ -28,7 +28,7 @@ * Admin pages; GPU View pages only read. */ final class Pages { - public const VIEW = ['gpu_inventory.php']; + public const VIEW = ['gpu_inventory.php', 'gpu_health.php']; public const ADMIN = ['gpu_nodes.php']; /** @@ -57,6 +57,7 @@ public static function menu(): array { return [ 'gpu_nodes.php' => __('GPU Nodes', 'gpu'), 'gpu_inventory.php' => __('GPU Inventory', 'gpu'), + 'gpu_health.php' => __('GPU Health', 'gpu'), ]; } diff --git a/lib/ThrottleMask.php b/lib/ThrottleMask.php index cc779a0..192dd12 100644 --- a/lib/ThrottleMask.php +++ b/lib/ThrottleMask.php @@ -57,4 +57,20 @@ public static function indicators(?int $mask): array { return $out; } + + /** + * The raw mask as the health page shows it: 16 hexadecimal digits, and + * the bits that have no indicator, so a reason the decoder does not know + * stays visible (REQ-THR-005). + */ + public static function describe(?int $mask): string { + if ($mask === null) { + return __('Unknown', 'gpu'); + } + + $text = sprintf('0x%016X', $mask); + $other = $mask & ~array_sum(MetricModel::BITS); + + return $other === 0 ? $text : $text . '; ' . __('bits without an indicator: %s', sprintf('0x%X', $other), 'gpu'); + } } diff --git a/locales/po/cacti.pot b/locales/po/cacti.pot index 883e812..69e4d7b 100644 --- a/locales/po/cacti.pot +++ b/locales/po/cacti.pot @@ -109,39 +109,47 @@ msgid "ECC mode not reported" msgstr "" #: lib/ExecutionState.php -msgid "Collected" +msgid "Completed" msgstr "" #: lib/ExecutionState.php -msgid "No GPUs reported" +msgid "Permission denied" msgstr "" #: lib/ExecutionState.php -msgid "SNMP agent unreachable" +msgid "Timed out" +msgstr "" + +#: lib/ExecutionState.php lib/ThrottleMask.php +msgid "Unknown" msgstr "" #: lib/ExecutionState.php -msgid "Extend entry missing" +msgid "Tool error" msgstr "" #: lib/ExecutionState.php -msgid "Timed out" +msgid "Collected" msgstr "" #: lib/ExecutionState.php -msgid "Permission denied" +msgid "No GPUs reported" msgstr "" #: lib/ExecutionState.php -msgid "Driver not loaded" +msgid "SNMP agent unreachable" msgstr "" #: lib/ExecutionState.php -msgid "Tool not found" +msgid "Extend entry missing" msgstr "" #: lib/ExecutionState.php -msgid "Tool error" +msgid "Driver not loaded" +msgstr "" + +#: lib/ExecutionState.php +msgid "Tool not found" msgstr "" #: lib/ExecutionState.php @@ -160,96 +168,212 @@ msgstr "" msgid "Result not stored" msgstr "" -#: lib/InventoryPage.php +#: lib/FreshnessState.php +msgid "Current" +msgstr "" + +#: lib/FreshnessState.php +msgid "Delayed" +msgstr "" + +#: lib/FreshnessState.php +msgid "Stale" +msgstr "" + +#: lib/FreshnessState.php +msgid "Never observed" +msgstr "" + +#: lib/FreshnessState.php +msgid "Ahead of the Cacti server's clock" +msgstr "" + +#: lib/HealthPage.php +msgid "Admin State" +msgstr "" + +#: lib/HealthPage.php +msgid "Backend" +msgstr "" + +#: lib/HealthPage.php lib/InventoryPage.php msgid "Driver" msgstr "" -#: lib/InventoryPage.php -msgid "Index" +#: lib/HealthPage.php +msgid "Freshness" msgstr "" -#: lib/InventoryPage.php lib/NodesPage.php -msgid "Last Seen" +#: lib/HealthPage.php +msgid "GPUs" msgstr "" -#: lib/InventoryPage.php lib/NodesPage.php -msgid "Name" +#: lib/HealthPage.php lib/NodesPage.php +msgid "Last Collection" msgstr "" -#: lib/InventoryPage.php +#: lib/HealthPage.php +msgid "Maintenance" +msgstr "" + +#: lib/HealthPage.php lib/InventoryPage.php msgid "Node" msgstr "" -#: lib/InventoryPage.php -msgid "PCI Bus ID" +#: lib/HealthPage.php +msgid "Tool" msgstr "" -#: lib/InventoryPage.php -msgid "Reported By" +#: lib/HealthPage.php +msgid "GPU Node Health" msgstr "" -#: lib/InventoryPage.php lib/NodesPage.php +#: lib/HealthPage.php +msgid "No GPU nodes you may see." +msgstr "" + +#: lib/HealthPage.php +msgid "Clock Event Reasons" +msgstr "" + +#: lib/HealthPage.php +msgid "ECC" +msgstr "" + +#: lib/HealthPage.php lib/InventoryPage.php +msgid "Index" +msgstr "" + +#: lib/HealthPage.php lib/InventoryPage.php lib/NodesPage.php +msgid "Name" +msgstr "" + +#: lib/HealthPage.php +msgid "Sample" +msgstr "" + +#: lib/HealthPage.php lib/InventoryPage.php lib/NodesPage.php msgid "State" msgstr "" -#: lib/InventoryPage.php lib/NodesPage.php +#: lib/HealthPage.php lib/InventoryPage.php lib/NodesPage.php msgid "UUID" msgstr "" -#: lib/InventoryPage.php lib/Pages.php -msgid "GPU Inventory" +#: lib/HealthPage.php lib/Pages.php +msgid "GPU Health" msgstr "" -#: lib/InventoryPage.php +#: lib/HealthPage.php lib/InventoryPage.php msgid "No GPUs recorded yet. GPUs appear here once a node's collection reports them." msgstr "" -#: lib/InventoryPage.php +#: lib/HealthPage.php lib/NodesPage.php +msgid "Disabled" +msgstr "" + +#: lib/HealthPage.php lib/NodesPage.php +msgid "Enabled" +msgstr "" + +#: lib/HealthPage.php +msgid "In maintenance" +msgstr "" + +#: lib/HealthPage.php +msgid "Maint not installed" +msgstr "" + +#: lib/HealthPage.php +msgid "Not in maintenance" +msgstr "" + +#: lib/HealthPage.php +#, php-format +msgid "%d present, %d absent, %d possible replacements" +msgstr "" + +#: lib/HealthPage.php lib/InventoryPage.php msgid "Absent" msgstr "" -#: lib/InventoryPage.php +#: lib/HealthPage.php lib/InventoryPage.php msgid "Present" msgstr "" -#: lib/InventoryPage.php +#: lib/HealthPage.php lib/InventoryPage.php #, php-format msgid "possible replacement of GPU record %d" msgstr "" -#: lib/InventoryPage.php +#: lib/HealthPage.php +msgid "Unknown: not collected yet" +msgstr "" + +#: lib/HealthPage.php #, php-format -msgid "seen at %s, move not confirmed" +msgid "%d GPUs" msgstr "" -#: lib/InventoryPage.php -msgid "seen at another node, move not confirmed" +#: lib/HealthPage.php +#, php-format +msgid "last completed %s" msgstr "" -#: lib/InventoryPage.php -msgid "Never" +#: lib/HealthPage.php +#, php-format +msgid "%d later runs skipped while another run held the node" msgstr "" -#: lib/InventoryPage.php +#: lib/HealthPage.php lib/InventoryPage.php #, php-format msgid "%d seconds ago" msgstr "" -#: lib/InventoryPage.php +#: lib/HealthPage.php lib/InventoryPage.php #, php-format msgid "%d minutes ago" msgstr "" -#: lib/InventoryPage.php +#: lib/HealthPage.php lib/InventoryPage.php #, php-format msgid "%d hours ago" msgstr "" -#: lib/InventoryPage.php +#: lib/HealthPage.php lib/InventoryPage.php #, php-format msgid "%d days ago" msgstr "" +#: lib/InventoryPage.php lib/NodesPage.php +msgid "Last Seen" +msgstr "" + +#: lib/InventoryPage.php +msgid "PCI Bus ID" +msgstr "" + +#: lib/InventoryPage.php +msgid "Reported By" +msgstr "" + +#: lib/InventoryPage.php lib/Pages.php +msgid "GPU Inventory" +msgstr "" + +#: lib/InventoryPage.php +#, php-format +msgid "seen at %s, move not confirmed" +msgstr "" + +#: lib/InventoryPage.php +msgid "seen at another node, move not confirmed" +msgstr "" + +#: lib/InventoryPage.php +msgid "Never" +msgstr "" + #: lib/NodesPage.php lib/Pages.php msgid "GPU Nodes" msgstr "" @@ -270,10 +394,6 @@ 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 "" @@ -283,14 +403,6 @@ msgstr "" msgid "Deleted device %d" msgstr "" -#: lib/NodesPage.php -msgid "Disabled" -msgstr "" - -#: lib/NodesPage.php -msgid "Enabled" -msgstr "" - #: lib/NodesPage.php msgid "Delete" msgstr "" @@ -453,6 +565,11 @@ msgstr "" msgid "When checked, uninstalling the plugin keeps its node and GPU records. Clear it to have the uninstall drop them; export them first from GPU Nodes. Cacti devices, data sources, graphs, and RRD files are never touched either way." msgstr "" +#: lib/ThrottleMask.php +#, php-format +msgid "bits without an indicator: %s" +msgstr "" + #: setup.php #, php-format msgid "The GPU plugin requires PHP %s or later. This server runs PHP %s, so the plugin was not installed or enabled." diff --git a/setup.php b/setup.php index e458144..cadffd4 100644 --- a/setup.php +++ b/setup.php @@ -350,6 +350,23 @@ function gpu_remove_device(int $id): void { api_device_remove($id); } +/** + * Whether Maint holds a device in maintenance, or null when Maint is not + * enabled. It asks Maint's own check, guarded, because core has no caller + * of the is_device_in_maintenance hook (PLAN, Measurement state). + */ +function gpu_in_maintenance(int $host_id): ?bool { + global $config; + + if (!api_plugin_is_enabled('maint') || !is_file($config['base_path'] . '/plugins/maint/functions.php')) { + return null; + } + + include_once($config['base_path'] . '/plugins/maint/functions.php'); + + return function_exists('plugin_maint_check_cacti_host') ? (bool) plugin_maint_check_cacti_host($host_id) : null; +} + /** * poller_bottom hook: start the collector in the background once the * poller cycle has finished. The collector reads the GPU nodes; the poller diff --git a/tests/Integration/LifecycleTest.php b/tests/Integration/LifecycleTest.php index 972fc69..70db98b 100644 --- a/tests/Integration/LifecycleTest.php +++ b/tests/Integration/LifecycleTest.php @@ -20,6 +20,10 @@ // 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'] ?? '')); +// The schema version the code migrates to (Schema::VERSION); nothing from +// the plugin is loaded in this process. +define('GPU_SCHEMA', preg_match('/const VERSION\s*=\s*(\d+);/', (string) file_get_contents(dirname(__DIR__, 2) . '/lib/Schema.php'), $gpu_schema) === 1 ? $gpu_schema[1] : ''); + const GPU_TABLES = ['plugin_gpu_collection', 'plugin_gpu_gpu', 'plugin_gpu_node', 'plugin_gpu_observation', 'plugin_gpu_reindex', 'plugin_gpu_retired']; // Row counts after the seed action: one node and one GPU record. @@ -40,12 +44,12 @@ expect($state['plugin']['status'])->toEqual('4') ->and($state['plugin']['version'])->toEqual(GPU_VERSION) - ->and($state['schema'])->toEqual('2') + ->and($state['schema'])->toEqual(GPU_SCHEMA) ->and(array_keys($state['tables']))->toBe(GPU_TABLES) ->and($state['tracked'])->toBe(GPU_TABLES) ->and(array_keys($state['hooks']))->toBe(GPU_HOOKS) ->and($state['realms'])->toEqual([ - 'gpu_inventory.php' => 'GPU View', + 'gpu_inventory.php,gpu_health.php' => 'GPU View', 'gpu_nodes.php' => 'GPU Admin', ]) ->and($state['admin'])->toBe(2); @@ -137,7 +141,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('2') + ->and($state['schema'])->toEqual(GPU_SCHEMA) ->and($state['plugin']['version'])->toEqual(GPU_VERSION); }); @@ -150,7 +154,7 @@ ->and($stopped['schema'])->toEqual('0'); $finished = lifecycle('upgrade'); - expect($finished['schema'])->toEqual('2'); + expect($finished['schema'])->toEqual(GPU_SCHEMA); }); it('upgrades a version 1 schema by adding the collection tables and keeping the records', function () { @@ -166,12 +170,30 @@ $state = lifecycle('upgrade'); expect($state['result'])->toBeTrue() - ->and($state['schema'])->toEqual('2') + ->and($state['schema'])->toEqual(GPU_SCHEMA) ->and(array_keys($state['tables']))->toBe(GPU_TABLES) ->and($state['tracked'])->toBe(GPU_TABLES) ->and($state['tables']['plugin_gpu_node'])->toBe(1); }); +it('upgrades a version 2 schema by adding the ECC columns and keeping the stored sample', function () { + lifecycle('install'); + lifecycle('seed'); + lifecycle('drop_columns'); + lifecycle('set_schema', '2'); + + $state = lifecycle('upgrade'); + + expect($state['result'])->toBeTrue() + ->and($state['schema'])->toEqual(GPU_SCHEMA) + ->and($state['observation_columns'])->toContain('ecc_corr_new') + ->and($state['observation_columns'])->toContain('ecc_uncorr_new') + ->and($state['observation_columns'])->toContain('retired_sbe') + ->and($state['observation_columns'])->toContain('retired_dbe') + ->and($state['observation_columns'])->toContain('ecc_mode') + ->and($state['tables']['plugin_gpu_observation'])->toBe(1); +}); + it('refuses a schema newer than the code and leaves the recorded version alone', function () { lifecycle('install'); lifecycle('set_schema', '99'); diff --git a/tests/Security/SourceRulesTest.php b/tests/Security/SourceRulesTest.php index 8a4fb87..89f1e32 100644 --- a/tests/Security/SourceRulesTest.php +++ b/tests/Security/SourceRulesTest.php @@ -312,3 +312,35 @@ function gpu_entry_points(): array { ->and(preg_match($mutating, "'nvidia-smi drain -p 0000:01:00.0 -m 1'"))->toBe(1) ->and(preg_match($mutating, "'nvidia-smi --query-gpu=uuid,index --format=csv'"))->toBe(0); }); + +it('renders the health and inventory pages from stored records, never from a node', function () { + // REQ-HEALTH-003 and REQ-PERF-002: no page reads the agent, runs the + // collector, or waits. The page classes and entry files name no SNMP + // function, reader, collector, or sleep. + $banned = '/\b(snmp\w*|cacti_snmp\w*|SnmpExtendReader|ExtendReader|Collector|Poller|gpu_poller|sleep|usleep|fsockopen|stream_socket_client|curl_\w+)\b/i'; + + foreach (['lib/HealthPage.php', 'lib/InventoryPage.php', 'gpu_health.php', 'gpu_inventory.php'] as $file) { + foreach (PhpToken::tokenize((string) file_get_contents(gpu_root() . '/' . $file)) as $token) { + if ($token->is([T_STRING, T_NAME_QUALIFIED, T_NAME_FULLY_QUALIFIED])) { + expect($token->text)->not->toMatch($banned, "$file:{$token->line}"); + } + } + } +}); + +it('sends no notification of its own: no mail, webhook, or outbound request', function () { + // REQ-ALERT-005: Thold and Maint own alerting (ADR 0002). + $banned = ['mail', 'mb_send_mail', 'send_mail', 'mailer', 'curl_init', 'curl_exec', 'fsockopen', 'stream_socket_client', 'file_get_contents_url', 'thold_mail', 'syslog', 'openlog']; + + 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]))); + + foreach ($tokens as $i => $token) { + if ($token->is(T_STRING) && in_array(strtolower($token->text), $banned, true) && ($tokens[$i + 1]->text ?? '') === '(') { + expect(false)->toBeTrue("$file:{$token->line} calls " . $token->text . '()'); + } + } + + expect((string) file_get_contents(gpu_root() . '/' . $file))->not->toMatch('#[\'"]https?://#i', "$file names a URL"); + } +}); diff --git a/tests/Unit/HealthPageTest.php b/tests/Unit/HealthPageTest.php new file mode 100644 index 0000000..85e373e --- /dev/null +++ b/tests/Unit/HealthPageTest.php @@ -0,0 +1,159 @@ + + * 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\CollectionRepository; +use Somethingwithproof\Gpu\CollectionStatus; +use Somethingwithproof\Gpu\ExecutionState; +use Somethingwithproof\Gpu\FixedClock; +use Somethingwithproof\Gpu\FreshnessState; +use Somethingwithproof\Gpu\GpuRecord; +use Somethingwithproof\Gpu\GpuRepository; +use Somethingwithproof\Gpu\HealthPage; +use Somethingwithproof\Gpu\Node; +use Somethingwithproof\Gpu\NodeRepository; +use Somethingwithproof\Gpu\ObservationRepository; +use Somethingwithproof\Gpu\Presence; +use Somethingwithproof\Gpu\ThrottleMask; +use Somethingwithproof\Gpu\Vendor; + +const HEALTH_NOW = 100000; + +function health_page(?bool $maintenance = false): HealthPage { + return new HealthPage( + new NodeRepository(false, new FixedClock(0)), + new GpuRepository(false), + new CollectionRepository(false), + new ObservationRepository(false), + static fn (int $host): bool => true, + static fn (int $host): ?bool => $maintenance, + new FixedClock(HEALTH_NOW), + 300, + 600, + ); +} + +function health_gpu(int $id, Presence $presence = Presence::Present, int $replaces = 0): GpuRecord { + return new GpuRecord($id, Vendor::Nvidia, sprintf('GPU-00000000-0000-4000-8000-%012x', $id), 1, $id - 1, '00000000:18:00.0', 'NVIDIA H100', '580.95.05', 'nvidia-smi', '580.95.05', $presence, 0, $replaces, 0, 0, 1, HEALTH_NOW); +} + +function health_status(ExecutionState $state, string $detail = '', int $lastOk = 0): CollectionStatus { + return new CollectionStatus(1, $state, $detail, HEALTH_NOW - 40, HEALTH_NOW - 30, HEALTH_NOW - 30, 2, 0, 0, 0, $lastOk); +} + +it('names freshness from the sample time and the expected interval, never the page time', function (int $age, FreshnessState $want) { + expect(FreshnessState::of($age < 0 ? 0 : HEALTH_NOW - $age, HEALTH_NOW, 300, 600))->toBe($want); +})->with([ + 'never sampled' => [-1, FreshnessState::Never], + 'just taken' => [0, FreshnessState::Current], + 'one and a half intervals' => [450, FreshnessState::Current], + 'later than that' => [451, FreshnessState::Delayed], + 'at the staleness limit' => [600, FreshnessState::Delayed], + 'past it' => [601, FreshnessState::Stale], +]); + +it('never calls a sample current once it is too old to graph', function () { + expect(FreshnessState::of(HEALTH_NOW - 200, HEALTH_NOW, 300, 120))->toBe(FreshnessState::Stale); +}); + +it('calls a sample ahead once it is stamped further ahead of Cacti than skew explains', function () { + expect(FreshnessState::of(HEALTH_NOW + 120, HEALTH_NOW, 300, 600))->toBe(FreshnessState::Current) + ->and(FreshnessState::of(HEALTH_NOW + 121, HEALTH_NOW, 300, 600))->toBe(FreshnessState::Ahead) + ->and(FreshnessState::Ahead->label())->toBe("Ahead of the Cacti server's clock"); +}); + +it('counts the runs that skipped a node another run held', function () { + $held = new CollectionStatus(1, ExecutionState::Ok, '', HEALTH_NOW - 40, HEALTH_NOW - 30, HEALTH_NOW - 30, 2, 0, 0, 3, HEALTH_NOW - 30); + + expect(health_page()->collection($held))->toBe('Completed: Collected, 2 GPUs (30 seconds ago); 3 later runs skipped while another run held the node') + ->and(health_page()->collection(health_status(ExecutionState::Ok)))->not->toContain('skipped'); +}); + +it('reports each collection outcome as completed, tool error, permission denied, timed out, or unknown', function (ExecutionState $state, string $outcome) { + $text = health_page()->collection(health_status($state)); + + expect($text)->toStartWith($outcome) + ->and($text)->toContain($state->label()); +})->with([ + [ExecutionState::Ok, 'Completed'], + [ExecutionState::Empty, 'Completed'], + [ExecutionState::DriverNotLoaded, 'Tool error'], + [ExecutionState::InvalidOutput, 'Tool error'], + [ExecutionState::Unreachable, 'Tool error'], + [ExecutionState::PermissionDenied, 'Permission denied'], + [ExecutionState::TimedOut, 'Timed out'], + [ExecutionState::Skipped, 'Unknown'], +]); + +it('says a node never collected is unknown, and when a failing node last completed', function () { + $page = health_page(); + + expect($page->collection(null))->toBe('Unknown: not collected yet') + ->and($page->collection(health_status(ExecutionState::TimedOut, 'no answer within 5 s', HEALTH_NOW - 3600)))->toBe('Timed out: no answer within 5 s (30 seconds ago); last completed 60 minutes ago'); +}); + +it('bounds the collection detail and strips control characters', function () { + expect(HealthPage::detail("line one\nline\x1b[31m two\x00"))->toBe('line one line [31m two') + ->and(mb_strlen(HealthPage::detail(str_repeat('é', 500))))->toBe(HealthPage::DETAIL_LIMIT) + ->and(HealthPage::detail(str_repeat('x', 500)))->toEndWith('...'); +}); + +it('counts present, absent, and possibly replaced GPUs, and names backend, tool, and driver per node', function () { + $node = new Node(1, 101, AdminState::Enabled, 'node1', true, 0, 0); + $gpus = [health_gpu(1), health_gpu(2, Presence::Absent), health_gpu(3, Presence::Present, 2)]; + $samples = [1 => ['observed_at' => HEALTH_NOW - 30, 'backend' => 'nvidia-smi', 'thr_mask' => '1', 'ecc_mode' => 'enabled']]; + + expect(health_page(true)->nodeRow($node, health_status(ExecutionState::Ok), $gpus, $samples))->toBe([ + 'node1', 'Enabled', 'Current (30 seconds ago)', 'Completed: Collected, 2 GPUs (30 seconds ago)', 'In maintenance', 'nvidia-smi', 'nvidia-smi 580.95.05', '580.95.05', '2 present, 1 absent, 1 possible replacements', + ])->and(health_page(null)->nodeRow($node, null, [], [])[4])->toBe('Maint not installed') + ->and(health_page(null)->nodeRow($node, null, [], [])[2])->toBe('Never observed'); +}); + +it('shows why ECC is unknown, and the raw clock event mask with bits that have no indicator', function () { + $node = new Node(1, 101, AdminState::Enabled, 'node1', true, 0, 0); + $page = health_page(); + + $off = $page->gpuRow(health_gpu(1), $node, ['observed_at' => HEALTH_NOW - 700, 'thr_mask' => (string) (0x40 | 0x400), 'ecc_mode' => 'unavailable']); + $on = $page->gpuRow(health_gpu(1), $node, ['observed_at' => HEALTH_NOW - 10, 'thr_mask' => null, 'ecc_mode' => 'enabled']); + $unseen = $page->gpuRow(health_gpu(2, Presence::Absent), $node, null); + + expect($off[5])->toBe('Stale (11 minutes ago)') + ->and($off[6])->toBe('This GPU does not report ECC') + ->and($off[7])->toBe('0x0000000000000440; bits without an indicator: 0x400') + ->and($on[6])->toBe('Enabled') + ->and($on[7])->toBe('Unknown') + ->and($unseen[4])->toBe('Absent') + ->and($unseen[5])->toBe('Never observed'); +}); + +it('decodes each clock event bit alone and in combination, and keeps bits without an indicator in the raw mask', function () { + foreach (\Somethingwithproof\Gpu\MetricModel::BITS as $name => $bit) { + $values = ThrottleMask::indicators($bit); + + expect($values[$name])->toBe(1.0) + ->and(array_sum($values))->toBe(1.0); + } + + $all = ThrottleMask::indicators(array_sum(\Somethingwithproof\Gpu\MetricModel::BITS)); + + expect(array_unique($all))->toBe([array_key_first($all) => 1.0]) + ->and(ThrottleMask::indicators(0x1 | 0x2 | 0x10 | 0x100 | 0x200 | 0x400))->toBe(array_fill_keys(array_keys(\Somethingwithproof\Gpu\MetricModel::BITS), 0.0)) + ->and(ThrottleMask::describe(0x7ff))->toBe('0x00000000000007FF; bits without an indicator: 0x713') + ->and(ThrottleMask::describe(0))->toBe('0x0000000000000000'); +}); diff --git a/tests/bin/lifecycle.php b/tests/bin/lifecycle.php index 4ad9efa..e3b3ebe 100644 --- a/tests/bin/lifecycle.php +++ b/tests/bin/lifecycle.php @@ -111,6 +111,18 @@ 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 'drop_columns': + // As a version 2 schema had it: the observation table without the + // columns migration 3 adds, and one stored sample. + gpu_boot(); + + foreach (\Somethingwithproof\Gpu\Schema::OBSERVATION_METRICS_3 + array(99 => 'ecc_mode') as $column) { + db_execute('ALTER TABLE plugin_gpu_observation DROP COLUMN `' . $column . '`'); + } + + db_execute_prepared("INSERT INTO plugin_gpu_observation (gpu_id, node_id, observed_at, ingested_at, reported_at, backend, tool_version, temp_gpu) SELECT id, node_id, 1, 1, 1, 'nvidia-smi', '580.95.05', 40 FROM plugin_gpu_gpu LIMIT 1"); + break; case 'seed': // A node and a GPU record, so table drops and keeps are visible. @@ -249,6 +261,7 @@ '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, + 'observation_columns' => array_column(db_fetch_assoc("SELECT COLUMN_NAME AS c FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'plugin_gpu_observation' ORDER BY ORDINAL_POSITION"), 'c'), // 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'"), diff --git a/tests/bin/page-permissions.php b/tests/bin/page-permissions.php index 1bcabe4..1b3044a 100644 --- a/tests/bin/page-permissions.php +++ b/tests/bin/page-permissions.php @@ -53,8 +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'"); -$admin = (int) db_fetch_cell("SELECT id + 100 FROM plugin_realms WHERE plugin = 'gpu' AND file = 'gpu_nodes.php'"); +$view = (int) db_fetch_cell("SELECT id + 100 FROM plugin_realms WHERE plugin = 'gpu' AND FIND_IN_SET('gpu_inventory.php', file) > 0"); +$admin = (int) db_fetch_cell("SELECT id + 100 FROM plugin_realms WHERE plugin = 'gpu' AND FIND_IN_SET('gpu_nodes.php', file) > 0"); 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))); @@ -140,12 +140,15 @@ function perm_login($user) { } // Markers that only the rendered plugin page contains. -$pages = array('gpu_nodes.php' => 'Export Records', 'gpu_inventory.php' => 'PCI Bus ID'); +$pages = array('gpu_nodes.php' => 'Export Records', 'gpu_inventory.php' => 'PCI Bus ID', 'gpu_health.php' => 'Clock Event Reasons'); $plans = array( - 'anonymous' => array('gpu_nodes.php' => false, 'gpu_inventory.php' => false), - 'admin' => array('gpu_nodes.php' => true, 'gpu_inventory.php' => true), - 'viewer' => array('gpu_nodes.php' => false, 'gpu_inventory.php' => true), - 'norealm' => array('gpu_nodes.php' => false, 'gpu_inventory.php' => false), + 'anonymous' => array('gpu_nodes.php' => false, 'gpu_inventory.php' => false, 'gpu_health.php' => false), + 'admin' => array('gpu_nodes.php' => true, 'gpu_inventory.php' => true, 'gpu_health.php' => true), + 'viewer' => array('gpu_nodes.php' => false, 'gpu_inventory.php' => true, 'gpu_health.php' => true), + 'norealm' => array('gpu_nodes.php' => false, 'gpu_inventory.php' => false, 'gpu_health.php' => false), + // GPU Admin alone does not include the GPU View pages: each page file + // is checked against its own realm (REQ-PERM-004). + 'scoped' => array('gpu_nodes.php' => true, 'gpu_inventory.php' => false, 'gpu_health.php' => false), ); foreach ($plans as $user => $expect) { @@ -161,19 +164,49 @@ function perm_login($user) { perm_expect(strpos($body, 'login_username') !== false, "anonymous is sent to the login form from $page"); } - if ($page === 'gpu_inventory.php' && $allowed) { + if ($page !== 'gpu_nodes.php' && $allowed) { $sees = strpos($body, $hidden) !== false; perm_expect(strpos($body, $open) !== false && $sees === ($user === 'admin'), "$user " . ($user === 'admin' ? 'sees' : 'does not see') . ' the GPU of a device it ' . ($user === 'admin' ? 'may' : 'may not') . ' view'); // Tool-reported names and device descriptions are text. - perm_expect(strpos($body, '') === false && strpos($body, '<img src=x id="gpuname">') !== false, "$user's inventory escapes the GPU name"); - perm_expect(strpos($body, '') === false && strpos($body, '<b id="gpuprobe">') !== false, "$user's inventory escapes the device description"); + perm_expect(strpos($body, '') === false && strpos($body, '<img src=x id="gpuname">') !== false, "$user's $page escapes the GPU name"); + perm_expect(strpos($body, '') === false && strpos($body, '<b id="gpuprobe">') !== false, "$user's $page escapes the device description"); } } unlink($jar); } +// Revocation takes effect on the viewer's next request, in the same session +// (REQ-PERM-002): first the device permission, then the GPU View realm, +// which Cacti caches per session until user_auth.reset_perms changes, as +// it does when an administrator saves the user. +$jar = perm_login('viewer'); + +foreach (array('gpu_inventory.php', 'gpu_health.php') as $page) { + list(, $body) = perm_http($base . $page, $jar); + perm_expect(strpos($body, $open) !== false, "viewer sees the open GPU on $page before revocation"); +} + +db_execute_prepared('DELETE FROM user_auth_perms WHERE user_id = ? AND item_id = ? AND type = 3', array($users['viewer'], $devices['open'])); + +foreach (array('gpu_inventory.php', 'gpu_health.php') as $page) { + list(, $body) = perm_http($base . $page, $jar); + perm_expect(strpos($body, $pages[$page]) !== false && strpos($body, $open) === false && strpos($body, 'Open node') === false, "viewer no longer sees the GPU or node on $page on the request after its device permission is revoked"); +} + +db_execute_prepared('INSERT INTO user_auth_perms (user_id, item_id, type) VALUES (?, ?, 3)', array($users['viewer'], $devices['open'])); +db_execute_prepared('DELETE FROM user_auth_realm WHERE user_id = ? AND realm_id = ?', array($users['viewer'], $view)); +db_execute_prepared('UPDATE user_auth SET reset_perms = ? WHERE id = ?', array(mt_rand(), $users['viewer'])); + +foreach (array('gpu_inventory.php', 'gpu_health.php') as $page) { + list(, $body) = perm_http($base . $page, $jar); + perm_expect(strpos($body, $pages[$page]) === false && strpos($body, $open) === false, "viewer is denied $page on the request after GPU View is revoked"); +} + +db_execute_prepared('INSERT INTO user_auth_realm (realm_id, user_id) VALUES (?, ?)', array($view, $users['viewer'])); +unlink($jar); + $jar = perm_login('admin'); foreach (array('gpu_nodes.php', 'gpu_nodes.php?action=edit&id=' . $nodes['open']) as $page) { @@ -270,6 +303,7 @@ function perm_login($user) { 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'); +perm_expect(strpos($edit, 'hidden.invalid') === false && strpos($edit, 'Hidden node') === false && strpos($edit, $hidden) === false && strpos($edit, '0000000000c3') === false && strpos($edit, 'plugins/gpu/lib/') === false && strpos($edit, 'plugins/gpu/setup.php') === false && preg_match('#\.php(:| on line )\d#', $edit) !== 1, 'the refusal names no hostname, device, UUID, or path of the hidden node (REQ-PERM-005)'); 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'); @@ -337,9 +371,11 @@ function perm_login($user) { // With Cacti's device management, a device this user would not be allowed // to see is removed again in the same request, and no node is made for it. db_execute_prepared('INSERT INTO user_auth_realm (realm_id, user_id) VALUES (3, ?)', array($users['scoped'])); +// A new session loads the added realm with a token of its own. +$jar = perm_login('scoped'); list(, $form) = perm_http($base . 'gpu_nodes.php?action=edit', $jar); list(, $result) = perm_http($base . 'gpu_nodes.php', $jar, array('__csrf_magic' => perm_token($form), 'action' => 'create_device', 'description' => 'Invisible created', 'hostname' => 'invisible.invalid')); -perm_expect((int) db_fetch_cell("SELECT COUNT(*) FROM host WHERE hostname = 'invisible.invalid'") === 0 && (int) db_fetch_cell('SELECT COUNT(*) FROM plugin_gpu_node WHERE host_id NOT IN (SELECT id FROM host) AND host_id NOT IN (999998)') === 0 && strpos($result, 'was not kept') !== false, 'a created device the creator may not see is removed again, with an error'); +perm_expect((int) db_fetch_cell("SELECT COUNT(*) FROM host WHERE hostname = 'invisible.invalid'") === 0 && (int) db_fetch_cell('SELECT COUNT(*) FROM plugin_gpu_node WHERE host_id NOT IN (SELECT id FROM host) AND host_id NOT IN (999998)') === 0 && strpos($result, 'was not kept') !== false, 'a created device the creator may not see is removed again, with an error (' . (int) db_fetch_cell("SELECT COUNT(*) FROM host WHERE hostname = 'invisible.invalid'") . ' devices kept, message ' . (($perm_at = strpos($result, '"message":')) !== false ? substr($result, $perm_at, 300) : 'none') . ')'); db_execute_prepared('DELETE FROM user_auth_realm WHERE realm_id = 3 AND user_id = ?', array($users['scoped'])); unlink($jar); From 20babde960b43fb7a850508e4c97860089332efd Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 12:31:42 -0800 Subject: [PATCH 05/18] test(failure): qualify phase 1 collection failures end to end (#52) tests/bin/failure-flow.php breaks one thing at a time behind a real snmpd and checks the state each failure leaves, then that collection recovers: the agent down, wrong SNMPv3 credentials, the tool missing, permission denied, the driver unloaded, a tool that outlives timeout(1), output cut mid-line, output past snmpd's line limit, a node clock an hour ahead, a second collector start while a run holds the node, the database lost in the middle of a run, and an RRD file Cacti cannot write. In each, no stored value becomes zero or goes back in time, every GPU record, data source, graph, and RRD file is kept, the script server input prints U while age keeps counting, Cacti writes no zero, and GPU Health names the outcome. The fake nvidia-smi gains a delay so a timeout can be provoked. The collector now refuses a sample stamped more than the skew allowance ahead of Cacti's clock, before anything is recorded. Stored samples only move forward, so keeping such a sample would have held back every real sample until Cacti's clock caught up. Signed-off-by: Thomas Vincent --- lib/Collector.php | 13 ++ tests/Unit/CollectorTest.php | 21 +- tests/bin/failure-flow.php | 380 +++++++++++++++++++++++++++++++++++ tests/bin/fake-nvidia-smi | 6 + 4 files changed, 418 insertions(+), 2 deletions(-) create mode 100644 tests/bin/failure-flow.php diff --git a/lib/Collector.php b/lib/Collector.php index d672b16..17f8ee1 100644 --- a/lib/Collector.php +++ b/lib/Collector.php @@ -88,6 +88,19 @@ private function run(Node $node, NodeDevice $device, Settings $settings): array return [$e->state, $e->getMessage()]; } + // A sample stamped ahead of Cacti's clock is refused before anything + // is recorded: stored samples only move forward, so keeping it would + // hold back every real sample until Cacti's clock caught up. + $ahead = $collection->newestSample() - $this->clock->now(); + + if ($ahead > Freshness::SKEW_ALLOWANCE) { + $detail = sprintf('The sample time is %d seconds ahead of the Cacti server\'s clock', $ahead); + + $this->collections->finish($node->id, ExecutionState::InvalidOutput, $detail, $this->clock->now()); + + return [ExecutionState::InvalidOutput, $detail]; + } + $changes = $this->inventory->record($node, $collection->snapshot, $settings->absentAfter); $records = $this->gpus->forReconcile($node, $collection->snapshot); diff --git a/tests/Unit/CollectorTest.php b/tests/Unit/CollectorTest.php index 7c4a8a7..5cab108 100644 --- a/tests/Unit/CollectorTest.php +++ b/tests/Unit/CollectorTest.php @@ -60,7 +60,7 @@ 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 __construct(private readonly string $fixture, private readonly ?CollectionError $error = null, private readonly int $status = 0, private readonly string $sampled = '2027/01/15 08:00:00.250') { } public function read(NodeDevice $device, string $token): ExtendOutput { @@ -71,7 +71,7 @@ public function read(NodeDevice $device, string $token): ExtendOutput { } $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)); + $text = $this->fixture === '' ? '' : str_replace('@NOW@', $this->sampled, (string) file_get_contents($file)); $lines = $text === '' ? [] : explode("\n", rtrim($text, "\n")); return new ExtendOutput($token === SnmpdConfig::METRICS ? $this->status : 0, count($lines), $lines); @@ -135,6 +135,23 @@ function collect_known(int $node = 3): array { 'driver not ready' => [9, ExecutionState::DriverNotLoaded], ]); +it('refuses a sample stamped further ahead of Cacti than clock skew explains, and records nothing', function () { + $GLOBALS['__gpu_db_rows']['FROM plugin_gpu_gpu'] = collect_known(); + + // COLLECT_NOW is 08:01:40; 120 seconds ahead is allowed, 121 is not. + expect(collector(new FixtureReader('r595-1gpu', sampled: '2027/01/15 08:03:41.000'))->collect(collect_node(), collect_device(), Settings::fromRow([])))->toBe(ExecutionState::InvalidOutput) + ->and(collect_writes('plugin_gpu_gpu'))->toBe([]) + ->and(collect_writes('plugin_gpu_observation'))->toBe([]); + + $finish = array_values(array_filter($GLOBALS['__gpu_db_exec'], fn ($e) => str_contains($e['sql'], 'last_ok_at'))); + + expect($finish[0]['params'][2])->toBe("The sample time is 121 seconds ahead of the Cacti server's clock"); + + $GLOBALS['__gpu_db_exec'] = []; + + expect(collector(new FixtureReader('r595-1gpu', sampled: '2027/01/15 08:03:40.000'))->collect(collect_node(), collect_device(), Settings::fromRow([])))->toBe(ExecutionState::Ok); +}); + it('records an empty collection as successful without marking any GPU absent', function () { $GLOBALS['__gpu_db_rows']['FROM plugin_gpu_gpu'] = collect_known(); diff --git a/tests/bin/failure-flow.php b/tests/bin/failure-flow.php new file mode 100644 index 0000000..7a43224 --- /dev/null +++ b/tests/bin/failure-flow.php @@ -0,0 +1,380 @@ + + * 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. + */ + +/* + * Failure qualification (#52, REQ-FAIL-001 to REQ-FAIL-003), end to end + * against the real snmpd of tests/bin/e2e.php, with its environment. Run + * from the Cacti root: + * + * php plugins/gpu/tests/bin/failure-flow.php + * + * Each scenario breaks one thing, collects, and runs Cacti's poller, then + * checks that no value became zero, the GPU records and Cacti objects are + * all still there, the RRD history is intact, and the health page names + * the failure. Then it repairs the fault and checks that collection + * recovers: + * + * agent down the device points at a port no agent listens on + * wrong credentials the device's SNMPv3 authentication passphrase is wrong + * tool timeout the fake nvidia-smi outlasts timeout(1) in the extend line + * cut output the last metrics line stops partway + * agent limit more lines than snmpd keeps + * database lost the collector's database connection is killed mid-run + * RRD not writable Cacti cannot write the GPU's RRD file + * + * Must parse on PHP 8.0. + */ + +require(__DIR__ . '/e2e-lib.php'); + +use Somethingwithproof\Gpu\ExtendOutput; +use Somethingwithproof\Gpu\ExtendReader; +use Somethingwithproof\Gpu\NodeDevice; + +db_execute("REPLACE INTO settings (name, value) VALUES ('gpu_absent_after', '1')"); + +list($e2e_host, $e2e_node_id) = e2e_node('gpu-node-fail'); + +$fail_metrics = e2e_fixture('r580-8gpu', 'metrics'); +$fail_names = e2e_fixture('r580-8gpu', 'names'); + +function fail_sources(): array { + global $e2e_host; + + return array_column(db_fetch_assoc_prepared('SELECT id, snmp_index FROM data_local WHERE host_id = ? AND snmp_query_id = ? ORDER BY id', array($e2e_host, gpu_provisioner()->dataQueryId())), 'id', 'snmp_index'); +} + +/** + * What a failure must leave alone: the GPU records and their presence, + * the stored values, the data sources and graphs, and the RRD files. + * + * @return array + */ +function fail_kept(): array { + global $e2e_host, $e2e_node_id; + + $rrd = array(); + + foreach (fail_sources() as $id) { + $path = get_data_source_path((int) $id, true); + $rrd[$id] = is_file($path) ? filesize($path) : -1; + } + + return array( + 'gpus' => db_fetch_assoc_prepared('SELECT id, uuid, presence FROM plugin_gpu_gpu WHERE node_id = ? ORDER BY id', array($e2e_node_id)), + 'graphs' => (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM graph_local WHERE host_id = ?', array($e2e_host)), + 'sources' => fail_sources(), + 'rrd' => $rrd, + ); +} + +/** + * The stored values of every GPU at the node: none may be zero where the + * healthy sample was not, and none may go back in time. + * + * @return array> + */ +function fail_values(): array { + global $e2e_node_id; + + return array_column(db_fetch_assoc_prepared('SELECT g.uuid, o.observed_at, o.util_gpu, o.temp_gpu, o.power, o.mem_total FROM plugin_gpu_gpu AS g INNER JOIN plugin_gpu_observation AS o ON o.gpu_id = g.id WHERE g.node_id = ? ORDER BY g.uuid', array($e2e_node_id)), null, 'uuid'); +} + +function fail_health(): string { + global $e2e_node_id; + + $page = new \Somethingwithproof\Gpu\HealthPage(gpu_nodes(), gpu_gpus(), new \Somethingwithproof\Gpu\CollectionRepository(false), new \Somethingwithproof\Gpu\ObservationRepository(false), function ($host) { + return true; + }, function ($host) { + return null; + }, new \Somethingwithproof\Gpu\SystemClock(), 300, gpu_settings()->staleAfter); + + return $page->collection((new \Somethingwithproof\Gpu\CollectionRepository(false))->find($e2e_node_id)); +} + +/** + * The checks after a failed collection and a Cacti poll. + * + * @param array $kept fail_kept() before the fault + * @param array> $values fail_values() before the fault + */ +function fail_check(string $scenario, string $state, string $outcome, array $kept, array $values): void { + global $e2e_host, $e2e_node_id; + + $status = db_fetch_row_prepared('SELECT state, detail FROM plugin_gpu_collection WHERE node_id = ?', array($e2e_node_id)); + + e2e_check(($status['state'] ?? '') === $state, "$scenario: the collection is recorded as $state (" . ($status['state'] ?? 'none') . ')'); + + e2e_poll(); + + $after = fail_values(); + $zeros = array(); + + foreach ($values as $uuid => $row) { + foreach (array('util_gpu', 'temp_gpu', 'power', 'mem_total') as $field) { + if ((string) ($after[$uuid][$field] ?? '') !== (string) $row[$field] && (float) ($after[$uuid][$field] ?? 0) === 0.0) { + $zeros[] = "$uuid $field"; + } + } + + if ((int) ($after[$uuid]['observed_at'] ?? 0) < (int) $row['observed_at']) { + $zeros[] = "$uuid went back in time"; + } + } + + e2e_check($zeros === array(), "$scenario: no stored value became zero or older (" . implode(', ', $zeros) . ')'); + e2e_check(fail_kept() === $kept, "$scenario: every GPU record, data source, graph, and RRD file is kept, and no GPU is marked absent"); + e2e_check(e2e_ss($e2e_host, 'get', 'util_gpu', e2e_key(1)) === 'U' && is_numeric(e2e_ss($e2e_host, 'get', 'age', e2e_key(1))), "$scenario: the script server input prints U, never 0, while age keeps counting"); + + $rrd = e2e_rrd((int) $kept['sources'][e2e_key(1)]); + + e2e_check(($rrd['util_gpu'] ?? '') !== '0' && ($rrd['temp_gpu'] ?? '') !== '0', "$scenario: Cacti wrote no zero to the RRD file (util_gpu " . ($rrd['util_gpu'] ?? '?') . ')'); + + $health = fail_health(); + + e2e_check(strpos($health, $outcome) === 0, "$scenario: the health page shows '$health'"); +} + +/** + * Repair, collect, and check the node is healthy again. + */ +function fail_recover(string $scenario): void { + global $e2e_node_id; + + e2e_collect(); + + e2e_check(db_fetch_cell_prepared('SELECT state FROM plugin_gpu_collection WHERE node_id = ?', array($e2e_node_id)) === 'ok' && strpos(fail_health(), 'Completed') === 0, "$scenario: collection recovers once the fault is repaired"); +} + +/* A healthy node with history. */ + +e2e_tool($fail_metrics, $fail_names); +e2e_collect(); +e2e_poll(); +sleep(1); +e2e_poll(); + +$kept = fail_kept(); +$values = fail_values(); + +e2e_check(count($kept['gpus']) === 8 && count($kept['sources']) === 8 && min($kept['rrd']) > 0, 'setup: eight GPUs with data sources and RRD files'); + +/* The agent is down: nothing listens on the device's port. */ + +$fail_port = (int) db_fetch_cell_prepared('SELECT snmp_port FROM host WHERE id = ?', array($e2e_host)); + +db_execute_prepared('UPDATE host SET snmp_port = ? WHERE id = ?', array($fail_port + 1, $e2e_host)); +e2e_collect(); +fail_check('agent down', 'unreachable', 'Tool error: SNMP agent unreachable', $kept, $values); +db_execute_prepared('UPDATE host SET snmp_port = ? WHERE id = ?', array($fail_port, $e2e_host)); +fail_recover('agent down'); + +/* Wrong SNMPv3 credentials. */ + +$fail_secret = (string) db_fetch_cell_prepared('SELECT snmp_password FROM host WHERE id = ?', array($e2e_host)); + +db_execute_prepared('UPDATE host SET snmp_password = ? WHERE id = ?', array('wrong-' . bin2hex(random_bytes(6)), $e2e_host)); +e2e_collect(); +fail_check('wrong credentials', 'unreachable', 'Tool error: SNMP agent unreachable', $kept, $values); +db_execute_prepared('UPDATE host SET snmp_password = ? WHERE id = ?', array($fail_secret, $e2e_host)); +fail_recover('wrong credentials'); + +/* + * The tool hangs past timeout(1)'s 10 seconds. snmpd answers nothing while + * the command runs, so the first read may time out at the SNMP layer; the + * read after the command ends gets its cached exit status 124. + */ + +file_put_contents($e2e_fixtures . '/current.delay', '15'); +e2e_tool($fail_metrics, $fail_names); +e2e_collect(); +sleep(16); +e2e_collect(); +fail_check('tool timeout', 'timed_out', 'Timed out', $kept, $values); +file_put_contents($e2e_fixtures . '/current.delay', ''); +e2e_tool($fail_metrics, $fail_names); +fail_recover('tool timeout'); + +/* The output stops partway through the last line. */ + +$fail_cut = $fail_metrics; +$fail_cut[count($fail_cut) - 1] = substr($fail_cut[count($fail_cut) - 1], 0, 60); + +e2e_tool($fail_cut, $fail_names); +e2e_collect(); +fail_check('cut output', 'invalid_output', 'Tool error: Output rejected', $kept, $values); +e2e_tool($fail_metrics, $fail_names); +fail_recover('cut output'); + +/* More lines than snmpd keeps: the plugin refuses output that may be cut. */ + +e2e_tool(array_merge($fail_metrics, array_fill(0, 1100, $fail_metrics[0])), $fail_names); +e2e_collect(); +fail_check('agent limit', 'truncated', 'Tool error: Output truncated', $kept, $values); +e2e_tool($fail_metrics, $fail_names); +fail_recover('agent limit'); + +/* Exit statuses of the documented commands: tool missing, permission denied, driver unloaded. */ + +foreach (array(127 => array('tool missing', 'tool_missing', 'Tool error: Tool not found'), 4 => array('permission denied', 'permission_denied', 'Permission denied'), 9 => array('driver unloaded', 'driver_not_loaded', 'Tool error: Driver not loaded')) as $fail_status => $fail_case) { + e2e_tool($fail_metrics, $fail_names, $fail_status); + e2e_collect(); + fail_check($fail_case[0], $fail_case[1], $fail_case[2], $kept, $values); + e2e_tool($fail_metrics, $fail_names); + fail_recover($fail_case[0]); +} + +/* + * Clock skew: the node's clock runs an hour ahead of Cacti's. The sample is + * refused, so a real sample is stored again as soon as the clock is fixed. + */ + +e2e_tool(str_replace('@NOW@', gmdate('Y/m/d H:i:s', time() + 3600) . '.000', $fail_metrics), $fail_names); +e2e_collect(); +fail_check('clock skew', 'invalid_output', 'Tool error: Output rejected: The sample time is', $kept, $values); +e2e_tool($fail_metrics, $fail_names); +fail_recover('clock skew'); + +/* A second collector start while another run holds the node. */ + +$fail_other = db_connect_real($database_hostname, $database_username, $database_password, $database_default, 'mysql', $database_port, 1); +$fail_lock = is_object($fail_other) ? (int) db_fetch_cell_prepared("SELECT GET_LOCK(SHA2(CONCAT(DATABASE(), '.plugin_gpu.', ?), 256), 0)", array('node_' . $e2e_node_id), '', true, $fail_other) : 0; +$fail_stats = e2e_collect(); + +e2e_check($fail_lock === 1 && $fail_stats['skipped'] === 1 && $fail_stats['ok'] === 0, 'duplicate start: a run that finds the node held skips it and counts the skip (' . json_encode($fail_stats) . ')'); +e2e_check(fail_kept() === $kept && strpos(fail_health(), '1 later runs skipped') !== false, "duplicate start: nothing is changed, and the health page shows the skip ('" . fail_health() . "')"); + +if (is_object($fail_other)) { + db_close($fail_other); +} + +fail_recover('duplicate start'); + +/* + * The database goes away mid-run: a reader that kills the collector's own + * connection right after the agent answered, before anything is stored. + */ + +final class FailKillingReader implements ExtendReader { + /** @var ExtendReader */ + private $inner; + + /** @var bool */ + public $killed = false; + + public function __construct(ExtendReader $inner) { + $this->inner = $inner; + } + + public function read(NodeDevice $device, string $token): ExtendOutput { + global $database_hostname, $database_username, $database_password, $database_default, $database_port; + + $out = $this->inner->read($device, $token); + + if (!$this->killed && $token === 'cacti_gpu') { + $id = (int) db_fetch_cell('SELECT CONNECTION_ID()'); + $other = db_connect_real($database_hostname, $database_username, $database_password, $database_default, 'mysql', $database_port, 1); + + if (is_object($other)) { + db_execute('KILL CONNECTION ' . $id, false, $other); + db_close($other); + $this->killed = true; + } + } + + return $out; + } +} + +$fail_clock = new \Somethingwithproof\Gpu\SystemClock(); +$fail_reader = new FailKillingReader(new \Somethingwithproof\Gpu\SnmpExtendReader(0)); +$fail_gpus = gpu_gpus(); +$fail_node = gpu_nodes()->find($e2e_node_id); +$fail_dev = $fail_node === null ? null : gpu_nodes()->device($fail_node); +$fail_state = 'not run'; + +$fail_collector = new \Somethingwithproof\Gpu\Collector($fail_reader, new \Somethingwithproof\Gpu\NvidiaSmiParser(), new \Somethingwithproof\Gpu\Inventory($fail_gpus, new \Somethingwithproof\Gpu\IdentityReconciler(), $fail_clock), $fail_gpus, new \Somethingwithproof\Gpu\ObservationRepository(false), new \Somethingwithproof\Gpu\CollectionRepository(false), new \Somethingwithproof\Gpu\ReindexRepository(false), new \Somethingwithproof\Gpu\LockRepository(false), $fail_clock); + +// The tool's sample must be newer than the stored one, or there is nothing +// the lost connection could have written. +e2e_tool($fail_metrics, $fail_names); + +try { + $fail_state = $fail_node !== null && $fail_dev !== null ? $fail_collector->collect($fail_node, $fail_dev, gpu_settings())->value : 'no node'; +} catch (\Throwable $e) { + $fail_state = 'threw ' . get_class($e); +} + +e2e_check($fail_reader->killed, "database lost: the collector's connection was killed mid-run (collect returned $fail_state)"); + +$after = fail_values(); +$zeros = 0; + +foreach ($after as $row) { + $zeros += (float) $row['util_gpu'] === 0.0 || (float) $row['mem_total'] === 0.0 ? 1 : 0; +} + +e2e_check($zeros === 0 && count($after) === 8 && fail_kept() === $kept, 'database lost: every stored value is a real sample, and every record is kept'); +e2e_check(strpos(fail_health(), 'Completed') === 0 || strpos(fail_health(), 'Unknown') === 0 || strpos(fail_health(), 'Tool error: Result not stored') === 0, "database lost: the health page shows '" . fail_health() . "'"); +fail_recover('database lost'); + +/* Cacti cannot write the RRD file. */ + +$fail_source = (int) $kept['sources'][e2e_key(1)]; +$fail_path = get_data_source_path($fail_source, true); +$fail_before = e2e_rrd($fail_source); +$fail_root = function_exists('posix_geteuid') && posix_geteuid() === 0; + +// root writes through any mode, so as root the file is moved aside and a +// directory takes its name; otherwise the file is made read-only. +if ($fail_root) { + rename($fail_path, $fail_path . '.aside'); + mkdir($fail_path); +} else { + chmod($fail_path, 0444); +} + +e2e_tool($fail_metrics, $fail_names); +e2e_collect(); +sleep(1); +e2e_poll(); + +e2e_check(db_fetch_cell_prepared('SELECT state FROM plugin_gpu_collection WHERE node_id = ?', array($e2e_node_id)) === 'ok' && strpos(fail_health(), 'Completed') === 0, 'RRD not writable: collection is unaffected, so the health page shows it completed; Cacti logs the write error'); + +if ($fail_root) { + rmdir($fail_path); + rename($fail_path . '.aside', $fail_path); +} else { + chmod($fail_path, 0644); +} + +$fail_after = e2e_rrd($fail_source); + +e2e_check(($fail_after['time'] ?? '') === ($fail_before['time'] ?? 'x') && fail_kept() === $kept, 'RRD not writable: the RRD file and its history are unchanged (' . ($fail_root ? 'directory in its place' : 'read-only file') . ')'); + +sleep(1); +e2e_poll(); + +$fail_after = e2e_rrd($fail_source); + +e2e_check((int) ($fail_after['time'] ?? 0) > (int) ($fail_before['time'] ?? 0) && ($fail_after['util_gpu'] ?? '') === '30', 'RRD not writable: once writable, Cacti writes the GPU values again'); + +print ($e2e_failures === 0 ? 'failure flow ok' : "failure flow: $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 index 5c37594..6ccdbfe 100755 --- a/tests/bin/fake-nvidia-smi +++ b/tests/bin/fake-nvidia-smi @@ -25,6 +25,8 @@ # 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 +# current.delay optional: sleep this many seconds first, as a hung +# 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. @@ -33,6 +35,10 @@ set -eu dir=/var/lib/gpu-e2e +if [ -s "$dir/current.delay" ]; then + sleep "$(cat "$dir/current.delay")" +fi + if [ -s "$dir/current.status" ]; then echo 'Failed to initialize NVML: Driver/library version mismatch' >&2 exit "$(cat "$dir/current.status")" From 6239e74d46130761cb06afc9b4d118a666e609fd Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 12:32:47 -0800 Subject: [PATCH 06/18] fix(provisioner): never let a new GPU data source inherit an RRD file (#53) Cacti names an RRD file after its data source id. After a database restore older than the RRD directory, Cacti hands out ids it had already used, so a GPU that first appears after the restore could be given a data source whose file already holds another GPU's history. When the provisioner creates a data source and finds a file at its path, it now renames the file with a .gpu-orphan-