diff --git a/.github/workflows/plugin-ci-workflow.yml b/.github/workflows/plugin-ci-workflow.yml index 3a2cc42..5c9416a 100644 --- a/.github/workflows/plugin-ci-workflow.yml +++ b/.github/workflows/plugin-ci-workflow.yml @@ -63,7 +63,7 @@ jobs: run: | set -euo pipefail php -v - for f in *.php include/*.php locales/*.php tests/bin/*.php; do + for f in *.php include/*.php locales/*.php scripts/*.php tests/bin/*.php; do php -l "$f" done @@ -219,7 +219,7 @@ jobs: working-directory: cacti run: php plugins/redfish/poller_redfish.php --poller=1 - - name: Check page permissions and POST-only actions + - name: Check page, device, and graph permissions and POST-only actions working-directory: cacti env: REDFISH_TEST_DATABASE: disposable @@ -230,10 +230,62 @@ jobs: sleep 1 done php plugins/redfish/tests/bin/page-permissions.php http://127.0.0.1:8080/cacti/ + php plugins/redfish/tests/bin/device-permissions.php http://127.0.0.1:8080/cacti/ if grep -E "Fatal error|Warning:|Uncaught" "$RUNNER_TEMP/php-server.log"; then exit 1 fi + # Device creation from Cacti's CLI bootstrap and the plugin's setup.php + # alone: the provisioner loads the Cacti libraries it uses itself. + - name: Provision a device from a minimal bootstrap + working-directory: cacti + env: + REDFISH_TEST_DATABASE: disposable + run: php plugins/redfish/tests/bin/provision-bootstrap.php + + # Templates, device creation, data queries, and graphs end to end, around + # real poller runs; the 11 second waits let the RRD with a 10 second step + # record a gap. Three unknown updates after the change span a whole + # step, which rrdtool then stores as unknown (tests/bin/device-flow.php). + - name: Run the device and graph flow + working-directory: cacti + env: + REDFISH_TEST_DATABASE: disposable + run: | + set -euo pipefail + flow=plugins/redfish/tests/bin/device-flow.php + poll() { php poller.php --poller=1 --force > /dev/null; sleep 11; php poller.php --poller=1 --force > /dev/null; } + php "$flow" setup + poll + php "$flow" check + poll + sleep 11 + php poller.php --poller=1 --force > /dev/null + php "$flow" later + + # Thold and Maint, unchanged, at their release tags. + - name: Checkout Thold v1.8.2 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + repository: Cacti/plugin_thold + ref: 1eb406bd0f81f3204358cce7bd43c8bb5adc8e4a # v1.8.2 + path: cacti/plugins/thold + + - name: Checkout Maint v1.3 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + repository: Cacti/plugin_maint + ref: cd62de9cc323a4f5a8ac80a8d9dda3c7fa16c470 # v1.3 + path: cacti/plugins/maint + + - name: Run Thold and Maint end to end + working-directory: cacti + env: + REDFISH_TEST_DATABASE: disposable + run: sh plugins/redfish/tests/bin/alert-replay.sh + - name: Check Cacti log for errors if: always() run: | @@ -244,7 +296,22 @@ jobs: if [ -f cacti/log/cacti.log ]; then echo "== install and poller run" cat cacti/log/cacti.log - if grep -E "FATAL:|ERROR:|WARNING:" cacti/log/cacti.log; then + # Cacti 1.2.31 leaves incomplete rows after the replay serves U. + # Keep these core diagnostics visible; the replay still asserts + # the values and alerts. Do not allow them on newer core versions. + core_warnings='^$' + if [ "$(cat cacti/include/cacti_version)" = '1.2.31' ]; then + core_warnings="^[^ ]+ [0-9:]+ - POLLER: Poller\[1\] PID\[[0-9]+\] WARNING: (Poller Output Table not Empty\. Issues: [0-9]+, DS\[[0-9, ]+\]|There are [0-9]+ Data Sources not returning all data leaving rows in the poller output table\. Details to follow\.|Data Template 'Redfish - [^']+' is impacted by lack of complete information)\$" + grep -E "$core_warnings" cacti/log/cacti.log || true + fi + # The device flow, on purpose, makes the plugin remove a device its + # creator cannot see (and checks that warning itself), and gives + # one data source a 10 second step, which Cacti warns about, also + # trying to mail the warning to an admin with no address. It also + # replaces the fan query file with a symbolic link and checks that + # the installer refuses it and logs so. Each exclusion matches that + # one whole line and nothing else. + if grep -E "FATAL:|ERROR:|WARNING:" cacti/log/cacti.log | grep -vE "$core_warnings" | grep -vE -e '^[^ ]+ [0-9:]+ - REDFISH WARNING: Device [0-9]+ for BMC [0-9]+ was removed again: user [0-9]+ may not see it$' -e '^[^ ]+ [0-9:]+ - REDFISH ERROR: /[^ ]+/resource/script_server/redfish_fans\.xml is a symbolic link; it was left as it is\. Replace it with a copy of plugins/redfish/resource/script_server/redfish_fans\.xml$' -e '^[^ ]+ [0-9:]+ - POLLER: Poller\[1\] PID\[[0-9]+\] WARNING: The Poller Interval is 300 and you have a Data Source with a sampling interval of 10\. Change your Poller Interval to 10 seconds, and repopulate your poller cache\.$' -e '^[^ ]+ [0-9:]+ - SYSTEM WARNING: Primary Admin account notifications disabled! Unable to send administrative Email\.$'; then exit 1 fi fi @@ -402,6 +469,285 @@ jobs: - name: Lint licensing metadata run: pipx run --spec 'reuse[charset-normalizer]==6.3.0' reuse lint + # Runs the plugin's real collector, through Cacti's poller_redfish.php with the + # production client (TLS verified against a throwaway CA, no loopback + # allowance), against DMTF's Redfish Mockup Server. It asserts the sensor set a + # subsystem BMC yields, the fallback to the legacy Thermal and Power resources, + # and one real iLO capture that mixes both. The fake-BMC hostile-case suite + # (tests/fake-bmc) stays a separate, unit-level job: this one only proves the + # plugin works against a third-party Redfish implementation. + # + # Why a shim: the mock server answers a session POST with 204 and no body, and + # the plugin (correctly, DSP0266 section 12.4) accepts only 200 or 201. The + # server's --headers files apply to GET and HEAD only, so they cannot fix it. + # tests/redfish-mockup/session-201-shim.py changes that one status in the + # server's own process; the Location header and X-Auth-Token it already sends + # are what the plugin reads. + # + # The mock server does no authentication, so this job cannot test rejected + # credentials, lockout, or token checks. + # + # The plugin refuses loopback BMC addresses outside tests, so the servers are + # reached on the runner's primary address, and the test certificate names it. + # Keys exist only in $RUNNER_TEMP and are never uploaded. + mockup-bmc: + name: DMTF mockup BMC on Cacti ${{ matrix.cacti }} + runs-on: ubuntu-latest + timeout-minutes: 30 + + strategy: + fail-fast: false + matrix: + cacti: ['release/1.2.31', '1.2.x'] + + env: + # dmtf/redfish-mockup-server 1.3.0 (BSD-3-Clause), by manifest digest. + MOCKUP_IMAGE: dmtf/redfish-mockup-server@sha256:4e33a3a6912e15bcc9ea9cd12151e24242f1ea7c52d2d374cd034de8265b2095 + # HPE ilo-redfish-emulator (BSD-3-Clause), mockups/DL380a: a Gen11 + # capture. Fetched at test time at this commit, not vendored. + HPE_EMULATOR_SHA: d668ab1580157961cad27ee7b5fa509bb9347d67 + + services: + mariadb: + image: mariadb:11.8@sha256:6422478cb8e159f080fb1d8ccf65101e26fe51385787fde7d16c3b165a331f15 + env: + MYSQL_ROOT_PASSWORD: cactiroot + MYSQL_DATABASE: cacti + MYSQL_USER: cactiuser + MYSQL_PASSWORD: cactiuser + ports: + - 3306:3306 + options: >- + --health-cmd="mariadb-admin ping" + --health-interval=10s + --health-timeout=5s + --health-retries=3 + + steps: + - name: Checkout Cacti + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + repository: Cacti/cacti + ref: ${{ matrix.cacti }} + path: cacti + + - name: Checkout redfish plugin + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + path: cacti/plugins/redfish + + - name: Install PHP 8.3 + uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 + with: + php-version: '8.3' + extensions: intl, mysql, gd, ldap, gmp, xml, json, mbstring, openssl, snmp + ini-values: "post_max_size=256M, max_execution_time=60, date.timezone=America/New_York" + coverage: none + + - name: Install system dependencies + run: | + sudo apt-get update + sudo apt-get install -y rrdtool mariadb-client jq + + - name: Initialize Cacti database + run: | + echo -e "[client]\nuser = root\npassword = cactiroot\nhost = 127.0.0.1\n" > ~/.my.cnf + chmod 600 ~/.my.cnf + mariadb -e "CREATE USER IF NOT EXISTS 'cactiuser'@'127.0.0.1' IDENTIFIED BY 'cactiuser';" + mariadb -e "GRANT ALL PRIVILEGES ON cacti.* TO 'cactiuser'@'127.0.0.1';" + mariadb -e "GRANT SELECT ON mysql.time_zone_name TO 'cactiuser'@'127.0.0.1';" + mariadb -e "FLUSH PRIVILEGES;" + mariadb cacti < cacti/cacti.sql + mariadb -e "INSERT INTO settings (name, value) VALUES ('path_php_binary', '$(command -v php)')" cacti + sed -r "s/localhost/127.0.0.1/g" cacti/include/config.php.dist > cacti/include/config.php + + - name: Install Cacti via CLI + working-directory: cacti + run: php cli/install_cacti.php --accept-eula --install --force + + - name: Install and enable the plugin + working-directory: cacti + run: php plugins/redfish/tests/bin/php-guard-check.php + + # The plugin treats loopback as hostile, so the BMCs live on the runner's + # own non-loopback address, and the certificate carries it as an IP SAN. + - name: Create a throwaway CA and server certificate + run: | + set -euo pipefail + ip="$(ip -4 route get 1.1.1.1 | awk '{for (i = 1; i <= NF; i++) if ($i == "src") { print $(i + 1); exit }}')" + test -n "$ip" + case "$ip" in 127.*) echo "no non-loopback address" >&2; exit 1 ;; esac + echo "MOCKUP_IP=$ip" >> "$GITHUB_ENV" + pki="$RUNNER_TEMP/mockup-pki" + install -d -m 700 "$pki" + cd "$pki" + openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \ + -keyout ca.key -out ca.pem -days 2 -subj "/CN=plugin_redfish test CA" \ + -addext "basicConstraints=critical,CA:TRUE" -addext "keyUsage=critical,keyCertSign,cRLSign" + openssl req -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \ + -keyout server.key -out server.csr -subj "/CN=mockup-bmc" + printf 'subjectAltName=IP:%s\nbasicConstraints=CA:FALSE\nextendedKeyUsage=serverAuth\n' "$ip" > ext.cnf + openssl x509 -req -in server.csr -CA ca.pem -CAkey ca.key -CAcreateserial \ + -out server.pem -days 2 -extfile ext.cnf + openssl verify -CAfile ca.pem -verify_ip "$ip" server.pem + + - name: Prepare the mockups + run: | + set -euo pipefail + mk="$RUNNER_TEMP/mockups" + mkdir -p "$mk" + docker pull "$MOCKUP_IMAGE" + + # public-rackmount1 is bundled in the image; the legacy-only variant + # is derived from it. + docker create --name mockup-src "$MOCKUP_IMAGE" > /dev/null + docker cp mockup-src:/usr/src/app/public-rackmount1 "$mk/rackmount1" + docker rm mockup-src > /dev/null + sh cacti/plugins/redfish/tests/redfish-mockup/make-legacy-only.sh "$mk/rackmount1" "$mk/legacy-only" + + # One real iLO Gen11 capture, fetched at a pinned commit. + git init -q "$mk/hpe" + git -C "$mk/hpe" remote add origin https://github.com/HewlettPackard/ilo-redfish-emulator.git + git -C "$mk/hpe" sparse-checkout set mockups/DL380a + git -C "$mk/hpe" fetch -q --depth 1 --filter=blob:none origin "$HPE_EMULATOR_SHA" + git -C "$mk/hpe" -c advice.detachedHead=false checkout -q FETCH_HEAD + + # All three servers run the pinned image under the shim, over HTTPS with + # the test certificate. --short-form is needed for any mockup that has no + # redfish/v1 directory, which is the case for all three. + - name: Start the mock BMCs + run: | + set -euo pipefail + pki="$RUNNER_TEMP/mockup-pki" + mk="$RUNNER_TEMP/mockups" + shim="$GITHUB_WORKSPACE/cacti/plugins/redfish/tests/redfish-mockup/session-201-shim.py" + + start() { + name=$1; port=$2; dir=$3 + docker run -d --name "$name" -p "$port:8443" \ + -v "$pki:/pki:ro" -v "$shim:/shim/shim.py:ro" -v "$dir:/mockup:ro" \ + --entrypoint python "$MOCKUP_IMAGE" /shim/shim.py \ + -H 0.0.0.0 -p 8443 -D /mockup --short-form \ + --ssl --cert /pki/server.pem --key /pki/server.key > /dev/null + } + + start mockup-subsystem 8443 "$mk/rackmount1" + start mockup-legacy 8444 "$mk/legacy-only" + start mockup-hpe-gen11 8445 "$mk/hpe/mockups/DL380a" + + for port in 8443 8444 8445; do + up= + for _ in $(seq 1 30); do + if curl -fsS --cacert "$pki/ca.pem" -o /dev/null "https://$MOCKUP_IP:$port/redfish/v1/"; then + up=1 + break + fi + sleep 1 + done + if [ -z "$up" ]; then + echo "mock BMC on $port did not come up" >&2 + docker ps -a >&2 + exit 1 + fi + # The mockups ship with sessions already in their collection, so + # compare against the count at start, not against zero. + curl -sS --cacert "$pki/ca.pem" "https://$MOCKUP_IP:$port/redfish/v1/SessionService/Sessions" \ + | jq '."Members@odata.count"' > "$RUNNER_TEMP/sessions-$port" + done + + # What the server gives the plugin, checked with the test CA, so a change + # in the pinned image or the shim shows up here and not as a collector + # failure. + - name: Check the mock server contract + run: | + set -euo pipefail + pki="$RUNNER_TEMP/mockup-pki" + base="https://$MOCKUP_IP:8443" + c() { curl -sS --cacert "$pki/ca.pem" "$@"; } + + c "$base/redfish/v1/" | jq -e '.Links.Sessions."@odata.id" == "/redfish/v1/SessionService/Sessions" and .Chassis."@odata.id" == "/redfish/v1/Chassis"' > /dev/null + + headers="$(c -D - -o /dev/null -X POST -H 'Content-Type: application/json' \ + -d '{"UserName":"probe","Password":"probe"}' "$base/redfish/v1/SessionService/Sessions")" + echo "$headers" | head -1 | grep -q ' 201 ' + echo "$headers" | grep -qi '^x-auth-token: .' + location="$(echo "$headers" | tr -d '\r' | awk 'tolower($1) == "location:" { print $2 }')" + case "$location" in /redfish/v1/SessionService/Sessions/*) ;; *) echo "unexpected Location: $location" >&2; exit 1 ;; esac + test "$(c -o /dev/null -w '%{http_code}' -X DELETE "$base$location")" = 204 + test "$(c "$base/redfish/v1/SessionService/Sessions" | jq '."Members@odata.count"')" = "$(cat "$RUNNER_TEMP/sessions-8443")" + + - name: Register the mock BMCs + working-directory: cacti + env: + REDFISH_TEST_DATABASE: disposable + run: | + set -euo pipefail + ca="$RUNNER_TEMP/mockup-pki/ca.pem" + php plugins/redfish/tests/bin/mockup-check.php seed mock-subsystem "$MOCKUP_IP" 8443 "$ca" + php plugins/redfish/tests/bin/mockup-check.php seed mock-legacy "$MOCKUP_IP" 8444 "$ca" + php plugins/redfish/tests/bin/mockup-check.php seed mock-hpe-gen11 "$MOCKUP_IP" 8445 "$ca" + + - name: Discover and collect through the poller entry point + working-directory: cacti + run: php plugins/redfish/poller_redfish.php --poller=1 --force --debug + + - name: Assert the sensor sets and the legacy fallback + working-directory: cacti + env: + REDFISH_TEST_DATABASE: disposable + run: | + set -euo pipefail + php plugins/redfish/tests/bin/mockup-check.php assert mock-subsystem subsystem + php plugins/redfish/tests/bin/mockup-check.php assert mock-legacy legacy + php plugins/redfish/tests/bin/mockup-check.php assert mock-hpe-gen11 hpe-gen11 + + # The same BMCs on Cacti devices the plugin creates: the data queries + # index what the collector found, and the summary input serves it. + - name: Create the Cacti devices and read them through the script server + working-directory: cacti + env: + REDFISH_TEST_DATABASE: disposable + run: | + set -euo pipefail + php plugins/redfish/tests/bin/mockup-check.php cacti mock-subsystem + php plugins/redfish/tests/bin/mockup-check.php cacti mock-legacy + php plugins/redfish/tests/bin/mockup-check.php cacti mock-hpe-gen11 + + # REQ-RF-004: a run that logs in logs out, so no session stays behind. The + # shipped mockups already hold two sessions, so the count is compared with + # the one taken at start. + - name: Check that no session is left open + run: | + set -euo pipefail + for port in 8443 8444 8445; do + now="$(curl -sS --cacert "$RUNNER_TEMP/mockup-pki/ca.pem" "https://$MOCKUP_IP:$port/redfish/v1/SessionService/Sessions" | jq '."Members@odata.count"')" + test "$now" = "$(cat "$RUNNER_TEMP/sessions-$port")" || { echo "port $port: $now sessions, expected $(cat "$RUNNER_TEMP/sessions-$port")" >&2; exit 1; } + done + + - name: Check Cacti log for errors + if: always() + run: | + if [ -f cacti/log/cacti.log ]; then + cat cacti/log/cacti.log + if grep -E "FATAL:|ERROR:|WARNING:" cacti/log/cacti.log; then + exit 1 + fi + fi + + - name: Mock server logs + if: failure() + run: | + for name in mockup-subsystem mockup-legacy mockup-hpe-gen11; do + echo "== $name" + docker logs "$name" 2>&1 | tail -n 60 || true + done + + - name: Stop the mock BMCs + if: always() + run: docker rm -f mockup-subsystem mockup-legacy mockup-hpe-gen11 > /dev/null 2>&1 || true + ci-ok: name: ci-ok if: ${{ always() }} @@ -409,6 +755,7 @@ jobs: - entry-point-lint - integration-test - php-guard + - mockup-bmc - workflow-lint - reuse runs-on: ubuntu-latest diff --git a/README.md b/README.md index 93cd01e..2d7b675 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ A Cacti 1.2 plugin that brings server power draw, inlet temperature, fan state, and power supply health from baseboard management controllers (BMCs) into Cacti as ordinary devices, data sources, and graphs, using Redfish with an optional IPMI fallback. Thold and Maint then alert on and suppress them, and a later phase adds rack-level power totals. -> **Status: in development, no release yet (0.1.0-dev).** Milestone 2 (foundation) is merged on `main`. This plugin is not affiliated with the Cacti project. It installs on Cacti 1.2.31 under PHP 8.2 or later, registers BMCs and credentials, reads power, temperatures, fans, and power supply health from each BMC over Redfish into its own cache, and shows collection health. It does not yet create Cacti devices, data sources, or graphs, and it does not alert; those arrive in milestone 3. It has been tested only against a fake BMC built from hand-written fixtures, never a real one. The design and research are in [docs/PLAN.md](docs/PLAN.md), [docs/research/](docs/research/), and [docs/decisions/](docs/decisions/). +> **Status: in development, no release yet (0.1.0-dev).** Milestone 2 (foundation) is merged on `main`; milestone 3 (Cacti objects and alerting) is in review. This plugin is not affiliated with the Cacti project. It installs on Cacti 1.2.31 under PHP 8.2 or later, registers BMCs and credentials, reads power, temperatures, fans, and power supply health from each BMC over Redfish into its own cache, and shows collection health. Milestone 3 adds Cacti devices, per-member and summary graphs, and Thold and Maint support through ordinary data sources. It has been tested only against a fake BMC built from hand-written fixtures and the DMTF Redfish mockup server, never a real BMC. The design and research are in [docs/PLAN.md](docs/PLAN.md), [docs/research/](docs/research/), and [docs/decisions/](docs/decisions/). ### What milestone 2 ships @@ -15,6 +15,19 @@ A Cacti 1.2 plugin that brings server power draw, inlet temperature, fan state, - A collector started from `poller_bottom` for BMCs on the main poller, with per-BMC leases and deadlines, backoff, and cleanup after a crash of the one session the plugin recorded. Remote collectors are not supported yet; they need an explicit choice of how the collector reaches the database and the key (phase 4). - BMC records and credentials follow Cacti device permissions: a Redfish Admin sees, changes, and binds only BMCs on devices they may see, and only credentials that no BMC on a hidden device uses. +### What milestone 3 adds + +- Templates shipped as Cacti template XML in `templates/` and imported with Cacti's own importer at install and upgrade, matched by hash, so an import updates the plugin's objects and adds nothing twice. The three data query files are copied to `/resource/script_server/` with a recorded hash; the plugin never replaces a file there that it did not write, and the health page warns administrators when the templates or a query file are not in place. **Reinstall the Redfish Templates** on the BMCs page imports them again; it needs Cacti's Import Templates permission. +- **Create Device** or **Add Graphs** on each BMC ([ADR 0015](docs/decisions/0015-attach-to-the-server-device-or-create-one-per-bmc.md)). A BMC mapped to a server's existing device gets its data queries and graphs on that device. An unmapped BMC gets a new device from the "Redfish BMC" device template, with availability checks off and a host name under `.invalid`, so Cacti never contacts the BMC and never shows its address. Either way an administrator first confirms a plan listing what will be added. Both need Cacti's device management permission as well as Redfish Admin; a new device the creator could not see is removed again. +- Three script server data queries, "Redfish Fans", "Redfish Temperatures", and "Redfish Power Supplies", indexed by the BMC's member key, with a graph per member: fan speed in percent or RPM (whichever unit the BMC reports), temperature, and power supply input and output watts, each with its health code. +- A "Redfish Node Summary" input with power, inlet temperature, the highest temperature, fans and supplies not OK, node health, and the age of the last good read, drawn on four graphs: power, temperatures, component health, and data age. Thold thresholds on these data sources alert, and Maint suppresses them, with no change to either plugin. +- The script server answers only from the plugin's cache and never contacts a BMC. A value that is missing, stale, of another unit, or from a member that is gone is `U`, so graphs show a gap, never zero; `age` always has a value, so a threshold on it catches a BMC that stopped answering. +- A graph link from each Redfish graph to the device's Redfish graphs, shown only to users Cacti lets see the device. + +**When a BMC's members change** (a fan replaced, a firmware update renaming sensors), choose **Add Graphs** again. A fan or power supply that was present and is now absent or gone counts in `fans_bad` or `psus_bad` until you do, so a pulled fan alerts; a slot that was never filled does not. Add Graphs accepts the members the BMC reports now, and Cacti indexes the queries again; a member that is gone keeps its data source and graph, which read `U` from then on, and a new member gets a graph. Delete the graphs of members that are gone by hand once their history is no longer needed. + +Deleting a device unmaps its BMC and keeps the BMC and its cache. Deleting a BMC, or uninstalling the plugin, keeps its device and graphs. + ## Why Every server has a BMC that reports power and thermal state independently of the operating system, so it keeps answering when the OS is down. The data serves capacity and cost tracking, early warning of a failed fan or power supply, and, in high-performance computing, power-capping decisions. The plugin is not HPC-specific. @@ -44,6 +57,7 @@ Out of scope: setting power caps or any other BMC configuration, power control, | Component | Target | |---|---| | Cacti | 1.2.31 or later, no core patches | +| Database | MariaDB 10.2 or MySQL 5.7 or later: one BMC per device is held by a unique key on a generated column | | PHP | 8.2 or later; `setup.php` stays parseable on 8.0 so an unsupported runtime gets a refusal instead of a broken Cacti UI | | BMCs | Dell iDRAC, HPE iLO, Lenovo XCC, and OpenBMC, by firmware range; see [the vendor matrix](docs/research/vendor-matrix.md) | | Redfish | New subsystem and sensor resources first, deprecated `Power` and `Thermal` as fallback | 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/docs/PLAN.md b/docs/PLAN.md index c597e02..52f0869 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -1,6 +1,6 @@ # Cacti 1.2 Redfish and IPMI Power and Thermal Plugin Plan -Status: in development, plan revision 2 (2026-11-15). Revision 2 adds the documentation and source research for milestone 1; see [Milestone 1 research](#milestone-1-research). Milestone 2 (foundation) is merged on `main`: the lifecycle and PHP guard, realms and settings, the BMC registry, the encrypted credential store, the read-only Redfish client with its TLS trust modes, discovery and the reading model, the collector, and the health, BMC, and credential pages, tested only against a fake BMC. Decisions are recorded in ADRs 0009 to 0014, and divergences from this plan are stated in place. Milestone 3 and later are not done: no Cacti device, data source, graph, Thold or Maint integration exists, and there is no release. Statements about the Redfish standard, BMC firmware, ipmitool, Cacti core, and Cacti plugins describe upstream behavior as observed on the date and revision named in each source. Anything that was not verified is marked as an assumption and has a research issue; items that need real BMC hardware or a running Cacti are marked *live*. Owner is not assigned; size estimates are in [research/estimates.md](research/estimates.md), and calendar time is not estimated. +Status: in development, plan revision 2 (2026-11-15). Revision 2 adds the documentation and source research for milestone 1; see [Milestone 1 research](#milestone-1-research). Milestone 2 (foundation) is merged on `main`: the lifecycle and PHP guard, realms and settings, the BMC registry, the encrypted credential store, the read-only Redfish client with its TLS trust modes, discovery and the reading model, the collector, and the health, BMC, and credential pages, tested only against a fake BMC. Decisions are recorded in ADRs 0009 to 0014, and divergences from this plan are stated in place. Milestone 3 (Cacti objects and alerting) is in review: shipped templates, device creation or mapping ([ADR 0015](decisions/0015-attach-to-the-server-device-or-create-one-per-bmc.md)), per-member and summary graphs, Thold and Maint replays against pinned releases, the device permission suite, and a scale harness; its divergences are stated under [Cacti objects](#cacti-objects), [Alerting and maintenance](#alerting-and-maintenance), and [Performance](#performance). Milestone 4 and later are not done, and there is no release. Statements about the Redfish standard, BMC firmware, ipmitool, Cacti core, and Cacti plugins describe upstream behavior as observed on the date and revision named in each source. Anything that was not verified is marked as an assumption and has a research issue; items that need real BMC hardware or a running Cacti are marked *live*. Owner is not assigned; size estimates are in [research/estimates.md](research/estimates.md), and calendar time is not estimated. `plugin_redfish` is a Cacti 1.2 plugin that reads power draw, temperatures, fan state, and power supply health from server baseboard management controllers (BMCs) over Redfish, with IPMI as an optional fallback, and presents them as ordinary Cacti devices, data sources, and graphs. Thold and Maint then work on them unchanged, and a later phase adds rack-level totals. @@ -247,13 +247,24 @@ The collector runs outside Cacti's per-device polling threads. It reads BMCs on | Object | Created from | Notes | |---|---|---| | Device | Existing server device (mapped) or a "Redfish BMC" device template; each device the plugin creates gets `availability_method` 0 (None) through `api_device_save()`, because a device template cannot carry availability | Decision #11 settles the default | -| Per-index data query | "Redfish Sensors" script server data query | Indexes are fans, temperature sensors, and power supplies of the device | -| Per-index data sources and graphs | Data templates per kind: fan, temperature, power supply | Created through Cacti's data query and graph APIs | -| Summary data source | "Redfish Node Summary" data template, script server input | Polled; reaches Thold through `poller_output` | +| Per-index data queries | "Redfish Fans", "Redfish Temperatures", "Redfish Power Supplies" script server data queries | Indexes are the device's fans, temperature sensors, and power supplies (milestone 3 divergence, below) | +| Per-index data sources and graphs | Data templates per kind: fan speed in percent, fan speed in RPM, temperature, power supply | Created through Cacti's data query and graph APIs | +| Summary data sources | "Redfish Node Summary" data template, script server input | Polled; reaches Thold through `poller_output`; one data source per summary graph (below) | | Rack objects (phase 3) | Plugin rack table; a template-marked device per rack for totals | Decision #15 settles the rack model | Templates ship as Cacti template XML in the plugin and are imported with `import_xml_data()` at install and upgrade, matched by hash so re-imports update. Per-index graphs follow the pattern used by plugin_cloudflare, where one data query supplies the indexes (its tunnels) and one device carries many indexed graphs ([plugin_cloudflare tree](https://github.com/somethingwithproof/plugin_cloudflare/tree/a26f78dc48473ff97f518fab3e7a37cf00538c43), `templates/resource/cloudflare_tunnels.xml`). Milestone 1 builds a spike for variable index counts ([#29](https://github.com/somethingwithproof/plugin_redfish/issues/29)). +Milestone 3 divergences, as built: + +- **Three data queries, not one.** A Cacti data query has one set of output fields for every index, and fans, temperatures, and supplies report different values, so each kind has its own query, query file, and graph templates. The index is the member key from the cache, kept as is when it is short and plain and otherwise shortened with a hash suffix, sorted alphabetically. +- **Fan speed has two graph templates.** The unit comes from the BMC (see [Upstream behavior](#upstream-behavior-the-design-depends-on)), so the plugin creates the percent or the RPM graph for each fan from the unit it cached; a fan whose unit is unknown gets no graph until a later **Add Graphs**. A value in the other unit is served as `U`. +- **One summary data source per graph.** Cacti's RRD for a data source holds only the values its graph draws, so each of the four summary graphs (power, temperatures, component health, data age) has its own data source from the one template. +- **Query files are copied into Cacti.** Cacti reads a script server query's XML from its own `resource/script_server/` directory, so the plugin copies its three files there and records the hash of each file as it writes it. It claims only files it wrote, so uninstall leaves an identical file the site put there, refuses to replace a file it did not write, and refuses a link in place of a file; it writes a temporary file and renames it over the target. +- **Data source profile.** The templates carry no data source profile; Cacti's default profile applies at import. +- **One BMC per device.** A Cacti device carries at most one BMC. The edit form, the CSV import (against the registry and within one file), and device creation check it, and a unique key in the database holds it when two writes race; any number of BMCs can stay unmapped. Schema version 2 adds the key and unmaps all but the lowest BMC id of a device that already carried several, with a log line for each. +- **Provisioning needs every template.** Device creation is refused until the device template, the data input, every data template and graph template, every data query, each data query's graph association, and the query files are in place. +- **Re-index.** Members that disappear keep their index, data source, and graph, which read `U`; **Add Graphs** indexes again, graphs new members, and accepts the members as reported, so a fan or supply that is gone stops counting as failed. Nothing deletes graphs automatically. + ## Normalized measurement model The collector maps every source to one set of readings. Each reading has a value, a unit, an observation time, a source (`redfish.environment`, `redfish.sensor`, `redfish.legacy`, `ipmi.dcmi`, `ipmi.sdr`), and a freshness. @@ -314,11 +325,15 @@ The "Redfish Node Summary" data source returns, from the cache: | `power_watts` | Latest node power | `U` | | `inlet_celsius` | Latest inlet temperature | `U` | | `max_temp_celsius` | Highest temperature reading on the node | `U` | -| `fans_bad` | Fans whose health is not OK, absent members counted separately | `U` | -| `psus_bad` | Power supplies whose health is not OK | `U` | +| `fans_bad` | Fans whose health is not OK, plus fans that were present and are now absent or gone until an administrator accepts the change; a second rotor of the same fan is not counted again | `U` | +| `psus_bad` | Power supplies whose health is not OK, plus supplies that were present and are now absent or gone until accepted | `U` | | `health_code` | Worst node health | `U` | | `age` | Seconds since the last successful read | Always numeric, so Thold can alert on a BMC that stopped answering | +Every value the plugin stores is a `GAUGE`. Thold 1.8.2 fails with a PHP TypeError when a thresholded `COUNTER` or `DERIVE` data source reads `U`, and Cacti then disables Thold for every user; the plugin has no counter today, and any later one will be computed in the plugin from consecutive reads, `U` on a reset or a missing read, and stored as a gauge. The alert replay checks that thresholded values reading `U` leave Thold enabled. + +Absent members (decided in review of milestone 3): a slot the BMC has never reported present is not counted. A fan or supply seen present that the BMC then reports `Absent`, or drops from its tree, counts as bad, because losing one is the failure an operator needs to see. It keeps counting until an administrator chooses **Add Graphs**, which accepts the members the BMC reports at that moment; the confirmation page says how many would stop counting. Each member carries an `expected` flag (schema version 2) that collection sets while the member is present and acceptance clears when it is not. `fans_bad` and `psus_bad` are `U` while node health is not usable. + Thold thresholds and Maint schedules apply with no change to either plugin ([ADR 0002](decisions/0002-alert-through-cacti-data-sources.md)). Stated limits: - **Sampling alignment.** Cacti polls on its own interval and the collector runs on its own. If the collector interval is longer than Cacti's, the same reading repeats; `age` shows it. Documentation tells operators to set Thold durations to at least one collector interval. @@ -406,6 +421,19 @@ Engineering targets, to be measured, not yet demonstrated: The setup screen shows request rate and Cacti object count before a bulk import. +### Milestone 3 measurements + +Measured on 2026-11-15 with `tests/bin/scale-replay.sh` on Cacti 1.2.31, PHP 8.2.35, and MariaDB 11.8.9 in Docker on an Apple M3 Max laptop (14 CPUs and about 16 GiB given to Docker). **These numbers describe that machine and the fake BMC, not a BMC network.** The collector ran in one process as one worker against one fake BMC on loopback, which serves one connection at a time from the Dell fixture; no real BMC, management network, or TLS handshake cost of embedded hardware is included. + +| BMCs | Added latency per answer | First run (discovery and readings) | Second run (readings) | Requests per BMC, first and second | Collector peak memory | Summary input, mean and p99 | Member query get, mean and p99 | +|---|---|---|---|---|---|---|---| +| 100 | none | 4.8 s (48 ms per BMC) | 2.0 s (20 ms per BMC) | 28, 11 | 10 MiB | 0.22 ms, 0.96 ms | 0.08 ms, 0.26 ms | +| 100 | 20 ms | 70.0 s (700 ms per BMC) | 27.4 s (274 ms per BMC) | 28, 11 | 10 MiB | 0.14 ms, 0.21 ms | 0.06 ms, 0.16 ms | +| 1,000 | none | 46.5 s (47 ms per BMC) | 20.6 s (21 ms per BMC) | 28, 11 | 12 MiB | 0.14 ms, 0.28 ms | 0.08 ms, 0.27 ms | + +What this shows: collector time grows linearly with the BMC count, memory stays flat, and the script server answers from the cache in well under a millisecond per call at 1,000 BMCs (26,000 reading rows), so Cacti's poll does not wait on BMCs. What it does not show: whether the collector finishes within `T` at 1,000 real BMCs. By the arithmetic above, at the 20 ms row's 274 ms per BMC one worker would need about 274 s for 1,000 BMCs; at the illustrative 0.5 s per request and 11 requests, about 5.5 s per BMC, or about 19 workers for `T = 300 s`. Real latency is *live*, as is the overview page target, which was not measured. + + ## Security | Boundary | Control | @@ -456,7 +484,7 @@ Phase 2 needs a security review covering command construction, environment handl | Redfish resource model | **Decided:** new subsystem resources first with legacy fallback, chosen per reading ([ADR 0013](decisions/0013-choose-the-resource-source-per-reading.md)) | Milestone 2 | Milestone 1 vendor matrix | | Credential storage | **Decided:** plugin-owned AES-256-GCM vault with the key file outside the database, not plugin_credentials, which has no release ([ADR 0009](decisions/0009-plugin-owned-credential-vault.md)) | Milestone 2 | Research #28 | | TLS trust for BMC certificates | **Decided:** system store, CA bundle, or per-BMC SPKI SHA-256 pin, with an explicit, logged, per-BMC unverified opt-out shown on the health page ([ADR 0011](decisions/0011-tls-trust-modes.md)) | Milestone 2 | Plugin maintainer; pilots may revise | -| BMC to Cacti device mapping | Map onto the existing server device, create a BMC device only when none exists (proposed); always a separate BMC device | Milestone 3 | Plugin maintainer and pilots | +| BMC to Cacti device mapping | **Decided:** attach to the server's existing device when the operator maps one, otherwise create one device per BMC from the plugin device template after confirmation, through Cacti's API and only for users with device management ([ADR 0015](decisions/0015-attach-to-the-server-device-or-create-one-per-bmc.md)) | Milestone 3 | Plugin maintainer; pilots may revise | | Repository and name | Slug `redfish`, namespace `Somethingwithproof\Redfish` used provisionally ([ADR 0014](decisions/0014-plugin-name-namespace-and-provisional-harness.md)); still open | Before any code is published | Cacti maintainers | | Test harness | Pest from Cacti core's locked harness, used provisionally ([ADR 0014](decisions/0014-plugin-name-namespace-and-provisional-harness.md)); still open | Milestone 2 | Cacti maintainers | | IPMI client | `ipmitool`; FreeIPMI; a native implementation; ship no IPMI | Milestone 5 | Research and security review | 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`. diff --git a/lib/BmcImport.php b/lib/BmcImport.php index b9d7bb9..1db3c42 100644 --- a/lib/BmcImport.php +++ b/lib/BmcImport.php @@ -44,8 +44,9 @@ private function __construct(public array $bmcs, public array $errors) { * @param callable(string, int): ?string $addressTaken name of a BMC already at the address and port * @param callable(string): bool $nameTaken * @param callable(int): bool $hostExists + * @param callable(int): ?string $hostTaken name of a BMC already on the device */ - public static function parse(string $csv, array $credentials, callable $addressTaken, callable $nameTaken, callable $hostExists): self { + public static function parse(string $csv, array $credentials, callable $addressTaken, callable $nameTaken, callable $hostExists, ?callable $hostTaken = null): self { if ($csv === '' || strlen($csv) > self::MAX_BYTES) { return new self([], [__('The file is empty or larger than 1 MiB.', 'redfish')]); } @@ -60,7 +61,7 @@ public static function parse(string $csv, array $credentials, callable $addressT rewind($handle); try { - return self::rows($handle, $credentials, $addressTaken, $nameTaken, $hostExists); + return self::rows($handle, $credentials, $addressTaken, $nameTaken, $hostExists, $hostTaken ?? static fn (int $host): ?string => null); } finally { fclose($handle); } @@ -70,7 +71,7 @@ public static function parse(string $csv, array $credentials, callable $addressT * @param resource $handle * @param array $credentials */ - private static function rows($handle, array $credentials, callable $addressTaken, callable $nameTaken, callable $hostExists): self { + private static function rows($handle, array $credentials, callable $addressTaken, callable $nameTaken, callable $hostExists, callable $hostTaken): self { $header = fgetcsv($handle, 0, ',', '"', ''); if (!is_array($header)) { @@ -95,6 +96,7 @@ private static function rows($handle, array $credentials, callable $addressTaken $errors = []; $addresses = []; $names = []; + $hosts = []; $line = 1; while (($fields = fgetcsv($handle, 0, ',', '"', '')) !== false) { @@ -165,6 +167,19 @@ private static function rows($handle, array $credentials, callable $addressTaken continue; } + // One BMC per device, against the registry and within the file. + if ($bmc->hostId > 0) { + $holder = $hostTaken($bmc->hostId); + + if ($holder !== null || isset($hosts[$bmc->hostId])) { + $errors[] = __('Line %d: device %d already has the BMC %s.', $line, $bmc->hostId, $holder ?? __('of line %d', $hosts[$bmc->hostId], 'redfish'), 'redfish'); + + continue; + } + + $hosts[$bmc->hostId] = $line; + } + $addresses[$where] = $line; $names[$bmc->name] = $line; $bmcs[] = $bmc; diff --git a/lib/BmcRepository.php b/lib/BmcRepository.php index a1c95c3..52ef173 100644 --- a/lib/BmcRepository.php +++ b/lib/BmcRepository.php @@ -98,6 +98,80 @@ 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 an unmapped BMC to the device the provisioner just created, with + * an audit entry. Compare and set: false when the BMC was mapped in the + * meantime or another BMC holds the device, and nothing changes then. + */ + public function mapHost(int $bmcId, int $hostId, int $userId): bool { + if ($hostId <= 0 || $this->findByHost($hostId, $bmcId) !== null) { + return false; + } + + $ok = db_execute_prepared('UPDATE plugin_redfish_bmc SET host_id = ?, updated_at = ? WHERE id = ? AND host_id = 0', [$hostId, $this->clock->now(), $bmcId], true, $this->connection) + && db_affected_rows($this->connection) === 1; + + if ($ok) { + $this->audit($bmcId, $userId, 'update', ['host_id']); + } + + return $ok; + } + + /** + * Accept the BMC's members as they are now: members present stay + * expected, and members no longer present stop counting as failed. + * Audited, as an administrator's decision. + */ + public function acceptMembers(int $bmcId, int $userId): bool { + $ok = (bool) db_execute_prepared("UPDATE plugin_redfish_member SET expected = IF(presence = 'present', 'on', '') WHERE bmc_id = ?", [$bmcId], true, $this->connection); + + if ($ok) { + $this->audit($bmcId, $userId, 'update', ['members']); + } + + return $ok; + } + + /** + * 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; + } + + $in = implode(', ', array_fill(0, count($hostIds), '?')); + $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 ($in)", $hostIds, true, $this->connection))); + $cleared = 0; + + // Compare and set: a BMC moved to a surviving device since the + // SELECT keeps that mapping, and only cleared mappings are audited. + foreach ($ids as $id) { + if (db_execute_prepared("UPDATE plugin_redfish_bmc SET host_id = 0, updated_at = ? WHERE id = ? AND host_id IN ($in)", array_merge([$this->clock->now(), $id], $hostIds), true, $this->connection) && db_affected_rows($this->connection) === 1) { + $this->audit($id, 0, 'unmap', ['host_id']); + $cleared++; + } + } + + return $cleared; + } + /** * Device choices for the edit form: id => description. * @@ -292,6 +366,12 @@ private function write(Bmc $bmc, ?Bmc $before): int { $row = $bmc->toRow(); $now = $this->clock->now(); + // One BMC per device; the host_owner unique key backs this up when + // two writes race, and the write then fails instead of doubling up. + if ($bmc->hostId > 0 && $this->findByHost($bmc->hostId, $bmc->id) !== null) { + return 0; + } + if ($before === null) { $columns = array_keys($row); $ok = db_execute_prepared('INSERT INTO plugin_redfish_bmc (' . implode(', ', $columns) . ', created_at, updated_at) VALUES (' . implode(', ', array_fill(0, count($columns) + 2, '?')) . ')', array_merge(array_values($row), [$now, $now]), true, $this->connection); 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..0f0574c --- /dev/null +++ b/lib/CactiObjectRepository.php @@ -0,0 +1,145 @@ + + * 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. + */ + /** + * The query graph by hash, only while it still belongs to the shipped + * data query and points at its shipped graph template. + */ + public function queryGraphId(string $queryName, string $graphName): int { + $template = TemplateInstaller::QUERY_GRAPHS[$queryName][$graphName] ?? ''; + + return (int) db_fetch_cell_prepared('SELECT sqg.id FROM snmp_query_graph AS sqg + INNER JOIN snmp_query AS sq ON sq.id = sqg.snmp_query_id + INNER JOIN graph_templates AS gt ON gt.id = sqg.graph_template_id + WHERE sqg.hash = ? AND sq.hash = ? AND gt.hash = ?', [ + TemplateInstaller::hash('data_query_graph', $queryName . ':' . $graphName), + TemplateInstaller::hash('data_query', $queryName), + TemplateInstaller::hash('graph_template', $template), + ], '', 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..34d887a --- /dev/null +++ b/lib/DeviceProvisioner.php @@ -0,0 +1,249 @@ + + * 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(): void $loadCacti loads the Cacti libraries that + * device and graph creation use, so + * no caller has to load them first + * @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 TemplateInstaller $templates, + private readonly \Closure $loadCacti, + private readonly \Closure $visible, + ) { + } + + /** + * Why the plugin cannot provision now, or null when it can: every + * shipped template, data query, and query graph, and the query files. + */ + public function refusal(): ?string { + if (!$this->templates->present() || $this->templates->queryFileProblems() !== []) { + return __('The Redfish templates are not installed completely. 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'); + } + } + + if (($members['missing'] ?? 0) > 0) { + $lines[] = __('%d fans or power supplies that were present are no longer reported. They count as failed until you confirm; confirming accepts the members the BMC reports now.', $members['missing'], '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(); + $refusal = $this->refusal(); + + if ($refusal !== null || $templateId === 0 || $bmc->hostId > 0) { + $error = $refusal ?? __('The BMC is already mapped to a device.', 'redfish'); + + return 0; + } + + ($this->loadCacti)(); + + $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::warning(sprintf('Device %d was created for BMC %d, which was mapped elsewhere meanwhile or could not be mapped, so the device was removed again', $hostId, $bmc->id)); + $error = __('The BMC was mapped to a device by someone else meanwhile, or could not be mapped, so the new device was removed again. Reload the page and check its mapping.', 'redfish'); + + return 0; + } + + $this->attach($bmc->id, $hostId, $userId); + + 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 $userId): int { + ($this->loadCacti)(); + + $created = 0; + + // Adding graphs accepts the members the BMC reports now. + if (!$this->bmcs->acceptMembers($bmcId, $userId)) { + Log::error(sprintf('The members of BMC %d could not be accepted', $bmcId)); + } + + 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..673525e --- /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, expected: bool} $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, expected: bool} $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..0a4ca0f --- /dev/null +++ b/lib/NodeCache.php @@ -0,0 +1,107 @@ + + * 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, expected: bool}|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; + } + + /** + * A fan or supply that was present since its members were last accepted + * and is not present now: pulled, failed so far that the BMC reports it + * absent, or gone from the tree. A slot never seen present is not + * missing. A second rotor follows its fan and is never counted. + * + * @param array{key: string, kind: string, name: string, chassis: string, presence: string, expected: bool} $member + */ + public static function missing(array $member): bool { + return in_array($member['kind'], ['fan', 'psu'], true) && $member['expected'] && $member['presence'] !== 'present' && !self::secondRotor($member); + } + + /** + * The second rotor of a fan, which the normalizer files under the fan's + * key plus ":secondary". Only fans have one: a supply whose own id ends + * that way is a supply like any other. + * + * @param array{key: string, kind: string, name: string, chassis: string, presence: string, expected: bool} $member + */ + public static function secondRotor(array $member): bool { + return $member['kind'] === 'fan' && str_ends_with($member['key'], ':secondary'); + } +} diff --git a/lib/NodeCacheRepository.php b/lib/NodeCacheRepository.php new file mode 100644 index 0000000..b7e4aa3 --- /dev/null +++ b/lib/NodeCacheRepository.php @@ -0,0 +1,109 @@ + + * 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, + * and under 'missing' the fans and supplies that were present and are not + * now, which count as failed until they are accepted. + * + * @return array + */ + public function memberCounts(int $bmcId): array { + $counts = []; + + foreach ($this->forBmc($bmcId)->members ?? [] as $member) { + $counts[$member['kind']] = ($counts[$member['kind']] ?? 0) + 1; + + if (NodeCache::missing($member)) { + $counts['missing'] = ($counts['missing'] ?? 0) + 1; + } + } + + return $counts; + } + + /** + * @param 'b.host_id = ?'|'b.id = ?' $where + */ + private function load(string $where, int $id): ?NodeCache { + // The three reads share one snapshot (InnoDB's default repeatable + // read), so a collection committing in between cannot pair new + // members with old readings. Inside a caller's transaction PDO + // refuses a second one; the reads then share the caller's. + try { + $snapshot = db_begin_transaction($this->connection); + } catch (\PDOException) { + $snapshot = false; + } + + try { + return $this->read($where, $id); + } finally { + if ($snapshot) { + db_commit_transaction($this->connection); + } + } + } + + private function read(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, expected 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'), 'expected' => Row::string($m, 'expected') === 'on']; + } + + $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/ReadingRepository.php b/lib/ReadingRepository.php index e15d760..bbb3395 100644 --- a/lib/ReadingRepository.php +++ b/lib/ReadingRepository.php @@ -55,9 +55,10 @@ public function commit(int $bmcId, string $holder, int $now, BmcHealth $health, } foreach ($ok && $observation !== null ? $observation->members : [] as $member) { - $ok = $ok && db_execute_prepared('INSERT INTO plugin_redfish_member (bmc_id, member_key, kind, chassis_id, name, source, presence, first_seen, last_seen) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) - ON DUPLICATE KEY UPDATE kind = VALUES(kind), chassis_id = VALUES(chassis_id), name = VALUES(name), source = VALUES(source), presence = VALUES(presence), last_seen = VALUES(last_seen)', [ - $bmcId, $member->key, $member->kind, substr($member->chassis, 0, 64), $member->name, $member->source, $member->absent ? 'absent' : 'present', $now, $now, + // A member seen present stays expected until it is accepted again. + $ok = $ok && db_execute_prepared("INSERT INTO plugin_redfish_member (bmc_id, member_key, kind, chassis_id, name, source, presence, expected, first_seen, last_seen) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + ON DUPLICATE KEY UPDATE kind = VALUES(kind), chassis_id = VALUES(chassis_id), name = VALUES(name), source = VALUES(source), presence = VALUES(presence), expected = IF(VALUES(presence) = 'present', 'on', expected), last_seen = VALUES(last_seen)", [ + $bmcId, $member->key, $member->kind, substr($member->chassis, 0, 64), $member->name, $member->source, $member->absent ? 'absent' : 'present', $member->absent ? '' : 'on', $now, $now, ], true, $this->connection); } diff --git a/lib/Schema.php b/lib/Schema.php index 0aca00e..c01f24d 100644 --- a/lib/Schema.php +++ b/lib/Schema.php @@ -34,12 +34,15 @@ * the next run (REQ-LIFE-001). No migration contacts a BMC. */ final class Schema { - public const VERSION = 1; + public const VERSION = 2; 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', ]; @@ -134,9 +137,70 @@ public function forgetVersion(): void { private function migrations(): array { return [ 1 => fn (): bool => $this->createTables(self::tables()), + 2 => fn (): bool => $this->addMemberBaseline(), ]; } + /** + * Version 2: the host_id key on plugin_redfish_bmc, at most one BMC per + * Cacti device, and the expected flag on plugin_redfish_member. A member + * present today is expected, so an upgrade starts from the members the + * BMC reports now. Each step checks first, so a repeated or interrupted + * run is safe. + */ + private function addMemberBaseline(): bool { + if (!$this->indexExists('plugin_redfish_bmc', 'host_id') && !db_execute_prepared('ALTER TABLE plugin_redfish_bmc ADD KEY host_id (host_id)', [], true, $this->connection)) { + return false; + } + + if (!$this->indexExists('plugin_redfish_bmc', 'host_owner') && !$this->addHostOwner()) { + return false; + } + + if (!$this->columnExists('plugin_redfish_member', 'expected') && !db_execute_prepared("ALTER TABLE plugin_redfish_member ADD COLUMN expected varchar(3) NOT NULL DEFAULT '' AFTER presence", [], true, $this->connection)) { + return false; + } + + // The column is committed on its own, so the baseline runs on every + // attempt until version 2 is recorded: an attempt stopped after the + // column was added still sets it. Setting it again changes nothing. + if (!db_execute_prepared("UPDATE plugin_redfish_member SET expected = 'on' WHERE presence = 'present'", [], true, $this->connection)) { + return false; + } + + return $this->indexExists('plugin_redfish_bmc', 'host_id') && $this->columnExists('plugin_redfish_member', 'expected'); + } + + /** + * One BMC per device, held by the database: host_owner is host_id, or + * NULL for an unmapped BMC, and NULLs do not collide in a unique key. + * Before the key, a device that carries several BMCs keeps the lowest + * BMC id; the others are unmapped and logged. + */ + private function addHostOwner(): bool { + foreach (Row::rows(db_fetch_assoc_prepared('SELECT DISTINCT b.id, b.host_id FROM plugin_redfish_bmc AS b INNER JOIN plugin_redfish_bmc AS f ON f.host_id = b.host_id AND f.id < b.id WHERE b.host_id > 0 ORDER BY b.id', [], true, $this->connection)) as $row) { + if (!db_execute_prepared('UPDATE plugin_redfish_bmc SET host_id = 0 WHERE id = ? AND host_id = ?', [Row::int($row, 'id'), Row::int($row, 'host_id')], true, $this->connection)) { + return false; + } + + Log::warning(sprintf('BMC %d was unmapped from device %d, which another BMC already carries', Row::int($row, 'id'), Row::int($row, 'host_id'))); + } + + if (!$this->columnExists('plugin_redfish_bmc', 'host_owner') && !db_execute_prepared('ALTER TABLE plugin_redfish_bmc ADD COLUMN host_owner int(10) unsigned AS (NULLIF(host_id, 0)) STORED', [], true, $this->connection)) { + return false; + } + + return (bool) db_execute_prepared('ALTER TABLE plugin_redfish_bmc ADD UNIQUE KEY host_owner (host_owner)', [], true, $this->connection); + } + + private function columnExists(string $table, string $column): bool { + return db_fetch_cell_prepared('SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?', [$table, $column], '', true, $this->connection) > 0; + } + + private function indexExists(string $table, string $index): bool { + return db_fetch_cell_prepared('SELECT COUNT(*) FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND INDEX_NAME = ?', [$table, $index], '', true, $this->connection) > 0; + } + /** * Track every existing plugin table for uninstall again. * @@ -215,7 +279,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', @@ -279,6 +344,10 @@ public static function tables(): array { $text('name', 255), $text('source', 32), $text('presence', 16, 'present'), + // 'on' once seen present, until an administrator accepts + // the BMC's members again with Add Graphs; an expected + // member that is not present counts as failed. + $text('expected', 3), $count('first_seen'), $count('last_seen'), ], diff --git a/lib/SummaryScript.php b/lib/SummaryScript.php new file mode 100644 index 0000000..4905cad --- /dev/null +++ b/lib/SummaryScript.php @@ -0,0 +1,124 @@ + + * 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; + } + + /** + * Members of a kind that failed: present with usable health of Warning or + * worse, or missing (NodeCache::missing) since they were last accepted. + * A second fan rotor shares its fan's health and is not counted twice; + * a slot never seen present is not counted. + */ + private function bad(NodeCache $cache, string $kind): int { + $bad = 0; + + foreach ($cache->membersOf($kind) as $member) { + if (NodeCache::missing($member)) { + $bad++; + + continue; + } + + if ($member['presence'] !== 'present' || NodeCache::secondRotor($member)) { + 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..55e7468 --- /dev/null +++ b/lib/TemplateInstaller.php @@ -0,0 +1,373 @@ + + * 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_link($target) && 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; + } + } + + foreach (self::QUERY_GRAPHS as $query => $graphs) { + foreach (array_keys($graphs) as $graph) { + if ($this->objects->queryGraphId($query, $graph) === 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(); + + 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 is missing, or %s/resource/script_server is missing, is a symbolic link, or lies outside the Cacti directory', $file, $this->cactiPath); + } + + // A link could point the write anywhere; the plugin never follows one. + if (is_link($target)) { + return sprintf('%s is a symbolic link; it was left as it is. Replace it with a copy of plugins/redfish/resource/script_server/%s', $target, $file); + } + + $want = (string) hash_file('sha256', $source); + + if (file_exists($target)) { + $have = is_file($target) ? (string) hash_file('sha256', $target) : ''; + + // Matching contents the plugin did not write stay the site's: + // no ownership is claimed, so uninstall leaves them. + if ($have === $want) { + continue; + } + + if (!isset($written[$file]) || $written[$file] !== $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 (!$this->writeQueryFile($source, $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); + } + + // Recorded at once, so a later file that fails cannot lose it. + $written[$file] = $want; + set_config_option(self::FILES_SETTING, (string) json_encode($written)); + } + + return null; + } + + /** + * Write through a temporary file in the same directory and rename it + * over the target, so the target is never half written and a link put + * there after the check is replaced, not followed. + */ + private function writeQueryFile(string $source, string $target, string $want): bool { + $dir = dirname($target); + + if (!is_writable($dir)) { + return false; + } + + $temp = @tempnam($dir, '.redfish-'); + + if ($temp === false) { + return false; + } + + if (@copy($source, $temp) === false || hash_file('sha256', $temp) !== $want || !@chmod($temp, 0644) || !@rename($temp, $target)) { + @unlink($temp); + + return false; + } + + return !is_link($target) && hash_file('sha256', $target) === $want; + } + + /** + * @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->queryDir(); + + return $dir === null ? null : $dir . '/' . $file; + } + + /** + * Cacti's script server resource directory, or null when it is missing + * or would lead outside the Cacti tree: resource and resource/script_server + * must be real directories, and the directory must resolve inside + * /resource, so no write or delete follows a link elsewhere. + */ + private function queryDir(): ?string { + $resource = $this->cactiPath . '/resource'; + $dir = $resource . '/script_server'; + + if (is_link($resource) || is_link($dir) || !is_dir($dir)) { + return null; + } + + $root = realpath($this->cactiPath); + $real = realpath($dir); + + return $root !== false && $real === $root . '/resource/script_server' ? $dir : null; + } +} diff --git a/locales/po/cacti.pot b/locales/po/cacti.pot index d525004..4431455 100644 --- a/locales/po/cacti.pot +++ b/locales/po/cacti.pot @@ -78,6 +78,16 @@ msgstr "" msgid "Line %d: no Cacti device has ID %d." msgstr "" +#: lib/BmcImport.php +#, php-format +msgid "Line %d: device %d already has the BMC %s." +msgstr "" + +#: lib/BmcImport.php +#, php-format +msgid "of line %d" +msgstr "" + #: lib/BmcImport.php msgid "The file has no BMC rows." msgstr "" @@ -186,16 +196,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 +322,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 +346,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 +404,74 @@ msgstr "" msgid "Stored encrypted with the vault key." msgstr "" +#: lib/DeviceProvisioner.php +msgid "The Redfish templates are not installed completely. 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 "%d fans or power supplies that were present are no longer reported. They count as failed until you confirm; confirming accepts the members the BMC reports 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 BMC was mapped to a device by someone else meanwhile, or could not be mapped, so the new device was removed again. Reload the page and check its mapping." +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 +813,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..a180f33 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, $redfish_user); + 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': @@ -128,6 +182,9 @@ function (string $name) use ($redfish_bmcs): bool { }, function (int $host) use ($redfish_scope): bool { return $redfish_scope->allowsNew($host); + }, + function (int $host) use ($redfish_bmcs): ?string { + return $redfish_bmcs->findByHost($host)?->name; } ); 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..ba707d0 100644 --- a/setup.php +++ b/setup.php @@ -192,6 +192,58 @@ 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()); +} + +/** + * The Cacti libraries device creation, data queries, and graph creation use, + * the set Cacti's own cli/add_graphs.php loads. + */ +function redfish_load_cacti(): void { + // The files expect file scope: lib/snmp.php reads $config and sets + // $banned_snmp_strings, which its functions read as a global. + global $config, $banned_snmp_strings; + + foreach (['api_automation_tools', 'api_automation', 'api_data_source', 'api_graph', 'api_device', 'api_tree', 'data_query', 'poller', 'snmp', 'sort', 'template', 'utility'] as $library) { + require_once($config['library_path'] . '/' . $library . '.php'); + } +} + +function redfish_provisioner(): \Somethingwithproof\Redfish\DeviceProvisioner { + return new \Somethingwithproof\Redfish\DeviceProvisioner( + redfish_bmcs(), + redfish_cacti_objects(), + redfish_template_installer(), + \Closure::fromCallable('redfish_load_cacti'), + 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 +262,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 +282,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 +359,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 +404,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..523800a 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'); @@ -53,7 +53,8 @@ expect($state['plugin']['status'])->toEqual('4') ->and($state['plugin']['version'])->toEqual(REDFISH_VERSION) - ->and($state['schema'])->toEqual('1') + ->and($state['schema'])->toEqual('2') + ->and($state['v2']['host_owner'])->toBeTrue() ->and(array_keys($state['tables']))->toBe(REDFISH_TABLES) ->and($state['tracked'])->toBe(REDFISH_TABLES) ->and(array_keys($state['hooks']))->toBe(REDFISH_HOOKS) @@ -123,10 +124,35 @@ expect($state['result'])->toBeTrue() ->and(array_keys($state['tables']))->toBe(REDFISH_TABLES) ->and($state['tables']['plugin_redfish_credential'])->toBe(1) - ->and($state['schema'])->toEqual('1') + ->and($state['schema'])->toEqual('2') ->and($state['plugin']['version'])->toEqual(REDFISH_VERSION); }); +it('upgrades a milestone 2 schema, expecting the members present now', function () { + lifecycle('install'); + lifecycle('schema_v1'); + + $state = lifecycle('upgrade'); + expect($state['result'])->toBeTrue() + ->and($state['schema'])->toEqual('2') + ->and($state['v2'])->toBe(['host_owner' => true, 'hosts' => [1 => 50, 2 => 0, 3 => 0, 4 => 0], 'host_key' => true, 'expected' => ['1/fan/A' => 'on', '1/fan/B' => '']]) + ->and($state['logged'])->toContain('BMC 2 was unmapped from device 50, which another BMC already carries'); + + expect(lifecycle('upgrade')['v2'])->toBe($state['v2']); +}); + +it('finishes the member baseline of an upgrade stopped after adding the column', function () { + lifecycle('install'); + lifecycle('schema_v1'); + lifecycle('upgrade'); + lifecycle('schema_v1_column_only'); + + $state = lifecycle('upgrade'); + expect($state['result'])->toBeTrue() + ->and($state['schema'])->toEqual('2') + ->and($state['v2']['expected'])->toBe(['1/fan/A' => 'on', '1/fan/B' => '']); +}); + it('does not advance past a migration that did not run', function () { lifecycle('install'); lifecycle('set_schema', '0'); @@ -136,7 +162,7 @@ ->and($stopped['schema'])->toEqual('0'); $finished = lifecycle('upgrade'); - expect($finished['schema'])->toEqual('1'); + expect($finished['schema'])->toEqual('2'); }); it('refuses a schema newer than the code and leaves the recorded version alone', function () { @@ -148,7 +174,8 @@ expect($state['result'])->toBeFalse() ->and($state['plugin']['version'])->toEqual('0.0') - ->and($state['schema'])->toEqual('99'); + ->and($state['schema'])->toEqual('99') + ->and($state['logged'])->toContain('REDFISH ERROR: Schema version 99 is newer than this code (2); refusing to downgrade'); }); it('keeps tables on uninstall by default, and drops them only when the box was cleared', function () { diff --git a/tests/Support/FakeBmc.php b/tests/Support/FakeBmc.php index be9c934..7ae7c36 100644 --- a/tests/Support/FakeBmc.php +++ b/tests/Support/FakeBmc.php @@ -59,17 +59,25 @@ public static function certs(): string { } /** - * @param array $state initial flags and sessions + * @param array $state initial flags and sessions + * @param int $lifetime seconds the server runs, 600 when 0 */ - public function __construct(string $fixture = 'dell-subsystem', string $cert = 'good', array $state = [], bool $old = false) { + public function __construct(string $fixture = 'dell-subsystem', string $cert = 'good', array $state = [], bool $old = false, int $lifetime = 0) { $this->port = self::freePort(); $this->state = tempnam(sys_get_temp_dir(), 'redfish-fake-state-'); file_put_contents($this->state, json_encode($state + ['flags' => [], 'sessions' => [], 'log' => [], 'next' => 1])); - $args = [PHP_BINARY, __DIR__ . '/../fake-bmc/server.php', (string) $this->port, self::certs() . '/' . $cert . '.pem', __DIR__ . '/../fixtures/' . $fixture . '.json', $this->state]; + // A fixture name, or the absolute path of a fixture a test wrote. + $file = str_starts_with($fixture, '/') ? $fixture : __DIR__ . '/../fixtures/' . $fixture . '.json'; + $args = [PHP_BINARY, __DIR__ . '/../fake-bmc/server.php', (string) $this->port, self::certs() . '/' . $cert . '.pem', $file, $this->state]; - if ($old) { - $args[] = 'tls1.1'; + if ($old || $lifetime > 0) { + $args[] = $old ? 'tls1.1' : 'tls'; + } + + // Seconds the server runs before it stops itself, past the default. + if ($lifetime > 0) { + $args[] = (string) $lifetime; } $env = getenv() + ['REDFISH_FAKE_USER' => self::USER, 'REDFISH_FAKE_PASSWORD' => self::PASSWORD]; diff --git a/tests/Unit/BmcTest.php b/tests/Unit/BmcTest.php index d14bf07..56f7814 100644 --- a/tests/Unit/BmcTest.php +++ b/tests/Unit/BmcTest.php @@ -120,3 +120,17 @@ function redfish_import(string $csv, array $taken = []): BmcImport { ->and(redfish_import('')->errors[0])->toContain('empty') ->and(redfish_import("name,address,credential\n")->errors[0])->toContain('no BMC rows'); }); + +it('imports at most one BMC per device, against the registry and within the file', function () { + $csv = "name,address,credential,host_id\na,10.0.0.1,ro-monitor,7\nb,10.0.0.2,ro-monitor,7\nc,10.0.0.3,ro-monitor,\nd,10.0.0.4,ro-monitor,\n"; + + // An import is all or nothing, so a conflict imports no row. + $inFile = redfish_import($csv); + expect($inFile->bmcs)->toBe([]) + ->and($inFile->errors)->toBe(['Line 3: device 7 already has the BMC of line 2.']) + ->and(redfish_import(str_replace(',7', ',', $csv))->bmcs)->toHaveCount(4); + + $registry = BmcImport::parse($csv, ['ro-monitor' => 3], fn (string $a, int $p) => null, fn (string $n) => false, fn (int $h) => $h === 7, fn (int $h) => $h === 7 ? 'r660' : null); + expect($registry->bmcs)->toBe([]) + ->and($registry->errors)->toBe(['Line 2: device 7 already has the BMC r660.', 'Line 3: device 7 already has the BMC r660.']); +}); diff --git a/tests/Unit/QueryFilesTest.php b/tests/Unit/QueryFilesTest.php new file mode 100644 index 0000000..cf7baae --- /dev/null +++ b/tests/Unit/QueryFilesTest.php @@ -0,0 +1,97 @@ + + * 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\CactiObjectRepository; +use Somethingwithproof\Redfish\TemplateInstaller; + +/* + * Query files go only into /resource/script_server as a real + * directory: no write or delete follows a link out of the Cacti tree. + */ + +/** + * A scratch Cacti tree, and a directory outside it. + * + * @return array{0: string, 1: string} + */ +function query_tree(): array { + $base = sys_get_temp_dir() . '/redfish-query-' . bin2hex(random_bytes(4)); + mkdir("$base/cacti/resource/script_server", 0700, true); + mkdir("$base/outside/script_server", 0700, true); + + return ["$base/cacti", "$base/outside"]; +} + +function query_tree_remove(string $path): void { + if (is_link($path) || is_file($path)) { + unlink($path); + + return; + } + + foreach (is_dir($path) ? array_diff((array) scandir($path), ['.', '..']) : [] as $entry) { + query_tree_remove("$path/$entry"); + } + + if (is_dir($path)) { + rmdir($path); + } +} + +/** + * @return array{0: ?string, 1: list} the install refusal and the files with problems + */ +function query_install(string $cacti): array { + $GLOBALS['__redfish_options'] = []; + $installer = new TemplateInstaller(dirname(__DIR__, 2), $cacti, new CactiObjectRepository(false)); + $refusal = (fn (): ?string => $this->installQueryFiles())->call($installer); + + return [$refusal, $installer->queryFileProblems()]; +} + +it('writes the query files into a real resource directory', function () { + [$cacti, $outside] = query_tree(); + [$refusal, $problems] = query_install($cacti); + + expect($refusal)->toBeNull() + ->and($problems)->toBe([]) + ->and(count(glob("$cacti/resource/script_server/redfish_*.xml")))->toBe(count(TemplateInstaller::QUERIES)); + + query_tree_remove(dirname($cacti)); +}); + +it('refuses a resource directory that is a link or leads outside the Cacti tree', function (string $link) { + [$cacti, $outside] = query_tree(); + query_tree_remove("$cacti/$link"); + + if ($link === 'resource') { + symlink($outside, "$cacti/resource"); + } else { + symlink("$outside/script_server", "$cacti/resource/script_server"); + } + + [$refusal, $problems] = query_install($cacti); + + expect($refusal)->toContain('is a symbolic link, or lies outside the Cacti directory') + ->and($problems)->toBe(array_column(array_values(TemplateInstaller::QUERIES), 1)) + ->and(glob("$outside/script_server/*"))->toBe([]) + ->and(glob("$outside/*.xml"))->toBe([]); + + query_tree_remove(dirname($cacti)); +})->with(['resource', 'resource/script_server']); diff --git a/tests/Unit/ScriptServerTest.php b/tests/Unit/ScriptServerTest.php new file mode 100644 index 0000000..9992d34 --- /dev/null +++ b/tests/Unit/ScriptServerTest.php @@ -0,0 +1,300 @@ + + * 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], expected]. + * + * @param list, 4?: bool}> $members + */ +function redfish_cache(array $members, int $lastSuccessAge = 60, int $registeredAge = 86400): void { + $m = []; + $r = []; + + foreach ($members as $member) { + [$key, $kind, $presence, $readings] = $member; + // Expected unless given: a member present now has been seen present. + $expected = $member[4] ?? ($presence === 'present'); + $m[] = ['member_key' => $key, 'kind' => $kind, 'name' => 'Name of ' . $key, 'chassis_id' => '1', 'presence' => $presence, 'expected' => $expected ? 'on' : '']; + + 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', "