From 1ff29aba2eeb4e1904f38225a18ff23692be31bd Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 08:49:53 -0800 Subject: [PATCH 01/14] docs: decide how BMC data reaches Cacti devices (ADR 0015) Attach a BMC's data queries and graphs to the server device it is mapped to; otherwise create one device per BMC from the plugin's device template after an administrator confirms the plan. Creation goes through Cacti's device API, needs Cacti's device management permission, and is rolled back when the creator could not see the new device. Resolves #11. Signed-off-by: Thomas Vincent --- ...the-server-device-or-create-one-per-bmc.md | 31 +++++++++++++++++++ docs/decisions/README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 docs/decisions/0015-attach-to-the-server-device-or-create-one-per-bmc.md diff --git a/docs/decisions/0015-attach-to-the-server-device-or-create-one-per-bmc.md b/docs/decisions/0015-attach-to-the-server-device-or-create-one-per-bmc.md new file mode 100644 index 0000000..6850a23 --- /dev/null +++ b/docs/decisions/0015-attach-to-the-server-device-or-create-one-per-bmc.md @@ -0,0 +1,31 @@ +# 0015. Attach BMC data to the server's Cacti device, or create one device per BMC + +Status: Accepted (2026-11-15). Resolves decision issue 11. + +## Context + +A BMC reports on one server. Operators usually already monitor that server in Cacti over SNMP or an agent, and want its BMC graphs, thresholds, and permissions on the same device. Others have no device for the server, or monitor only the BMC. Cacti's device permissions, graph permissions, trees, Thold thresholds, and Maint schedules all key on the device, so the choice decides who sees the BMC's data and how it alerts. The research for this issue compared mapping onto the server device, always creating a separate BMC device, and leaving the choice to each site; it left the default open. + +## Decision + +- When the operator maps a BMC to an existing Cacti device, the plugin attaches its data queries and summary graphs to that device and changes nothing else about it. +- Otherwise the plugin creates one device per BMC from the shipped "Redfish BMC" device template, and only after an administrator confirms a plan that lists what will be added (REQ-DEV-002). +- Device creation goes through Cacti's `api_device_save()`. It requires Cacti's device management realm in addition to Redfish Admin. The new device has availability checks off and a host name in the reserved `.invalid` domain, so Cacti never contacts the BMC and the device page never shows the BMC's address. It is polled by the BMC's poller. +- If the creating user's device permissions would hide the new device, the plugin removes it again with `api_device_remove()` and reports why. +- A device carries at most one BMC, because the script server finds the BMC by its device. +- The `device_remove` hook unmaps the BMC of a deleted device. The BMC, its credential, and its cache stay, visible only to administrators until it is mapped again. +- The `api_device_new` hook logs a mapped device moved to another poller than its BMC's. The health page shows the mismatch; the plugin does not move either back. + +## Consequences + +- BMC data inherits the server device's permissions, trees, thresholds, and maintenance schedules, with no Thold or Maint change. +- A plugin-created device is an ordinary Cacti device. Deleting it never deletes the BMC, and uninstalling the plugin never deletes it. +- A user who may manage Redfish BMCs but not Cacti devices can map a BMC to a device they can see, but cannot create one. +- Mapping a second BMC to a device is refused; a server with two management controllers needs a second device. + +## Alternatives rejected + +- **Always a separate BMC device.** Splits one server's graphs, permissions, and maintenance across two devices. +- **Map only, never create.** Leaves BMC-only sites with no way to graph or alert without hand-building devices. +- **Create devices automatically on discovery.** Adds Cacti objects without an administrator's confirmation and bypasses device permissions. +- **Write the `host` table directly.** Skips Cacti's own validation, hooks, and poller cache updates. diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 23e7af7..be8b8a2 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -18,5 +18,6 @@ Each record captures one architecture decision: its context, the decision, its c | [0012](0012-bounded-same-origin-redirects.md) | Follow at most three same-origin HTTPS redirects on GET | Accepted | | [0013](0013-choose-the-resource-source-per-reading.md) | Choose the subsystem or legacy source per reading, and take inlet only from a confirmed intake summary | Accepted | | [0014](0014-plugin-name-namespace-and-provisional-harness.md) | Name the plugin `redfish` under `Somethingwithproof\Redfish`, with a provisional Pest harness | Accepted, provisional | +| [0015](0015-attach-to-the-server-device-or-create-one-per-bmc.md) | Attach BMC data to the server's Cacti device, or create one device per BMC | Accepted | Open decisions are tracked as issues labelled `type: decision`. From 1cd34a685ea05e8fecce582fd7443b0633ef1fbc Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 08:50:55 -0800 Subject: [PATCH 02/14] feat: Cacti templates, script server inputs, and device provisioning Ship the Redfish device, data, and graph templates as Cacti template XML and import them by hash at install and upgrade. Copy the three data query files into Cacti's script server directory with a recorded hash, never replacing a file the plugin did not write. Add script server inputs for fans, temperatures, power supplies, and a node summary that answer only from the plugin's cache and report U for missing, stale, mismatched, or removed values. Add Create Device and Add Graphs actions on the BMCs page with a confirmed plan, a template reinstall action, one BMC per device, device removal and poller move handling, a graph link to the device's Redfish graphs, and health page warnings. Every new action is POST only and checks the Redfish realm, Cacti's device or import permission, and the user's device permissions. Refs #44, #45, #46, #47, #49, #50. Signed-off-by: Thomas Vincent --- REUSE.toml | 5 +- lib/BmcRepository.php | 47 + lib/BmcsPage.php | 46 +- lib/CactiObjectRepository.php | 132 ++ lib/DeviceProvisioner.php | 237 ++ lib/DeviceWarnings.php | 59 + lib/GraphLinks.php | 51 + lib/HealthPage.php | 23 +- lib/IndexKey.php | 57 + lib/MemberQuery.php | 176 ++ lib/NodeCache.php | 84 + lib/NodeCacheRepository.php | 83 + lib/Number.php | 38 + lib/Schema.php | 6 +- lib/SummaryScript.php | 117 + lib/TemplateInstaller.php | 317 +++ locales/po/cacti.pot | 144 +- redfish_bmcs.php | 56 +- redfish_health.php | 3 +- resource/script_server/redfish_fans.xml | 54 + resource/script_server/redfish_psus.xml | 54 + .../script_server/redfish_temperatures.xml | 49 + scripts/ss_redfish_members.php | 61 + scripts/ss_redfish_summary.php | 55 + setup.php | 138 +- templates/redfish-templates.xml | 2045 +++++++++++++++++ tests/Integration/LifecycleTest.php | 2 +- tests/Unit/ScriptServerTest.php | 236 ++ tests/Unit/TemplateFilesTest.php | 120 + tests/bin/build-templates.php | 468 ++++ tests/bin/php-guard-check.php | 16 + 31 files changed, 4961 insertions(+), 18 deletions(-) create mode 100644 lib/CactiObjectRepository.php create mode 100644 lib/DeviceProvisioner.php create mode 100644 lib/DeviceWarnings.php create mode 100644 lib/GraphLinks.php create mode 100644 lib/IndexKey.php create mode 100644 lib/MemberQuery.php create mode 100644 lib/NodeCache.php create mode 100644 lib/NodeCacheRepository.php create mode 100644 lib/Number.php create mode 100644 lib/SummaryScript.php create mode 100644 lib/TemplateInstaller.php create mode 100644 resource/script_server/redfish_fans.xml create mode 100644 resource/script_server/redfish_psus.xml create mode 100644 resource/script_server/redfish_temperatures.xml create mode 100644 scripts/ss_redfish_members.php create mode 100644 scripts/ss_redfish_summary.php create mode 100644 templates/redfish-templates.xml create mode 100644 tests/Unit/ScriptServerTest.php create mode 100644 tests/Unit/TemplateFilesTest.php create mode 100644 tests/bin/build-templates.php diff --git a/REUSE.toml b/REUSE.toml index fbd35c8..3e11274 100644 --- a/REUSE.toml +++ b/REUSE.toml @@ -2,7 +2,8 @@ version = 1 # Files that cannot carry a comment header, or whose format makes one # awkward: documentation, repository metadata, GitHub templates, test -# configuration, and translation catalogs, which gettext regenerates. +# configuration, translation catalogs, which gettext regenerates, and the +# Cacti template export and data query files, which Cacti reads and writes. [[annotations]] path = [ "README.md", @@ -18,6 +19,8 @@ path = [ "locales/po/**", "tests/fixtures/**", "locales/LC_MESSAGES/**", + "templates/**", + "resource/**", ] precedence = "aggregate" SPDX-FileCopyrightText = "2026 Thomas Vincent " diff --git a/lib/BmcRepository.php b/lib/BmcRepository.php index a1c95c3..08bf2e9 100644 --- a/lib/BmcRepository.php +++ b/lib/BmcRepository.php @@ -98,6 +98,53 @@ public function hostExists(int $hostId): bool { return (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM host WHERE id = ?', [$hostId], '', true, $this->connection) === 1; } + /** + * The BMC mapped to a Cacti device, or null. A device carries at most one + * BMC, because the script server finds a BMC by its device. + */ + public function findByHost(int $hostId, int $exceptId = 0): ?Bmc { + $id = $hostId > 0 ? (int) db_fetch_cell_prepared('SELECT id FROM plugin_redfish_bmc WHERE host_id = ? AND id != ? ORDER BY id LIMIT 1', [$hostId, $exceptId], '', true, $this->connection) : 0; + + return $id > 0 ? $this->find($id) : null; + } + + /** + * Map a BMC to a device the provisioner created or attached, with an + * audit entry. + */ + public function mapHost(int $bmcId, int $hostId, int $userId): bool { + $ok = db_execute_prepared('UPDATE plugin_redfish_bmc SET host_id = ?, updated_at = ? WHERE id = ?', [$hostId, $this->clock->now(), $bmcId], true, $this->connection); + + if ($ok) { + $this->audit($bmcId, $userId, 'update', ['host_id']); + } + + return (bool) $ok && $this->find($bmcId)?->hostId === $hostId; + } + + /** + * device_remove hook: BMCs of deleted devices become unmapped. The BMC, + * its credential, and its cache stay (REQ-DEV-003). + * + * @param list $hostIds + */ + public function unmapHosts(array $hostIds): int { + $hostIds = array_values(array_filter($hostIds, static fn (int $id): bool => $id > 0)); + + if ($hostIds === []) { + return 0; + } + + $ids = array_map(static fn (array $row): int => Row::int($row, 'id'), Row::rows(db_fetch_assoc_prepared('SELECT id FROM plugin_redfish_bmc WHERE host_id IN (' . implode(', ', array_fill(0, count($hostIds), '?')) . ')', $hostIds, true, $this->connection))); + + foreach ($ids as $id) { + db_execute_prepared('UPDATE plugin_redfish_bmc SET host_id = 0, updated_at = ? WHERE id = ?', [$this->clock->now(), $id], true, $this->connection); + $this->audit($id, 0, 'unmap', ['host_id']); + } + + return count($ids); + } + /** * Device choices for the edit form: id => description. * diff --git a/lib/BmcsPage.php b/lib/BmcsPage.php index 248c821..2870150 100644 --- a/lib/BmcsPage.php +++ b/lib/BmcsPage.php @@ -59,7 +59,9 @@ public function renderList(): void { . '' . html_escape($bmc->basicFallback ? __('Allowed', 'redfish') : __('Off', 'redfish')) . '' . '' . html_escape($bmc->hostId > 0 ? (string) $bmc->hostId : '-') . '' . '' . html_escape($bmc->enabled() ? __('Enabled', 'redfish') : __('Disabled', 'redfish')) . '' - . '' . Html::action(self::FILE, $bmc->id, 'retry', __('Retry Now', 'redfish')) . ' ' . Html::action(self::FILE, $bmc->id, 'delete', __('Delete', 'redfish')) . '' + . '' . Html::action(self::FILE, $bmc->id, 'retry', __('Retry Now', 'redfish')) + . ' ' . Html::action(self::FILE, $bmc->id, 'provision', $bmc->hostId > 0 ? __('Add Graphs', 'redfish') : __('Create Device', 'redfish')) + . ' ' . Html::action(self::FILE, $bmc->id, 'delete', __('Delete', 'redfish')) . '' . ''; } @@ -68,6 +70,41 @@ public function renderList(): void { $this->renderImport([]); print '

' . html_escape(__('Export the BMC registry as JSON (no secrets)', 'redfish')) . '

'; + + print '

' . Html::action(self::FILE, 0, 'templates', __('Reinstall the Redfish Templates', 'redfish')) . '

'; + } + + /** + * The confirmation page of a device creation or graph attach: what will + * be added, and a form that does it (REQ-DEV-002). Names only the BMC, + * never its address or credential. + * + * @param list $plan + */ + public function renderProvision(Bmc $bmc, array $plan, ?string $refusal): void { + html_start_box($bmc->hostId > 0 ? __('Add Redfish graphs for %s', html_escape($bmc->name), 'redfish') : __('Create a Cacti device for %s', html_escape($bmc->name), 'redfish'), '100%', '', '3', 'center', ''); + + if ($refusal !== null) { + print '' . html_escape($refusal) . ''; + } elseif ($plan === []) { + print '' . html_escape(__('Everything is already in place. Confirming indexes the data queries again and adds graphs for new members only.', 'redfish')) . ''; + } else { + print '' . html_escape(__('Confirming adds:', 'redfish')) . '
    '; + + foreach ($plan as $line) { + print '
  • ' . html_escape($line) . '
  • '; + } + + print '
' . html_escape(__('Existing devices, graphs, and thresholds are not changed.', 'redfish')) . ''; + } + + html_end_box(); + + if ($refusal === null) { + print Html::action(self::FILE, $bmc->id, 'provision_confirm', __('Confirm', 'redfish')); + } + + print ' ' . html_escape(__('Cancel', 'redfish')) . ''; } /** @@ -139,7 +176,7 @@ public function renderEdit(?Bmc $bmc, array $input = [], array $errors = []): vo print Html::text('ca_file', __('CA Bundle File', 'redfish'), $value('ca_file', $bmc->caFile ?? ''), 512, __('For the CA bundle mode: absolute path on the poller to a PEM file that others cannot write.', 'redfish')); print Html::text('pin_sha256', __('Public Key Pin', 'redfish'), $value('pin_sha256', $bmc->pin ?? ''), 51, __('For the pinned mode: base64 SHA-256 of the BMC public key, as sha256//... or the bare hash. A changed key fails until this is updated.', 'redfish')); print Html::checkbox('basic_fallback', __('Allow Basic Authentication Fallback', 'redfish'), $flag('basic_fallback', $bmc->basicFallback ?? false), __('Used only when the BMC offers no session service. Every request then carries the password; the health page warns while it is in use.', 'redfish')); - print Html::select('host_id', __('Device', 'redfish'), $hosts, (string) $hostId, __('The Cacti device this BMC belongs to. This release creates no devices.', 'redfish')); + print Html::select('host_id', __('Device', 'redfish'), $hosts, (string) $hostId, __('The Cacti device of the server this BMC manages. Leave it at none to have the plugin create a device from the list.', 'redfish')); print Html::checkbox('enabled', __('Enabled', 'redfish'), $flag('enabled', $bmc?->enabled() ?? true)); html_end_box(); @@ -190,6 +227,11 @@ public function databaseErrors(Bmc $bmc): array { $errors['host_id'] = __('Device: no Cacti device has this ID.', 'redfish'); } + // The script server finds a BMC by its device (ADR 0015). + if (!isset($errors['host_id']) && $bmc->hostId > 0 && $this->bmcs->findByHost($bmc->hostId, $bmc->id) !== null) { + $errors['host_id'] = __('Device: another BMC is already mapped to this device.', 'redfish'); + } + return $errors; } diff --git a/lib/CactiObjectRepository.php b/lib/CactiObjectRepository.php new file mode 100644 index 0000000..0cd6d88 --- /dev/null +++ b/lib/CactiObjectRepository.php @@ -0,0 +1,132 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_redfish, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_redfish + * + * 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\Redfish; + +/** + * Read-only lookups in Cacti's own tables: templates by hash, devices, and + * graphs. Every change to a Cacti object goes through Cacti's API functions + * in DeviceProvisioner; nothing here writes. + */ +final class CactiObjectRepository { + /** Tables whose rows the plugin looks up by hash. */ + private const HASHED = ['host_template', 'data_input', 'data_template', 'graph_templates', 'snmp_query']; + + public function __construct(private readonly \PDO|false $connection) { + } + + public function idByHash(string $table, string $hash): int { + if (!in_array($table, self::HASHED, true) || preg_match('/^[0-9a-f]{32}$/', $hash) !== 1) { + return 0; + } + + return (int) db_fetch_cell_prepared("SELECT id FROM `$table` WHERE hash = ? ORDER BY id LIMIT 1", [$hash], '', true, $this->connection); + } + + public function graphTemplateId(string $name): int { + return $this->idByHash('graph_templates', TemplateInstaller::hash('graph_template', $name)); + } + + public function queryId(string $name): int { + return $this->idByHash('snmp_query', TemplateInstaller::hash('data_query', $name)); + } + + public function deviceTemplateId(): int { + return $this->idByHash('host_template', TemplateInstaller::hash('host_template', TemplateInstaller::DEVICE_TEMPLATE)); + } + + public function defaultProfileId(): int { + $id = (int) db_fetch_cell_prepared("SELECT id FROM data_source_profiles WHERE `default` = 'on' ORDER BY id LIMIT 1", [], '', true, $this->connection); + + return $id > 0 ? $id : 1; + } + + /** + * @return array{id: int, description: string, poller_id: int, disabled: bool}|null + */ + public function device(int $hostId): ?array { + $row = $hostId > 0 ? db_fetch_row_prepared("SELECT id, description, poller_id, disabled FROM host WHERE id = ? AND deleted = ''", [$hostId], true, $this->connection) : false; + + if (!is_array($row) || Row::int($row, 'id', 0, 1) === 0) { + return null; + } + + return ['id' => Row::int($row, 'id', 0, 1), 'description' => Row::string($row, 'description'), 'poller_id' => Row::int($row, 'poller_id', 1, 1), 'disabled' => Row::string($row, 'disabled') === 'on']; + } + + public function graphCount(int $hostId, int $graphTemplateId): int { + return (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM graph_local WHERE host_id = ? AND graph_template_id = ?', [$hostId, $graphTemplateId], '', true, $this->connection); + } + + public function hasQuery(int $hostId, int $queryId): bool { + return (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM host_snmp_query WHERE host_id = ? AND snmp_query_id = ?', [$hostId, $queryId], '', true, $this->connection) > 0; + } + + /** + * Indexes of a data query on a device that already have a graph from + * one graph template, so a repeated provision adds only missing graphs. + * + * @return list + */ + public function graphedIndexes(int $hostId, int $queryId, int $graphTemplateId): array { + return array_map(static fn (array $row): string => Row::string($row, 'snmp_index'), Row::rows(db_fetch_assoc_prepared('SELECT DISTINCT snmp_index FROM graph_local WHERE host_id = ? AND snmp_query_id = ? AND graph_template_id = ?', [$hostId, $queryId, $graphTemplateId], true, $this->connection))); + } + + /** + * The data query graph id of a graph name under a query, found by hash. + */ + public function queryGraphId(string $queryName, string $graphName): int { + return (int) db_fetch_cell_prepared('SELECT id FROM snmp_query_graph WHERE hash = ?', [TemplateInstaller::hash('data_query_graph', $queryName . ':' . $graphName)], '', true, $this->connection); + } + + /** + * Indexes Cacti cached for a data query on a device. + * + * @return list + */ + public function cachedIndexes(int $hostId, int $queryId): array { + return array_map(static fn (array $row): string => Row::string($row, 'snmp_index'), Row::rows(db_fetch_assoc_prepared('SELECT DISTINCT snmp_index FROM host_snmp_cache WHERE host_id = ? AND snmp_query_id = ? ORDER BY snmp_index', [$hostId, $queryId], true, $this->connection))); + } + + /** + * One field Cacti cached for each index of a data query on a device. + * + * @return array index => value + */ + public function cachedField(int $hostId, int $queryId, string $field): array { + $out = []; + + foreach (Row::rows(db_fetch_assoc_prepared('SELECT snmp_index, field_value FROM host_snmp_cache WHERE host_id = ? AND snmp_query_id = ? AND field_name = ?', [$hostId, $queryId, $field], true, $this->connection)) as $row) { + $out[Row::string($row, 'snmp_index')] = Row::string($row, 'field_value'); + } + + return $out; + } + + /** + * @return list local graph ids of a device, oldest first + */ + public function graphsOf(int $hostId): array { + return array_map(static fn (array $row): int => Row::int($row, 'id', 0, 0), Row::rows(db_fetch_assoc_prepared('SELECT id FROM graph_local WHERE host_id = ? ORDER BY id', [$hostId], true, $this->connection))); + } + + public function hostOfGraph(int $localGraphId): int { + return (int) db_fetch_cell_prepared('SELECT host_id FROM graph_local WHERE id = ?', [$localGraphId], '', true, $this->connection); + } +} diff --git a/lib/DeviceProvisioner.php b/lib/DeviceProvisioner.php new file mode 100644 index 0000000..2555c9e --- /dev/null +++ b/lib/DeviceProvisioner.php @@ -0,0 +1,237 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_redfish, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_redfish + * + * 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\Redfish; + +/** + * Attaches a BMC's readings to a Cacti device (ADR 0015, REQ-DEV-001 to + * REQ-DEV-006): the server's existing device when the operator mapped one, + * otherwise a new device from the "Redfish BMC" device template, created + * only after the administrator confirmed the plan. + * + * Everything goes through Cacti's own functions: api_device_save() for the + * device, api_device_dq_add() for the data queries (which runs the first + * index), create_complete_graph_from_template() for graphs, and + * api_device_remove() to roll back. The plugin writes only its own mapping. + * An existing device keeps every setting; only the data queries and graphs + * are added, and a repeated run adds only what is missing. + */ +final class DeviceProvisioner { + /** Fan graph by the unit Cacti cached for the index. */ + private const FAN_GRAPHS = ['%' => 'Fan Speed Percent', 'RPM' => 'Fan Speed RPM']; + + /** + * @param \Closure(int, int): bool $visible whether a user may see a device + */ + public function __construct( + private readonly BmcRepository $bmcs, + private readonly CactiObjectRepository $objects, + private readonly string $cactiPath, + private readonly \Closure $visible, + ) { + } + + /** + * Why the plugin cannot provision now, or null when it can. + */ + public function refusal(): ?string { + if ($this->objects->deviceTemplateId() === 0) { + return __('The Redfish templates are not installed. Reinstall them from the Redfish BMCs page.', 'redfish'); + } + + return null; + } + + /** + * What provisioning would add, for the confirmation page (REQ-DEV-002). + * + * @param array $members member kind => count in the cache + * + * @return list + */ + public function plan(Bmc $bmc, array $members): array { + $lines = []; + + if ($bmc->hostId === 0) { + $lines[] = __('A device "%s" from the %s device template, polled by poller %d, with availability checks off. Its host name is a reserved name that is never contacted.', $bmc->name, TemplateInstaller::DEVICE_TEMPLATE, $bmc->pollerId, 'redfish'); + } + + foreach (TemplateInstaller::QUERIES as $name => [$kind]) { + if ($bmc->hostId === 0 || !$this->objects->hasQuery($bmc->hostId, $this->objects->queryId($name))) { + $lines[] = __('The data query "%s", with a graph for each of the %d members known now.', $name, $members[$kind] ?? 0, 'redfish'); + } + } + + foreach (TemplateInstaller::SUMMARY_GRAPHS as $name) { + if ($bmc->hostId === 0 || $this->objects->graphCount($bmc->hostId, $this->objects->graphTemplateId($name)) === 0) { + $lines[] = __('The graph "%s", with its "%s" data source.', $name, TemplateInstaller::SUMMARY, 'redfish'); + } + } + + return $lines; + } + + /** + * Create a device for an unmapped BMC and attach it. Returns the new + * device id, or 0 with the reason in $error. A device the creating user + * cannot see is removed again, so nobody is left holding a device that + * the permissions they were given would hide. + */ + public function create(Bmc $bmc, int $userId, ?string &$error = null): int { + $templateId = $this->objects->deviceTemplateId(); + + if ($templateId === 0 || $bmc->hostId > 0) { + $error = $this->refusal() ?? __('The BMC is already mapped to a device.', 'redfish'); + + return 0; + } + + include_once($this->cactiPath . '/lib/api_device.php'); + + $hostId = (int) api_device_save(0, $templateId, $bmc->name, self::hostname($bmc), '', 0, '', '', 161, 500, '', AVAIL_NONE, 0, 23, 400, 1, + __('Created by the Redfish plugin for BMC %s. Its values come from the plugin cache; the host name is a reserved name that is never contacted.', $bmc->name, 'redfish'), + 'MD5', '', 'DES', '', '', 5, 1, $bmc->pollerId, 0); + + if ($hostId <= 0) { + Log::error(sprintf('Cacti refused the device for BMC %d', $bmc->id)); + $error = __('Cacti refused to create the device. See the Cacti log.', 'redfish'); + + return 0; + } + + if (!($this->visible)($hostId, $userId)) { + api_device_remove($hostId); + Log::warning(sprintf('Device %d for BMC %d was removed again: user %d may not see it', $hostId, $bmc->id, $userId)); + $error = __('The new device would be hidden from you by your device permissions, so it was removed again. Ask an administrator to grant access, or map the BMC to a device you can see.', 'redfish'); + + return 0; + } + + if (!$this->bmcs->mapHost($bmc->id, $hostId, $userId)) { + api_device_remove($hostId); + Log::error(sprintf('Device %d was created for BMC %d but could not be mapped, so it was removed again', $hostId, $bmc->id)); + $error = __('The device could not be mapped to the BMC, so it was removed again.', 'redfish'); + + return 0; + } + + $this->attach($bmc->id, $hostId); + + return $hostId; + } + + /** + * Add the data queries, the summary graphs, and a graph for each cached + * index that has none. Safe to repeat: a query already on the device is + * indexed again, and existing graphs are kept. This is also the reindex + * action: indexes that disappeared keep their graphs and read U + * (REQ-DQ-003), and new ones get graphs. + * + * @return int graphs created + */ + public function attach(int $bmcId, int $hostId): int { + include_once($this->cactiPath . '/lib/api_device.php'); + include_once($this->cactiPath . '/lib/data_query.php'); + include_once($this->cactiPath . '/lib/template.php'); + include_once($this->cactiPath . '/lib/utility.php'); + + $created = 0; + + foreach (TemplateInstaller::QUERIES as $name => [$kind]) { + $queryId = $this->objects->queryId($name); + + if ($queryId === 0) { + continue; + } + + if ($this->objects->hasQuery($hostId, $queryId)) { + run_data_query($hostId, $queryId); + } else { + api_device_dq_add($hostId, $queryId, DATA_QUERY_AUTOINDEX_INDEX_NUM_CHANGE); + } + + $created += $this->queryGraphs($bmcId, $hostId, $name, $kind, $queryId); + } + + foreach (TemplateInstaller::SUMMARY_GRAPHS as $name) { + $templateId = $this->objects->graphTemplateId($name); + + if ($templateId === 0 || $this->objects->graphCount($hostId, $templateId) > 0) { + continue; + } + + $none = []; + $suggested = []; + $graph = create_complete_graph_from_template($templateId, $hostId, $none, $suggested); + + if (is_array($graph) && is_numeric($graph['local_graph_id'] ?? null)) { + $created++; + } else { + Log::error(sprintf('Cacti did not create the %s graph for BMC %d', $name, $bmcId)); + } + } + + // Fills the summary data source's host_id input and the poller cache. + push_out_host($hostId, 0); + + return $created; + } + + private function queryGraphs(int $bmcId, int $hostId, string $queryName, string $kind, int $queryId): int { + $created = 0; + $units = $kind === 'fan' ? $this->objects->cachedField($hostId, $queryId, 'redfishUnit') : []; + + foreach ($this->objects->cachedIndexes($hostId, $queryId) as $index) { + $graphName = $kind === 'fan' ? (self::FAN_GRAPHS[$units[$index] ?? ''] ?? null) : array_key_first(TemplateInstaller::QUERY_GRAPHS[$queryName]); + + // A fan whose unit is not known yet gets its graph on a later + // reindex, once the unit is, so it never lands on the wrong axis. + if ($graphName === null) { + continue; + } + + $templateId = $this->objects->graphTemplateId(TemplateInstaller::QUERY_GRAPHS[$queryName][$graphName] ?? ''); + $sqgId = $this->objects->queryGraphId($queryName, $graphName); + + if ($templateId === 0 || $sqgId === 0 || in_array($index, $this->objects->graphedIndexes($hostId, $queryId, $templateId), true)) { + continue; + } + + $suggested = []; + $graph = create_complete_graph_from_template($templateId, $hostId, ['snmp_query_id' => $queryId, 'snmp_index_on' => 'redfishIndex', 'snmp_query_graph_id' => $sqgId, 'snmp_index' => $index], $suggested); + + if (is_array($graph) && is_numeric($graph['local_graph_id'] ?? null)) { + $created++; + } else { + Log::error(sprintf('Cacti did not create the %s graph of index %s for BMC %d', $graphName, $index, $bmcId)); + } + } + + return $created; + } + + /** + * A name in the reserved .invalid domain (RFC 6761), so no lookup or + * availability check of the device reaches the BMC or anything else, and + * the device page never shows the BMC's address (REQ-PERM-002). + */ + public static function hostname(Bmc $bmc): string { + return 'bmc-' . $bmc->id . '.redfish.invalid'; + } +} diff --git a/lib/DeviceWarnings.php b/lib/DeviceWarnings.php new file mode 100644 index 0000000..17990a9 --- /dev/null +++ b/lib/DeviceWarnings.php @@ -0,0 +1,59 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_redfish, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_redfish + * + * 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\Redfish; + +/** + * Health page warnings about the Cacti side: templates that failed to + * install, and mapped devices that are deleted or polled by another poller + * than their BMC (REQ-DEV-006). Template problems are for administrators; + * a device warning is shown to whoever may see that BMC. + */ +final class DeviceWarnings { + /** + * @param list $bmcs the BMCs the viewer may see + * + * @return list + */ + public static function for(array $bmcs, CactiObjectRepository $objects, TemplateInstaller $templates): array { + $out = []; + + if ($templates->failure() !== '') { + $out[] = ['admin' => true, 'message' => __('The Redfish templates could not be installed: %s', $templates->failure(), 'redfish')]; + } elseif (!$templates->isCurrent()) { + $out[] = ['admin' => true, 'message' => __('The Redfish templates are not installed or not current. Reinstall them from the Redfish BMCs page.', 'redfish')]; + } + + foreach ($bmcs as $bmc) { + if ($bmc->hostId === 0) { + continue; + } + + $device = $objects->device($bmc->hostId); + + if ($device === null) { + $out[] = ['admin' => false, 'message' => __('%s: its Cacti device was deleted. Map it to another device or create one from the BMCs page.', $bmc->name, 'redfish')]; + } elseif ($device['poller_id'] !== $bmc->pollerId) { + $out[] = ['admin' => false, 'message' => __('%s: its device is polled by poller %d but the BMC is read by poller %d. Move one of them so both use the same poller, or its graphs can read as unknown.', $bmc->name, $device['poller_id'], $bmc->pollerId, 'redfish')]; + } + } + + return $out; + } +} diff --git a/lib/GraphLinks.php b/lib/GraphLinks.php new file mode 100644 index 0000000..d94ed2c --- /dev/null +++ b/lib/GraphLinks.php @@ -0,0 +1,51 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_redfish, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_redfish + * + * 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\Redfish; + +/** + * The graph_buttons link from any graph of a device with a BMC to all of + * that device's Redfish graphs (REQ-GRAPH-003), so an operator looking at a + * server's SNMP graphs finds its BMC graphs, and back. Cacti's graph and + * device permissions still decide what the linked page shows; the link + * itself names only the device, never the BMC's address or credential. + */ +final class GraphLinks { + public function __construct( + private readonly BmcRepository $bmcs, + private readonly CactiObjectRepository $objects, + ) { + } + + /** + * The device whose Redfish graphs the graph links to, or 0 for no link. + */ + public function hostFor(int $localGraphId): int { + $hostId = $localGraphId > 0 ? $this->objects->hostOfGraph($localGraphId) : 0; + + return $hostId > 0 && $this->bmcs->findByHost($hostId) !== null ? $hostId : 0; + } + + public static function html(string $urlPath, int $hostId): string { + $url = $urlPath . 'graph_view.php?action=preview&reset=1&host_id=' . $hostId . '&rfilter=' . rawurlencode('Redfish'); + $title = __('Redfish graphs of this device', 'redfish'); + + return '
'; + } +} diff --git a/lib/HealthPage.php b/lib/HealthPage.php index 25d7be6..e068353 100644 --- a/lib/HealthPage.php +++ b/lib/HealthPage.php @@ -40,12 +40,13 @@ public function __construct( } /** - * @param bool $admin whether the viewer has Redfish Admin, which alone - * sees credential warnings + * @param bool $admin whether the viewer has Redfish Admin, which alone + * sees credential and template warnings + * @param list $extra warnings about Cacti objects, from DeviceWarnings */ - public function render(Settings $settings, bool $admin): void { + public function render(Settings $settings, bool $admin, array $extra = []): void { $now = $this->clock->now(); - $bmcs = $this->scope->filter($this->bmcs->all()); + $bmcs = self::visible($this->scope->filter($this->bmcs->all()), $admin); $health = []; $has = []; @@ -60,7 +61,7 @@ public function render(Settings $settings, bool $admin): void { $shown = 0; - foreach (HealthWarnings::for($bmcs, $health, $has, $admin ? $this->credentials->keyProblem() : null, $runs, $settings, $now) as $warning) { + foreach (array_merge(HealthWarnings::for($bmcs, $health, $has, $admin ? $this->credentials->keyProblem() : null, $runs, $settings, $now), $extra) as $warning) { if ($warning['admin'] && !$admin) { continue; } @@ -110,6 +111,18 @@ public function render(Settings $settings, bool $admin): void { html_end_box(); } + /** + * A BMC with no Cacti device has no device permission to follow, so only + * Redfish administrators see it (REQ-DEV-005). + * + * @param list $bmcs + * + * @return list + */ + public static function visible(array $bmcs, bool $admin): array { + return $admin ? $bmcs : array_values(array_filter($bmcs, static fn (Bmc $bmc): bool => $bmc->hostId > 0)); + } + /** * The cells of one BMC's row, as plain text. * diff --git a/lib/IndexKey.php b/lib/IndexKey.php new file mode 100644 index 0000000..0f08618 --- /dev/null +++ b/lib/IndexKey.php @@ -0,0 +1,57 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_redfish, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_redfish + * + * 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\Redfish; + +/** + * The data query index of a member: its stable member key (chassis Id, kind, + * member Id; REQ-DISC-005), made safe for Cacti. Cacti keeps each data + * source keyed by this value and re-maps or orphans data sources by it, so + * it must never be a list position (REQ-DQ-002, docs/research/data-query.md). + * + * The value passes through Cacti's `|query_*|` substitution, its `!` output + * delimiter, and a 191-character cache column. A key made only of safe + * characters is used as it is. Any other key has each unsafe character + * replaced and a digest of the original appended, so two keys that differ + * only in unsafe characters never share an index, and the same key always + * gives the same index. + */ +final class IndexKey { + public const MAX = 120; + + private const SAFE = '/^[A-Za-z0-9._:\/-]+$/'; + + public static function of(string $memberKey): string { + if ($memberKey !== '' && strlen($memberKey) <= self::MAX && preg_match(self::SAFE, $memberKey) === 1) { + return $memberKey; + } + + $clean = substr((string) preg_replace('/[^A-Za-z0-9._:\/-]/', '_', $memberKey), 0, self::MAX - 9); + + return $clean . '~' . substr(hash('sha256', $memberKey), 0, 8); + } + + /** + * Whether a value received from Cacti could be an index at all, checked + * before it is compared with anything. + */ + public static function plausible(string $index): bool { + return $index !== '' && strlen($index) <= self::MAX && preg_match('/^[A-Za-z0-9._:\/~-]+$/', $index) === 1; + } +} diff --git a/lib/MemberQuery.php b/lib/MemberQuery.php new file mode 100644 index 0000000..af654d2 --- /dev/null +++ b/lib/MemberQuery.php @@ -0,0 +1,176 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_redfish, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_redfish + * + * 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\Redfish; + +/** + * Answers the three script server data queries, one per member kind: + * fans, temperature sensors, and power supplies (REQ-DQ-001 to REQ-DQ-005). + * + * Cacti runs the index and query steps as a PHP CLI process and the get + * step through the script server, one call per value per index. Every + * argument arrives from Cacti's command line or the script server, so each + * is checked here: the kind and field against fixed lists, the index + * against the index pattern. Anything else is answered with U or an empty + * list and never echoed back. + * + * Indexes are every member of the kind that discovery ever found on the + * device's BMC, including members now absent or gone, so a member that + * disappears keeps its data source and graph and reads U (REQ-DQ-003). A + * value is served only while its member is present and its reading is + * current or delayed. + */ +final class MemberQuery { + /** Kind => output field => [metric, unit the field requires, or '' for any]. */ + public const OUTPUTS = [ + 'fan' => ['fan_percent' => ['fan_speed', '%'], 'fan_rpm' => ['fan_speed', 'RPM'], 'fan_health' => ['health_code', '']], + 'temperature' => ['temperature' => ['temperature_celsius', 'Cel'], 'temp_health' => ['health_code', '']], + 'psu' => ['psu_input_watts' => ['psu_input_watts', 'W'], 'psu_output_watts' => ['psu_output_watts', 'W'], 'psu_health' => ['health_code', '']], + ]; + + /** The reading whose unit the unit field reports, which decides a fan's graph. */ + public const UNIT_METRIC = ['fan' => 'fan_speed', 'temperature' => 'temperature_celsius', 'psu' => 'psu_input_watts']; + + /** Input fields every query has. */ + public const INPUTS = ['index', 'name', 'chassis', 'unit']; + + private const CACHE_SECONDS = 30; + + /** @var array */ + private array $loaded = []; + + public function __construct( + private readonly NodeCacheRepository $caches, + private readonly FreshnessEvaluator $freshness, + private readonly Clock $clock, + ) { + } + + public function answer(int $hostId, string $kind, string $command, string $field = '', string $index = ''): string { + if (!isset(self::OUTPUTS[$kind]) || $hostId <= 0) { + return $command === 'get' ? 'U' : ''; + } + + $cache = $this->load($hostId); + + if ($cache === null) { + return match ($command) { + 'get' => 'U', + 'num_indexes' => '0', + default => '', + }; + } + + $members = $cache->membersOf($kind); + + return match ($command) { + 'index' => self::lines(array_map(static fn (array $m): string => IndexKey::of($m['key']), $members)), + 'num_indexes' => (string) count($members), + 'query' => $this->query($cache, $kind, $field, $members), + 'get' => $this->get($cache, $kind, $field, $index), + default => '', + }; + } + + /** + * @param list $members + */ + private function query(NodeCache $cache, string $kind, string $field, array $members): string { + if (!in_array($field, self::INPUTS, true) && !isset(self::OUTPUTS[$kind][$field])) { + return ''; + } + + $lines = []; + + foreach ($members as $member) { + $lines[] = IndexKey::of($member['key']) . '!' . $this->field($cache, $kind, $field, $member); + } + + return self::lines($lines); + } + + private function get(NodeCache $cache, string $kind, string $field, string $index): string { + if (!isset(self::OUTPUTS[$kind][$field]) || !IndexKey::plausible($index)) { + return 'U'; + } + + $member = $cache->memberAt($kind, $index); + + return $member === null ? 'U' : $this->field($cache, $kind, $field, $member); + } + + /** + * @param array{key: string, kind: string, name: string, chassis: string, presence: string} $member + */ + private function field(NodeCache $cache, string $kind, string $field, array $member): string { + return match ($field) { + 'index' => IndexKey::of($member['key']), + 'name' => self::label($member['name'] !== '' ? $member['name'] : $member['key']), + 'chassis' => self::label($member['chassis']), + 'unit' => self::label($cache->reading($member['key'], self::UNIT_METRIC[$kind] ?? '')['unit'] ?? ''), + default => Number::format($this->value($cache, self::OUTPUTS[$kind][$field] ?? null, $member)), + }; + } + + /** + * @param array{0: string, 1: string}|null $spec metric and required unit of the field + * @param array{key: string, kind: string, name: string, chassis: string, presence: string} $member + */ + private function value(NodeCache $cache, ?array $spec, array $member): ?float { + if ($spec === null || $member['presence'] !== 'present') { + return null; + } + + [$metric, $unit] = $spec; + + // A fan in percent is never presented as RPM, nor the reverse. + if ($unit !== '' && ($cache->reading($member['key'], $metric)['unit'] ?? '') !== $unit) { + return null; + } + + return $cache->served($member['key'], $metric, $this->freshness); + } + + /** + * A BMC-supplied name, as Cacti stores it in its index cache: no + * control characters, no output delimiter, and bounded. + */ + private static function label(string $text): string { + $clean = trim((string) preg_replace('/[\x00-\x1f\x7f!|<>"\'\\\\]+/', ' ', $text)); + + return mb_substr($clean === '' ? '-' : $clean, 0, 100); + } + + private function load(int $hostId): ?NodeCache { + $now = $this->clock->now(); + + if (!isset($this->loaded[$hostId]) || $now - $this->loaded[$hostId]['at'] >= self::CACHE_SECONDS || $now < $this->loaded[$hostId]['at']) { + $this->loaded[$hostId] = ['at' => $now, 'cache' => $this->caches->forHost($hostId)]; + } + + return $this->loaded[$hostId]['cache']; + } + + /** + * @param list $lines + */ + private static function lines(array $lines): string { + return $lines === [] ? '' : implode("\n", $lines) . "\n"; + } +} diff --git a/lib/NodeCache.php b/lib/NodeCache.php new file mode 100644 index 0000000..d011ecd --- /dev/null +++ b/lib/NodeCache.php @@ -0,0 +1,84 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_redfish, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_redfish + * + * 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\Redfish; + +/** + * What the cache holds for the BMC mapped to one Cacti device: the members + * discovery found and the latest reading of each, as the collector stored + * them. The script server answers from this only; it never contacts a BMC + * (REQ-DQ-005, REQ-ALERT-004). + */ +final readonly class NodeCache { + /** + * @param list $members + * @param array> $readings member key => metric => reading + */ + public function __construct( + public int $bmcId, + public int $registeredAt, + public int $lastSuccess, + public array $members, + public array $readings, + ) { + } + + /** + * Members of one kind, ordered by index so every listing agrees. + * + * @return list + */ + public function membersOf(string $kind): array { + $out = array_values(array_filter($this->members, static fn (array $m): bool => $m['kind'] === $kind)); + usort($out, static fn (array $a, array $b): int => strcmp(IndexKey::of($a['key']), IndexKey::of($b['key']))); + + return $out; + } + + /** + * @return array{key: string, kind: string, name: string, chassis: string, presence: string}|null + */ + public function memberAt(string $kind, string $index): ?array { + foreach ($this->members as $member) { + if ($member['kind'] === $kind && IndexKey::of($member['key']) === $index) { + return $member; + } + } + + return null; + } + + /** + * A value the script server may hand to Cacti: the reading exists, is + * current or delayed, and is known. Anything else is unknown, never + * zero (REQ-MODEL-002). + */ + public function served(string $member, string $metric, FreshnessEvaluator $freshness): ?float { + $reading = $this->readings[$member][$metric] ?? null; + + return $reading !== null && $freshness->evaluate($reading['observed_at'])->usable() ? $reading['value'] : null; + } + + /** + * @return array{value: ?float, unit: string, observed_at: int}|null + */ + public function reading(string $member, string $metric): ?array { + return $this->readings[$member][$metric] ?? null; + } +} diff --git a/lib/NodeCacheRepository.php b/lib/NodeCacheRepository.php new file mode 100644 index 0000000..92381bc --- /dev/null +++ b/lib/NodeCacheRepository.php @@ -0,0 +1,83 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_redfish, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_redfish + * + * 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\Redfish; + +/** + * Reads the cache of the BMC mapped to a Cacti device, for the script + * server. Three prepared reads per device; the callers keep the result for + * a short time, because the script server asks for one value at a time. + */ +final class NodeCacheRepository { + public function __construct(private readonly \PDO|false $connection) { + } + + public function forHost(int $hostId): ?NodeCache { + if ($hostId <= 0) { + return null; + } + + return $this->load('b.host_id = ?', $hostId); + } + + public function forBmc(int $bmcId): ?NodeCache { + return $bmcId > 0 ? $this->load('b.id = ?', $bmcId) : null; + } + + /** + * Members the cache holds for a BMC, by kind, for the provisioning plan. + * + * @return array + */ + public function memberCounts(int $bmcId): array { + $counts = []; + + foreach ($this->forBmc($bmcId)->members ?? [] as $member) { + $counts[$member['kind']] = ($counts[$member['kind']] ?? 0) + 1; + } + + return $counts; + } + + /** + * @param 'b.host_id = ?'|'b.id = ?' $where + */ + private function load(string $where, int $id): ?NodeCache { + $row = db_fetch_row_prepared("SELECT b.id, b.created_at, COALESCE(h.last_success, 0) AS last_success FROM plugin_redfish_bmc AS b LEFT JOIN plugin_redfish_health AS h ON h.bmc_id = b.id WHERE $where ORDER BY b.id LIMIT 1", [$id], true, $this->connection); + + if (!is_array($row) || Row::int($row, 'id', 0, 1) === 0) { + return null; + } + + $bmcId = Row::int($row, 'id', 0, 1); + $members = []; + + foreach (Row::rows(db_fetch_assoc_prepared('SELECT member_key, kind, name, chassis_id, presence FROM plugin_redfish_member WHERE bmc_id = ?', [$bmcId], true, $this->connection)) as $m) { + $members[] = ['key' => Row::string($m, 'member_key'), 'kind' => Row::string($m, 'kind'), 'name' => Row::string($m, 'name'), 'chassis' => Row::string($m, 'chassis_id'), 'presence' => Row::string($m, 'presence')]; + } + + $readings = []; + + foreach (Row::rows(db_fetch_assoc_prepared('SELECT member_key, metric, value, unit, observed_at FROM plugin_redfish_reading WHERE bmc_id = ?', [$bmcId], true, $this->connection)) as $r) { + $readings[Row::string($r, 'member_key')][Row::string($r, 'metric')] = ['value' => Row::float($r, 'value'), 'unit' => Row::string($r, 'unit'), 'observed_at' => Row::int($r, 'observed_at', 0, 0)]; + } + + return new NodeCache($bmcId, Row::int($row, 'created_at', 0, 0), Row::int($row, 'last_success', 0, 0), $members, $readings); + } +} diff --git a/lib/Number.php b/lib/Number.php new file mode 100644 index 0000000..8a0d4bd --- /dev/null +++ b/lib/Number.php @@ -0,0 +1,38 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_redfish, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_redfish + * + * 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\Redfish; + +/** + * Values as Cacti's poller reads them: `U` for unknown, otherwise a plain + * decimal without an exponent, which RRDtool and Thold both parse. + */ +final class Number { + public static function format(?float $value): string { + if ($value === null || !is_finite($value)) { + return 'U'; + } + + if (floor($value) === $value && abs($value) < 1e15) { + return (string) (int) $value; + } + + return rtrim(rtrim(number_format($value, 3, '.', ''), '0'), '.'); + } +} diff --git a/lib/Schema.php b/lib/Schema.php index 0aca00e..7c5a84b 100644 --- a/lib/Schema.php +++ b/lib/Schema.php @@ -37,9 +37,12 @@ final class Schema { public const VERSION = 1; public const HOOKS = [ + 'api_device_new' => 'redfish_api_device_new', 'config_arrays' => 'redfish_config_arrays', 'config_settings' => 'redfish_config_settings', + 'device_remove' => 'redfish_device_remove', 'draw_navigation_text' => 'redfish_draw_navigation_text', + 'graph_buttons' => 'redfish_graph_buttons', 'poller_bottom' => 'redfish_poller_bottom', ]; @@ -215,7 +218,8 @@ public static function tables(): array { ], 'primary' => 'id', 'unique_keys' => [['name' => 'name', 'columns' => ['name']], ['name' => 'address_port', 'columns' => ['address', 'port']]], - 'keys' => [['name' => 'poller_id', 'columns' => ['poller_id']], ['name' => 'credential_id', 'columns' => ['credential_id']]], + // host_id: the script server finds a device's BMC on every poll. + 'keys' => [['name' => 'poller_id', 'columns' => ['poller_id']], ['name' => 'credential_id', 'columns' => ['credential_id']], ['name' => 'host_id', 'columns' => ['host_id']]], ], 'plugin_redfish_credential' => $innodb + [ 'comment' => 'BMC credentials; the password is in plugin_redfish_secret', diff --git a/lib/SummaryScript.php b/lib/SummaryScript.php new file mode 100644 index 0000000..e8218b1 --- /dev/null +++ b/lib/SummaryScript.php @@ -0,0 +1,117 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_redfish, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_redfish + * + * 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\Redfish; + +/** + * Answers the "Redfish Node Summary" script server input: every summary + * value as name:value pairs in one call (REQ-ALERT-001 to REQ-ALERT-004), + * from the cache only. + * + * Every value but age is U when its readings are missing, stale, or never + * observed, never 0 (REQ-ALERT-002). The fan and supply counts are U unless + * the node's own health reading is usable, so a BMC that stopped answering + * never reports "no bad fans". age is the seconds since the last successful + * read, or since the BMC was registered when no read has succeeded, so it + * is always a number while the BMC is registered (REQ-ALERT-003) and Thold + * can alert on a BMC that stopped answering. + */ +final class SummaryScript { + public const VALUES = ['power_watts', 'inlet_celsius', 'max_temp_celsius', 'fans_bad', 'psus_bad', 'health_code', 'age']; + + public function __construct( + private readonly NodeCacheRepository $caches, + private readonly FreshnessEvaluator $freshness, + private readonly Clock $clock, + ) { + } + + public function answer(int $hostId): string { + return self::format($this->values($this->caches->forHost($hostId))); + } + + /** + * @return array value name => value, null for U + */ + public function values(?NodeCache $cache): array { + $out = array_fill_keys(self::VALUES, null); + + if ($cache === null) { + return $out; + } + + $node = fn (string $metric): ?float => $cache->served(Member::NODE, $metric, $this->freshness); + + $out['power_watts'] = $node('power_watts'); + $out['inlet_celsius'] = $node('inlet_celsius'); + $out['health_code'] = $node('health_code'); + + foreach ($cache->membersOf('temperature') as $member) { + $value = $member['presence'] === 'present' ? $cache->served($member['key'], 'temperature_celsius', $this->freshness) : null; + + if ($value !== null) { + $out['max_temp_celsius'] = max($out['max_temp_celsius'] ?? $value, $value); + } + } + + if ($out['health_code'] !== null) { + $out['fans_bad'] = (float) $this->bad($cache, 'fan'); + $out['psus_bad'] = (float) $this->bad($cache, 'psu'); + } + + $since = $cache->lastSuccess > 0 ? $cache->lastSuccess : $cache->registeredAt; + $out['age'] = (float) max(0, $this->clock->now() - $since); + + return $out; + } + + /** + * Present members of a kind whose usable health is Warning or worse. A + * second fan rotor shares its fan's health and is not counted twice; + * absent members are counted by the node, not here. + */ + private function bad(NodeCache $cache, string $kind): int { + $bad = 0; + + foreach ($cache->membersOf($kind) as $member) { + if ($member['presence'] !== 'present' || str_ends_with($member['key'], ':secondary')) { + continue; + } + + if (($cache->served($member['key'], 'health_code', $this->freshness) ?? 0.0) >= 1.0) { + $bad++; + } + } + + return $bad; + } + + /** + * @param array $values + */ + public static function format(array $values): string { + $pairs = []; + + foreach (self::VALUES as $name) { + $pairs[] = $name . ':' . Number::format($values[$name] ?? null); + } + + return implode(' ', $pairs); + } +} diff --git a/lib/TemplateInstaller.php b/lib/TemplateInstaller.php new file mode 100644 index 0000000..ae8f6e0 --- /dev/null +++ b/lib/TemplateInstaller.php @@ -0,0 +1,317 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_redfish, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_redfish + * + * 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\Redfish; + +/** + * Imports the shipped device, data, and graph templates and the three data + * queries with Cacti's own import_xml_data() (REQ-TPL-001, REQ-TPL-002), and + * installs the data query XML files under Cacti's resource/script_server/. + * + * templates/redfish-templates.xml is Cacti's own export of templates that + * tests/bin/build-templates.php builds in a disposable Cacti; it is never + * edited by hand. Every object carries a hash derived from its name, so a + * second import updates the objects of the first instead of adding copies, + * and the plugin finds its objects by hash even after an operator renames + * them. Import updates templates only; graphs, data sources, thresholds, + * and tree entries made from them stay (REQ-TPL-004). + * + * Cacti 1.2.31 and 1.2.x read a data query XML only from inside + * /resource (get_data_query_array() rejects any other path after + * resolving it), so the files are copied there. A file the plugin did not + * write, or that was changed after it was written, is never replaced or + * removed: the plugin records the SHA-256 of each file it wrote. + */ +final class TemplateInstaller { + /** Bump when templates/redfish-templates.xml or a query XML changes. */ + public const VERSION = 1; + + public const SETTING = 'redfish_templates_version'; + public const FAILURE_SETTING = 'redfish_templates_failure'; + public const FILES_SETTING = 'redfish_query_files'; + + public const DEVICE_TEMPLATE = 'Redfish BMC'; + public const SUMMARY = 'Redfish Node Summary'; + + /** Graph templates of the summary data source, on every mapped device. */ + public const SUMMARY_GRAPHS = [ + 'Redfish - Node Power', + 'Redfish - Node Temperatures', + 'Redfish - Node Component Health', + 'Redfish - Node Data Age', + ]; + + /** Data query name => [member kind, XML file], one query per kind. */ + public const QUERIES = [ + 'Redfish Fans' => ['fan', 'redfish_fans.xml'], + 'Redfish Temperatures' => ['temperature', 'redfish_temperatures.xml'], + 'Redfish Power Supplies' => ['psu', 'redfish_psus.xml'], + ]; + + /** + * Graph template per data query graph, by query. Each per-index graph + * template has a data template of the same name holding exactly the + * values it draws. Fans have one template per unit, so percent and RPM + * never share an axis (REQ-GRAPH-005). + */ + public const QUERY_GRAPHS = [ + 'Redfish Fans' => ['Fan Speed Percent' => 'Redfish - Fan Speed Percent', 'Fan Speed RPM' => 'Redfish - Fan Speed RPM'], + 'Redfish Temperatures' => ['Temperature' => 'Redfish - Temperature'], + 'Redfish Power Supplies' => ['Power Supply' => 'Redfish - Power Supply'], + ]; + + /** + * @param string $pluginPath the plugin directory + * @param string $cactiPath Cacti's base path + */ + public function __construct( + private readonly string $pluginPath, + private readonly string $cactiPath, + private readonly CactiObjectRepository $objects, + ) { + } + + /** + * The hash the template builder gives an object, 32 hex characters as + * Cacti stores it. + */ + public static function hash(string $kind, string $name): string { + return md5('plugin_redfish:' . $kind . ':' . $name); + } + + public function isCurrent(): bool { + return (int) read_config_option(self::SETTING) === self::VERSION && $this->present() && $this->queryFileProblems() === []; + } + + /** + * The reason the last install failed, or '' when it succeeded. + */ + public function failure(): string { + return (string) read_config_option(self::FAILURE_SETTING); + } + + /** + * Install the query files and import the templates. A failure is logged + * and kept for the health page; success clears it. + */ + public function install(): bool { + $error = $this->installQueryFiles() ?? $this->import(); + + if ($error !== null) { + Log::error($error); + set_config_option(self::FAILURE_SETTING, $error); + + return false; + } + + set_config_option(self::SETTING, (string) self::VERSION); + set_config_option(self::FAILURE_SETTING, ''); + + return true; + } + + /** + * Remove the query files the plugin wrote and nobody changed since. The + * templates and every Cacti object made from them stay: they belong to + * the site once imported. + */ + public function uninstall(): void { + $written = $this->written(); + + foreach ($written as $file => $hash) { + $target = $this->queryTarget($file); + + if ($target !== null && is_file($target) && hash_file('sha256', $target) === $hash) { + @unlink($target); + } + } + + set_config_option(self::FILES_SETTING, ''); + set_config_option(self::SETTING, ''); + } + + /** + * Every shipped object exists, found by hash. + */ + public function present(): bool { + if ($this->objects->idByHash('host_template', self::hash('host_template', self::DEVICE_TEMPLATE)) === 0) { + return false; + } + + if ($this->objects->idByHash('data_input', self::hash('data_input', self::SUMMARY)) === 0) { + return false; + } + + $perTarget = array_merge(...array_map('array_values', array_values(self::QUERY_GRAPHS))); + + foreach (array_merge([self::SUMMARY], $perTarget) as $name) { + if ($this->objects->idByHash('data_template', self::hash('data_template', $name)) === 0) { + return false; + } + } + + foreach (array_merge(self::SUMMARY_GRAPHS, $perTarget) as $name) { + if ($this->objects->idByHash('graph_templates', self::hash('graph_template', $name)) === 0) { + return false; + } + } + + foreach (array_keys(self::QUERIES) as $name) { + if ($this->objects->idByHash('snmp_query', self::hash('data_query', $name)) === 0) { + return false; + } + } + + return true; + } + + /** + * Query files that are missing from Cacti's resource tree or differ from + * the shipped ones. + * + * @return list file names + */ + public function queryFileProblems(): array { + $problems = []; + + foreach (self::QUERIES as [, $file]) { + $source = $this->querySource($file); + $target = $this->queryTarget($file); + + if ($target === null || !is_file($target) || !is_file($source) || hash_file('sha256', $target) !== hash_file('sha256', $source)) { + $problems[] = $file; + } + } + + return $problems; + } + + /** + * @return string|null the reason, or null when every file is in place + */ + private function installQueryFiles(): ?string { + $written = $this->written(); + $changed = false; + + foreach (self::QUERIES as [, $file]) { + $source = $this->querySource($file); + $target = $this->queryTarget($file); + + if ($target === null || !is_file($source)) { + return sprintf('The data query file %s cannot be installed: the source or the Cacti resource directory is missing', $file); + } + + $want = (string) hash_file('sha256', $source); + + if (is_file($target)) { + $have = (string) hash_file('sha256', $target); + + if ($have === $want) { + $written[$file] ??= $want; + + continue; + } + + if (($written[$file] ?? null) !== $have) { + return sprintf('%s exists and was not written by this plugin, or was changed after; it was left as it is. Compare it with plugins/redfish/resource/script_server/%s', $target, $file); + } + } + + if (!is_writable(dirname($target)) || @copy($source, $target) === false || hash_file('sha256', $target) !== $want) { + return sprintf('Could not write %s. Copy plugins/redfish/resource/script_server/%s there as the web server user, then reinstall the templates from the Redfish BMCs page', $target, $file); + } + + $written[$file] = $want; + $changed = true; + } + + if ($changed || $written !== $this->written()) { + set_config_option(self::FILES_SETTING, (string) json_encode($written)); + } + + return null; + } + + /** + * @return string|null the reason, or null when every object imported + */ + private function import(): ?string { + $file = $this->pluginPath . '/templates/redfish-templates.xml'; + $xml = is_readable($file) ? file_get_contents($file) : false; + + if (!is_string($xml) || $xml === '') { + return 'The template file ' . $file . ' is missing or empty'; + } + + include_once($this->cactiPath . '/lib/utility.php'); + include_once($this->cactiPath . '/lib/import.php'); + + $result = import_xml_data($xml, false, $this->objects->defaultProfileId()); + + if (!is_array($result) || $result === []) { + return 'Importing the Redfish templates returned nothing'; + } + + $failed = 0; + + foreach ($result as $type => $entries) { + if ($type === 'files' || !is_array($entries)) { + continue; + } + + foreach ($entries as $entry) { + if (is_array($entry) && ($entry['result'] ?? '') === 'fail') { + $failed++; + } + } + } + + if ($failed > 0) { + return sprintf('%d Redfish template objects failed to import', $failed); + } + + return $this->present() ? null : 'The Redfish templates are missing after import'; + } + + /** + * @return array file name => SHA-256 the plugin wrote + */ + private function written(): array { + $decoded = json_decode((string) read_config_option(self::FILES_SETTING), true); + $out = []; + + foreach (is_array($decoded) ? $decoded : [] as $file => $hash) { + if (is_string($file) && is_string($hash) && preg_match('/^[0-9a-f]{64}$/', $hash) === 1 && in_array($file, array_column(self::QUERIES, 1), true)) { + $out[$file] = $hash; + } + } + + return $out; + } + + private function querySource(string $file): string { + return $this->pluginPath . '/resource/script_server/' . $file; + } + + private function queryTarget(string $file): ?string { + $dir = $this->cactiPath . '/resource/script_server'; + + return is_dir($dir) ? $dir . '/' . $file : null; + } +} diff --git a/locales/po/cacti.pot b/locales/po/cacti.pot index d525004..3d69bf1 100644 --- a/locales/po/cacti.pot +++ b/locales/po/cacti.pot @@ -186,16 +186,58 @@ msgstr "" msgid "Enabled" msgstr "" +#: lib/BmcsPage.php +msgid "Retry Now" +msgstr "" + +#: lib/BmcsPage.php +msgid "Add Graphs" +msgstr "" + +#: lib/BmcsPage.php +msgid "Create Device" +msgstr "" + #: lib/BmcsPage.php lib/CredentialsPage.php msgid "Delete" msgstr "" #: lib/BmcsPage.php -msgid "Retry Now" +msgid "Export the BMC registry as JSON (no secrets)" msgstr "" #: lib/BmcsPage.php -msgid "Export the BMC registry as JSON (no secrets)" +msgid "Reinstall the Redfish Templates" +msgstr "" + +#: lib/BmcsPage.php +#, php-format +msgid "Add Redfish graphs for %s" +msgstr "" + +#: lib/BmcsPage.php +#, php-format +msgid "Create a Cacti device for %s" +msgstr "" + +#: lib/BmcsPage.php +msgid "Everything is already in place. Confirming indexes the data queries again and adds graphs for new members only." +msgstr "" + +#: lib/BmcsPage.php +msgid "Confirming adds:" +msgstr "" + +#: lib/BmcsPage.php +msgid "Existing devices, graphs, and thresholds are not changed." +msgstr "" + +#: lib/BmcsPage.php +msgid "Confirm" +msgstr "" + +#: lib/BmcsPage.php +msgid "Cancel" msgstr "" #: lib/BmcsPage.php @@ -270,7 +312,7 @@ msgid "Used only when the BMC offers no session service. Every request then carr msgstr "" #: lib/BmcsPage.php -msgid "The Cacti device this BMC belongs to. This release creates no devices." +msgid "The Cacti device of the server this BMC manages. Leave it at none to have the plugin create a device from the list." msgstr "" #: lib/BmcsPage.php lib/CredentialsPage.php @@ -294,6 +336,10 @@ msgstr "" msgid "Device: no Cacti device has this ID." msgstr "" +#: lib/BmcsPage.php +msgid "Device: another BMC is already mapped to this device." +msgstr "" + #: lib/CredentialsPage.php lib/Pages.php msgid "Redfish Credentials" msgstr "" @@ -348,6 +394,69 @@ msgstr "" msgid "Stored encrypted with the vault key." msgstr "" +#: lib/DeviceProvisioner.php +msgid "The Redfish templates are not installed. Reinstall them from the Redfish BMCs page." +msgstr "" + +#: lib/DeviceProvisioner.php +#, php-format +msgid "A device \"%s\" from the %s device template, polled by poller %d, with availability checks off. Its host name is a reserved name that is never contacted." +msgstr "" + +#: lib/DeviceProvisioner.php +#, php-format +msgid "The data query \"%s\", with a graph for each of the %d members known now." +msgstr "" + +#: lib/DeviceProvisioner.php +#, php-format +msgid "The graph \"%s\", with its \"%s\" data source." +msgstr "" + +#: lib/DeviceProvisioner.php +msgid "The BMC is already mapped to a device." +msgstr "" + +#: lib/DeviceProvisioner.php +#, php-format +msgid "Created by the Redfish plugin for BMC %s. Its values come from the plugin cache; the host name is a reserved name that is never contacted." +msgstr "" + +#: lib/DeviceProvisioner.php +msgid "Cacti refused to create the device. See the Cacti log." +msgstr "" + +#: lib/DeviceProvisioner.php +msgid "The new device would be hidden from you by your device permissions, so it was removed again. Ask an administrator to grant access, or map the BMC to a device you can see." +msgstr "" + +#: lib/DeviceProvisioner.php +msgid "The device could not be mapped to the BMC, so it was removed again." +msgstr "" + +#: lib/DeviceWarnings.php +#, php-format +msgid "The Redfish templates could not be installed: %s" +msgstr "" + +#: lib/DeviceWarnings.php +msgid "The Redfish templates are not installed or not current. Reinstall them from the Redfish BMCs page." +msgstr "" + +#: lib/DeviceWarnings.php +#, php-format +msgid "%s: its Cacti device was deleted. Map it to another device or create one from the BMCs page." +msgstr "" + +#: lib/DeviceWarnings.php +#, php-format +msgid "%s: its device is polled by poller %d but the BMC is read by poller %d. Move one of them so both use the same poller, or its graphs can read as unknown." +msgstr "" + +#: lib/GraphLinks.php +msgid "Redfish graphs of this device" +msgstr "" + #: lib/HealthPage.php msgid "Redfish Warnings" msgstr "" @@ -689,6 +798,35 @@ msgstr "" msgid "Backoff and held failures were cleared; the collector reads the BMC on its next run." msgstr "" +#: redfish_bmcs.php +msgid "Adding devices and graphs needs Cacti's device management permission." +msgstr "" + +#: redfish_bmcs.php +msgid "The device of this BMC was deleted. Choose another device, or none, on the BMC form first." +msgstr "" + +#: redfish_bmcs.php +#, php-format +msgid "The data queries were indexed again and %d graphs were added." +msgstr "" + +#: redfish_bmcs.php +msgid "The device was created with its Redfish graphs." +msgstr "" + +#: redfish_bmcs.php +msgid "Installing the Redfish templates needs Cacti's Import Templates permission." +msgstr "" + +#: redfish_bmcs.php +msgid "The Redfish templates are installed." +msgstr "" + +#: redfish_bmcs.php +msgid "The Redfish templates could not be installed. The health page shows why." +msgstr "" + #: redfish_bmcs.php msgid "The import could not be saved; nothing was imported." msgstr "" diff --git a/redfish_bmcs.php b/redfish_bmcs.php index 036c43c..2be3e0a 100644 --- a/redfish_bmcs.php +++ b/redfish_bmcs.php @@ -31,7 +31,7 @@ exit; } -redfish_require_post('redfish_bmcs.php', array('save', 'delete', 'retry', 'import')); +redfish_require_post('redfish_bmcs.php', array('save', 'delete', 'retry', 'import', 'provision', 'provision_confirm', 'templates')); $redfish_bmcs = redfish_bmcs(); $redfish_scope = redfish_device_scope(); @@ -108,6 +108,60 @@ function redfish_requested_bmc(\Somethingwithproof\Redfish\BmcRepository $bmcs, raise_message('redfish_retry', __('Backoff and held failures were cleared; the collector reads the BMC on its next run.', 'redfish'), MESSAGE_LEVEL_INFO); } + header('Location: redfish_bmcs.php'); + exit; + case 'provision': + case 'provision_confirm': + $redfish_bmc = redfish_requested_bmc($redfish_bmcs, $redfish_scope, (int) get_filter_request_var('id')); + + if ($redfish_bmc === null) { + header('Location: redfish_bmcs.php'); + exit; + } + + $redfish_provisioner = redfish_provisioner(); + $redfish_objects = redfish_cacti_objects(); + + // Adding a device, data queries, or graphs is device management in + // Cacti, so it needs that realm as well as Redfish Admin (ADR 0015). + // A mapping to a device deleted since cannot take graphs. + $redfish_refusal = $redfish_provisioner->refusal(); + + if (!is_realm_allowed(3)) { + $redfish_refusal = __('Adding devices and graphs needs Cacti\'s device management permission.', 'redfish'); + } elseif ($redfish_bmc->hostId > 0 && $redfish_objects->device($redfish_bmc->hostId) === null) { + $redfish_refusal = __('The device of this BMC was deleted. Choose another device, or none, on the BMC form first.', 'redfish'); + } + + if (get_nfilter_request_var('action') === 'provision' || $redfish_refusal !== null) { + top_header(); + $redfish_page->renderProvision($redfish_bmc, $redfish_refusal === null ? $redfish_provisioner->plan($redfish_bmc, (new \Somethingwithproof\Redfish\NodeCacheRepository(false))->memberCounts($redfish_bmc->id)) : array(), $redfish_refusal); + bottom_footer(); + exit; + } + + if ($redfish_bmc->hostId > 0) { + $redfish_graphs = $redfish_provisioner->attach($redfish_bmc->id, $redfish_bmc->hostId); + raise_message('redfish_provisioned', __('The data queries were indexed again and %d graphs were added.', $redfish_graphs, 'redfish'), MESSAGE_LEVEL_INFO); + } else { + $redfish_error = null; + $redfish_host = $redfish_provisioner->create($redfish_bmc, $redfish_user, $redfish_error); + + raise_message('redfish_provisioned', $redfish_host > 0 ? __('The device was created with its Redfish graphs.', 'redfish') : (string) $redfish_error, $redfish_host > 0 ? MESSAGE_LEVEL_INFO : MESSAGE_LEVEL_ERROR); + } + + header('Location: redfish_bmcs.php'); + exit; + case 'templates': + // Import updates templates already in Cacti, so it needs Cacti's + // Import Templates permission as well as Redfish Admin. + if (!is_realm_allowed(17)) { + raise_message('redfish_templates', __('Installing the Redfish templates needs Cacti\'s Import Templates permission.', 'redfish'), MESSAGE_LEVEL_ERROR); + } else { + $redfish_installed = redfish_template_installer()->install(); + raise_message('redfish_templates', $redfish_installed ? __('The Redfish templates are installed.', 'redfish') : __('The Redfish templates could not be installed. The health page shows why.', 'redfish'), $redfish_installed ? MESSAGE_LEVEL_INFO : MESSAGE_LEVEL_ERROR); + } + header('Location: redfish_bmcs.php'); exit; case 'import': diff --git a/redfish_health.php b/redfish_health.php index 12eef08..2b71a88 100644 --- a/redfish_health.php +++ b/redfish_health.php @@ -45,5 +45,6 @@ ); top_header(); -$redfish_page->render($redfish_settings, api_user_realm_auth('redfish_bmcs.php')); +$redfish_admin = api_user_realm_auth('redfish_bmcs.php'); +$redfish_page->render($redfish_settings, $redfish_admin, \Somethingwithproof\Redfish\DeviceWarnings::for(\Somethingwithproof\Redfish\HealthPage::visible(redfish_device_scope()->filter(redfish_bmcs()->all()), $redfish_admin), redfish_cacti_objects(), redfish_template_installer())); bottom_footer(); diff --git a/resource/script_server/redfish_fans.xml b/resource/script_server/redfish_fans.xml new file mode 100644 index 0000000..a3639e4 --- /dev/null +++ b/resource/script_server/redfish_fans.xml @@ -0,0 +1,54 @@ + + Redfish Fans + Fans of a server, read over Redfish and answered from the plugin cache + |path_cacti|/plugins/redfish/scripts/ss_redfish_members.php + ss_redfish_members + php + |host_id| fan + index + query + get + num_indexes + ! + redfishIndex + alphabetic + |chosen_order_field| + + + + Member Key + input + index + + + Name + input + name + + + Chassis + input + chassis + + + Unit + input + unit + + + Fan Speed (percent) + output + fan_percent + + + Fan Speed (RPM) + output + fan_rpm + + + Fan Health (0 OK, 1 Warning, 2 Critical) + output + fan_health + + + diff --git a/resource/script_server/redfish_psus.xml b/resource/script_server/redfish_psus.xml new file mode 100644 index 0000000..8dac954 --- /dev/null +++ b/resource/script_server/redfish_psus.xml @@ -0,0 +1,54 @@ + + Redfish Power Supplies + Power supplies of a server, read over Redfish and answered from the plugin cache + |path_cacti|/plugins/redfish/scripts/ss_redfish_members.php + ss_redfish_members + php + |host_id| psu + index + query + get + num_indexes + ! + redfishIndex + alphabetic + |chosen_order_field| + + + + Member Key + input + index + + + Name + input + name + + + Chassis + input + chassis + + + Unit + input + unit + + + Input Power (W) + output + psu_input_watts + + + Output Power (W) + output + psu_output_watts + + + Supply Health (0 OK, 1 Warning, 2 Critical) + output + psu_health + + + diff --git a/resource/script_server/redfish_temperatures.xml b/resource/script_server/redfish_temperatures.xml new file mode 100644 index 0000000..e57605a --- /dev/null +++ b/resource/script_server/redfish_temperatures.xml @@ -0,0 +1,49 @@ + + Redfish Temperatures + Temperature sensors of a server, read over Redfish and answered from the plugin cache + |path_cacti|/plugins/redfish/scripts/ss_redfish_members.php + ss_redfish_members + php + |host_id| temperature + index + query + get + num_indexes + ! + redfishIndex + alphabetic + |chosen_order_field| + + + + Member Key + input + index + + + Name + input + name + + + Chassis + input + chassis + + + Unit + input + unit + + + Temperature (degrees Celsius) + output + temperature + + + Sensor Health (0 OK, 1 Warning, 2 Critical) + output + temp_health + + + diff --git a/scripts/ss_redfish_members.php b/scripts/ss_redfish_members.php new file mode 100644 index 0000000..9baeb41 --- /dev/null +++ b/scripts/ss_redfish_members.php @@ -0,0 +1,61 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_redfish, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_redfish + * + * 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. + */ + +/* + * Script server data queries for the fans, temperature sensors, and power + * supplies of a BMC (resource/script_server/redfish_*.xml). Cacti runs this + * file as a PHP CLI process for the index and query steps and through the + * script server for each polled value. It answers from the plugin cache + * only and never contacts a BMC (REQ-DQ-005). + * + * This file must parse on PHP 8.0: the script server includes it on + * whatever PHP the site runs, and redfish_boot() refuses before any plugin + * class loads, answering U. + */ + +if (!isset($called_by_script_server)) { + include_once(__DIR__ . '/../../../include/cli_check.php'); + + $redfish_args = isset($_SERVER['argv']) && is_array($_SERVER['argv']) ? array_values(array_filter(array_slice($_SERVER['argv'], 1), 'is_string')) : array(); + + print ss_redfish_members(...$redfish_args); +} + +/** + * @param int|string $host_id the Cacti device the BMC is mapped to + * @param string $kind fan, temperature, or psu, fixed by the query XML + * @param string $cmd index, num_indexes, query, or get + * @param string $arg1 the field for query and get + * @param string $arg2 the index for get + */ +function ss_redfish_members($host_id = 0, $kind = '', $cmd = 'index', $arg1 = '', $arg2 = ''): string { + static $query = null; + + include_once(dirname(__DIR__) . '/setup.php'); + + if (!redfish_boot()) { + return $cmd === 'get' ? 'U' : ''; + } + + if ($query === null) { + $query = redfish_member_query(); + } + + return $query->answer((int) $host_id, (string) $kind, (string) $cmd, (string) $arg1, (string) $arg2); +} diff --git a/scripts/ss_redfish_summary.php b/scripts/ss_redfish_summary.php new file mode 100644 index 0000000..2918640 --- /dev/null +++ b/scripts/ss_redfish_summary.php @@ -0,0 +1,55 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_redfish, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_redfish + * + * 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. + */ + +/* + * Script server input "Redfish Node Summary": the summary values of the BMC + * mapped to a Cacti device as name:value pairs, from the plugin cache only + * (REQ-ALERT-001 to REQ-ALERT-004). Thold reads these values through + * Cacti's poller output. + * + * This file must parse on PHP 8.0 for the same reason as + * ss_redfish_members.php. + */ + +if (!isset($called_by_script_server)) { + include_once(__DIR__ . '/../../../include/cli_check.php'); + + $redfish_args = isset($_SERVER['argv']) && is_array($_SERVER['argv']) ? array_values(array_filter(array_slice($_SERVER['argv'], 1), 'is_string')) : array(); + + print ss_redfish_summary(...$redfish_args); +} + +/** + * @param int|string $host_id the Cacti device the BMC is mapped to + */ +function ss_redfish_summary($host_id = 0): string { + static $script = null; + + include_once(dirname(__DIR__) . '/setup.php'); + + if (!redfish_boot()) { + return 'power_watts:U inlet_celsius:U max_temp_celsius:U fans_bad:U psus_bad:U health_code:U age:U'; + } + + if ($script === null) { + $script = redfish_summary_script(); + } + + return $script->answer((int) $host_id); +} diff --git a/setup.php b/setup.php index f0a0b3e..6541fce 100644 --- a/setup.php +++ b/setup.php @@ -192,6 +192,45 @@ function redfish_credential_store(): \Somethingwithproof\Redfish\CredentialStore return new \Somethingwithproof\Redfish\CredentialStore(redfish_credentials(), redfish_settings()->vaultKeyFile); } +function redfish_cacti_objects(): \Somethingwithproof\Redfish\CactiObjectRepository { + return new \Somethingwithproof\Redfish\CactiObjectRepository(false); +} + +function redfish_template_installer(): \Somethingwithproof\Redfish\TemplateInstaller { + global $config; + + return new \Somethingwithproof\Redfish\TemplateInstaller(__DIR__, $config['base_path'], redfish_cacti_objects()); +} + +function redfish_provisioner(): \Somethingwithproof\Redfish\DeviceProvisioner { + global $config; + + return new \Somethingwithproof\Redfish\DeviceProvisioner( + redfish_bmcs(), + redfish_cacti_objects(), + $config['base_path'], + static fn (int $hostId, int $userId): bool => (bool) is_device_allowed($hostId, $userId) + ); +} + +/** + * The data query answerer of scripts/ss_redfish_members.php. + */ +function redfish_member_query(): \Somethingwithproof\Redfish\MemberQuery { + $clock = new \Somethingwithproof\Redfish\SystemClock(); + + return new \Somethingwithproof\Redfish\MemberQuery(new \Somethingwithproof\Redfish\NodeCacheRepository(false), \Somethingwithproof\Redfish\FreshnessEvaluator::fromSettings($clock, redfish_settings()), $clock); +} + +/** + * The summary answerer of scripts/ss_redfish_summary.php. + */ +function redfish_summary_script(): \Somethingwithproof\Redfish\SummaryScript { + $clock = new \Somethingwithproof\Redfish\SystemClock(); + + return new \Somethingwithproof\Redfish\SummaryScript(new \Somethingwithproof\Redfish\NodeCacheRepository(false), \Somethingwithproof\Redfish\FreshnessEvaluator::fromSettings($clock, redfish_settings()), $clock); +} + /** * Bring the schema, hooks, and realms up to the code's version. * @@ -210,10 +249,15 @@ function plugin_redfish_upgrade(bool $grant = false): bool { return false; } - $info = plugin_redfish_version(); - $schema = new \Somethingwithproof\Redfish\Schema(false); + $info = plugin_redfish_version(); + $schema = new \Somethingwithproof\Redfish\Schema(false); + $templates = redfish_template_installer(); + + // A template install that failed for this template version is retried + // only from the Plugins page or the health page, not on every request. + $templatesSettled = $templates->isCurrent() || ($templates->failure() !== '' && !$grant); - if ($schema->isCurrent() && $schema->recordedPluginVersion() === $info['version'] && $schema->hooksRegistered()) { + if ($schema->isCurrent() && $schema->recordedPluginVersion() === $info['version'] && $schema->hooksRegistered() && $templatesSettled) { return true; } @@ -225,6 +269,12 @@ function plugin_redfish_upgrade(bool $grant = false): bool { redfish_setup_hooks($grant); + // A missing template stops only device provisioning, which the health + // page reports; the plugin's pages and collector still work. + if (!$templates->isCurrent() && ($grant || $templates->failure() === '')) { + $templates->install(); + } + $schema->recordPluginVersion($info['version'], $info['author'], $info['homepage']); return true; @@ -296,6 +346,10 @@ function plugin_redfish_uninstall(): void { } else { $schema->forgetVersion(); } + + // The shipped templates and every graph made from them stay; only the + // query files the plugin wrote and that nobody changed are removed. + redfish_template_installer()->uninstall(); } function redfish_config_arrays(): void { @@ -337,6 +391,84 @@ function redfish_draw_navigation_text($nav) { return array_merge($nav, \Somethingwithproof\Redfish\Pages::navigation()); } +/** + * device_remove hook: a deleted device no longer carries a BMC. The BMC, its + * credential, and its cache stay, unmapped, so only administrators see it + * until it is mapped again (REQ-DEV-003, REQ-DEV-005). + * + * @param mixed $hostIds + * @return mixed + */ +function redfish_device_remove($hostIds) { + if (!redfish_boot()) { + return $hostIds; + } + + $ids = array(); + + foreach (is_array($hostIds) ? $hostIds : array($hostIds) as $id) { + if (is_numeric($id) && (int) $id > 0) { + $ids[] = (int) $id; + } + } + + $count = redfish_bmcs()->unmapHosts($ids); + + if ($count > 0) { + \Somethingwithproof\Redfish\Log::info(sprintf('%d BMCs lost their device when it was deleted; they can be mapped again from the BMC list', $count)); + } + + return $hostIds; +} + +/** + * api_device_new hook, which Cacti runs after every device save: a mapped + * device moved to another poller than its BMC's is reported, not changed + * back (REQ-DEV-006). The health page shows it too. + * + * @param mixed $save + * @return mixed + */ +function redfish_api_device_new($save) { + if (!redfish_boot() || !is_array($save) || !isset($save['id']) || !is_numeric($save['id'])) { + return $save; + } + + $bmc = redfish_bmcs()->findByHost((int) $save['id']); + $poller = isset($save['poller_id']) && is_numeric($save['poller_id']) ? (int) $save['poller_id'] : 0; + + if ($bmc !== null && $poller > 0 && $poller !== $bmc->pollerId) { + \Somethingwithproof\Redfish\Log::warning(sprintf('Device %d of BMC %d is now polled by poller %d, but the BMC is read by poller %d', (int) $save['id'], $bmc->id, $poller, $bmc->pollerId)); + } + + return $save; +} + +/** + * graph_buttons hook: link the graphs of a device with a BMC to all of that + * device's Redfish graphs (REQ-GRAPH-003). + * + * @param mixed $data + * @return mixed + */ +function redfish_graph_buttons($data) { + global $config; + + if (!redfish_boot() || !api_plugin_is_enabled('redfish')) { + return $data; + } + + $payload = is_array($data) && isset($data[1]) && is_array($data[1]) ? $data[1] : array(); + $graphId = isset($payload['local_graph_id']) && is_numeric($payload['local_graph_id']) ? (int) $payload['local_graph_id'] : 0; + $hostId = (new \Somethingwithproof\Redfish\GraphLinks(redfish_bmcs(), redfish_cacti_objects()))->hostFor($graphId); + + if ($hostId > 0 && is_device_allowed($hostId, redfish_user_id())) { + print \Somethingwithproof\Redfish\GraphLinks::html($config['url_path'], $hostId); + } + + return $data; +} + /** * poller_bottom hook: start this poller's collector in the background * (REQ-COLL-001). The collector itself reads only BMCs of its poller. diff --git a/templates/redfish-templates.xml b/templates/redfish-templates.xml new file mode 100644 index 0000000..9d3d1ee --- /dev/null +++ b/templates/redfish-templates.xml @@ -0,0 +1,2045 @@ + + + Redfish BMC + + hash_00010308066884c7dcfc09cca0a3ccafac46ed|hash_000103f857093de6f97628583177bd5d496d36|hash_000103e7af7daff4d9485a6506a59dc967e3aa|hash_000103d195e57b859150dac801d2926c5ea044 + hash_0401030b974ffd842488a330f48e494f77a7c4|hash_040103babeddbb8aada8e196e25db9d5ee664f|hash_040103d460e2908c7dc1d158975d62549702f7 + + + Redfish - Node Power + + + + + |host_description| - Redfish - Node Power + + watts + + 1 + + 150 + + 600 + + 1000 + + on + + on + + 2 + + + + + + + + 100 + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + 30 + + + + + + + + 7 + hash_080103e3a2b895210875b6d9923573cee7de5e + 2471A3 + FF + 1 + 0 + 0 + + + 0 + + Power consumed + + 0.00 + + + 1 + + + 11 + hash_080103e3a2b895210875b6d9923573cee7de5e + 0 + FF + 1 + 0 + 0 + + + hash_0601032e57a9c64daf1019713671f784022fe0 + + Current: + + 0.00 + + + 2 + + + 14 + hash_080103e3a2b895210875b6d9923573cee7de5e + 0 + FF + 1 + 0 + 0 + + + hash_0601032e57a9c64daf1019713671f784022fe0 + + Average: + + 0.00 + + + 3 + + + 12 + hash_080103e3a2b895210875b6d9923573cee7de5e + 0 + FF + 1 + 0 + 0 + + + hash_0601032e57a9c64daf1019713671f784022fe0 + + Maximum: + on + 0.00 + + + 4 + + + + + First Item Color + The color of the first item + color_id + hash_000103aa0721fdb2974303c156a4998c2f4030 + + + + + Redfish - Node Temperatures + + + + + |host_description| - Redfish - Node Temperatures + + degrees Celsius + + 1 + + 150 + + 600 + + 1000 + + on + + on + + 2 + + + + + + + + 100 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 30 + + + + + + + + 5 + hash_080103b9ee470a07ccc93d337d129b67a3bd54 + 1E8449 + FF + 1 + 0 + 0 + + + 0 + + Inlet + + 0.00 + + + 1 + + + 11 + hash_080103b9ee470a07ccc93d337d129b67a3bd54 + 0 + FF + 1 + 0 + 0 + + + hash_0601032e57a9c64daf1019713671f784022fe0 + + Current: + + 0.00 + + + 2 + + + 14 + hash_080103b9ee470a07ccc93d337d129b67a3bd54 + 0 + FF + 1 + 0 + 0 + + + hash_0601032e57a9c64daf1019713671f784022fe0 + + Average: + + 0.00 + + + 3 + + + 12 + hash_080103b9ee470a07ccc93d337d129b67a3bd54 + 0 + FF + 1 + 0 + 0 + + + hash_0601032e57a9c64daf1019713671f784022fe0 + + Maximum: + on + 0.00 + + + 4 + + + 5 + hash_08010351bfe463e66816bcd179930695a7f4b1 + C0392B + FF + 1 + 0 + 0 + + + 0 + + Hottest sensor + + 0.00 + + + 5 + + + 11 + hash_08010351bfe463e66816bcd179930695a7f4b1 + 0 + FF + 1 + 0 + 0 + + + hash_0601032e57a9c64daf1019713671f784022fe0 + + Current: + + 0.00 + + + 6 + + + 14 + hash_08010351bfe463e66816bcd179930695a7f4b1 + 0 + FF + 1 + 0 + 0 + + + hash_0601032e57a9c64daf1019713671f784022fe0 + + Average: + + 0.00 + + + 7 + + + 12 + hash_08010351bfe463e66816bcd179930695a7f4b1 + 0 + FF + 1 + 0 + 0 + + + hash_0601032e57a9c64daf1019713671f784022fe0 + + Maximum: + on + 0.00 + + + 8 + + + + + First Item Color + The color of the first item + color_id + hash_0001036881f6c6755845668ddc5997b372f93e + + + + + Redfish - Node Component Health + + + + + |host_description| - Redfish - Node Component Health + + components + + 1 + + 150 + + 600 + + 1000 + + on + + on + + 2 + + + + + + + + 5 + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + 30 + + + + + + + + 5 + hash_08010399f379f3fb4da7bfae73ed3cdbec8d1b + B9770E + FF + 1 + 0 + 0 + + + 0 + + Fans not OK + + 0.00 + + + 1 + + + 11 + hash_08010399f379f3fb4da7bfae73ed3cdbec8d1b + 0 + FF + 1 + 0 + 0 + + + hash_0601037fdd76c962036449a8b4c5e5f98745f5 + + Current: + on + 0.00 + + + 2 + + + 5 + hash_08010332cba92f3fd0ef30bd31c6a6d3dc80f0 + 7D3C98 + FF + 1 + 0 + 0 + + + 0 + + Power supplies not OK + + 0.00 + + + 3 + + + 11 + hash_08010332cba92f3fd0ef30bd31c6a6d3dc80f0 + 0 + FF + 1 + 0 + 0 + + + hash_0601037fdd76c962036449a8b4c5e5f98745f5 + + Current: + on + 0.00 + + + 4 + + + 11 + hash_0801038c89fc5e5bf6364a393ba2b102b48784 + 0 + FF + 1 + 0 + 0 + + + hash_0601037fdd76c962036449a8b4c5e5f98745f5 + + Node health (0 OK, 1 Warning, 2 Critical): + on + 0.00 + + + 5 + + + + + First Item Color + The color of the first item + color_id + hash_00010356368aff9174c59cc7b9ba5a4455de99 + + + + + Redfish - Node Data Age + + + + + |host_description| - Redfish - Node Data Age + + seconds + + 1 + + 150 + + 600 + + 1000 + + on + + on + + 2 + + + + + + + + 100 + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + 30 + + + + + + + + 7 + hash_08010308382f2e6d853662bb8ab092c7fe1029 + 7F8C8D + FF + 1 + 0 + 0 + + + 0 + + Seconds since the last successful read + + 0.00 + + + 1 + + + 11 + hash_08010308382f2e6d853662bb8ab092c7fe1029 + 0 + FF + 1 + 0 + 0 + + + hash_0601032e57a9c64daf1019713671f784022fe0 + + Current: + + 0.00 + + + 2 + + + 14 + hash_08010308382f2e6d853662bb8ab092c7fe1029 + 0 + FF + 1 + 0 + 0 + + + hash_0601032e57a9c64daf1019713671f784022fe0 + + Average: + + 0.00 + + + 3 + + + 12 + hash_08010308382f2e6d853662bb8ab092c7fe1029 + 0 + FF + 1 + 0 + 0 + + + hash_0601032e57a9c64daf1019713671f784022fe0 + + Maximum: + on + 0.00 + + + 4 + + + + + First Item Color + The color of the first item + color_id + hash_0001038d65aadc268cba90faf9d48cd7e52eee + + + + + Redfish - Fan Speed Percent + + + + + |host_description| - Redfish - |query_redfishName| - Fan Speed (percent) + + percent + + 1 + + 150 + + 600 + + 1000 + + on + + + + 2 + + + + + + on + + 100 + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + 30 + + + + + + + + 5 + hash_080103f05b1915004952007380783d03036c96 + 2471A3 + FF + 1 + 0 + 0 + + + 0 + + Speed + + 0.00 + + + 1 + + + 11 + hash_080103f05b1915004952007380783d03036c96 + 0 + FF + 1 + 0 + 0 + + + hash_0601032e57a9c64daf1019713671f784022fe0 + + Current: + + 0.00 + + + 2 + + + 14 + hash_080103f05b1915004952007380783d03036c96 + 0 + FF + 1 + 0 + 0 + + + hash_0601032e57a9c64daf1019713671f784022fe0 + + Average: + + 0.00 + + + 3 + + + 12 + hash_080103f05b1915004952007380783d03036c96 + 0 + FF + 1 + 0 + 0 + + + hash_0601032e57a9c64daf1019713671f784022fe0 + + Maximum: + on + 0.00 + + + 4 + + + 11 + hash_080103b0b0420774982a5a49432b6ec4ba39a8 + 0 + FF + 1 + 0 + 0 + + + hash_0601037fdd76c962036449a8b4c5e5f98745f5 + + Fan health (0 OK, 1 Warning, 2 Critical): + on + 0.00 + + + 5 + + + + + First Item Color + The color of the first item + color_id + hash_00010359cb051995208e6e2495da6643670b41 + + + + + Redfish - Fan Speed RPM + + + + + |host_description| - Redfish - |query_redfishName| - Fan Speed (RPM) + + RPM + + 1 + + 150 + + 600 + + 1000 + + on + + on + + 2 + + + + + + + + 100 + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + 30 + + + + + + + + 5 + hash_0801035859938059f7db743b085328e8feed8f + 2471A3 + FF + 1 + 0 + 0 + + + 0 + + Speed + + 0.00 + + + 1 + + + 11 + hash_0801035859938059f7db743b085328e8feed8f + 0 + FF + 1 + 0 + 0 + + + hash_0601032e57a9c64daf1019713671f784022fe0 + + Current: + + 0.00 + + + 2 + + + 14 + hash_0801035859938059f7db743b085328e8feed8f + 0 + FF + 1 + 0 + 0 + + + hash_0601032e57a9c64daf1019713671f784022fe0 + + Average: + + 0.00 + + + 3 + + + 12 + hash_0801035859938059f7db743b085328e8feed8f + 0 + FF + 1 + 0 + 0 + + + hash_0601032e57a9c64daf1019713671f784022fe0 + + Maximum: + on + 0.00 + + + 4 + + + 11 + hash_080103791d7cbb1361b0119c8cf04459079100 + 0 + FF + 1 + 0 + 0 + + + hash_0601037fdd76c962036449a8b4c5e5f98745f5 + + Fan health (0 OK, 1 Warning, 2 Critical): + on + 0.00 + + + 5 + + + + + First Item Color + The color of the first item + color_id + hash_0001032bf0a034441b56e9e4cc9940f764cc92 + + + + + Redfish - Temperature + + + + + |host_description| - Redfish - |query_redfishName| - Temperature + + degrees Celsius + + 1 + + 150 + + 600 + + 1000 + + on + + on + + 2 + + + + + + + + 100 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 30 + + + + + + + + 5 + hash_0801035b774f098fb38b4081362e8d7b748d19 + C0392B + FF + 1 + 0 + 0 + + + 0 + + Temperature + + 0.00 + + + 1 + + + 11 + hash_0801035b774f098fb38b4081362e8d7b748d19 + 0 + FF + 1 + 0 + 0 + + + hash_0601032e57a9c64daf1019713671f784022fe0 + + Current: + + 0.00 + + + 2 + + + 14 + hash_0801035b774f098fb38b4081362e8d7b748d19 + 0 + FF + 1 + 0 + 0 + + + hash_0601032e57a9c64daf1019713671f784022fe0 + + Average: + + 0.00 + + + 3 + + + 12 + hash_0801035b774f098fb38b4081362e8d7b748d19 + 0 + FF + 1 + 0 + 0 + + + hash_0601032e57a9c64daf1019713671f784022fe0 + + Maximum: + on + 0.00 + + + 4 + + + 11 + hash_080103ebf3ae7dccca59ff9b918037aa322091 + 0 + FF + 1 + 0 + 0 + + + hash_0601037fdd76c962036449a8b4c5e5f98745f5 + + Sensor health (0 OK, 1 Warning, 2 Critical): + on + 0.00 + + + 5 + + + + + First Item Color + The color of the first item + color_id + hash_0001035190a040cfaa7d50d694ad86d30bf889 + + + + + Redfish - Power Supply + + + + + |host_description| - Redfish - |query_redfishName| - Power Supply + + watts + + 1 + + 150 + + 600 + + 1000 + + on + + on + + 2 + + + + + + + + 100 + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + 30 + + + + + + + + 5 + hash_08010397d08b47a20ea66a3bab4eba3f677681 + 2471A3 + FF + 1 + 0 + 0 + + + 0 + + Input + + 0.00 + + + 1 + + + 11 + hash_08010397d08b47a20ea66a3bab4eba3f677681 + 0 + FF + 1 + 0 + 0 + + + hash_0601032e57a9c64daf1019713671f784022fe0 + + Current: + + 0.00 + + + 2 + + + 14 + hash_08010397d08b47a20ea66a3bab4eba3f677681 + 0 + FF + 1 + 0 + 0 + + + hash_0601032e57a9c64daf1019713671f784022fe0 + + Average: + + 0.00 + + + 3 + + + 12 + hash_08010397d08b47a20ea66a3bab4eba3f677681 + 0 + FF + 1 + 0 + 0 + + + hash_0601032e57a9c64daf1019713671f784022fe0 + + Maximum: + on + 0.00 + + + 4 + + + 5 + hash_080103da84a35e0b079080cb1e0098f34cdba7 + 1E8449 + FF + 1 + 0 + 0 + + + 0 + + Output + + 0.00 + + + 5 + + + 11 + hash_080103da84a35e0b079080cb1e0098f34cdba7 + 0 + FF + 1 + 0 + 0 + + + hash_0601032e57a9c64daf1019713671f784022fe0 + + Current: + + 0.00 + + + 6 + + + 14 + hash_080103da84a35e0b079080cb1e0098f34cdba7 + 0 + FF + 1 + 0 + 0 + + + hash_0601032e57a9c64daf1019713671f784022fe0 + + Average: + + 0.00 + + + 7 + + + 12 + hash_080103da84a35e0b079080cb1e0098f34cdba7 + 0 + FF + 1 + 0 + 0 + + + hash_0601032e57a9c64daf1019713671f784022fe0 + + Maximum: + on + 0.00 + + + 8 + + + 11 + hash_080103be873b0cf308809921032a9ee2fb5178 + 0 + FF + 1 + 0 + 0 + + + hash_0601037fdd76c962036449a8b4c5e5f98745f5 + + Supply health (0 OK, 1 Warning, 2 Critical): + on + 0.00 + + + 9 + + + + + First Item Color + The color of the first item + color_id + hash_0001031ca6566631e7ed1364bd533fd3b95a7a + + + + + Redfish Node Summary + + |host_description| - Redfish - Node Summary + + hash_030103c0854afc0a476f61a6eb334da5caacb6 + + hash_200103d62c52891f4f9688729a5bc9fad91b18 + + 300 + + on + + + + power_watts + 0 + 100000 + 1 + 600 + hash_070103788ed93d5f5e8bd9fe4f16964b6c6ee9 + + + inlet_celsius + -60 + 200 + 1 + 600 + hash_070103de214828e03f5d6d5001fcf3caa72a22 + + + max_temp_celsius + -60 + 200 + 1 + 600 + hash_070103a621bbb1823e6f896c651c169a753c56 + + + fans_bad + 0 + 1000 + 1 + 600 + hash_0701032c07cbfee904c0a3fa54d59e00f29f71 + + + psus_bad + 0 + 1000 + 1 + 600 + hash_0701030288e10e41b8705a4ac0eda8ce9cd194 + + + health_code + 0 + 2 + 1 + 600 + hash_070103f9defcf047914ff90fd2d63fc41dabc2 + + + age + 0 + U + 1 + 600 + hash_070103d52b9e4962d3e6a2786be534188177ea + + + + + hash_070103cee05b271a5147c3bb3efd58d130b530 + + + + + + + Redfish - Fan Speed Percent + + |host_description| - Redfish - |query_redfishName| - Fan Speed + + hash_030103332111d8b54ac8ce939af87a7eac0c06 + + hash_200103d62c52891f4f9688729a5bc9fad91b18 + + 300 + + on + + + + fan_percent + 0 + 100 + 1 + 600 + 0 + + + fan_health + 0 + 2 + 1 + 600 + 0 + + + + + hash_070103172b4b0eacee4948c6479f587b62e512 + on + + + + hash_07010330fb5d5bcf3d66bb5abe88596f357c26 + on + + + + hash_07010331112c85ae4ff821d3b288336288818c + on + + + + + + Redfish - Fan Speed RPM + + |host_description| - Redfish - |query_redfishName| - Fan Speed + + hash_030103332111d8b54ac8ce939af87a7eac0c06 + + hash_200103d62c52891f4f9688729a5bc9fad91b18 + + 300 + + on + + + + fan_rpm + 0 + 100000 + 1 + 600 + 0 + + + fan_health + 0 + 2 + 1 + 600 + 0 + + + + + hash_070103172b4b0eacee4948c6479f587b62e512 + on + + + + hash_07010330fb5d5bcf3d66bb5abe88596f357c26 + on + + + + hash_07010331112c85ae4ff821d3b288336288818c + on + + + + + + Redfish - Temperature + + |host_description| - Redfish - |query_redfishName| - Temperature + + hash_030103332111d8b54ac8ce939af87a7eac0c06 + + hash_200103d62c52891f4f9688729a5bc9fad91b18 + + 300 + + on + + + + temperature + -60 + 200 + 1 + 600 + 0 + + + temp_health + 0 + 2 + 1 + 600 + 0 + + + + + hash_070103172b4b0eacee4948c6479f587b62e512 + on + + + + hash_07010330fb5d5bcf3d66bb5abe88596f357c26 + on + + + + hash_07010331112c85ae4ff821d3b288336288818c + on + + + + + + Redfish - Power Supply + + |host_description| - Redfish - |query_redfishName| - Power Supply + + hash_030103332111d8b54ac8ce939af87a7eac0c06 + + hash_200103d62c52891f4f9688729a5bc9fad91b18 + + 300 + + on + + + + psu_input_watts + 0 + 100000 + 1 + 600 + 0 + + + psu_output_watts + 0 + 100000 + 1 + 600 + 0 + + + psu_health + 0 + 2 + 1 + 600 + 0 + + + + + hash_070103172b4b0eacee4948c6479f587b62e512 + on + + + + hash_07010330fb5d5bcf3d66bb5abe88596f357c26 + on + + + + hash_07010331112c85ae4ff821d3b288336288818c + on + + + + + + Redfish Node Summary + 5 + PHBhdGhfY2FjdGk+L3BsdWdpbnMvcmVkZmlzaC9zY3JpcHRzL3NzX3JlZGZpc2hfc3VtbWFyeS5waHAgc3NfcmVkZmlzaF9zdW1tYXJ5IDxob3N0X2lkPg== + + + Device ID + + + + host_id + in + host_id + + + Power watts + on + + + + out + power_watts + + + Inlet celsius + on + + + + out + inlet_celsius + + + Max temp celsius + on + + + + out + max_temp_celsius + + + Fans bad + on + + + + out + fans_bad + + + Psus bad + on + + + + out + psus_bad + + + Health code + on + + + + out + health_code + + + Age + on + + + + out + age + + + + + Get Script Server Data (Indexed) + 6 + + + + Index Type + + + + index_type + in + index_type + + + Index Value + + + + index_value + in + index_value + + + Output Type ID + + + + output_type + in + output_type + + + Output Value + on + + + + out + output + + + + + Redfish - Number + %8.1lf + + + Redfish - Count + %5.0lf + + + Redfish Fans + Fans of a server, read over Redfish and answered from the plugin cache + <path_cacti>/resource/script_server/redfish_fans.xml + hash_030103332111d8b54ac8ce939af87a7eac0c06 + + + hash_0001033eb492b581142156b980c42902da3b50 + Fan Speed Percent + + + fan_percent + hash_010103b63a46db2aab9ba7165f9fdc3339117b + hash_080103f05b1915004952007380783d03036c96 + + + fan_health + hash_010103b63a46db2aab9ba7165f9fdc3339117b + hash_080103b0b0420774982a5a49432b6ec4ba39a8 + + + + + title + 1 + |host_description| - Redfish - |query_redfishName| - Fan Speed + + + + + name + hash_010103b63a46db2aab9ba7165f9fdc3339117b + 1 + |host_description| - Redfish - |query_redfishName| + + + + + hash_000103bd895d129b286da0aa3440b2a0fe3844 + Fan Speed RPM + + + fan_rpm + hash_010103f7abc4502849afac4841ccab958fedff + hash_0801035859938059f7db743b085328e8feed8f + + + fan_health + hash_010103f7abc4502849afac4841ccab958fedff + hash_080103791d7cbb1361b0119c8cf04459079100 + + + + + title + 1 + |host_description| - Redfish - |query_redfishName| - Fan Speed + + + + + name + hash_010103f7abc4502849afac4841ccab958fedff + 1 + |host_description| - Redfish - |query_redfishName| + + + + + + + Redfish Temperatures + Temperature sensors of a server, read over Redfish and answered from the plugin cache + <path_cacti>/resource/script_server/redfish_temperatures.xml + hash_030103332111d8b54ac8ce939af87a7eac0c06 + + + hash_00010399899a2fddce85714c5f807f49c44ef0 + Temperature + + + temperature + hash_0101030e355f8be821b4aebad277fc83d8b6e5 + hash_0801035b774f098fb38b4081362e8d7b748d19 + + + temp_health + hash_0101030e355f8be821b4aebad277fc83d8b6e5 + hash_080103ebf3ae7dccca59ff9b918037aa322091 + + + + + title + 1 + |host_description| - Redfish - |query_redfishName| - Temperature + + + + + name + hash_0101030e355f8be821b4aebad277fc83d8b6e5 + 1 + |host_description| - Redfish - |query_redfishName| + + + + + + + Redfish Power Supplies + Power supplies of a server, read over Redfish and answered from the plugin cache + <path_cacti>/resource/script_server/redfish_psus.xml + hash_030103332111d8b54ac8ce939af87a7eac0c06 + + + hash_000103d96d25464dcd5db7b52a47578551b19c + Power Supply + + + psu_input_watts + hash_01010354e311a43bec1ff433cef874f680c156 + hash_08010397d08b47a20ea66a3bab4eba3f677681 + + + psu_output_watts + hash_01010354e311a43bec1ff433cef874f680c156 + hash_080103da84a35e0b079080cb1e0098f34cdba7 + + + psu_health + hash_01010354e311a43bec1ff433cef874f680c156 + hash_080103be873b0cf308809921032a9ee2fb5178 + + + + + title + 1 + |host_description| - Redfish - |query_redfishName| - Power Supply + + + + + name + hash_01010354e311a43bec1ff433cef874f680c156 + 1 + |host_description| - Redfish - |query_redfishName| + + + + + + \ No newline at end of file diff --git a/tests/Integration/LifecycleTest.php b/tests/Integration/LifecycleTest.php index 27f4fd0..9ac78a9 100644 --- a/tests/Integration/LifecycleTest.php +++ b/tests/Integration/LifecycleTest.php @@ -38,7 +38,7 @@ 'plugin_redfish_secret', ]; -const REDFISH_HOOKS = ['config_arrays', 'config_settings', 'draw_navigation_text', 'poller_bottom']; +const REDFISH_HOOKS = ['api_device_new', 'config_arrays', 'config_settings', 'device_remove', 'draw_navigation_text', 'graph_buttons', 'poller_bottom']; beforeEach(function () { lifecycle('reset'); diff --git a/tests/Unit/ScriptServerTest.php b/tests/Unit/ScriptServerTest.php new file mode 100644 index 0000000..a5ba0d5 --- /dev/null +++ b/tests/Unit/ScriptServerTest.php @@ -0,0 +1,236 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_redfish, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_redfish + * + * 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\Redfish\FixedClock; +use Somethingwithproof\Redfish\FreshnessEvaluator; +use Somethingwithproof\Redfish\IndexKey; +use Somethingwithproof\Redfish\MemberQuery; +use Somethingwithproof\Redfish\NodeCacheRepository; +use Somethingwithproof\Redfish\SummaryScript; + +const REDFISH_NOW = 1_800_000_000; + +/** + * Queue the cache of BMC 1 on device 10 for the DB stubs. Each member is + * [key, kind, presence, readings as metric => [value, unit, age]]. + * + * @param list}> $members + */ +function redfish_cache(array $members, int $lastSuccessAge = 60, int $registeredAge = 86400): void { + $m = []; + $r = []; + + foreach ($members as [$key, $kind, $presence, $readings]) { + $m[] = ['member_key' => $key, 'kind' => $kind, 'name' => 'Name of ' . $key, 'chassis_id' => '1', 'presence' => $presence]; + + foreach ($readings as $metric => [$value, $unit, $age]) { + $r[] = ['member_key' => $key, 'metric' => $metric, 'value' => $value === null ? null : (string) $value, 'unit' => $unit, 'observed_at' => (string) (REDFISH_NOW - $age)]; + } + } + + $GLOBALS['__redfish_db_rows'] = [ + 'FROM plugin_redfish_bmc AS b' => [['id' => '1', 'created_at' => (string) (REDFISH_NOW - $registeredAge), 'last_success' => $lastSuccessAge < 0 ? '0' : (string) (REDFISH_NOW - $lastSuccessAge)]], + 'FROM plugin_redfish_member' => $m, + 'FROM plugin_redfish_reading' => $r, + ]; +} + +function redfish_freshness(FixedClock $clock): FreshnessEvaluator { + // 300 s interval: current up to 600 s, delayed up to 1,800 s. + return new FreshnessEvaluator($clock, 300, 2, 6); +} + +function redfish_query(): MemberQuery { + $clock = new FixedClock(REDFISH_NOW); + + return new MemberQuery(new NodeCacheRepository(false), redfish_freshness($clock), $clock); +} + +function redfish_summary(): string { + $clock = new FixedClock(REDFISH_NOW); + + return (new SummaryScript(new NodeCacheRepository(false), redfish_freshness($clock), $clock))->answer(10); +} + +/** + * @return list}> + */ +function redfish_fans(int $count, string $unit = '%'): array { + $fans = []; + + for ($i = $count; $i >= 1; $i--) { + $fans[] = ["1/fan/Fan$i", 'fan', 'present', ['fan_speed' => [40.0 + $i, $unit, 30], 'health_code' => [0.0, '', 30]]]; + } + + return $fans; +} + +beforeEach(function () { + $GLOBALS['__redfish_db_rows'] = []; +}); + +it('keeps safe member keys as indexes and makes any other key safe and distinct', function () { + expect(IndexKey::of('1/fan/Fan1'))->toBe('1/fan/Fan1') + ->and(IndexKey::of('1/fan/Fan1:secondary'))->toBe('1/fan/Fan1:secondary') + ->and(IndexKey::of('1/temperature/CPU 1'))->not->toBe(IndexKey::of('1/temperature/CPU_1')) + ->and(IndexKey::of('1/temperature/CPU 1'))->toStartWith('1/temperature/CPU_1~') + ->and(IndexKey::of('1/psu/a!b|c'))->not->toContain('!') + ->and(IndexKey::of('1/psu/a!b|c'))->not->toContain('|') + ->and(strlen(IndexKey::of(str_repeat('x', 400))))->toBeLessThanOrEqual(IndexKey::MAX) + ->and(IndexKey::of('1/temperature/CPU 1'))->toBe(IndexKey::of('1/temperature/CPU 1')) + ->and(IndexKey::plausible(IndexKey::of('1/psu/a!b|c')))->toBeTrue() + ->and(IndexKey::plausible('1/fan/Fan1; DROP'))->toBeFalse() + ->and(IndexKey::plausible(''))->toBeFalse(); +}); + +it('indexes every fan by its stable key, whatever the order discovery found them in', function (int $count) { + redfish_cache(redfish_fans($count)); + + $index = array_filter(explode("\n", redfish_query()->answer(10, 'fan', 'index'))); + $want = array_map(fn (int $i) => "1/fan/Fan$i", range(1, $count)); + sort($want, SORT_STRING); + + expect(array_values($index))->toBe($want) + ->and(redfish_query()->answer(10, 'fan', 'num_indexes'))->toBe((string) $count) + ->and(redfish_query()->answer(10, 'fan', 'get', 'fan_percent', '1/fan/Fan3'))->toBe('43'); +})->with([4, 8, 16]); + +it('answers query lines as index, delimiter, value', function () { + redfish_cache(redfish_fans(2)); + + expect(redfish_query()->answer(10, 'fan', 'query', 'fan_percent'))->toBe("1/fan/Fan1!41\n1/fan/Fan2!42\n") + ->and(redfish_query()->answer(10, 'fan', 'query', 'name'))->toBe("1/fan/Fan1!Name of 1/fan/Fan1\n1/fan/Fan2!Name of 1/fan/Fan2\n") + ->and(redfish_query()->answer(10, 'fan', 'query', 'unit'))->toBe("1/fan/Fan1!%\n1/fan/Fan2!%\n"); +}); + +it('keeps an absent or gone member indexed and reads it as unknown', function (string $presence) { + $fans = redfish_fans(3); + $fans[1][2] = $presence; + redfish_cache($fans); + + expect(redfish_query()->answer(10, 'fan', 'index'))->toContain('1/fan/Fan2') + ->and(redfish_query()->answer(10, 'fan', 'get', 'fan_percent', '1/fan/Fan2'))->toBe('U') + ->and(redfish_query()->answer(10, 'fan', 'get', 'fan_percent', '1/fan/Fan1'))->toBe('41'); +})->with(['absent', 'gone']); + +it('never serves a stale, missing, or unknown reading, and never as zero', function () { + redfish_cache([ + ['1/temperature/A', 'temperature', 'present', ['temperature_celsius' => [30.0, 'Cel', 700]]], + ['1/temperature/B', 'temperature', 'present', ['temperature_celsius' => [31.0, 'Cel', 1900]]], + ['1/temperature/C', 'temperature', 'present', ['temperature_celsius' => [null, 'Cel', 10]]], + ['1/temperature/D', 'temperature', 'present', []], + ['1/temperature/E', 'temperature', 'present', ['temperature_celsius' => [-5.5, 'Cel', 10]]], + ]); + + $q = redfish_query(); + + expect($q->answer(10, 'temperature', 'get', 'temperature', '1/temperature/A'))->toBe('30') + ->and($q->answer(10, 'temperature', 'get', 'temperature', '1/temperature/B'))->toBe('U') + ->and($q->answer(10, 'temperature', 'get', 'temperature', '1/temperature/C'))->toBe('U') + ->and($q->answer(10, 'temperature', 'get', 'temperature', '1/temperature/D'))->toBe('U') + ->and($q->answer(10, 'temperature', 'get', 'temperature', '1/temperature/E'))->toBe('-5.5'); +}); + +it('serves a fan only on the graph of its own unit', function () { + redfish_cache(array_merge(redfish_fans(1, '%'), [['1/fan/R1', 'fan', 'present', ['fan_speed' => [5400.0, 'RPM', 30]]]])); + + $q = redfish_query(); + + expect($q->answer(10, 'fan', 'get', 'fan_percent', '1/fan/Fan1'))->toBe('41') + ->and($q->answer(10, 'fan', 'get', 'fan_rpm', '1/fan/Fan1'))->toBe('U') + ->and($q->answer(10, 'fan', 'get', 'fan_rpm', '1/fan/R1'))->toBe('5400') + ->and($q->answer(10, 'fan', 'get', 'fan_percent', '1/fan/R1'))->toBe('U'); +}); + +it('refuses unknown kinds, fields, indexes, commands, and devices without echoing them', function () { + redfish_cache(redfish_fans(2)); + + $q = redfish_query(); + + expect($q->answer(10, 'chassis', 'get', 'x', '1/fan/Fan1'))->toBe('U') + ->and($q->answer(10, 'fan', 'get', 'psu_input_watts', '1/fan/Fan1'))->toBe('U') + ->and($q->answer(10, 'fan', 'get', 'fan_percent', '1/psu/Fan1'))->toBe('U') + ->and($q->answer(10, 'fan', 'get', 'fan_percent', "