diff --git a/.github/workflows/plugin-ci-workflow.yml b/.github/workflows/plugin-ci-workflow.yml index fafc2ec..637b5ae 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 @@ -230,6 +230,34 @@ jobs: exit 1 fi + # Thold v1.8.2 and Maint v1.3 at pinned commits, unchanged, against the + # Fabric data sources through Cacti's own poller (tests/bin/e2e.sh). On + # PHP 8.2, the oldest PHP the plugin supports, for both Cacti refs. + - name: Checkout Thold v1.8.2 + if: matrix.php == '8.2' + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + repository: Cacti/plugin_thold + ref: 1eb406bd0f81f3204358cce7bd43c8bb5adc8e4a + path: cacti/plugins/thold + + - name: Checkout Maint v1.3 + if: matrix.php == '8.2' + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + repository: Cacti/plugin_maint + ref: cd62de9cc323a4f5a8ac80a8d9dda3c7fa16c470 + path: cacti/plugins/maint + + - name: Run Thold and Maint end to end + if: matrix.php == '8.2' + working-directory: cacti + run: | + mkdir -p "$RUNNER_TEMP/fabric-e2e" + sh plugins/fabric/tests/bin/e2e.sh /opt/fabric-e2e-tools "$RUNNER_TEMP/fabric-e2e" + - name: Check Cacti log for errors if: always() run: | @@ -240,7 +268,16 @@ 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 'Fabric Port [^']+' is impacted by lack of complete information)\$" + grep -E "$core_warnings" cacti/log/cacti.log || true + fi + # The end to end run logs a counter reset as a warning on purpose. + if grep -E "FATAL:|ERROR:|WARNING:" cacti/log/cacti.log | grep -v "counters went down" | grep -vE "$core_warnings" | grep -vE '^[^ ]+ [0-9:]+ - SYSTEM WARNING: Primary Admin account notifications disabled! Unable to send administrative Email\.$'; then exit 1 fi fi @@ -398,6 +435,72 @@ jobs: - name: Lint licensing metadata run: pipx run --spec 'reuse[charset-normalizer]==6.3.0' reuse lint + # The real ibnetdiscover, iblinkinfo, and perfquery of rdma-core 50.0 + # (Ubuntu 24.04's infiniband-diags) against a simulated fabric: linux-rdma + # ibsim and OpenSM under the libumad2sim LD_PRELOAD shim, in an + # unprivileged container with no /dev/infiniband and no added capability. + # The plugin's parsers then read the output. It proves the parsers on real + # tool output; it does not show counter behavior, congestion, or vendor + # hardware output (the plan's live checks). + # + # The image is pinned by digest and the packages by version in + # tests/ibsim/run.sh. Ubuntu drops superseded security builds from its + # archive, so a pinned version can start failing to install: bump the + # digest and the versions together, then compare the new output with + # tests/fixtures/ibsim/. + ibsim-fabric: + name: ibsim fabric tools (rdma-core 50.0) + runs-on: ubuntu-latest + timeout-minutes: 25 + env: + # ubuntu:24.04 index digest (multi-arch). + IBSIM_IMAGE: ubuntu@sha256:2198e4c65076e9cb0b3d695219df667c0e3b0072da64ca3c2648aca17dcecaf5 + steps: + - name: Checkout plugin + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install PHP 8.2 + uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 + with: + php-version: '8.2' + coverage: none + + - name: Check the parsers against the committed captures + run: php tests/bin/check-ibsim-fixtures.php tests/fixtures/ibsim + + # Detached, then bounded with docker wait: `timeout docker run` stops + # only the client, and the container's shell, as PID 1, ignores the + # SIGTERM it forwards. Two APT stages plus two scenario watchdogs + # take at most 1,142 s; the outer wait also allows cleanup time. + - name: Run the tools against the simulated fabric + timeout-minutes: 23 + run: | + set -euo pipefail + out="$RUNNER_TEMP/ibsim-out" + mkdir -p "$out" + docker pull --quiet "$IBSIM_IMAGE" > /dev/null + docker run --detach --name ibsim-fabric \ + --volume "$GITHUB_WORKSPACE:/repo:ro" \ + --volume "$out:/out" \ + "$IBSIM_IMAGE" \ + sh /repo/tests/ibsim/run.sh /repo /out > /dev/null + rc=$(timeout 1200 docker wait ibsim-fabric) || rc=timeout + docker logs ibsim-fabric 2>&1 + docker rm --force ibsim-fabric > /dev/null + if [ "$rc" = timeout ]; then + echo "::error::the ibsim run did not finish within 1200 s; the last stage logged above is the one that stalled" + exit 1 + fi + [ "$rc" = 0 ] || { echo "::error::the ibsim run exited $rc"; exit 1; } + echo "IBSIM_OUT=$out" >> "$GITHUB_ENV" + + # LIDs and line order come from OpenSM and change between runs, so the + # check is structural, never a byte comparison with the captures. + - name: Check the parsers against this run's output + run: php tests/bin/check-ibsim-fixtures.php "$IBSIM_OUT" + ci-ok: name: ci-ok if: ${{ always() }} @@ -407,6 +510,7 @@ jobs: - php-guard - workflow-lint - reuse + - ibsim-fabric runs-on: ubuntu-latest timeout-minutes: 5 permissions: {} diff --git a/README.md b/README.md index b4aee54..8c02b0d 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ A Cacti 1.2 plugin that brings InfiniBand port counters, link width and speed, and congestion indicators into Cacti as ordinary devices, data sources, and graphs. A link that trained at 1X instead of 4X then shows up as a graph and a Thold alert next to the host it serves, under Cacti's permissions, with Maint able to suppress it. -> **Status: in development, no release yet.** Milestone 2 (foundation) is merged on `main`. Milestone 1 confirmed the design against documentation and upstream source (PR #71); the results, with sources, are in [docs/research/](docs/research/). Milestone 2 adds the plugin foundation: +> **Status: in development, no release yet.** Milestone 2 (foundation) is merged on `main`, and milestone 3 (Cacti objects and alerting) is in review. Milestone 1 confirmed the design against documentation and upstream source (PR #71); the results, with sources, are in [docs/research/](docs/research/). Milestone 2 adds the plugin foundation: > > - install, upgrade, uninstall, and the PHP 8.2 guard > - two realms and the settings @@ -12,7 +12,15 @@ A Cacti 1.2 plugin that brings InfiniBand port counters, link width and speed, a > - link state and the counter sweep cache > - inventory, admin, and health pages > -> It creates no Cacti devices, data sources, graphs, or alerts yet; those are milestone 3. A fabric can be swept only from the main poller until remote data collectors are supported in phase 3. It has been tested only against fake tools, never on an InfiniBand fabric. Checks that need a fabric remain open in each research page's live-checks table. This project is not affiliated with the Cacti project. +> Milestone 3 adds the Cacti objects: +> +> - device, data, and graph templates shipped as Cacti template XML, and the "Fabric Port" data query +> - mapping a node to a Cacti device, or creating one on confirmation ([ADR 0010](docs/decisions/0010-one-device-per-node.md)) +> - counter data sources for graphs, and GAUGE link state and rate data sources for Thold ([ADR 0011](docs/decisions/0011-derive-counters-and-gauge-alert-values.md)) +> - discontinuity handling and saturated basic counters read as unknown ([ADR 0012](docs/decisions/0012-saturated-basic-counters-read-as-unknown.md)), counter validity and graph links on the port page, and a congestion ranking +> - an end-to-end test with unchanged Thold v1.8.2 and Maint v1.3, and a CI job that runs the real diagnostic tools against a simulated fabric +> +> A fabric can be swept only from the main poller until remote data collectors are supported in phase 3. It has been tested against fake tools and the ibsim fabric simulator, never on an InfiniBand fabric. Checks that need a fabric remain open in each research page's live-checks table. This project is not affiliated with the Cacti project. ## Why @@ -45,6 +53,8 @@ Out of scope: changing fabric state, replacing a fabric manager or subnet manage | UFM | UFM Enterprise REST API, phase 2; release matrix is a milestone 1 deliverable | | Thold, Maint | No changes required | +Keep Cacti's script timeout at its default 25 seconds or higher. A sweep started by a data-query read limits tool execution to that timeout minus five seconds, reserving time to read the cache and reply. When the budget expires, the query serves the last current sample or unknown; the next cycle retries the sweep. This limit also applies to the PHP poller. A timeout of five seconds or less leaves no time to start a tool. + ## Design - [docs/PLAN.md](docs/PLAN.md) is the full plan: architecture, upstream facts it depends on (with sources) and assumptions still to confirm, identity model, counter and link-state rules, security boundaries, performance arithmetic, testing, and risks. diff --git a/REUSE.toml b/REUSE.toml index 08e78f7..589ce93 100644 --- a/REUSE.toml +++ b/REUSE.toml @@ -2,8 +2,8 @@ version = 1 # Files that cannot carry a comment header, or whose format makes one # awkward: documentation, repository metadata, GitHub templates, test -# configuration, tool output fixtures, and translation catalogs, -# which gettext regenerates. +# configuration, tool output fixtures, generated Cacti template and data +# query XML, and translation catalogs, which gettext regenerates. [[annotations]] path = [ "README.md", @@ -17,6 +17,8 @@ path = [ "phpunit.xml", "phpunit-integration.xml", "tests/fixtures/**", + "templates/**", + "resource/**", "locales/po/**", "locales/LC_MESSAGES/**", ] diff --git a/docs/PLAN.md b/docs/PLAN.md index 9750480..b2abc23 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -252,13 +252,13 @@ Each node record has its type, GUID, display name, fabric, mapped Cacti device ( ## Cacti objects -Ports appear as indexes of a script data query on the node's Cacti device ([decision pending](#open-decisions) on device granularity): +Ports appear as indexes of a script data query on the node's Cacti device, one device per node ([ADR 0010](decisions/0010-one-device-per-node.md)): | Object | Created from | Notes | |---|---|---| | Device | "Fabric Node" device template; each created device is saved with `availability_method` 0 (none) unless an address exists and `poller_id` set to the poller that sweeps the fabric | Existing devices can be mapped instead; created only on operator confirmation. A device template has no availability field in Cacti 1.2; it is set per device through `api_device_save()` | | Data query | "Fabric Port", a script query reading the inventory cache | Index `:`; the XML sets `arg_num_indexes` and an `output_delimiter` that is not `:`; ports down with no remote end are skipped by default | -| Data sources | Four data templates per port: traffic (4 data sources), errors (12), congestion (4), link state (5) | Grouping measured in [research](research/rrd-layout.md): same disk as one file per counter (about 2.3 MB per port with the default profile), about one sixth of the files and update time. Data source names are at most 19 characters and `max` is set explicitly | +| Data sources | Four data templates per port: traffic (4 data sources), errors (12), congestion (4), link state (5). As built, five: traffic (4), errors (9), congestion (4), link state (5), alert rates (5); see [Milestone 3 as built](#milestone-3-as-built) | Grouping measured in [research](research/rrd-layout.md): same disk as one file per counter (about 2.3 MB per port with the default profile), about one sixth of the files and update time. Data source names are at most 19 characters and `max` is set explicitly | | State data source | "Fabric Port State" using the script server input | Polled; reaches Thold through `poller_output` | | Graphs | Graph templates per group, plus a fabric overview | Placed in graph trees and protected by graph permissions like any Cacti graph | @@ -270,7 +270,7 @@ Devices created by the plugin appear in device lists and in plugins such as moni **Counters** are stored as received from the port. -- Basic counters are narrow and cap instead of wrapping (see the facts table). With no reset, a narrow counter eventually stops changing. The plugin uses the 64-bit forms where the port supports them, marks a capped basic counter as saturated and publishes unknown for it, and shows the reason on the port page. The alternative of resetting is rejected ([ADR 0004](decisions/0004-read-only-fabric-access.md)). A decision issue tracks the treatment and waits for hardware evidence. +- Basic counters are narrow and cap instead of wrapping (see the facts table). With no reset, a narrow counter eventually stops changing. The plugin uses the 64-bit forms where the port supports them, marks a capped basic counter as saturated and publishes unknown for it, and shows the reason on the port page. The alternative of resetting is rejected ([ADR 0004](decisions/0004-read-only-fabric-access.md)). The treatment is decided ([ADR 0012](decisions/0012-saturated-basic-counters-read-as-unknown.md)); confirming it needs hardware evidence. - Data counters are octets divided by 4. Stored values stay in the tools' unit; graph definitions multiply by 4. - Data sources are COUNTER type with an explicit `max` (a `max` of 0 would be created as 1). For counters of 16 bits or fewer, `max` equal to the cap per interval turns a reset into a gap; for data counters, `max` is the link's capacity in words per second and can be a per-port data query field. That is not enough for 32-bit counters, or for 64-bit counters reset from a value below 2^32, where the false rate stays below any useful `max`. The plugin therefore always compares each sample to the previous one, publishes unknown for one cycle after a decrease, and counts discontinuities on the port page ([research](research/counters.md)). Another tool can cause the decrease: OpenSM's optional performance manager resets counters at about three-quarters of their range by its documentation. The `max` is set once, when the RRD file is created, so it uses a bound that does not depend on the current speed: the capacity of the best width and speed the port supports at both ends. A later speed change within that bound needs no action; if a port's supported speed rises (a firmware or cable change), the plugin runs an `rrdtool tune` step for that port's files. - A value the port does not support is unknown, never `0`. This applies in particular to PortXmitWait in basic counters, which the tools zero when unsupported. @@ -449,6 +449,25 @@ Milestone 2 is implemented on a local branch. Where it differs from the requirem - **Schema version 1 changed before release.** Columns and keys added in review went into the version 1 definition, not a migration, because no release has shipped it. A database created from an earlier branch build must be reinstalled. - **Main poller only.** A remote poller reads its own copy of the database, which holds no fabric inventory or claims, so until phase 3 a fabric may be assigned only to the main poller (ID 1). Saving any other poller is refused, the health page warns about a stored row that names one, and `fabric_sweep.php` refuses to run for such a fabric or on a remote poller and logs why. +### Milestone 3 as built + +Milestone 3 is implemented on a branch. Where it differs from the requirement texts or from the sections above: + +- **Device granularity.** One device per node, mapped by an operator or created on confirmation ([ADR 0010](decisions/0010-one-device-per-node.md)), decided in #9. The code keeps the mapping in one column, so a change the Cacti maintainers ask for later is a migration. +- **Saturated counters.** Decided in #8 ([ADR 0012](decisions/0012-saturated-basic-counters-read-as-unknown.md)): 64-bit counters where supported, `U` for a saturated basic counter, never a reset. Confirming it needs captures from real hardware. +- **Data source types.** The [Counters](#counters-and-link-state) section above names COUNTER with a per-port `max`. As built, counters are DERIVE with minimum 0 and a fixed plausibility `max`, for graphs only, and thresholds use GAUGE values: the link state values and five rates the plugin computes from its own samples ([ADR 0011](decisions/0011-derive-counters-and-gauge-alert-values.md)). Thold 1.8.2 fails with a TypeError on a COUNTER or DERIVE threshold that reads `U`, and disables itself site-wide. No `rrdtool tune` step is needed, since `max` does not depend on the port speed. +- **Data source layout.** Five data templates of 4, 9, 4, 5, and 5 data sources, 27 per port, against four templates and 25 in [research](research/rrd-layout.md): the alert rates are added, and the error group leaves out QP1Dropped and the unicast and multicast packet counters. +- **Degraded.** With the diags backend `degraded` is `U` for every below-best port (ADR 0009), so REQ-ALERT-010's 4X to 1X alert is proven with a low threshold of 4 on `active_lanes`, not with `degraded`. +- **Sweep trigger.** REQ-ALERT-003 expected the state values to be fetched by a sweep before the poll. As built, the first script server `get` for a device in a cycle starts that device's due sweep ([ADR 0008](decisions/0008-lazy-per-device-sweep-with-a-claim.md)); a reindex (index, query) only reads the cache. +- **Sampling alignment.** Rates are over the plugin's sampling interval. Set the fabric's sweep interval equal to the poller interval; otherwise a repeated sample reads as a rate of 0. +- **Created devices outlive the plugin.** REQ-LIFE-003 expected the plugin's devices to go with the fabric or the plugin. They stay, with their data sources and RRD files, because removing them removes history; the delete confirmation says so. Deleting a device in Cacti clears its node mapping through the `device_remove` hook. +- **Template repair.** The upgrade check installs the templates when the template version changes. A template or the query file removed afterwards is shown on the health page, where a user with Cacti's template import permission can reinstall; a page load never imports. +- **Query file outside the plugin.** Cacti reads data query XML only from `/resource`, so the plugin copies `fabric_ports.xml` to `resource/script_server/`. It writes there only where no file is or over its own unchanged copy, refuses a symbolic link, and removes only its own unchanged copy on uninstall. An uninstall on an unsupported PHP version, which cannot load the plugin's classes, leaves the file. +- **Thold duration and congestion.** Thold's own repeat and time-based settings give the duration of a breach (REQ-ALERT-013); the plugin ships no thresholds. Transmit wait is published as ticks per second, with the meaning on the congestion ranking (REQ-CONG-004); the tick length is not published, so it is never converted to time. +- **Recorded fixtures.** REQ-TEST-001 now has captures from the real infiniband-diags 50.0 tools against the ibsim simulator (`tests/fixtures/ibsim/`), next to the generated ones. They are simulator output, not hardware output; #14 stays open for that, and #39 (test harness and CI matrix) stays open until hardware captures exist. +- **Poller output on Cacti 1.2.31.** In the end-to-end test, Cacti 1.2.31's poller leaves a fixed subset of the Fabric data sources' rows in `poller_output` each cycle and logs "Data Sources not returning all data"; the `1.2.x` branch, which rewrote that deletion, does not. Thold and Maint behave the same on both. The test reports those rows on 1.2.31 instead of failing; whether 1.2.31 sites lose samples for these data sources is not yet established. +- **Scale.** Measured with fake tools on one development machine ([research](research/scale.md)): the plugin's own steps stay small at 10,000 ports, but each port is 27 Cacti poller items with all graphs, and the overview page reaches 1.5 MB without paging. Sweep time on a fabric and the MAD budget remain *live* checks. + ## Estimates Sizes come from measured lines of plugin_cloudflare and plugin_smokeping; elapsed time is not estimated, because the evidence has no review latency and no hardware, and the owner's capacity is unknown ([research](research/estimates.md)). Production PHP, excluding tests: @@ -468,8 +487,8 @@ Phase 1 totals about 8,300 to 10,800 lines, through phase 2 about 9,300 to 12,80 | Decision | Options | Needed before | Decided by | |---|---|---|---| | Sweep timing | Decided for milestone 2: lazy per-device sweep with a claim ([ADR 0008](decisions/0008-lazy-per-device-sweep-with-a-claim.md)). Revisit only if live timing shows it is too slow | Milestone 3 measurements | Live timing measurements ([research](research/mad-budget.md)) | -| Saturated basic counters | Prefer 64-bit and publish unknown on saturation (proposed); opt-in reset; events only | Milestone 3 | Live counter evidence ([research](research/counters.md)) | -| Device granularity | One device per node (proposed); one per fabric; switches only | Milestone 3 | Cacti maintainers | +| Saturated basic counters | Decided: prefer 64-bit, publish unknown on saturation, never reset ([ADR 0012](decisions/0012-saturated-basic-counters-read-as-unknown.md)). Confirmation needs hardware evidence | Release | Live counter evidence ([research](research/counters.md)) | +| Device granularity | Decided: one device per node, mapped or created on confirmation ([ADR 0010](decisions/0010-one-device-per-node.md)). The maintainers may revisit it before an upstream proposal | Upstream proposal | Cacti maintainers | | UFM credential storage | A key file outside the database (Cacti 1.2.31 has no core storage; `1.2.x` has one whose key is in the same database); file outside web root; environment | Phase 2 | Security review ([research](research/ufm-rest.md)) | | Repository and name | `Cacti/plugin_fabric`, `Cacti/plugin_infiniband`, or community plugin | Before any code is published | Cacti maintainers | | Test harness | Provisional: Pest from Cacti's locked shared plugin harness, as maintained plugins use | Before upstream proposal | Cacti maintainers | diff --git a/docs/decisions/0004-read-only-fabric-access.md b/docs/decisions/0004-read-only-fabric-access.md index c49bd25..251e981 100644 --- a/docs/decisions/0004-read-only-fabric-access.md +++ b/docs/decisions/0004-read-only-fabric-access.md @@ -15,7 +15,7 @@ Status: Accepted (2026-11-14) ## Consequences -- Narrow basic counters can reach their cap and stay there. The plugin prefers 64-bit counters where supported and shows capped counters as unknown (see the saturated-counter decision). +- Narrow basic counters can reach their cap and stay there. The plugin prefers 64-bit counters where supported and shows capped counters as unknown ([ADR 0012](0012-saturated-basic-counters-read-as-unknown.md)). - A reset by another tool shows as a gap. - The plugin cannot repair a fabric; it only reports. diff --git a/docs/decisions/0010-one-device-per-node.md b/docs/decisions/0010-one-device-per-node.md new file mode 100644 index 0000000..acbb596 --- /dev/null +++ b/docs/decisions/0010-one-device-per-node.md @@ -0,0 +1,31 @@ +# 0010. Map each fabric node to one Cacti device, created only on confirmation + +Status: Accepted (2026-11-15); decides issue #9. The Cacti maintainers may still revisit it before an upstream proposal + +## Context + +Issue #9 asked how fabric nodes map to Cacti devices. Ports have to belong to a Cacti device: data queries, graphs, Thold thresholds, and Maint schedules all hang off a device. The plan left the granularity open: one device per node, one per fabric, or switches only. The research ([cacti-core.md](../research/cacti-core.md)) found that Thold checks thresholds only on a device whose status is up, that Maint schedules devices, and that device permissions are the main scoping tool in Cacti. A device per fabric would put every port of a fabric under one permission and one maintenance switch. Switches only would leave adapter ports without alerts. + +Many sites already have a Cacti device for each server and switch, polled over SNMP. Creating a second device for the same machine doubles its device count and splits its graphs. + +## Decision + +- One Cacti device per fabric node, switch or adapter host, keyed by node GUID, with the node's ports as indexes of the "Fabric Port" data query. A node attaches to an existing device when an operator maps it, and otherwise gets a device created for it. +- A fabric node maps to at most one Cacti device, by node GUID. An operator maps it to an existing device on the node's admin page, which lists devices whose host name or description starts with the node description's first word as evidence; the plugin never maps by itself. +- When no device fits, an operator with Cacti's device management permission (`host.php`), on top of Fabric Admin, can create one. A confirmation page lists what is added. The device uses the "Fabric Node" device template, a reserved host name `.fabric.invalid`, availability checks and SNMP off, and the poller that sweeps the fabric. If the creating user cannot see the new device under their device permissions, or the node changed meanwhile, the device is removed again. +- Mapping or creating adds the "Fabric Port" data query to the device and reindexes it. Unmapping or a confirmed re-link reindexes the old device. No graph or data source is created; operators choose ports on Cacti's New Graphs page. +- A device on a poller other than the fabric's is refused. More than one node may map to one device, for a server with two adapters; the index carries the node GUID. +- Deleting a mapped device in Cacti clears the mapping through the `device_remove` hook. Deleting a fabric or uninstalling the plugin keeps the devices. + +## Consequences + +- Thold, Maint, device permissions, and graph trees work per node, as for any device. +- A created device has no availability check, so its status stays as Cacti's poller sets it for such a device. The end-to-end test shows Thold reads it as up. +- A server already in Cacti gets its fabric ports beside its other graphs, with no second device. +- Created devices outlive the plugin's records. That is a divergence from REQ-LIFE-003, which expected the plugin's devices to go with it; removing a device also removes its RRD history, and that is left to the operator. + +## Alternatives rejected + +- **One device per fabric.** One permission and one maintenance switch for every port. +- **Switches only.** No alerts on adapter ports. +- **Automatic creation at discovery.** Adds devices nobody asked for and needs device management rights the poller does not have. diff --git a/docs/decisions/0011-derive-counters-and-gauge-alert-values.md b/docs/decisions/0011-derive-counters-and-gauge-alert-values.md new file mode 100644 index 0000000..6280865 --- /dev/null +++ b/docs/decisions/0011-derive-counters-and-gauge-alert-values.md @@ -0,0 +1,28 @@ +# 0011. Graph counters as DERIVE; alert only on GAUGE values the plugin computes + +Status: Accepted (2026-11-15); the saturation treatment is [ADR 0012](0012-saturated-basic-counters-read-as-unknown.md) + +## Context + +Fabric counters are cumulative. Basic counters are 8 to 32 bits wide and stop at their maximum instead of wrapping; extended counters are 64 bits. Another tool, such as OpenSM's performance manager, may reset them. RRDtool's COUNTER type treats a decrease as a wrap and records a spike; DERIVE with a minimum of 0 records unknown instead. + +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 the whole site. Every value the plugin publishes is `U` at some point: unsupported, saturated, stale, or just after a reset. + +## Decision + +- Counters as received are DERIVE data sources with minimum 0 and a plausibility maximum, for graphs only: Fabric Port Traffic, Errors, and Congestion. Data counters stay in the tools' unit of 4 octets; the graph multiplies by 4. +- Values meant for thresholds are GAUGE data sources: the link state values (`active_lanes`, `speed_rank`, `degraded`, `port_state`, `age`) and five rates in Fabric Port Alert Rates (`symbol_err_rate`, `rcv_err_rate`, `link_downed_rate`, `xmit_discard_rate`, `xmit_wait_rate`). +- The plugin computes each rate from its own two most recent samples of the port. A decrease is a discontinuity: the rate is unknown, the port's discontinuity count and time go up, and the port page shows it. A counter at its maximum, now or in the previous sample, is saturated and its rate unknown. A rate needs a current sample. +- A saturated or unsupported counter publishes `U`, never `0` and never a reset. The plugin prefers the 64-bit form when the port supports it, and keeps one width per data source. + +## Consequences + +- A reset never draws a spike and never fires or clears a threshold by itself. Thold sees `U` on a GAUGE and skips the check. +- The rates are over the plugin's sampling interval, not Cacti's. If the fabric's sweep interval differs from the poller interval, a repeated sample reads as a rate of 0 or the same rate twice; the fabric interval should equal the poller interval. +- 27 data sources per port, against the 25 of the research layout: the alert rates are added, and the port error group holds nine counters (QP1Dropped and the unicast and multicast packet counters are left out). + +## Alternatives rejected + +- **COUNTER type.** Draws a spike on every reset. +- **Thresholds on DERIVE data sources.** Disables Thold site-wide on the first `U`. +- **Resetting saturated counters.** Writes to the fabric ([ADR 0004](0004-read-only-fabric-access.md)). diff --git a/docs/decisions/0012-saturated-basic-counters-read-as-unknown.md b/docs/decisions/0012-saturated-basic-counters-read-as-unknown.md new file mode 100644 index 0000000..f99a5b3 --- /dev/null +++ b/docs/decisions/0012-saturated-basic-counters-read-as-unknown.md @@ -0,0 +1,24 @@ +# 0012. Prefer 64-bit counters; a saturated basic counter reads as unknown + +Status: Accepted (2026-11-15); confirming the behavior needs captures from real hardware + +## Context + +Basic PortCounters fields are narrow: LinkDownedCounter and LinkErrorRecoveryCounter are 8 bits, SymbolErrorCounter and PortRcvErrors are 16 bits, and PortXmitWait is 32 bits. infiniband-diags documents them as capping at their maximum, not wrapping. The plugin never resets counters ([ADR 0004](0004-read-only-fabric-access.md)), so a narrow counter that reaches its cap stops changing, and a graph of it would look healthy. The 64-bit forms exist only on ports that report extended counter support. Issue #8 listed three treatments and named the first as the proposal; [ADR 0004](0004-read-only-fabric-access.md) points to this decision. + +## Decision + +- The plugin reads the 64-bit extended form of a counter whenever the port reports support for it, and keeps one width per data source. +- A basic counter at its maximum is saturated. Its value and any rate computed from it publish `U`, never the capped value and never `0`, and the port page shows the counter as saturated. A counter at its maximum in the previous sample also gives no rate ([ADR 0011](0011-derive-counters-and-gauge-alert-values.md)). +- The plugin never resets or clears a counter to recover from saturation, through any tool, option, or setting. + +## Consequences + +- On ports without extended counters, a saturated error counter leaves a gap in its graph and in its alert rate until something else resets it; the port page says why. +- A reset by another tool shows as a discontinuity, and the counter is read again from there. +- The behavior is built and tested against generated fixtures and the ibsim simulator. Whether real HCAs and switches cap exactly at the documented widths, and which report extended support, needs captures from real hardware ([research](../research/counters.md)); until then this decision rests on the tools' documentation. + +## Alternatives rejected + +- **Opt-in reset of basic counters per fabric.** Keeps graphs alive on old hardware but clears counters that other tools and operators read, and breaks the read-only guarantee. +- **Basic error counters as events only.** Alerting on change without graphs loses the history operators use to judge a link, and a saturated counter still never changes. diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 99a8bcd..e51de4b 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -13,5 +13,8 @@ Each record captures one architecture decision: its context, the decision, its c | [0007](0007-php-82-floor-with-80-parse-guard.md) | Require PHP 8.2, keep entry points parseable on PHP 8.0 | Accepted | | [0008](0008-lazy-per-device-sweep-with-a-claim.md) | Sweep lazily per device, under a claim, from the script server | Accepted, timing pending live measurements | | [0009](0009-command-allowlist-and-privileges.md) | Run three allowlisted tools with fixed arguments; no smpquery, no sudo, no ibdiagnet | Accepted | +| [0010](0010-one-device-per-node.md) | Map each fabric node to one Cacti device, created only on confirmation | Accepted | +| [0011](0011-derive-counters-and-gauge-alert-values.md) | Graph counters as DERIVE; alert only on GAUGE values the plugin computes | Accepted | +| [0012](0012-saturated-basic-counters-read-as-unknown.md) | Prefer 64-bit counters; a saturated basic counter reads as unknown | Accepted, pending hardware evidence | Open decisions are tracked as issues labelled `type: decision`. diff --git a/docs/research/scale.md b/docs/research/scale.md new file mode 100644 index 0000000..335af2e --- /dev/null +++ b/docs/research/scale.md @@ -0,0 +1,55 @@ +# Scale at the documented fabric sizes + +Research for [#49](https://github.com/somethingwithproof/plugin_fabric/issues/49), run 2026-11-15. Question: how do the plugin's own steps (topology import, counter sweeps, data query answers, the overview page) and Cacti's objects for its ports grow from about 100 to about 10,000 ports? + +**Result.** The plugin's own work stays small at all three sizes. Importing the topology of a 9,992 port fabric took 2.7 seconds, a counter sweep of one adapter node about 0.09 seconds, and the data query answered in about 1 millisecond. The overview page rendered in 0.04 seconds but was 1.5 MB of HTML at 9,992 ports, which is the figure to watch. The cost that grows fastest is Cacti's, not the plugin's: every data source of a port is one poller item, 27 per port, so all graphs of 10,000 ports would be 270,000 poller items. One cmd.php run over 919 items took 1.7 seconds. Linear extrapolation to 270,000 items gives about 500 seconds for one cmd.php process, more than a 300 second interval; that is arithmetic, not a measurement. These numbers come from fake tools on one development machine, not from a fabric. + +## Machine caveat + +- One development machine: Apple M3 Max, 14 cores, 36 GB, running Docker 29.8.2 with a 14 CPU, 16 GB Linux VM. +- PHP 8.2 CLI in the `cloud-ci:8.2` replay image, Cacti `1.2.x`, and MariaDB in a separate container on the same VM, with warm caches. +- The diagnostic tools are the plugin's fake tools: PHP scripts that print generated output. Tool time is PHP start-up, never a fabric round trip, so the sweep figures measure the plugin's parsing and database work only. Sweep time on a real fabric and the management datagram budget remain live checks ([mad-budget](mad-budget.md)). + +## Method + +[tests/bin/scale.php](../../tests/bin/scale.php) runs inside the replay (`tests/bin/e2e.sh` installs the fake tools in a root-owned directory first). For each size it: + +1. builds a fabric with the [fabric generator](../../tests/Support/FabricGenerator.php) (`forCas(n)`: n adapters behind leaf and spine switches), +2. runs the production sweep for one switch with the topology forced, which runs `ibnetdiscover` and `iblinkinfo`, imports the topology, and sweeps that switch's counters, +3. sweeps the counters of 25 adapters as the poller does, without forcing the topology again, +4. maps the switch to a device and times the data query's `index` answer and every `get` answer for its ports, +5. renders the inventory overview as for an administrator. + +At the first size only it also creates all five graphs for each of the switch's 33 ports through `create_complete_graph_from_template()`, pushes them to the poller cache as `cli/add_graphs.php` does, and runs `poller.php --force` once. The device has availability checks off, as a created device has. + +## Measurements + +| Adapters | Nodes | Ports | Topology and one node (s) | Counter sweep per node (s) | Index answer (ms) | Get answer (ms) | Overview render (s) | Overview size (bytes) | Peak memory (MB) | +|---|---|---|---|---|---|---|---|---|---| +| 40 | 42 | 112 | 0.18 | 0.051 | 1.5 | 0.002 | 0.001 | 13,565 | 14 | +| 470 | 485 | 1,010 | 0.53 | 0.060 | 1.0 | 0.001 | 0.004 | 151,202 | 18 | +| 4,700 | 4,847 | 9,992 | 2.71 | 0.090 | 1.1 | 0.001 | 0.036 | 1,515,555 | 60 | + +Each size ran `ibnetdiscover` and `iblinkinfo` once and `perfquery` two times per swept node (basic and extended); at the first size the poller run swept the switch once more. The index answer covers the switch's 33 ports at every size. + +Cacti objects for one switch's 33 ports, all five graphs each: + +| Graphs | Data sources | Data source items | Poller items | Poller run | +|---|---|---|---|---| +| 165 | 165 | 891 | 891 | 1.72 s, cmd.php, 1 process, 919 items on 5 hosts, 174 RRD files updated | + +That is 5 graphs, 5 data sources, 27 data source items, and 27 poller items per port. The [layout research](rrd-layout.md) left open whether a script data query item returns several outputs in one item; as built, each output is its own poller item, the same as layout B's item count though with layout A's file count. + +## What follows + +- **Per port, Cacti grows faster than the plugin.** All graphs on 10,000 ports would mean 50,000 graphs and 270,000 poller items. Sites at that size should graph selected ports, or poll with Spine and several processes. The data query answers from the cache, so each item costs one script server call of about a millisecond of plugin work plus Cacti's per-item overhead. +- **The overview page needs paging before 10,000 ports.** 1.5 MB of HTML renders quickly on the server but is heavy in a browser. +- **The topology import is linear enough for a 300 second interval** at about 10,000 ports on this machine. A real `ibnetdiscover` on such a fabric takes far longer than the import itself; that is a live check. + +## Live checks + +| Issue | Check | What it settles | +|---|---|---| +| #49 | Repeat the run on a Linux host with Spine, the real tools, and a fabric or the ibsim simulator at about 1,000 ports | Sweep time with real tools and a realistic poller | +| #49 | Poll all graphs of 1,000 ports through a full cycle | Measured poll time instead of the extrapolation above | +| #49 | Time the overview page in a browser at 10,000 ports | Whether paging is needed before release | diff --git a/fabric.php b/fabric.php index 3915f42..41a9ccb 100644 --- a/fabric.php +++ b/fabric.php @@ -39,7 +39,10 @@ new \Somethingwithproof\Fabric\SampleRepository(false), $fabric_clock, \Closure::fromCallable('fabric_device_allowed'), - fabric_is_admin() + fabric_is_admin(), + new \Somethingwithproof\Fabric\PortReadingRepository(false, $fabric_clock), + new \Somethingwithproof\Fabric\CactiObjectRepository(false), + \Closure::fromCallable('fabric_graph_allowed') ); $fabric_node = (int) get_filter_request_var('node'); @@ -48,6 +51,8 @@ if ($fabric_node > 0) { $fabric_page->renderNode($fabric_node); +} elseif (get_nfilter_request_var('view') === 'congestion') { + $fabric_page->renderCongestion(); } else { $fabric_page->renderList(); } diff --git a/fabric_admin.php b/fabric_admin.php index 65ea6ee..6cfa2c8 100644 --- a/fabric_admin.php +++ b/fabric_admin.php @@ -38,7 +38,7 @@ exit; } -fabric_require_post('fabric_admin.php', array('save_fabric', 'delete_fabric_confirm', 'accept_conflict', 'confirm_relink', 'reject_relink', 'save_node')); +fabric_require_post('fabric_admin.php', array('save_fabric', 'delete_fabric_confirm', 'accept_conflict', 'confirm_relink', 'reject_relink', 'save_node', 'create_device_confirm')); $fabric_clock = new \Somethingwithproof\Fabric\SystemClock(); $fabric_fabrics = new \Somethingwithproof\Fabric\FabricRepository(false, $fabric_clock); @@ -52,7 +52,12 @@ $fabric_access = new \Somethingwithproof\Fabric\DeviceAccess(static function (int $host) use ($fabric_hosts): bool { return fabric_device_allowed($host) || $fabric_hosts->gone($host); }); -$fabric_page = new \Somethingwithproof\Fabric\AdminPage($fabric_fabrics, $fabric_nodes, $fabric_relinks, $fabric_pollers, $fabric_hosts, $fabric_access); +$fabric_objects = new \Somethingwithproof\Fabric\CactiObjectRepository(false); +$fabric_devices = new \Somethingwithproof\Fabric\DeviceProvisioner($fabric_nodes, $fabric_fabrics, $fabric_objects, $fabric_access, $config['base_path']); +// Creating a device needs Cacti's own device management permission, not +// only Fabric Admin: the realm grants plugin records, not core objects. +$fabric_create = (bool) api_user_realm_auth('host.php'); +$fabric_page = new \Somethingwithproof\Fabric\AdminPage($fabric_fabrics, $fabric_nodes, $fabric_relinks, $fabric_pollers, $fabric_hosts, $fabric_access, $fabric_devices, $fabric_objects, $fabric_create); $fabric_action = (string) get_nfilter_request_var('action'); /** @@ -173,7 +178,15 @@ function fabric_done(bool $ok, string $done, string $failed): void { fabric_done($fabric_node !== null && $fabric_nodes->acceptConflict($fabric_node), __('The node identity was updated. It is swept again from the next cycle.', 'fabric'), __('The node identity was not changed.', 'fabric')); case 'confirm_relink': - fabric_done($fabric_relinks->confirm((int) get_filter_request_var('id'), $fabric_access), __('The device mapping moved to the new node.', 'fabric'), __('The proposal could not be confirmed. The nodes may have changed since it was made.', 'fabric')); + $fabric_moved = $fabric_relinks->confirm((int) get_filter_request_var('id'), $fabric_access); + + // The device that moved now lists the new node's ports; the old + // node's data sources stay with their history (REQ-MAP-005). + if ($fabric_moved !== null) { + $fabric_devices->reindex($fabric_moved); + } + + fabric_done($fabric_moved !== null, __('The device mapping moved to the new node.', 'fabric'), __('The proposal could not be confirmed. The nodes may have changed since it was made.', 'fabric')); case 'reject_relink': $fabric_relink = $fabric_relinks->find((int) get_filter_request_var('id')); @@ -191,9 +204,41 @@ function fabric_done(bool $ok, string $done, string $failed): void { fabric_denied(); } - $fabric_ok = $fabric_node !== null && ($fabric_host === 0 || $fabric_host === $fabric_node->hostId || $fabric_hosts->exists($fabric_host)); + $fabric_ok = $fabric_node !== null && ($fabric_host === 0 || $fabric_host === $fabric_node->hostId || $fabric_hosts->exists($fabric_host)); + + if ($fabric_ok && $fabric_node !== null && $fabric_host !== 0) { + $fabric_refusal = $fabric_devices->mapRefusal($fabric_node, $fabric_host); + + if ($fabric_refusal !== null) { + fabric_done(false, '', __('The node mapping was not changed. %s', $fabric_refusal, 'fabric')); + } + } + + fabric_done($fabric_ok && $fabric_node !== null && $fabric_devices->map($fabric_node, $fabric_host), __('The node mapping was saved.', 'fabric'), __('The node mapping was not changed.', 'fabric')); + case 'create_device': + $fabric_node = $fabric_nodes->find((int) get_filter_request_var('id')); + + if ($fabric_node === null) { + header('Location: fabric_admin.php'); + exit; + } + + if (!$fabric_create || !$fabric_access->node($fabric_node)) { + fabric_denied(); + } + + top_header(); + $fabric_page->renderCreateConfirm($fabric_node); + bottom_footer(); + exit; + case 'create_device_confirm': + $fabric_node = fabric_posted_node($fabric_nodes); + + if ($fabric_node !== null && (!$fabric_create || !$fabric_access->node($fabric_node))) { + fabric_denied(); + } - fabric_done($fabric_ok && $fabric_node !== null && $fabric_nodes->setHost($fabric_node, $fabric_host), __('The node mapping was saved.', 'fabric'), __('The node mapping was not changed.', 'fabric')); + fabric_done($fabric_node !== null && $fabric_devices->create($fabric_node) > 0, __('The device was created and the node mapped to it. Choose the ports to graph on the New Graphs page.', 'fabric'), __('No device was created. See the Cacti log.', 'fabric')); case 'edit_fabric': $fabric_id = (int) get_filter_request_var('id'); diff --git a/fabric_health.php b/fabric_health.php index 104acc7..dec09ef 100644 --- a/fabric_health.php +++ b/fabric_health.php @@ -31,6 +31,21 @@ exit; } +fabric_require_post('fabric_health.php', array('reinstall_templates')); + +// Reinstalling imports templates into Cacti, so it needs Cacti's own +// template import permission as well as Fabric Admin. +$fabric_import = (bool) api_user_realm_auth('templates_import.php'); +$fabric_templates = fabric_templates(); + +if (get_nfilter_request_var('action') === 'reinstall_templates') { + $fabric_ok = $fabric_import && $fabric_templates->install(); + + raise_message('fabric_result', $fabric_ok ? __('The Fabric templates and data query file were installed.', 'fabric') : __('The Fabric templates were not installed. See the Cacti Objects table and the Cacti log.', 'fabric'), $fabric_ok ? MESSAGE_LEVEL_INFO : MESSAGE_LEVEL_ERROR); + header('Location: fabric_health.php'); + exit; +} + $fabric_clock = new \Somethingwithproof\Fabric\SystemClock(); $fabric_hosts = new \Somethingwithproof\Fabric\HostRepository(false); $fabric_page = new \Somethingwithproof\Fabric\HealthPage( @@ -43,7 +58,9 @@ new \Somethingwithproof\Fabric\DeviceAccess(static function (int $host) use ($fabric_hosts): bool { // As on the admin page: a deleted device protects nothing. return fabric_device_allowed($host) || $fabric_hosts->gone($host); - }) + }), + $fabric_templates, + $fabric_import ); top_header(); diff --git a/lib/AdminPage.php b/lib/AdminPage.php index 13b5471..06aa060 100644 --- a/lib/AdminPage.php +++ b/lib/AdminPage.php @@ -42,6 +42,9 @@ public function __construct( private readonly PollerRepository $pollers, private readonly HostRepository $hosts, private readonly DeviceAccess $access, + private readonly ?DeviceProvisioner $provisioner = null, + private readonly ?CactiObjectRepository $objects = null, + private readonly bool $canCreateDevices = false, ) { } @@ -154,13 +157,55 @@ public function renderNodeEdit(Node $node): void { $options = [0 => __('Unmapped', 'fabric')] + $hosts; $options = $this->keepCurrent($options, $node->hostId > 0 ? $node->hostId : null, __('Deleted device (ID %d)', $node->hostId, 'fabric')); + // Evidence for a mapping (REQ-MAP-003): devices whose host name or + // description starts with the node description's first word. + $evidence = array_filter($this->objects?->suggestions($node->description) ?? [], fn (int $id): bool => $this->access->host($id), ARRAY_FILTER_USE_KEY); + print '
'; html_start_box(html_escape(__('Fabric Node: %s', $node->label(), 'fabric')), '100%', '', '3', 'center', ''); print '' . html_escape(__('GUID', 'fabric')) . '' . html_escape($node->guid->text) . ''; + print '' . html_escape(__('Devices Matching the Node Name', 'fabric')) . '' + . ($evidence === [] ? html_escape(__('None', 'fabric')) : implode(', ', array_map(static fn (int $id, string $name): string => html_escape(__('%s (device %d)', $name, $id, 'fabric')), array_keys($evidence), $evidence))) + . ''; $this->select('host_id', __('Cacti Device', 'fabric'), $options, (string) $node->hostId); + print '' . html_escape(__('Saving maps the node to the device and adds the Fabric Port data query to the device, which lists the node\'s ports. No graph, data source, or device setting is changed. The device must be polled by the poller that sweeps the fabric.', 'fabric')) . ''; print ''; html_end_box(); $this->submit('save_node', $node->id, __('Save', 'fabric')); + + if ($node->hostId === 0 && $this->canCreateDevices && $this->provisioner !== null) { + print ''; + $this->submit('create_device', $node->id, __('Create a Device for This Node', 'fabric')); + } + } + + /** + * The confirmation before a device is created (REQ-MAP-002): what is + * added, and nothing until the operator posts the form. + */ + public function renderCreateConfirm(Node $node): void { + $refusal = $this->provisioner === null ? __('Devices cannot be created here.', 'fabric') : $this->provisioner->createRefusal($node); + + print ''; + html_start_box(html_escape(__('Create a Device for %s', $node->label(), 'fabric')), '100%', '', '3', 'center', ''); + + if ($refusal !== null || $this->provisioner === null) { + print '' . html_escape($refusal ?? '') . ''; + html_end_box(); + print '
'; + + return; + } + + print '' . html_escape(__('Creating the device adds:', 'fabric')) . ''; + + foreach ($this->provisioner->plan($node) as $line) { + print '' . html_escape($line) . ''; + } + + print ''; + html_end_box(); + $this->submit('create_device_confirm', $node->id, __('Create', 'fabric')); } /** diff --git a/lib/CactiObjectRepository.php b/lib/CactiObjectRepository.php new file mode 100644 index 0000000..02fe74d --- /dev/null +++ b/lib/CactiObjectRepository.php @@ -0,0 +1,150 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_fabric, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_fabric + * + * 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\Fabric; + +/** + * Read-only lookups in Cacti's own tables: the shipped 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_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}$/D', $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 deviceTemplateId(): int { + return $this->idByHash('host_template', TemplateInstaller::hash('host_template', TemplateInstaller::DEVICE_TEMPLATE)); + } + + public function queryId(): int { + return $this->idByHash('snmp_query', TemplateInstaller::hash('data_query', TemplateInstaller::QUERY)); + } + + public function graphTemplateId(string $name): int { + return $this->idByHash('graph_templates', TemplateInstaller::hash('graph_template', $name)); + } + + 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, hostname: string, poller_id: int, host_template_id: int}|null + */ + public function device(int $hostId): ?array { + $row = $hostId > 0 ? db_fetch_row_prepared("SELECT id, description, hostname, poller_id, host_template_id 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'), + 'hostname' => Row::string($row, 'hostname'), + 'poller_id' => Row::int($row, 'poller_id', 1, 1), + 'host_template_id' => Row::int($row, 'host_template_id', 0, 0), + ]; + } + + public function hasQuery(int $hostId): bool { + $queryId = $this->queryId(); + + return $queryId > 0 && (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM host_snmp_query WHERE host_id = ? AND snmp_query_id = ?', [$hostId, $queryId], '', true, $this->connection) > 0; + } + + /** + * Devices whose host name or description begins with the first word of + * a node description, the evidence offered when mapping a node + * (REQ-MAP-003). A word shorter than three characters suggests nothing. + * + * @return array host id => description + */ + public function suggestions(string $nodeDescription): array { + $word = strtolower((string) preg_replace('/[^A-Za-z0-9._-].*$/s', '', trim($nodeDescription))); + + if (strlen($word) < 3) { + return []; + } + + $like = str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $word); + $rows = Row::rows(db_fetch_assoc_prepared( + "SELECT id, description FROM host WHERE deleted = '' AND (LOWER(hostname) = ? OR LOWER(hostname) LIKE ? OR LOWER(description) = ? OR LOWER(description) LIKE ?) ORDER BY description, id LIMIT 10", + [$word, $like . '.%', $word, $like . ' %'], + true, + $this->connection, + )) ?? []; + + $out = []; + + foreach ($rows as $row) { + $out[Row::int($row, 'id', 0, 1)] = Row::string($row, 'description'); + } + + unset($out[0]); + + return $out; + } + + /** + * Graphs of a device made from one of the plugin's graph templates, + * by data query index. + * + * @return array> index => graphs + */ + public function portGraphs(int $hostId): array { + $ids = []; + + foreach (array_keys(PortValues::templates()) as $name) { + $id = $this->graphTemplateId($name); + + if ($id > 0) { + $ids[$id] = $name; + } + } + + if ($ids === []) { + return []; + } + + $placeholders = implode(', ', array_fill(0, count($ids), '?')); + $rows = Row::rows(db_fetch_assoc_prepared("SELECT id, graph_template_id, snmp_index FROM graph_local WHERE host_id = ? AND graph_template_id IN ($placeholders) ORDER BY id", [$hostId, ...array_keys($ids)], true, $this->connection)) ?? []; + $out = []; + + foreach ($rows as $row) { + $out[Row::string($row, 'snmp_index')][] = ['id' => Row::int($row, 'id', 0, 1), 'template' => $ids[Row::int($row, 'graph_template_id')] ?? '']; + } + + return $out; + } +} diff --git a/lib/CounterDelta.php b/lib/CounterDelta.php new file mode 100644 index 0000000..2913a64 --- /dev/null +++ b/lib/CounterDelta.php @@ -0,0 +1,112 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_fabric, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_fabric + * + * 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\Fabric; + +/** + * What changed between two samples of one port's counter group + * (REQ-CTR-005, REQ-DISC-001, ADR 0011). + * + * - A counter lower than in the previous sample is a discontinuity: a + * reset by another tool, a reboot, or a retrained link. Its rate is + * unknown, and the data query publishes it as unknown until the next + * sample (REQ-DISC-002). + * - A counter at its cap, now or before, is saturated: it no longer + * counts, so its rate is unknown, never 0 (REQ-CTR-005). + * - A counter the port does not support has no rate. + * - Anything else has a rate per second over the time between the two + * observations. + */ +final readonly class CounterDelta { + /** + * @param array $rates counter => per second, or null when unknown + * @param list $reset counters that went down + * @param int $since observation time of the previous sample, 0 for none + */ + public function __construct(public array $rates, public array $reset, public int $since) { + } + + /** + * @param array|null $previous the previous sample's counters, null for none + */ + public static function between(?array $previous, int $previousAt, Counters $current, int $now): self { + $usable = $previous !== null && $previousAt > 0 && $previousAt < $now; + $rates = []; + $reset = []; + + foreach ($current->values as $name => $value) { + $before = $usable ? ($previous[$name] ?? null) : null; + + if ($value === null || $before === null || !Decimal::valid($value) || !Decimal::valid($before)) { + $rates[$name] = null; + + continue; + } + + if (Decimal::compare($value, $before) < 0) { + $rates[$name] = null; + $reset[] = $name; + + continue; + } + + $cap = PerfqueryParser::cap(PerfqueryParser::width($current->group, $name)); + + $rates[$name] = $cap === '' || $value === $cap || $before === $cap ? null : Decimal::difference($value, $before) / ($now - $previousAt); + } + + return new self($rates, $reset, $usable ? $previousAt : 0); + } + + public function ratesJson(): string { + return json_encode($this->rates, JSON_THROW_ON_ERROR | JSON_PRESERVE_ZERO_FRACTION); + } + + public function resetJson(): string { + return json_encode($this->reset, JSON_THROW_ON_ERROR); + } + + /** + * Stored rates back from the sample table: each a number or null. + * + * @return array + */ + public static function ratesFromJson(string $json): array { + $data = json_decode($json, true); + $out = []; + + foreach (is_array($data) ? $data : [] as $name => $rate) { + if (is_string($name) && ($rate === null || is_int($rate) || is_float($rate)) && ($rate === null || $rate >= 0)) { + $out[$name] = $rate === null ? null : (float) $rate; + } + } + + return $out; + } + + /** + * @return list + */ + public static function resetFromJson(string $json): array { + $data = json_decode($json, true); + + return is_array($data) ? array_values(array_filter($data, 'is_string')) : []; + } +} diff --git a/lib/CounterSweep.php b/lib/CounterSweep.php index 390227c..7cbe275 100644 --- a/lib/CounterSweep.php +++ b/lib/CounterSweep.php @@ -42,6 +42,7 @@ public function __construct( private readonly ProcessRunner $runner, private readonly Settings $settings, private readonly int $toolOwner = 0, + private readonly ?float $deadline = null, ) { } @@ -127,12 +128,35 @@ private function sweep(Fabric $fabric, Node $node, NodeSweepResult $result, floa return; } - $builder = new CommandBuilder($this->settings, $fabric); - $budget = new SweepBudget($start + $this->settings->nodeBudget, $this->settings->failureBudget); - $samples = new SampleRepository($this->connection); + $builder = new CommandBuilder($this->settings, $fabric); + $budget = new SweepBudget(min($start + $this->settings->nodeBudget, $this->deadline ?? INF), $this->settings->failureBudget); + $samples = new SampleRepository($this->connection); + $previous = $samples->keyed($node->id); + + if ($previous === null) { + $result->error = CommandError::Storage; + $result->skipped = $result->total; + + return; + } + + // Existing attempt timestamps are the resume position. A capped run + // starts with the least recently attempted ports and counter group. + $extended = []; + foreach ($targets as $port => $lid) { + $mask = Row::int($previous[$port . ':basic'] ?? [], 'cap_mask'); + if (($mask & (Counters::CAP_EXT_WIDTH | Counters::CAP_EXT_WIDTH_NOIETF)) !== 0) { + $extended[$port] = $lid; + } + } + $extendedFirst = $extended !== [] && $this->oldest($extended, $previous, CounterGroup::Extended) < $this->oldest($targets, $previous, CounterGroup::Basic); + $extendedResult = null; try { - $basic = $this->group($builder, $fabric, $node, $targets, CounterGroup::Basic, $budget, $samples); + if ($extendedFirst) { + $extendedResult = $this->group($builder, $fabric, $node, $extended, CounterGroup::Extended, $budget, $samples, $previous); + } + $basic = $this->group($builder, $fabric, $node, $targets, CounterGroup::Basic, $budget, $samples, $previous); } catch (\InvalidArgumentException $e) { // Only the settings or the fabric record can make the first // command invalid; nothing was run. @@ -143,8 +167,6 @@ private function sweep(Fabric $fabric, Node $node, NodeSweepResult $result, floa return; } - $extended = []; - foreach ($basic['read'] as $port => $counters) { if ($counters->extendedSupported()) { $extended[$port] = $targets[$port]; @@ -156,25 +178,41 @@ private function sweep(Fabric $fabric, Node $node, NodeSweepResult $result, floa $result->skipped = $result->total - $result->read - $result->failed; $result->error = $basic['error']; - if ($extended !== []) { - $this->group($builder, $fabric, $node, $extended, CounterGroup::Extended, $budget, $samples); + if (!$extendedFirst && $extended !== []) { + $extendedResult = $this->group($builder, $fabric, $node, $extended, CounterGroup::Extended, $budget, $samples, $previous); + } + + if (($extendedResult['error'] ?? null) === CommandError::Storage) { + $result->error = CommandError::Storage; } } + /** + * @param non-empty-array $targets + * @param array> $previous + */ + private function oldest(array $targets, array $previous, CounterGroup $group): int { + return min(array_map(static fn (int $port): int => Row::int($previous[$port . ':' . $group->value] ?? [], 'attempted_at'), array_keys($targets))); + } + /** * Read one counter group for the given ports and record every result. * - * @param array $targets port number => LID + * @param array $targets port number => LID + * @param array> $previous stored rows, "port:group" => row * * @return array{read: array, failed: array, error: ?CommandError} */ - private function group(CommandBuilder $builder, Fabric $fabric, Node $node, array $targets, CounterGroup $group, SweepBudget $budget, SampleRepository $samples): array { - $tools = new ToolRunner($this->runner, $this->settings); + private function group(CommandBuilder $builder, Fabric $fabric, Node $node, array $targets, CounterGroup $group, SweepBudget $budget, SampleRepository $samples, array $previous): array { + $tools = new ToolRunner($this->runner, $this->settings, $this->deadline); $parser = new PerfqueryParser(); $read = []; $failed = []; $last = null; $pending = array_keys($targets); + usort($pending, static fn (int $a, int $b): int => + Row::int($previous[$a . ':' . $group->value] ?? [], 'attempted_at') + <=> Row::int($previous[$b . ':' . $group->value] ?? [], 'attempted_at')); while ($pending !== [] && !$budget->spent()) { $lid = $targets[$pending[0]]; @@ -183,7 +221,8 @@ private function group(CommandBuilder $builder, Fabric $fabric, Node $node, arra if ($lid < 1 || $lid > CommandBuilder::MAX_LID) { // A port without a unicast LID cannot be addressed. foreach ($batch as $port) { - $failed[$port] = CommandError::Config; + $failed[$port] = $samples->recordFailure($node->id, $port, $group, CommandError::Config, $this->clock->now()) + ? CommandError::Config : CommandError::Storage; } $last = CommandError::Config; @@ -216,8 +255,24 @@ private function group(CommandBuilder $builder, Fabric $fabric, Node $node, arra $now = $this->clock->now(); foreach ($got as $port => $counters) { + $delta = $samples->record($node->id, $counters, $fabric->backend, $now, $previous[$port . ':' . $group->value] ?? null); + + // A sample the database did not take was not read: the + // port fails as storage, and so does the node sweep. + if ($delta === null) { + $failed[$port] = CommandError::Storage; + $last = CommandError::Storage; + + continue; + } + $read[$port] = $counters; - $samples->record($node->id, $counters, $fabric->backend, $now); + + // A counter that went down is published as unknown until + // the next sample (REQ-DISC-002). + if ($delta->reset !== []) { + Log::warning(sprintf('Fabric %d: node %s port %d: %s counters went down (%s); their values are unknown until the next sample', $fabric->id, $node->guid->text, $port, $group->value, implode(', ', $delta->reset))); + } } $tried = $batch; @@ -252,6 +307,11 @@ private function group(CommandBuilder $builder, Fabric $fabric, Node $node, arra $last ??= CommandError::Budget; } + // A lost write outranks any later tool error in the node's result. + if (in_array(CommandError::Storage, $failed, true)) { + $last = CommandError::Storage; + } + return ['read' => $read, 'failed' => $failed, 'error' => $last]; } } diff --git a/lib/Decimal.php b/lib/Decimal.php new file mode 100644 index 0000000..5efe052 --- /dev/null +++ b/lib/Decimal.php @@ -0,0 +1,62 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_fabric, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_fabric + * + * 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\Fabric; + +/** + * Arithmetic on the unsigned decimal strings counters are stored as. The + * extended counters are 64 bits wide and exceed PHP's integer range, so + * values are split into a high part and the last nine digits, each of which + * fits an integer. Inputs are canonical: digits only, no leading zero. + */ +final class Decimal { + private const LOW = 9; + + public static function valid(string $value): bool { + return preg_match('/^(0|[1-9][0-9]{0,19})$/D', $value) === 1; + } + + /** + * -1, 0, or 1 as $a is below, equal to, or above $b. + */ + public static function compare(string $a, string $b): int { + return strlen($a) <=> strlen($b) ?: strcmp($a, $b) <=> 0; + } + + /** + * $a minus $b as a float, exact while the difference is below 2^53. + */ + public static function difference(string $a, string $b): float { + [$ah, $al] = self::split($a); + [$bh, $bl] = self::split($b); + + return (float) ($ah - $bh) * 1e9 + (float) ($al - $bl); + } + + /** + * @return array{0: int, 1: int} + */ + private static function split(string $value): array { + $high = strlen($value) > self::LOW ? substr($value, 0, -self::LOW) : '0'; + $low = strlen($value) > self::LOW ? substr($value, -self::LOW) : $value; + + return [(int) $high, (int) $low]; + } +} diff --git a/lib/DeviceProvisioner.php b/lib/DeviceProvisioner.php new file mode 100644 index 0000000..86e413b --- /dev/null +++ b/lib/DeviceProvisioner.php @@ -0,0 +1,250 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_fabric, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_fabric + * + * 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\Fabric; + +/** + * Creates or maps the Cacti device of a fabric node and attaches the + * Fabric Port data query to it (ADR 0010, REQ-MAP-001 to REQ-MAP-004). + * + * Everything goes through Cacti's own functions: api_device_save() for a + * new device, api_device_dq_add() for the data query, and + * run_data_query() for a reindex. The plugin writes only its own mapping. + * An existing device keeps every setting; only the data query is added. + * No graph is created: an operator chooses the ports to graph on Cacti's + * New Graphs page, as for any data query. + * + * A device is polled by the poller that sweeps its fabric, because the + * script server answers from that poller's cache (REQ-ALERT-004). Every + * fabric runs on the main poller in this phase, so a device on another + * poller is refused. + */ +final class DeviceProvisioner { + public function __construct( + private readonly NodeRepository $nodes, + private readonly FabricRepository $fabrics, + private readonly CactiObjectRepository $objects, + private readonly DeviceAccess $access, + private readonly string $cactiPath, + ) { + } + + /** + * Why a device cannot be created for the node now, or null. + */ + public function createRefusal(Node $node): ?string { + if ($this->objects->deviceTemplateId() === 0 || $this->objects->queryId() === 0) { + return __('The Fabric templates are not installed. Reinstall them from the health page.', 'fabric'); + } + + if ($node->hostId !== 0) { + return __('The node is already mapped to a device.', 'fabric'); + } + + $fabric = $this->fabrics->find($node->fabricId); + + if ($fabric === null || !$fabric->onMainPoller()) { + return __('The node\'s fabric is not swept by the main poller, so its device could not be polled.', 'fabric'); + } + + return null; + } + + /** + * Why the node cannot be mapped to the device, or null. + */ + public function mapRefusal(Node $node, int $hostId): ?string { + $device = $this->objects->device($hostId); + $fabric = $this->fabrics->find($node->fabricId); + + if ($device === null) { + return __('The device does not exist.', 'fabric'); + } + + if ($fabric === null || $device['poller_id'] !== $fabric->pollerId) { + return __('The device is polled by another poller than the one that sweeps this fabric, so it could not read the fabric cache.', 'fabric'); + } + + if ($this->objects->queryId() === 0) { + return __('The Fabric templates are not installed. Reinstall them from the health page.', 'fabric'); + } + + return null; + } + + /** + * What creating a device would add, for the confirmation page + * (REQ-MAP-002). + * + * @return list + */ + public function plan(Node $node): array { + $fabric = $this->fabrics->find($node->fabricId); + + return [ + __('A device "%s" from the %s device template, host name %s, polled by poller %d, with availability checks and SNMP off.', $this->description($node), TemplateInstaller::DEVICE_TEMPLATE, $this->hostname($node), $fabric->pollerId ?? Fabric::MAIN_POLLER, 'fabric'), + __('The %s data query on it, listing the node\'s ports. It creates no graph and no data source by itself.', TemplateInstaller::QUERY, 'fabric'), + ]; + } + + /** + * Create a device for an unmapped node, map the node to it, and + * attach the data query. A device the user cannot see afterwards, as + * with device permissions that deny new devices, is removed again. + * + * @return int the new device id, or 0 with the reason logged + */ + public function create(Node $node): int { + $fabric = $this->fabrics->find($node->fabricId); + $templateId = $this->objects->deviceTemplateId(); + + if ($fabric === null || $this->createRefusal($node) !== null) { + return 0; + } + + include_once($this->cactiPath . '/lib/api_device.php'); + + $hostId = (int) api_device_save(0, $templateId, $this->description($node), $this->hostname($node), '', 0, '', '', 161, 500, '', 0, 0, 23, 400, 1, + __('Created by the Fabric plugin for node %s. Its values come from the plugin cache; the host name is a reserved name that is never contacted.', $node->guid->text, 'fabric'), + 'MD5', '', 'DES', '', '', 5, 1, $fabric->pollerId, 0); + + if ($hostId <= 0) { + Log::error(sprintf('Cacti refused the device for node %s', $node->guid->text)); + + return 0; + } + + if (!$this->access->host($hostId)) { + api_device_remove($hostId); + Log::warning(sprintf('The device created for node %s was removed again: the user\'s device permissions do not show it', $node->guid->text)); + + return 0; + } + + if (!$this->nodes->setHost($node, $hostId)) { + api_device_remove($hostId); + Log::error(sprintf('The device created for node %s was removed again: the node changed while it was created', $node->guid->text)); + + return 0; + } + + $this->attach($hostId); + + return $hostId; + } + + /** + * Map a node to an existing device, or with 0 unmap it, and reindex the + * devices involved. The device's own settings are left alone. + */ + public function map(Node $node, int $hostId): bool { + if ($hostId !== 0 && $this->mapRefusal($node, $hostId) !== null) { + return false; + } + + $old = $node->hostId; + + if (!$this->nodes->setHost($node, $hostId)) { + return false; + } + + if ($hostId !== 0) { + $this->attach($hostId); + } + + if ($old !== 0 && $old !== $hostId) { + $this->reindex($old); + } + + return true; + } + + /** + * Add the data query to a device, or reindex it when it has the query. + * Safe to repeat. The query's reindex method is "Index Count Changed", + * which needs arg_num_indexes; the plugin reindexes itself whenever a + * mapping changes, which also covers a replacement of the same size. + */ + public function attach(int $hostId): void { + $queryId = $this->objects->queryId(); + + if ($queryId === 0 || $this->objects->device($hostId) === null) { + return; + } + + include_once($this->cactiPath . '/lib/api_device.php'); + include_once($this->cactiPath . '/lib/data_query.php'); + + if ($this->objects->hasQuery($hostId)) { + // The device template attaches the query with the site's + // default reindex method; set Index Count Changed, which also + // reindexes the device. + api_device_dq_change($hostId, $queryId, DATA_QUERY_AUTOINDEX_INDEX_NUM_CHANGE); + } else { + api_device_dq_add($hostId, $queryId, DATA_QUERY_AUTOINDEX_INDEX_NUM_CHANGE); + } + } + + /** + * Reindex a device that has the data query, as after a node left it. + * Data sources of ports that are gone stay until an operator removes + * them (REQ-IDX-004). + * + * With no node left on the device the query lists no ports, and Cacti + * 1.2.31 treats an empty script query as a failed reindex and keeps the + * old cache. The device's Fabric Port cache is then emptied directly + * through Cacti's own cache writer; graphs, data sources, and RRD files + * stay. + */ + public function reindex(int $hostId): void { + if ($this->objects->device($hostId) === null || !$this->objects->hasQuery($hostId)) { + return; + } + + include_once($this->cactiPath . '/lib/data_query.php'); + $queryId = $this->objects->queryId(); + + if ($this->nodes->forHost($hostId) === []) { + $none = []; + $empty = []; + data_query_update_host_cache_from_buffer($hostId, $queryId, $none, $empty); + + return; + } + + run_data_query($hostId, $queryId); + } + + /** + * The node's label, cleaned like every data query input, since Cacti + * substitutes the device description into titles. + */ + public function description(Node $node): string { + return substr(PortQuery::clean($node->label()), 0, 150); + } + + /** + * A name in the reserved .invalid domain (RFC 6761), so no lookup or + * availability check of the device can reach a real host. + */ + public function hostname(Node $node): string { + return substr($node->guid->text, 2) . '.fabric.invalid'; + } +} diff --git a/lib/HealthPage.php b/lib/HealthPage.php index b262ba3..a01e569 100644 --- a/lib/HealthPage.php +++ b/lib/HealthPage.php @@ -42,9 +42,41 @@ public function __construct( private readonly RelinkRepository $relinks, private readonly Clock $clock, private readonly DeviceAccess $access, + private readonly ?TemplateInstaller $templates = null, + private readonly bool $canImport = false, ) { } + /** + * Whether the shipped Cacti objects are in place (REQ-OBJ-003), and a + * reinstall for users who may import templates. + */ + private function renderObjects(): void { + if ($this->templates === null) { + return; + } + + $problem = $this->templates->queryFileProblem(); + $failure = $this->templates->failure(); + + html_start_box(__('Cacti Objects', 'fabric'), '100%', '', '3', 'center', ''); + print Format::row([__('Templates', 'fabric'), $this->templates->present() ? __('Installed', 'fabric') : __('Missing', 'fabric')]); + print Format::row([__('Data Query File', 'fabric'), $problem ?? __('Installed', 'fabric')]); + + if ($failure !== '') { + print Format::row([__('Last Install', 'fabric'), $failure]); + } + + html_end_box(); + + if ($this->canImport && !$this->templates->isCurrent()) { + print '
' + . '' + . '' + . '
'; + } + } + public function render(): void { $fabrics = $this->fabrics->all(); $nodes = $this->nodes->all(); @@ -64,6 +96,8 @@ public function render(): void { $now = $this->clock->now(); $freshness = new FreshnessEvaluator($this->clock); + $this->renderObjects(); + html_start_box(__('Fabrics', 'fabric'), '100%', '', '3', 'center', ''); print Format::header([__('Fabric', 'fabric'), __('Last Discovery', 'fabric'), __('Last Successful Discovery', 'fabric'), __('Discovery', 'fabric'), __('Nodes / Ports Seen', 'fabric'), __('Last Link Read', 'fabric'), __('Link Read', 'fabric'), __('Unmatched Link Records', 'fabric'), __('Skipped Link Lines', 'fabric'), __('Counter Sweeps', 'fabric')]); diff --git a/lib/InventoryPage.php b/lib/InventoryPage.php index 57f2691..b70d54a 100644 --- a/lib/InventoryPage.php +++ b/lib/InventoryPage.php @@ -30,12 +30,19 @@ * * Every stored string, including fabric-supplied descriptions, is escaped * where it is printed. + * + * Graph links appear only for graphs Cacti's own graph permissions allow + * (REQ-PERM-001); the page has no permission layer of its own for them. */ final class InventoryPage { public const FILE = 'fabric.php'; + /** Rows on the congestion ranking. */ + public const RANKED = 50; + /** - * @param \Closure(int): bool $deviceAllowed host id => whether the user may see it + * @param \Closure(int): bool $deviceAllowed host id => whether the user may see it + * @param (\Closure(int): bool)|null $graphAllowed local graph id => whether the user may see it */ public function __construct( private readonly FabricRepository $fabrics, @@ -44,6 +51,9 @@ public function __construct( private readonly Clock $clock, private readonly \Closure $deviceAllowed, private readonly bool $admin, + private readonly ?PortReadingRepository $readings = null, + private readonly ?CactiObjectRepository $objects = null, + private readonly ?\Closure $graphAllowed = null, ) { } @@ -93,7 +103,66 @@ public function renderList(): void { html_start_box(__('Fabrics', 'fabric'), '100%', '', '3', 'center', ''); print '' . html_escape(__('No fabrics are defined yet.', 'fabric')) . ''; html_end_box(); + } else { + print '

' . html_escape(__('Ports with the highest transmit wait', 'fabric')) . '

'; + } + } + + /** + * The ports with the highest transmit-wait rate over their last two + * samples, among nodes the user may see (REQ-CONG-003). A rate needs a + * current sample; ports without one are left out. + */ + public function renderCongestion(): void { + $nodes = $this->nodes->all(); + $readings = $nodes === null || $this->readings === null ? null : $this->readings->forNodes(array_values(array_filter($nodes, fn (Node $n): bool => $this->visible($n)))); + + html_start_box(__('Ports with the Highest Transmit Wait', 'fabric'), '100%', '', '3', 'center', ''); + + if ($readings === null) { + print '' . html_escape(__('The fabric inventory could not be read. See the Cacti log.', 'fabric')) . ''; + html_end_box(); + + return; + } + + print '' . html_escape(__('Transmit wait counts ticks in which a port had data to send but could not send it, for lack of credits or arbitration. A high value shows congestion toward the remote end; it does not show that the port or its cable is faulty. The tick length is not published for current link speeds, so values are ticks per second, not time.', 'fabric')) . ''; + print Format::header([__('Node', 'fabric'), __('Port', 'fabric'), __('Transmit Wait (ticks per second)', 'fabric'), __('Transmit Discards (per second)', 'fabric'), __('Remote', 'fabric')]); + + $ranked = []; + + foreach ($readings as $reading) { + $rate = $reading->lastRate('PortXmitWait'); + + if ($rate !== null && $reading->port->number > 0) { + $ranked[] = [$rate, $reading]; + } + } + + // Highest first; ties in index order, so the list is stable. + usort($ranked, static fn (array $a, array $b): int => [$b[0], $a[1]->ref()->key()] <=> [$a[0], $b[1]->ref()->key()]); + + if ($ranked === []) { + print '' . html_escape(__('No port has a current transmit wait rate.', 'fabric')) . ''; } + + foreach (array_slice($ranked, 0, self::RANKED) as [$rate, $reading]) { + $discards = $reading->lastRate('PortXmitDiscards'); + + print Format::row([ + $reading->node->label(), + (string) $reading->port->number, + self::rate($rate), + $discards === null ? __('Unknown', 'fabric') : self::rate($discards), + $reading->port->remote?->key() ?? '-', + ]); + } + + html_end_box(); + } + + private static function rate(float $value): string { + return number_format($value, $value >= 100 ? 0 : 2); } public function renderNode(int $id): void { @@ -118,23 +187,32 @@ public function renderNode(int $id): void { } $observed = []; + $validity = []; foreach ($samples as $row) { if (Row::string($row, 'counter_group') === CounterGroup::Basic->value) { $observed[Row::int($row, 'port_number')] = Row::int($row, 'observed_at'); } + + $sample = Sample::fromRow($row); + + if ($sample !== null) { + $validity[$sample->port][] = $sample; + } } + $graphs = $node->hostId > 0 && $this->objects !== null ? $this->objects->portGraphs($node->hostId) : []; + $now = $this->clock->now(); $evaluator = new LinkStateEvaluator(); $freshness = new FreshnessEvaluator($this->clock); $interval = $fabric->interval ?? Fabric::DEFAULT_INTERVAL; html_start_box(html_escape(__('Fabric Node: %s', $node->label(), 'fabric')), '100%', '', '3', 'center', ''); - print Format::header([__('Port', 'fabric'), __('Link', 'fabric'), __('State', 'fabric'), __('Active', 'fabric'), __('Best Both Ends Support', 'fabric'), __('Remote', 'fabric'), __('Counters', 'fabric')]); + print Format::header([__('Port', 'fabric'), __('Link', 'fabric'), __('State', 'fabric'), __('Active', 'fabric'), __('Best Both Ends Support', 'fabric'), __('Remote', 'fabric'), __('Counters', 'fabric'), __('Counter Validity', 'fabric'), __('Graphs', 'fabric')]); if ($ports === []) { - print '' . html_escape(__('No ports recorded yet.', 'fabric')) . ''; + print '' . html_escape(__('No ports recorded yet.', 'fabric')) . ''; } foreach ($ports as $port) { @@ -142,7 +220,7 @@ public function renderNode(int $id): void { $state = $link->logical === null ? '-' : $link->logical->value . '/' . ($link->physical->value ?? '-'); $seen = $observed[$port->number] ?? 0; - print Format::row([ + $cells = Format::row([ (string) $port->number, $port->presence === Presence::Present ? $evaluator->evaluate($link)->label() : __('Missing', 'fabric'), $state, @@ -150,7 +228,10 @@ public function renderNode(int $id): void { self::widthSpeed($link->bestWidth, $link->bestSpeed), $port->remote?->key() ?? '-', $seen > 0 ? $freshness->evaluate($seen, $interval)->value . ', ' . Format::age($seen, $now) : __('Never', 'fabric'), + self::validity($validity[$port->number] ?? [], $now), ]); + + print substr($cells, 0, -5) . '' . $this->graphLinks($graphs[(new PortRef($node->guid, $port->number))->key()] ?? []) . ''; } html_end_box(); @@ -165,6 +246,45 @@ private function device(Node $node): string { return $this->admin ? '' . $text . '' : $text; } + /** + * Saturated counters and discontinuities of a port's samples + * (REQ-CTR-005, REQ-DISC-003). + * + * @param list $samples + */ + private static function validity(array $samples, int $now): string { + $parts = []; + + foreach ($samples as $sample) { + $saturated = $sample->saturatedCounters(); + + if ($saturated !== []) { + $parts[] = __('%s counters saturated, published as unknown: %s', $sample->group->value, implode(', ', $saturated), 'fabric'); + } + + if ($sample->discontinuities > 0) { + $parts[] = __('%s counters: %d discontinuities, the last %s', $sample->group->value, $sample->discontinuities, Format::age($sample->discontinuityAt, $now), 'fabric'); + } + } + + return $parts === [] ? __('Valid', 'fabric') : implode('; ', $parts); + } + + /** + * @param list $graphs + */ + private function graphLinks(array $graphs): string { + $links = []; + + foreach ($graphs as $graph) { + if ($this->graphAllowed !== null && ($this->graphAllowed)($graph['id'])) { + $links[] = '' . html_escape(str_replace('Fabric Port ', '', $graph['template'])) . ''; + } + } + + return $links === [] ? '-' : implode(', ', $links); + } + private static function widthSpeed(?LinkWidth $width, ?LinkSpeed $speed): string { return $width === null && $speed === null ? '-' : ($width?->label() ?? '?') . ' ' . ($speed?->label() ?? '?'); } diff --git a/lib/LinkSpeed.php b/lib/LinkSpeed.php index bd66493..b4e73bb 100644 --- a/lib/LinkSpeed.php +++ b/lib/LinkSpeed.php @@ -73,24 +73,6 @@ public function rank(): int { }; } - /** - * Data rate of one lane in Gbit/s as signalled, for the RRD maximum the - * milestone 3 templates derive from the best width and speed. - */ - public function laneGbps(): float { - return match ($this) { - self::Sdr => 2.5, - self::Ddr => 5.0, - self::Qdr => 10.0, - self::Fdr10 => 10.3125, - self::Fdr => 14.0625, - self::Edr => 25.78125, - self::Hdr => 53.125, - self::Ndr => 106.25, - self::Xdr => 212.5, - }; - } - public function label(): string { return strtoupper($this->value); } diff --git a/lib/NodeRepository.php b/lib/NodeRepository.php index ec5a446..78e4625 100644 --- a/lib/NodeRepository.php +++ b/lib/NodeRepository.php @@ -43,7 +43,7 @@ public function forFabric(int $fabricId): ?array { } /** - * Nodes mapped to a Cacti device, for the script server path in M3. + * Nodes mapped to a Cacti device, for the data query. * * @return list|null */ @@ -108,6 +108,24 @@ public function setHost(Node $node, int $hostId): bool { return $this->guarded($node, 'host_id = ?', [max(0, $hostId)]); } + /** + * Unmap every node of the given devices, which Cacti is deleting. Not + * guarded by revision: the device is gone whatever a page showed. + * + * @param list $hostIds + */ + public function unmapHosts(array $hostIds): bool { + $hostIds = array_values(array_filter($hostIds, static fn (int $id): bool => $id > 0)); + + if ($hostIds === []) { + return true; + } + + $placeholders = implode(', ', array_fill(0, count($hostIds), '?')); + + return db_execute_prepared("UPDATE plugin_fabric_node SET host_id = 0, revision = revision + 1 WHERE host_id IN ($placeholders)", $hostIds, true, $this->connection) !== false; + } + /** * @param list $values */ diff --git a/lib/PerfqueryParser.php b/lib/PerfqueryParser.php index d4c8e23..008343e 100644 --- a/lib/PerfqueryParser.php +++ b/lib/PerfqueryParser.php @@ -97,6 +97,24 @@ final class PerfqueryParser { private const MAX = [4 => '15', 8 => '255', 16 => '65535', 32 => '4294967295', 64 => '18446744073709551615']; + /** + * The width in bits of a counter in a group, or 0 for a selector or a + * name the group does not have. + */ + public static function width(CounterGroup $group, string $name): int { + $layout = $group === CounterGroup::Basic ? self::BASIC : self::EXTENDED + self::EXTENDED_CAST + self::EXTENDED_ERRORS; + + return $name === 'PortSelect' ? 0 : $layout[$name] ?? 0; + } + + /** + * The largest value a counter of the width holds, where a basic counter + * stops (caps) instead of wrapping, as a decimal string; '' for 0. + */ + public static function cap(int $width): string { + return self::MAX[$width] ?? ''; + } + /** * @return list in print order */ diff --git a/lib/PortQuery.php b/lib/PortQuery.php new file mode 100644 index 0000000..653cdcf --- /dev/null +++ b/lib/PortQuery.php @@ -0,0 +1,178 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_fabric, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_fabric + * + * 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\Fabric; + +/** + * Answers the Fabric Port data query (resource/script_server/fabric_ports.xml) + * for one Cacti device, from the inventory and sample cache + * (REQ-IDX-001 to REQ-IDX-005). + * + * - index and num_indexes list ":" for the ports + * of every node mapped to the device, ordered by GUID and then port + * number, so an index never depends on a position (ADR 0003). + * - query prints "!" lines for one field; the delimiter is + * "!" because an index contains a colon. + * - get prints one value, or U. + * + * Only get, which the poller sends through the script server, starts a + * sweep: once per device and process, before the first answer, through the + * closure the caller passes (ADR 0008). index and query, which Cacti runs + * when a device is reindexed, never contact the fabric. + * + * A device's ports are read once and kept for CACHE_SECONDS, so a poll + * cycle's calls for one device cost one read of the cache tables. + */ +final class PortQuery { + public const DELIMITER = '!'; + public const INDEX_FIELD = 'fabricPort'; + public const INPUT_FIELDS = ['fabricPort', 'fabricGuid', 'fabricPortNum', 'fabricNode', 'fabricRemote']; + + private const CACHE_SECONDS = 30; + + /** @var array}> host id => [read at, index => port] */ + private array $cache = []; + + /** @var array */ + private array $swept = []; + + /** + * @param (\Closure(int): void)|null $sweep starts a due sweep for a device + */ + public function __construct( + private readonly \PDO|false $connection, + private readonly Clock $clock, + private readonly bool $indexDownPorts, + private readonly ?\Closure $sweep = null, + ) { + } + + public function answer(int $hostId, string $cmd, string $field = '', string $index = ''): string { + if ($hostId < 1) { + return $cmd === 'get' ? 'U' : ''; + } + + if ($cmd === 'get') { + return $this->get($hostId, $field, $index); + } + + $ports = $this->ports($hostId) ?? []; + + return match ($cmd) { + 'index' => implode('', array_map(static fn (string $i): string => $i . "\n", array_keys($ports))), + 'num_indexes' => (string) count($ports), + 'query' => $this->query($ports, $field), + default => '', + }; + } + + /** + * The device's indexed ports in index order, or null when the cache + * could not be read. + * + * @return array|null + */ + public function ports(int $hostId): ?array { + $now = $this->clock->now(); + + if (isset($this->cache[$hostId]) && $now - $this->cache[$hostId][0] < self::CACHE_SECONDS) { + return $this->cache[$hostId][1]; + } + + $readings = (new PortReadingRepository($this->connection, $this->clock))->forHost($hostId); + + if ($readings === null) { + unset($this->cache[$hostId]); + + return null; + } + + $out = []; + + foreach ($readings as $reading) { + if ($reading->indexed($this->indexDownPorts)) { + $out[$reading->ref()->key()] = $reading; + } + } + + $this->cache[$hostId] = [$now, $out]; + + return $out; + } + + /** + * Text of an input field: what Cacti stores in its query cache and may + * put in titles. Fabric-supplied text loses control characters and + * vertical bars, so it can neither break a line nor name a Cacti + * substitution variable such as a device's SNMP community. + */ + public static function input(PortReading $reading, string $field): ?string { + return match ($field) { + 'fabricPort' => $reading->ref()->key(), + 'fabricGuid' => $reading->node->guid->text, + 'fabricPortNum' => (string) $reading->port->number, + 'fabricNode' => self::clean($reading->node->label()), + 'fabricRemote' => $reading->port->remote?->key() ?? '', + default => null, + }; + } + + public static function clean(string $text): string { + return substr(trim((string) preg_replace('/[^\x20-\x7b\x7d\x7e]+/', ' ', $text)), 0, 96); + } + + private function get(int $hostId, string $field, string $index): string { + if ($this->sweep !== null && !isset($this->swept[$hostId])) { + $this->swept[$hostId] = true; + ($this->sweep)($hostId); + unset($this->cache[$hostId]); + } + + $reading = PortRef::fromKey($index) === null ? null : ($this->ports($hostId)[$index] ?? null); + + if ($reading === null) { + return 'U'; + } + + $value = in_array($field, self::INPUT_FIELDS, true) ? self::input($reading, $field) : $reading->value($field); + + return $value === null || $value === '' ? 'U' : $value; + } + + /** + * @param array $ports + */ + private function query(array $ports, string $field): string { + $known = in_array($field, self::INPUT_FIELDS, true) || in_array($field, PortValues::names(), true); + + if (!$known) { + return ''; + } + + $out = ''; + + foreach ($ports as $index => $reading) { + $value = in_array($field, self::INPUT_FIELDS, true) ? self::input($reading, $field) : $reading->value($field); + $out .= $index . self::DELIMITER . ($value ?? 'U') . "\n"; + } + + return $out; + } +} diff --git a/lib/PortReading.php b/lib/PortReading.php new file mode 100644 index 0000000..274bbca --- /dev/null +++ b/lib/PortReading.php @@ -0,0 +1,166 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_fabric, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_fabric + * + * 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\Fabric; + +/** + * The values one port publishes through the Fabric Port data query, from + * the cache only (REQ-IDX-002, REQ-ALERT-001 to REQ-ALERT-003). + * + * Every value that cannot be stated is null, which the query prints as U, + * never 0 (REQ-CTR-006, REQ-ALERT-002): + * + * - A counter or rate needs a current sample (observed within one and a + * half intervals): a repeated old value would read as an idle port. It is + * unknown when the port does not support the counter, when the counter + * holds its cap, and in the sample at which it went down. + * - Each counter comes from one group, chosen by what the port supports, + * not by which read succeeded last, so a failed read never switches a + * data source between widths (REQ-CTR-001): the extended group when the + * port's extended sample has the counter, or, for the data and packet + * counters, when the port says it supports extended counters at all. + * - The state values need a link state that is not stale; degraded is + * unknown for a link below best with no enabled values to explain it. + * - age is the seconds since the port's last basic sample and is numeric + * whenever the port was ever sampled. + */ +final readonly class PortReading { + private const WIDE = ['PortXmitData', 'PortRcvData', 'PortXmitPkts', 'PortRcvPkts']; + + public function __construct( + public Node $node, + public Port $port, + public int $interval, + public ?Sample $basic, + public ?Sample $extended, + private Clock $clock, + ) { + } + + public function ref(): PortRef { + return new PortRef($this->node->guid, $this->port->number); + } + + /** + * Listed as a data query index: every port but port 0, which is a + * switch's management port; a port that is down with no remote end + * only when the setting asks for it (REQ-IDX-003). + */ + public function indexed(bool $downPorts): bool { + if ($this->port->number < 1) { + return false; + } + + $link = $this->port->link; + $down = $this->port->presence !== Presence::Present || $link->logical === null || $link->logical === LogicalState::Down; + + return $downPorts || $this->port->remote !== null || !$down; + } + + public function value(string $name): ?string { + if (PortValues::isCounter($name)) { + return $this->counter(PortValues::COUNTERS[$name]); + } + + if (isset(PortValues::RATE_OF[$name])) { + return $this->rate(PortValues::RATE_OF[$name]); + } + + return match ($name) { + 'active_lanes' => $this->state(fn (LinkState $l): ?int => $l->activeWidth?->lanes()), + 'speed_rank' => $this->state(fn (LinkState $l): ?int => $l->activeSpeed?->rank()), + 'degraded' => $this->state(fn (LinkState $l): ?int => (new LinkStateEvaluator())->evaluate($l)->degradedValue()), + 'port_state' => $this->state(fn (LinkState $l): ?int => $l->logical?->number()), + 'age' => $this->age(), + default => null, + }; + } + + /** + * The sample a counter is read from, or null when the port has none. + */ + public function source(string $counter): ?Sample { + if ($this->extended !== null && $this->extended->has($counter)) { + return $this->extended; + } + + if (in_array($counter, self::WIDE, true) && $this->basic !== null && $this->basic->extendedSupported()) { + return $this->extended; + } + + return $this->basic; + } + + /** + * The counter's per-second rate as last computed, or null; for pages. + */ + public function lastRate(string $counter): ?float { + $sample = $this->source($counter); + + return $sample === null || !$this->current($sample) ? null : $sample->rates[$counter] ?? null; + } + + private function counter(string $counter): ?string { + $sample = $this->source($counter); + + if ($sample === null || !$this->current($sample) || in_array($counter, $sample->reset, true) || $sample->saturated($counter)) { + return null; + } + + return $sample->counters[$counter] ?? null; + } + + private function rate(string $counter): ?string { + $rate = $this->lastRate($counter); + + return $rate === null ? null : self::number($rate); + } + + /** + * @param \Closure(LinkState): ?int $read + */ + private function state(\Closure $read): ?string { + $freshness = (new FreshnessEvaluator($this->clock))->evaluate($this->port->linkObservedAt, $this->interval); + + if (!$freshness->usable()) { + return null; + } + + $value = $read($this->port->link); + + return $value === null ? null : (string) $value; + } + + private function age(): ?string { + $at = $this->basic->observedAt ?? 0; + + return $at > 0 ? (string) max(0, $this->clock->now() - $at) : null; + } + + private function current(Sample $sample): bool { + return (new FreshnessEvaluator($this->clock))->evaluate($sample->observedAt, $this->interval) === Freshness::Current; + } + + private static function number(float $value): string { + $text = rtrim(rtrim(sprintf('%.6F', $value), '0'), '.'); + + return $text === '' || $text === '-0' ? '0' : $text; + } +} diff --git a/lib/PortReadingRepository.php b/lib/PortReadingRepository.php new file mode 100644 index 0000000..0e4c6e5 --- /dev/null +++ b/lib/PortReadingRepository.php @@ -0,0 +1,87 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_fabric, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_fabric + * + * 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\Fabric; + +/** + * Builds PortReading objects from the stored inventory and samples. Reads + * only plugin tables; returns null on a database error, never a partial + * list. + */ +final class PortReadingRepository { + public function __construct(private readonly \PDO|false $connection, private readonly Clock $clock) { + } + + /** + * Every port of the nodes mapped to a device, ordered by node GUID and + * port number. + * + * @return list|null + */ + public function forHost(int $hostId): ?array { + $nodes = (new NodeRepository($this->connection))->forHost($hostId); + + return $nodes === null ? null : $this->forNodes($nodes); + } + + /** + * @param list $nodes + * + * @return list|null + */ + public function forNodes(array $nodes): ?array { + $repository = new NodeRepository($this->connection); + $samples = new SampleRepository($this->connection); + $fabrics = new FabricRepository($this->connection, $this->clock); + $intervals = []; + $out = []; + + usort($nodes, static fn (Node $a, Node $b): int => [$a->guid->text, $a->fabricId] <=> [$b->guid->text, $b->fabricId]); + + foreach ($nodes as $node) { + // Freshness depends on the fabric's own interval; without it no + // sample can be called current, so nothing is answered. + if (!isset($intervals[$node->fabricId])) { + $fabric = $fabrics->find($node->fabricId); + + if ($fabric === null) { + return null; + } + + $intervals[$node->fabricId] = $fabric->interval; + } + + $ports = $repository->ports($node->id); + $rows = $samples->keyed($node->id); + + if ($ports === null || $rows === null) { + return null; + } + + foreach ($ports as $number => $port) { + $basic = isset($rows[$number . ':' . CounterGroup::Basic->value]) ? Sample::fromRow($rows[$number . ':' . CounterGroup::Basic->value]) : null; + $extended = isset($rows[$number . ':' . CounterGroup::Extended->value]) ? Sample::fromRow($rows[$number . ':' . CounterGroup::Extended->value]) : null; + $out[] = new PortReading($node, $port, $intervals[$node->fabricId], $basic, $extended, $this->clock); + } + } + + return $out; + } +} diff --git a/lib/PortRef.php b/lib/PortRef.php index 694b288..bf5c54b 100644 --- a/lib/PortRef.php +++ b/lib/PortRef.php @@ -23,8 +23,8 @@ * A port's identity: its node's GUID and its port number (REQ-CODE-011, * ADR 0003). Parsers work with tool text; everything after them uses this. * - * The key form ":" is the planned data query index. It contains - * a colon, so the milestone 3 query XML must use another output delimiter + * The key form ":" is the Fabric Port data query index. It + * contains a colon, so the query XML uses "!" as its output delimiter * (docs/research/cacti-core.md); nothing here or in Cacti's RRD file names * depends on the colon. */ diff --git a/lib/PortValues.php b/lib/PortValues.php new file mode 100644 index 0000000..b52d580 --- /dev/null +++ b/lib/PortValues.php @@ -0,0 +1,109 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_fabric, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_fabric + * + * 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\Fabric; + +/** + * The values the Fabric Port data query returns per port, and the data + * template each belongs to (ADR 0011). + * + * Every value is drawn by the graph template of the same name as its data + * template, because Cacti puts in an RRD file only what a graph draws. + * Names are at most 19 characters, Cacti's limit for a data source name. + * + * - Counter values are the cumulative counters as received, stored as + * DERIVE with minimum 0, for graphs only: RRDtool turns them into rates. + * - Rate values are rates the plugin computed from two consecutive samples + * of one counter, GAUGE, so Thold can threshold them: Thold 1.8.2 fails + * with a type error on an unknown COUNTER or DERIVE reading and then + * disables itself. + * - State values are the state data source of the plan, GAUGE. + */ +final class PortValues { + public const TRAFFIC = 'Fabric Port Traffic'; + public const ERRORS = 'Fabric Port Errors'; + public const CONGESTION = 'Fabric Port Congestion'; + public const STATE = 'Fabric Port State'; + public const RATES = 'Fabric Port Alert Rates'; + + /** Data source name => perfquery counter, for the counter values. */ + public const COUNTERS = [ + 'xmit_data' => 'PortXmitData', + 'rcv_data' => 'PortRcvData', + 'xmit_pkts' => 'PortXmitPkts', + 'rcv_pkts' => 'PortRcvPkts', + 'symbol_err' => 'SymbolErrorCounter', + 'link_err_recov' => 'LinkErrorRecoveryCounter', + 'link_downed' => 'LinkDownedCounter', + 'rcv_err' => 'PortRcvErrors', + 'rcv_remote_phys' => 'PortRcvRemotePhysicalErrors', + 'rcv_switch_relay' => 'PortRcvSwitchRelayErrors', + 'local_link_integ' => 'LocalLinkIntegrityErrors', + 'buffer_overrun' => 'ExcessiveBufferOverrunErrors', + 'vl15_dropped' => 'VL15Dropped', + 'xmit_wait' => 'PortXmitWait', + 'xmit_discards' => 'PortXmitDiscards', + 'xmit_constraint' => 'PortXmitConstraintErrors', + 'rcv_constraint' => 'PortRcvConstraintErrors', + ]; + + /** Data source name => perfquery counter whose rate it is. */ + public const RATE_OF = [ + 'symbol_err_rate' => 'SymbolErrorCounter', + 'rcv_err_rate' => 'PortRcvErrors', + 'link_downed_rate' => 'LinkDownedCounter', + 'xmit_discard_rate' => 'PortXmitDiscards', + 'xmit_wait_rate' => 'PortXmitWait', + ]; + + /** The state values, in the plan's order. */ + public const STATE_VALUES = ['active_lanes', 'speed_rank', 'degraded', 'port_state', 'age']; + + /** Data counters count octets divided by four (REQ-CTR-004). */ + public const WORDS = ['PortXmitData', 'PortRcvData']; + + /** + * Data template name => its data source names. + * + * @return array> + */ + public static function templates(): array { + return [ + self::TRAFFIC => ['xmit_data', 'rcv_data', 'xmit_pkts', 'rcv_pkts'], + self::ERRORS => ['symbol_err', 'link_err_recov', 'link_downed', 'rcv_err', 'rcv_remote_phys', 'rcv_switch_relay', 'local_link_integ', 'buffer_overrun', 'vl15_dropped'], + self::CONGESTION => ['xmit_wait', 'xmit_discards', 'xmit_constraint', 'rcv_constraint'], + self::STATE => self::STATE_VALUES, + self::RATES => array_keys(self::RATE_OF), + ]; + } + + /** + * Every output field of the data query. + * + * @return list + */ + public static function names(): array { + return array_merge(...array_values(self::templates())); + } + + public static function isCounter(string $name): bool { + return isset(self::COUNTERS[$name]); + } +} diff --git a/lib/RelinkRepository.php b/lib/RelinkRepository.php index 4a6e873..d8b2cd2 100644 --- a/lib/RelinkRepository.php +++ b/lib/RelinkRepository.php @@ -74,12 +74,14 @@ public function find(int $id): ?array { * other open proposal for either node is rejected with it. The device * check uses the same node rows whose revisions the writes require, so * a mapping changed in between makes the confirmation fail. + * + * @return int|null the device that moved (0 when the old node had none), or null when nothing changed */ - public function confirm(int $id, DeviceAccess $access): bool { + public function confirm(int $id, DeviceAccess $access): ?int { $row = db_fetch_row_prepared('SELECT * FROM plugin_fabric_relink WHERE id = ? AND state = ?', [$id, RelinkState::Proposed->value], true, $this->connection); if (!is_array($row)) { - return false; + return null; } $nodes = new NodeRepository($this->connection); @@ -87,7 +89,7 @@ public function confirm(int $id, DeviceAccess $access): bool { $new = $nodes->find(Row::int($row, 'new_node_id')); if ($old === null || $new === null || !$access->node($old) || !$access->node($new) || $old->presence !== Presence::Missing || $new->presence !== Presence::Present || $new->hostId !== 0) { - return false; + return null; } $now = $this->clock->now(); @@ -95,7 +97,7 @@ public function confirm(int $id, DeviceAccess $access): bool { $tx = new TransactionRepository($this->connection); if (!$tx->begin()) { - return false; + return null; } $steps = [ @@ -109,7 +111,8 @@ public function confirm(int $id, DeviceAccess $access): bool { $tx->write($step[0], $step[1], $step[2] ?? null); } - return $tx->commit(); + // The revision guards make $old->hostId the device that moved. + return $tx->commit() ? $old->hostId : null; } public function reject(int $id): bool { diff --git a/lib/Sample.php b/lib/Sample.php new file mode 100644 index 0000000..804acde --- /dev/null +++ b/lib/Sample.php @@ -0,0 +1,101 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_fabric, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_fabric + * + * 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\Fabric; + +/** + * One stored sample row, typed: a port's latest values of one counter + * group with their rates and discontinuities (SampleRepository). + */ +final readonly class Sample { + /** + * @param array $counters + * @param array $rates + * @param list $reset + */ + public function __construct( + public int $port, + public CounterGroup $group, + public int $observedAt, + public int $attemptedAt, + public int $capMask, + public array $counters, + public array $rates, + public array $reset, + public int $discontinuities, + public int $discontinuityAt, + public string $error, + ) { + } + + /** + * @param array $row + */ + public static function fromRow(array $row): ?self { + $group = CounterGroup::tryFrom(Row::string($row, 'counter_group')); + + if ($group === null) { + return null; + } + + return new self( + port: Row::int($row, 'port_number', 0, 0), + group: $group, + observedAt: Row::int($row, 'observed_at', 0, 0), + attemptedAt: Row::int($row, 'attempted_at', 0, 0), + capMask: Row::int($row, 'cap_mask', 0, 0), + // A damaged column reads as no values, so every value is unknown. + counters: Counters::valuesFromJson(Row::string($row, 'counters')) ?? [], + rates: CounterDelta::ratesFromJson(Row::string($row, 'rates')), + reset: CounterDelta::resetFromJson(Row::string($row, 'reset')), + discontinuities: Row::int($row, 'discontinuities', 0, 0), + discontinuityAt: Row::int($row, 'discontinuity_at', 0, 0), + error: Row::string($row, 'error'), + ); + } + + public function has(string $counter): bool { + return $this->observedAt > 0 && array_key_exists($counter, $this->counters); + } + + /** + * Whether the counter holds its cap: a basic counter stops there and + * no longer counts (REQ-CTR-005). + */ + public function saturated(string $counter): bool { + $value = $this->counters[$counter] ?? null; + $cap = PerfqueryParser::cap(PerfqueryParser::width($this->group, $counter)); + + return $value !== null && $cap !== '' && $value === $cap; + } + + /** + * Counters of this sample that hold their cap. + * + * @return list + */ + public function saturatedCounters(): array { + return array_values(array_filter(array_keys($this->counters), fn (string $name): bool => $this->saturated($name))); + } + + public function extendedSupported(): bool { + return ($this->capMask & (Counters::CAP_EXT_WIDTH | Counters::CAP_EXT_WIDTH_NOIETF)) !== 0; + } +} diff --git a/lib/SampleRepository.php b/lib/SampleRepository.php index 3eceeea..8e1fa23 100644 --- a/lib/SampleRepository.php +++ b/lib/SampleRepository.php @@ -29,14 +29,36 @@ final class SampleRepository { public function __construct(private readonly \PDO|false $connection) { } - public function record(int $nodeId, Counters $counters, Backend $backend, int $observedAt): bool { - return db_execute_prepared( - "INSERT INTO plugin_fabric_sample (node_id, port_number, counter_group, observed_at, attempted_at, backend, cap_mask, cap_mask2, counters, error) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, '') - ON DUPLICATE KEY UPDATE observed_at = VALUES(observed_at), attempted_at = VALUES(attempted_at), backend = VALUES(backend), cap_mask = VALUES(cap_mask), cap_mask2 = VALUES(cap_mask2), counters = VALUES(counters), error = ''", - [$nodeId, $counters->port, $counters->group->value, $observedAt, $observedAt, $backend->value, $counters->capMask, $counters->capMask2 ?? 0, $counters->toJson()], + /** + * Replace a port's sample of one group, with the rates and + * discontinuities against the sample it replaces. + * + * @param array|null $previous the stored row of the same port and group, null for none + * + * @return CounterDelta|null what changed, or null when the write failed + */ + public function record(int $nodeId, Counters $counters, Backend $backend, int $observedAt, ?array $previous = null): ?CounterDelta { + $before = $previous === null ? null : Counters::valuesFromJson(Row::string($previous, 'counters')); + $beforeAt = $previous === null ? 0 : Row::int($previous, 'observed_at', 0, 0); + $delta = CounterDelta::between($before, $beforeAt, $counters, $observedAt); + $count = $previous === null ? 0 : Row::int($previous, 'discontinuities', 0, 0); + $lastAt = $previous === null ? 0 : Row::int($previous, 'discontinuity_at', 0, 0); + + if ($delta->reset !== []) { + $count++; + $lastAt = $observedAt; + } + + $ok = db_execute_prepared( + "INSERT INTO plugin_fabric_sample (node_id, port_number, counter_group, observed_at, attempted_at, backend, cap_mask, cap_mask2, counters, error, previous_at, rates, reset, discontinuities, discontinuity_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, '', ?, ?, ?, ?, ?) + ON DUPLICATE KEY UPDATE observed_at = VALUES(observed_at), attempted_at = VALUES(attempted_at), backend = VALUES(backend), cap_mask = VALUES(cap_mask), cap_mask2 = VALUES(cap_mask2), counters = VALUES(counters), error = '', + previous_at = VALUES(previous_at), rates = VALUES(rates), reset = VALUES(reset), discontinuities = VALUES(discontinuities), discontinuity_at = VALUES(discontinuity_at)", + [$nodeId, $counters->port, $counters->group->value, $observedAt, $observedAt, $backend->value, $counters->capMask, $counters->capMask2 ?? 0, $counters->toJson(), $delta->since, $delta->ratesJson(), $delta->resetJson(), $count, $lastAt], true, $this->connection, - ) !== false; + ); + + return $ok === false ? null : $delta; } public function recordFailure(int $nodeId, int $port, CounterGroup $group, CommandError $error, int $attemptedAt): bool { @@ -55,4 +77,25 @@ public function recordFailure(int $nodeId, int $port, CounterGroup $group, Comma public function forNode(int $nodeId): ?array { return Row::rows(db_fetch_assoc_prepared('SELECT * FROM plugin_fabric_sample WHERE node_id = ? ORDER BY port_number, counter_group', [$nodeId], true, $this->connection)); } + + /** + * A node's rows keyed by port and group, as CounterSweep compares them. + * + * @return array>|null "port:group" => row + */ + public function keyed(int $nodeId): ?array { + $rows = $this->forNode($nodeId); + + if ($rows === null) { + return null; + } + + $out = []; + + foreach ($rows as $row) { + $out[Row::int($row, 'port_number') . ':' . Row::string($row, 'counter_group')] = $row; + } + + return $out; + } } diff --git a/lib/Schema.php b/lib/Schema.php index ab230ef..c2554bf 100644 --- a/lib/Schema.php +++ b/lib/Schema.php @@ -39,14 +39,18 @@ * hooks, and the enabled check in fabric_sweep_allowed() stop them. */ final class Schema { - public const VERSION = 1; + public const VERSION = 2; public const HOOKS = [ 'config_arrays' => 'fabric_config_arrays', 'config_settings' => 'fabric_config_settings', 'draw_navigation_text' => 'fabric_draw_navigation_text', + 'device_remove' => 'fabric_device_remove', ]; + /** Columns version 2 adds to plugin_fabric_sample, for rates and discontinuities. */ + private const SAMPLE_V2 = ['previous_at', 'rates', 'reset', 'discontinuities', 'discontinuity_at']; + private const PLUGIN = 'fabric'; private const SETTING = 'fabric_schema_version'; @@ -142,6 +146,7 @@ public function forgetVersion(): void { private function migrations(): array { return [ 1 => fn (): bool => $this->createTables(self::tables()), + 2 => fn (): bool => $this->addColumns('plugin_fabric_sample', self::SAMPLE_V2), ]; } @@ -178,6 +183,47 @@ private function createTables(array $tables): bool { return true; } + /** + * Add columns of a table definition that an older version created + * without them. Plain ALTER TABLE, not api_plugin_db_add_column(): core + * records that one for uninstall and would drop the column from a table + * an administrator chose to keep. + * + * @param list $names + */ + private function addColumns(string $table, array $names): bool { + $columns = self::tables()[$table]['columns'] ?? []; + + foreach (is_array($columns) ? $columns : [] as $column) { + $name = is_array($column) ? Row::string($column, 'name') : ''; + + if (!is_array($column) || !in_array($name, $names, true)) { + continue; + } + + $exists = db_fetch_cell_prepared('SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?', [$table, $name], '', true, $this->connection); + + if ($exists === false) { + return false; + } + + if ((int) $exists > 0) { + continue; + } + + // The names, types, and defaults are this class's constants. + $sql = sprintf("ALTER TABLE `%s` ADD COLUMN `%s` %s%s NOT NULL DEFAULT '%s'", $table, $name, Row::string($column, 'type'), !empty($column['unsigned']) ? ' unsigned' : '', Row::string($column, 'default')); + + if (db_execute_prepared($sql, [], true, $this->connection) === false) { + Log::error(sprintf('Unable to add column %s to %s', $name, $table)); + + return false; + } + } + + return true; + } + private function tableExists(string $table): bool { return db_fetch_cell_prepared('SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?', [$table], '', true, $this->connection) > 0; } @@ -302,6 +348,16 @@ public static function tables(): array { $count('cap_mask2'), $text('counters', 2048), $text('error', 16), + // Version 2: the observation time of the sample the + // rates were computed against, the rates (JSON counter + // => per second or null), the counters that went down + // at this sample, and the count and time of the last + // discontinuity (CounterDelta). + $time('previous_at'), + $text('rates', 2048), + $text('reset', 1024), + $count('discontinuities'), + $time('discontinuity_at'), ], 'primary' => 'node_id`,`port_number`,`counter_group', ], diff --git a/lib/Settings.php b/lib/Settings.php index 9b7f96e..6f5a1cf 100644 --- a/lib/Settings.php +++ b/lib/Settings.php @@ -35,6 +35,7 @@ 'fabric_node_budget', 'fabric_failure_budget', 'fabric_uninstall_keep_tables', + 'fabric_index_down_ports', ]; public const DEFAULT_TOOL_DIR = '/usr/sbin'; @@ -53,6 +54,7 @@ public function __construct( public int $nodeBudget, public int $failureBudget, public bool $keepTablesOnUninstall, + public bool $indexDownPorts = false, ) { } @@ -75,6 +77,7 @@ public static function fromRow(array $row): self { nodeBudget: min(Row::int($row, 'fabric_node_budget', self::DEFAULT_BUDGET, 5), 300), failureBudget: min(Row::int($row, 'fabric_failure_budget', self::DEFAULT_FAILURES, 1), 64), keepTablesOnUninstall: array_key_exists('fabric_uninstall_keep_tables', $row) ? Row::bool($row, 'fabric_uninstall_keep_tables') : true, + indexDownPorts: Row::bool($row, 'fabric_index_down_ports'), ); } @@ -152,6 +155,16 @@ public static function form(): array { ], 'fabric_node_budget' => $number(__('Node Time Budget', 'fabric'), __('Seconds one node sweep may spend reading counters. Ports not reached are read in the next cycle.', 'fabric'), self::DEFAULT_BUDGET, 5, 300), 'fabric_failure_budget' => $number(__('Node Failure Budget', 'fabric'), __('Failed ports after which a node sweep stops for this cycle. A port that does not answer costs several seconds.', 'fabric'), self::DEFAULT_FAILURES, 1, 64), + 'fabric_header_objects' => [ + 'friendly_name' => __('Cacti Objects', 'fabric'), + 'method' => 'spacer', + ], + 'fabric_index_down_ports' => [ + 'friendly_name' => __('Index Down Ports', 'fabric'), + 'description' => __('When checked, the Fabric Port data query also lists ports that are down and have no remote end, such as unused adapter ports. Cleared, they are left out until they come up.', 'fabric'), + 'method' => 'checkbox', + 'default' => '', + ], 'fabric_header_uninstall' => [ 'friendly_name' => __('Uninstall', 'fabric'), 'method' => 'spacer', diff --git a/lib/Sweep.php b/lib/Sweep.php index 396e05a..1dd2308 100644 --- a/lib/Sweep.php +++ b/lib/Sweep.php @@ -20,15 +20,21 @@ namespace Somethingwithproof\Fabric; /** - * Starts sweeps lazily (ADR 0008). The M3 script server calls forDevice() - * when the poller asks for a mapped device's values; fabric_sweep.php calls + * Starts sweeps lazily (ADR 0008). The Fabric Port data query calls + * forDevice() through the script server when the poller asks for a mapped + * device's first value; fabric_sweep.php calls * forFabric(). Either way a sweep runs only on the poller the fabric is * assigned to, only while the plugin and the fabric are enabled, and only * for what is due. Claims keep concurrent callers from sweeping the same * fabric topology or node twice; a caller that loses a claim does not * wait, it returns and reads what the winner stores. * - * There is no poller_bottom prefetch in M2. + * There is no poller_bottom prefetch. + * + * A deadline (microtime(true)) bounds every tool run of this object's + * sweeps, the command timeout included; the script server passes one below + * Cacti's script timeout, so a get call returns in time with the last + * stored values or U (fabric_port_query()). */ final class Sweep { private readonly TopologySweep $topology; @@ -42,9 +48,13 @@ public function __construct( private readonly int $pollerId, private readonly bool $pluginEnabled, int $toolOwner = 0, + ?float $deadline = null, ) { - $this->topology = new TopologySweep($connection, $clock, $runner, $settings, $toolOwner); - $this->counters = new CounterSweep($connection, $clock, $runner, $settings, $toolOwner); + // Leave most of a script-server call for counters even when + // topology discovery runs up to its limit every polling cycle. + $topologyDeadline = $deadline === null ? null : microtime(true) + max(0.0, $deadline - microtime(true)) / 3; + $this->topology = new TopologySweep($connection, $clock, $runner, $settings, $toolOwner, $topologyDeadline); + $this->counters = new CounterSweep($connection, $clock, $runner, $settings, $toolOwner, $deadline); } /** diff --git a/lib/TemplateInstaller.php b/lib/TemplateInstaller.php new file mode 100644 index 0000000..95c881e --- /dev/null +++ b/lib/TemplateInstaller.php @@ -0,0 +1,288 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_fabric, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_fabric + * + * 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\Fabric; + +/** + * Installs the shipped Cacti objects (REQ-OBJ-001, REQ-OBJ-002, ADR 0011): + * the Fabric Port data query XML, copied into Cacti's resource tree, and + * the device, data, and graph templates, imported with Cacti's own + * import_xml_data(). + * + * templates/fabric-templates.xml is Cacti's own export of templates that + * tests/bin/build-templates.php builds in a disposable Cacti, 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 after an operator renames them. + * + * Cacti reads a data query XML only from inside /resource, so + * the file is copied there, the one place outside its own directory the + * plugin writes. It is written only where no file is, or over a file the + * plugin wrote itself and nobody changed since: the setting FILES_SETTING + * keeps the SHA-256 of what was written. A destination that is a symbolic + * link, dangling or not, is refused. The file is written beside the + * destination and renamed over it, so a reindex never reads half a file. + * + * Nothing here creates a device, data source, graph, or RRD file. + */ +final class TemplateInstaller { + /** Bump when templates/fabric-templates.xml or the query XML changes. */ + public const VERSION = 1; + + public const SETTING = 'fabric_templates_version'; + public const FAILURE_SETTING = 'fabric_templates_failure'; + public const FILES_SETTING = 'fabric_query_files'; + + public const DEVICE_TEMPLATE = 'Fabric Node'; + public const QUERY = 'Fabric Port'; + public const QUERY_FILE = 'fabric_ports.xml'; + public const TEMPLATE_FILE = 'fabric-templates.xml'; + + public function __construct( + private readonly string $pluginPath, + private readonly string $cactiPath, + private readonly CactiObjectRepository $objects, + ) { + } + + /** + * The hash the template builder gives an object: 32 hexadecimal + * characters, as Cacti stores it. + */ + public static function hash(string $kind, string $name): string { + return md5('plugin_fabric:' . $kind . ':' . $name); + } + + /** + * Whether this version's objects were installed. The upgrade check + * runs on page loads, so it reads only this setting; a template or + * file removed afterwards is found by isCurrent() on the health page, + * which offers a reinstall to users who may import templates. + */ + public function installed(): bool { + return (int) read_config_option(self::SETTING) === self::VERSION; + } + + public function isCurrent(): bool { + return $this->installed() && $this->present() && $this->queryFileProblem() === null; + } + + /** + * Why the last install failed, or '' after a success. + */ + public function failure(): string { + return (string) read_config_option(self::FAILURE_SETTING); + } + + /** + * Place the query file and import the templates. A failure is logged + * and kept for the health page; a success clears it. + */ + public function install(): bool { + $error = $this->installQueryFile() ?? $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 file if the plugin wrote it and nobody changed it. + * The templates and everything made from them stay: once imported they + * belong to the site. + */ + public function uninstall(): void { + $target = $this->target(); + $written = $this->written(); + + if ($target !== null && $written !== '' && !is_link($target) && is_file($target) && hash_file('sha256', $target) === $written) { + @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->deviceTemplateId() === 0 || $this->objects->queryId() === 0) { + return false; + } + + foreach (array_keys(PortValues::templates()) as $name) { + if ($this->objects->idByHash('data_template', self::hash('data_template', $name)) === 0 || $this->objects->graphTemplateId($name) === 0) { + return false; + } + } + + return true; + } + + /** + * Why Cacti's copy of the query file is not the shipped one, or null. + */ + public function queryFileProblem(): ?string { + $target = $this->target(); + $source = $this->source(); + + if ($target === null || !is_file($source)) { + return sprintf('The data query file %s cannot be installed: the plugin copy or the Cacti resource directory is missing', self::QUERY_FILE); + } + + if (is_link($target)) { + return sprintf('%s is a symbolic link; the plugin does not write through one. Replace it with a copy of plugins/fabric/resource/script_server/%s', $target, self::QUERY_FILE); + } + + if (!is_file($target) || hash_file('sha256', $target) !== hash_file('sha256', $source)) { + return sprintf('%s is missing or differs from plugins/fabric/resource/script_server/%s', $target, self::QUERY_FILE); + } + + return null; + } + + public function target(): ?string { + $dir = $this->cactiPath . '/resource/script_server'; + + return is_dir($dir) ? $dir . '/' . self::QUERY_FILE : null; + } + + /** + * @return string|null the reason, or null when the file is in place + */ + private function installQueryFile(): ?string { + $source = $this->source(); + $target = $this->target(); + $data = is_file($source) ? file_get_contents($source) : false; + + if ($target === null || !is_string($data) || $data === '') { + return sprintf('The data query file %s cannot be installed: the plugin copy or the Cacti resource directory is missing', self::QUERY_FILE); + } + + $want = hash('sha256', $data); + + if (is_link($target)) { + return sprintf('%s is a symbolic link, so it was not written. Remove the link and reinstall the templates from the health page', $target); + } + + if (file_exists($target)) { + $have = is_file($target) ? (string) hash_file('sha256', $target) : ''; + + if ($have === $want) { + return null; + } + + if ($have === '' || $have !== $this->written()) { + 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/fabric/resource/script_server/%s', $target, self::QUERY_FILE); + } + } + + $temporary = dirname($target) . '/.' . self::QUERY_FILE . '.' . bin2hex(random_bytes(8)) . '.tmp'; + $handle = @fopen($temporary, 'x'); + + if ($handle === false) { + return sprintf('Could not write in %s. Copy plugins/fabric/resource/script_server/%s there as the web server user, then reinstall the templates from the health page', dirname($target), self::QUERY_FILE); + } + + $complete = fwrite($handle, $data) === strlen($data) && fflush($handle); + fclose($handle); + + // Checked again just before the rename: a link placed meanwhile + // is replaced by the rename, never written through, but refused. + clearstatcache(true, $target); + + if (!$complete || is_link($target) || !@rename($temporary, $target)) { + @unlink($temporary); + + return sprintf('Could not write %s. Copy plugins/fabric/resource/script_server/%s there as the web server user, then reinstall the templates from the health page', $target, self::QUERY_FILE); + } + + if (hash_file('sha256', $target) !== $want) { + return sprintf('%s could not be verified after it was written', $target); + } + + set_config_option(self::FILES_SETTING, $want); + + return null; + } + + /** + * @return string|null the reason, or null when every object imported + */ + private function import(): ?string { + $file = $this->pluginPath . '/templates/' . self::TEMPLATE_FILE; + $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 Fabric 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 Fabric template objects failed to import', $failed); + } + + return $this->present() ? null : 'The Fabric templates are missing after import'; + } + + /** + * The SHA-256 of the query file the plugin last wrote, or ''. + */ + private function written(): string { + $hash = (string) read_config_option(self::FILES_SETTING); + + return preg_match('/^[0-9a-f]{64}$/D', $hash) === 1 ? $hash : ''; + } + + private function source(): string { + return $this->pluginPath . '/resource/script_server/' . self::QUERY_FILE; + } +} diff --git a/lib/ToolRunner.php b/lib/ToolRunner.php index 51bd251..994b127 100644 --- a/lib/ToolRunner.php +++ b/lib/ToolRunner.php @@ -23,13 +23,34 @@ * Runs a Command under the configured limits and logs any failure with a * cleaned excerpt of the tool's standard error. The excerpt is for the * operator reading the log; no decision is made from it (REQ-EXEC-006). + * + * With a deadline (a microtime(true) value), each run's time limit is the + * command timeout or the time left before the deadline, whichever is + * shorter, so the caller returns by the deadline whatever a tool does. A + * run with under MIN_SECONDS left is not started and reads as timed out. */ final class ToolRunner { - public function __construct(private readonly ProcessRunner $runner, private readonly Settings $settings) { + public const MIN_SECONDS = 1.0; + + public function __construct(private readonly ProcessRunner $runner, private readonly Settings $settings, private readonly ?float $deadline = null) { } public function run(Command $command): ProcessResult { - $result = $this->runner->run($command, (float) $this->settings->commandTimeout, $this->settings->maxOutputBytes()); + $limit = (float) $this->settings->commandTimeout; + + if ($this->deadline !== null) { + $left = $this->deadline - microtime(true); + + if ($left < self::MIN_SECONDS) { + Log::warning(sprintf('%s: not started: the time limit of this sweep is spent', $command->tool->value)); + + return new ProcessResult(null, '', '', true, false, true, 0.0); + } + + $limit = min($limit, $left); + } + + $result = $this->runner->run($command, $limit, $this->settings->maxOutputBytes()); $error = $result->error(); if ($error !== null) { diff --git a/lib/TopologySweep.php b/lib/TopologySweep.php index 1c78266..430fbcd 100644 --- a/lib/TopologySweep.php +++ b/lib/TopologySweep.php @@ -33,6 +33,7 @@ public function __construct( private readonly ProcessRunner $runner, private readonly Settings $settings, private readonly int $toolOwner = 0, + private readonly ?float $deadline = null, ) { } @@ -96,7 +97,7 @@ private function sweep(Fabric $fabric, ClaimRepository $claims, string $holder): $fabrics = new FabricRepository($this->connection, $this->clock); $owned = static fn (): bool => $claims->holdsForCommit(ClaimRepository::TOPOLOGY, $fabric->id, $holder) && $fabrics->existsForCommit($fabric->id); $health = new FabricHealthRepository($this->connection); - $tools = new ToolRunner($this->runner, $this->settings); + $tools = new ToolRunner($this->runner, $this->settings, $this->deadline); $now = $this->clock->now(); $probe = new PrivilegeProbe($this->settings->toolDir, toolOwner: $this->toolOwner); diff --git a/locales/po/cacti.pot b/locales/po/cacti.pot index 2fc210f..6e03d8f 100644 --- a/locales/po/cacti.pot +++ b/locales/po/cacti.pot @@ -76,6 +76,11 @@ msgstr "" msgid "The proposal was rejected." msgstr "" +#: fabric_admin.php +#, php-format +msgid "The node mapping was not changed. %s" +msgstr "" + #: fabric_admin.php msgid "The node mapping was not changed." msgstr "" @@ -84,10 +89,26 @@ msgstr "" msgid "The node mapping was saved." msgstr "" +#: fabric_admin.php +msgid "No device was created. See the Cacti log." +msgstr "" + +#: fabric_admin.php +msgid "The device was created and the node mapped to it. Choose the ports to graph on the New Graphs page." +msgstr "" + #: fabric_admin.php msgid "The inventory could not be read for export." msgstr "" +#: fabric_health.php +msgid "The Fabric templates and data query file were installed." +msgstr "" + +#: fabric_health.php +msgid "The Fabric templates were not installed. See the Cacti Objects table and the Cacti log." +msgstr "" + #: lib/AdminPage.php lib/HealthPage.php lib/Pages.php msgid "Fabric Admin" msgstr "" @@ -221,10 +242,48 @@ msgstr "" msgid "GUID" msgstr "" +#: lib/AdminPage.php +msgid "Devices Matching the Node Name" +msgstr "" + +#: lib/AdminPage.php +#, php-format +msgid "%s (device %d)" +msgstr "" + +#: lib/AdminPage.php +msgid "None" +msgstr "" + #: lib/AdminPage.php msgid "Cacti Device" msgstr "" +#: lib/AdminPage.php +msgid "Saving maps the node to the device and adds the Fabric Port data query to the device, which lists the node's ports. No graph, data source, or device setting is changed. The device must be polled by the poller that sweeps the fabric." +msgstr "" + +#: lib/AdminPage.php +msgid "Create a Device for This Node" +msgstr "" + +#: lib/AdminPage.php +msgid "Devices cannot be created here." +msgstr "" + +#: lib/AdminPage.php +#, php-format +msgid "Create a Device for %s" +msgstr "" + +#: lib/AdminPage.php +msgid "Creating the device adds:" +msgstr "" + +#: lib/AdminPage.php +msgid "Create" +msgstr "" + #: lib/AdminPage.php msgid "Identity Conflicts" msgstr "" @@ -321,6 +380,41 @@ msgstr "" msgid "The plugin tables could not be read or written" msgstr "" +#: lib/DeviceProvisioner.php +msgid "The Fabric templates are not installed. Reinstall them from the health page." +msgstr "" + +#: lib/DeviceProvisioner.php +msgid "The node is already mapped to a device." +msgstr "" + +#: lib/DeviceProvisioner.php +msgid "The node's fabric is not swept by the main poller, so its device could not be polled." +msgstr "" + +#: lib/DeviceProvisioner.php +msgid "The device does not exist." +msgstr "" + +#: lib/DeviceProvisioner.php +msgid "The device is polled by another poller than the one that sweeps this fabric, so it could not read the fabric cache." +msgstr "" + +#: lib/DeviceProvisioner.php +#, php-format +msgid "A device \"%s\" from the %s device template, host name %s, polled by poller %d, with availability checks and SNMP off." +msgstr "" + +#: lib/DeviceProvisioner.php +#, php-format +msgid "The %s data query on it, listing the node's ports. It creates no graph and no data source by itself." +msgstr "" + +#: lib/DeviceProvisioner.php +#, php-format +msgid "Created by the Fabric plugin for node %s. Its values come from the plugin cache; the host name is a reserved name that is never contacted." +msgstr "" + #: lib/FabricInput.php msgid "Name: use 1 to 64 letters, digits, spaces, dots, dashes, or underscores, starting with a letter or digit." msgstr "" @@ -375,6 +469,34 @@ msgstr "" msgid "%d days ago" msgstr "" +#: lib/HealthPage.php lib/Settings.php +msgid "Cacti Objects" +msgstr "" + +#: lib/HealthPage.php +msgid "Installed" +msgstr "" + +#: lib/HealthPage.php lib/InventoryPage.php +msgid "Missing" +msgstr "" + +#: lib/HealthPage.php +msgid "Templates" +msgstr "" + +#: lib/HealthPage.php +msgid "Data Query File" +msgstr "" + +#: lib/HealthPage.php +msgid "Last Install" +msgstr "" + +#: lib/HealthPage.php +msgid "Reinstall the Templates" +msgstr "" + #: lib/HealthPage.php lib/Pages.php msgid "Fabric Health" msgstr "" @@ -530,6 +652,46 @@ msgstr "" msgid "No fabrics are defined yet." msgstr "" +#: lib/InventoryPage.php +msgid "Ports with the highest transmit wait" +msgstr "" + +#: lib/InventoryPage.php +msgid "Ports with the Highest Transmit Wait" +msgstr "" + +#: lib/InventoryPage.php +msgid "The fabric inventory could not be read. See the Cacti log." +msgstr "" + +#: lib/InventoryPage.php +msgid "Transmit wait counts ticks in which a port had data to send but could not send it, for lack of credits or arbitration. A high value shows congestion toward the remote end; it does not show that the port or its cable is faulty. The tick length is not published for current link speeds, so values are ticks per second, not time." +msgstr "" + +#: lib/InventoryPage.php +msgid "Port" +msgstr "" + +#: lib/InventoryPage.php +msgid "Remote" +msgstr "" + +#: lib/InventoryPage.php +msgid "Transmit Discards (per second)" +msgstr "" + +#: lib/InventoryPage.php +msgid "Transmit Wait (ticks per second)" +msgstr "" + +#: lib/InventoryPage.php +msgid "No port has a current transmit wait rate." +msgstr "" + +#: lib/InventoryPage.php lib/LinkCondition.php +msgid "Unknown" +msgstr "" + #: lib/InventoryPage.php msgid "Fabric Node" msgstr "" @@ -547,19 +709,19 @@ msgid "Best Both Ends Support" msgstr "" #: lib/InventoryPage.php -msgid "Counters" +msgid "Counter Validity" msgstr "" #: lib/InventoryPage.php -msgid "Link" +msgid "Counters" msgstr "" #: lib/InventoryPage.php -msgid "Port" +msgid "Graphs" msgstr "" #: lib/InventoryPage.php -msgid "Remote" +msgid "Link" msgstr "" #: lib/InventoryPage.php @@ -567,16 +729,22 @@ msgid "No ports recorded yet." msgstr "" #: lib/InventoryPage.php -msgid "Missing" +#, php-format +msgid "Device %d" msgstr "" #: lib/InventoryPage.php #, php-format -msgid "Device %d" +msgid "%s counters saturated, published as unknown: %s" msgstr "" #: lib/InventoryPage.php -msgid "The fabric inventory could not be read. See the Cacti log." +#, php-format +msgid "%s counters: %d discontinuities, the last %s" +msgstr "" + +#: lib/InventoryPage.php +msgid "Valid" msgstr "" #: lib/LinkCondition.php @@ -599,10 +767,6 @@ msgstr "" msgid "Down" msgstr "" -#: lib/LinkCondition.php -msgid "Unknown" -msgstr "" - #: lib/NodeType.php msgid "Switch" msgstr "" @@ -703,6 +867,14 @@ msgstr "" msgid "Node Failure Budget" msgstr "" +#: lib/Settings.php +msgid "Index Down Ports" +msgstr "" + +#: lib/Settings.php +msgid "When checked, the Fabric Port data query also lists ports that are down and have no remote end, such as unused adapter ports. Cleared, they are left out until they come up." +msgstr "" + #: lib/Settings.php msgid "Uninstall" msgstr "" diff --git a/phpstan.neon b/phpstan.neon index 3326dc7..e772c19 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -24,6 +24,7 @@ parameters: - lib - setup.php - include/unbooted-uninstall.php + - scripts scanDirectories: - %env.CACTI_PATH%/lib - %env.CACTI_PATH%/include diff --git a/resource/script_server/fabric_ports.xml b/resource/script_server/fabric_ports.xml new file mode 100644 index 0000000..3899fb6 --- /dev/null +++ b/resource/script_server/fabric_ports.xml @@ -0,0 +1,179 @@ + + Fabric Port + InfiniBand ports of the fabric nodes mapped to a device, answered from the plugin cache + |path_cacti|/plugins/fabric/scripts/ss_fabric_ports.php + ss_fabric_ports + php + |host_id| + index + query + get + num_indexes + ! + fabricPort + alphabetic + |chosen_order_field| + + + + Port (node GUID:port) + input + fabricPort + + + Node GUID + input + fabricGuid + + + Port Number + input + fabricPortNum + + + Node + input + fabricNode + + + Remote Port + input + fabricRemote + + + Data Transmitted (4-octet words) + output + xmit_data + + + Data Received (4-octet words) + output + rcv_data + + + Packets Transmitted + output + xmit_pkts + + + Packets Received + output + rcv_pkts + + + Symbol Errors + output + symbol_err + + + Link Error Recoveries + output + link_err_recov + + + Link Downed Events + output + link_downed + + + Receive Errors + output + rcv_err + + + Receive Remote Physical Errors + output + rcv_remote_phys + + + Receive Switch Relay Errors + output + rcv_switch_relay + + + Local Link Integrity Errors + output + local_link_integ + + + Excessive Buffer Overruns + output + buffer_overrun + + + VL15 Packets Dropped + output + vl15_dropped + + + Transmit Wait (ticks) + output + xmit_wait + + + Transmit Discards + output + xmit_discards + + + Transmit Constraint Errors + output + xmit_constraint + + + Receive Constraint Errors + output + rcv_constraint + + + Active Lanes + output + active_lanes + + + Active Speed Rank + output + speed_rank + + + Degraded (0 or 1) + output + degraded + + + Logical Port State + output + port_state + + + Sample Age (seconds) + output + age + + + Symbol Errors per Second + output + symbol_err_rate + + + Receive Errors per Second + output + rcv_err_rate + + + Link Downed Events per Second + output + link_downed_rate + + + Transmit Discards per Second + output + xmit_discard_rate + + + Transmit Wait Ticks per Second + output + xmit_wait_rate + + + diff --git a/scripts/ss_fabric_ports.php b/scripts/ss_fabric_ports.php new file mode 100644 index 0000000..96e6db7 --- /dev/null +++ b/scripts/ss_fabric_ports.php @@ -0,0 +1,68 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_fabric, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_fabric + * + * 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 query for the ports of a fabric node's device + * (resource/script_server/fabric_ports.xml). Cacti runs this file as a PHP + * CLI process for the index and query steps of a reindex, which read the + * cache only, and calls the function through the script server for each + * polled value, where the first call for a device starts its due sweep + * (ADR 0008). + * + * This file must parse on PHP 8.0: the script server includes it on + * whatever PHP the site runs, and fabric_boot() refuses before any plugin + * class loads, answering U. + */ + +if (!isset($called_by_script_server)) { + include_once(__DIR__ . '/../../../include/cli_check.php'); + + $fabric_args = isset($_SERVER['argv']) && is_array($_SERVER['argv']) ? array_values(array_filter(array_slice($_SERVER['argv'], 1), 'is_string')) : array(); + + // A reindex never sweeps. + if (!in_array($fabric_args[1] ?? '', array('index', 'num_indexes', 'query'), true)) { + exit(1); + } + + print ss_fabric_ports(...$fabric_args); +} + +/** + * @param int|string $host_id the Cacti device the nodes are mapped to + * @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_fabric_ports($host_id = 0, $cmd = 'index', $arg1 = '', $arg2 = ''): string { + global $called_by_script_server; + + static $query = null; + + include_once(dirname(__DIR__) . '/setup.php'); + + if (!fabric_boot()) { + return $cmd === 'get' ? 'U' : ''; + } + + if ($query === null) { + $query = fabric_port_query(!empty($called_by_script_server)); + } + + return $query->answer((int) $host_id, (string) $cmd, (string) $arg1, (string) $arg2); +} diff --git a/setup.php b/setup.php index ddda43a..69a3d3b 100644 --- a/setup.php +++ b/setup.php @@ -160,11 +160,28 @@ function fabric_device_allowed(int $hostId): bool { return $hostId > 0 && (bool) is_device_allowed($hostId); } +/** + * Whether the current user may see a graph, by core's graph permissions. + */ +function fabric_graph_allowed(int $localGraphId): bool { + global $config; + + if (!function_exists('is_graph_allowed')) { + include_once($config['library_path'] . '/auth.php'); + } + + return $localGraphId > 0 && (bool) is_graph_allowed($localGraphId); +} + function fabric_settings(): \Somethingwithproof\Fabric\Settings { return (new \Somethingwithproof\Fabric\SettingsRepository(false))->load(); } +function fabric_templates(): \Somethingwithproof\Fabric\TemplateInstaller { + global $config; + return new \Somethingwithproof\Fabric\TemplateInstaller(__DIR__, (string) $config['base_path'], new \Somethingwithproof\Fabric\CactiObjectRepository(false)); +} /** * Bring the schema, hooks, and realms up to the code's version. @@ -187,7 +204,9 @@ function plugin_fabric_upgrade(bool $grant = false): bool { $info = plugin_fabric_version(); $schema = new \Somethingwithproof\Fabric\Schema(false); - if ($schema->isCurrent() && $schema->recordedPluginVersion() === $info['version'] && $schema->hooksRegistered()) { + $templates = fabric_templates(); + + if ($schema->isCurrent() && $schema->recordedPluginVersion() === $info['version'] && $schema->hooksRegistered() && $templates->installed()) { return true; } @@ -199,6 +218,13 @@ function plugin_fabric_upgrade(bool $grant = false): bool { fabric_setup_hooks($grant); + // A failed template install is logged and shown on the health page, + // and retried by the next upgrade check; the plugin itself works + // without the templates, so it does not fail the upgrade. + if (!$templates->installed()) { + $templates->install(); + } + $schema->recordPluginVersion($info['version'], $info['author'], $info['homepage']); return true; @@ -250,8 +276,9 @@ function fabric_uninstall_stop(): void { * and never runs a fabric tool (REQ-LIFE-005). Core drops the tracked * plugin tables afterwards unless the administrator left "Keep Plugin * Tables on Uninstall" checked, which is the default; the export on the - * Fabric Admin page is the copy to take first (REQ-LIFE-003). M2 creates no - * devices, so there is none to offer to delete. + * Fabric Admin page is the copy to take first (REQ-LIFE-003). Devices the + * plugin created stay, like every Cacti object: an administrator deletes + * them in Cacti, where the Fabric Node device template finds them. */ function plugin_fabric_uninstall(): void { if (!fabric_boot()) { @@ -263,6 +290,10 @@ function plugin_fabric_uninstall(): void { $schema = new \Somethingwithproof\Fabric\Schema(false); + // Only the query file the plugin wrote and nobody changed; templates + // and devices stay. + fabric_templates()->uninstall(); + if (fabric_settings()->keepTablesOnUninstall) { if (!$schema->untrackTables()) { fabric_uninstall_stop(); @@ -326,12 +357,51 @@ function fabric_draw_navigation_text($nav) { } /** - * The sweep entry point for this poller (ADR 0008). fabric_sweep.php uses - * it now and the M3 script server will. It runs nothing while the plugin is + * Clear the mappings of deleted devices (REQ-MAP-004). The nodes and their + * history stay; core passes the device ids and expects them back. + * + * @param mixed $device_ids + * @return mixed + */ +function fabric_device_remove($device_ids) { + if (fabric_boot() && is_array($device_ids)) { + $ids = array_filter(array_map(static fn ($id): int => is_numeric($id) ? (int) $id : 0, $device_ids), static fn (int $id): bool => $id > 0); + + (new \Somethingwithproof\Fabric\NodeRepository(false))->unmapHosts(array_values($ids)); + } + + return $device_ids; +} + +/** + * The Fabric Port data query (scripts/ss_fabric_ports.php). With $sweep, + * as the script server passes, the first value asked for a device starts + * its due sweep; a sweep that fails is logged and the values are answered + * from what the cache holds. + */ +function fabric_port_query(bool $sweep): \Somethingwithproof\Fabric\PortQuery { + $sweeper = null; + + if ($sweep) { + $sweeper = static function (int $hostId): void { + try { + fabric_sweep(null, microtime(true) + fabric_script_sweep_seconds())->forDevice($hostId); + } catch (\Throwable $e) { + \Somethingwithproof\Fabric\Log::error(sprintf('Sweep for device %d failed: %s', $hostId, \Somethingwithproof\Fabric\Log::excerpt($e->getMessage()))); + } + }; + } + + return new \Somethingwithproof\Fabric\PortQuery(false, new \Somethingwithproof\Fabric\SystemClock(), fabric_settings()->indexDownPorts, $sweeper); +} + +/** + * The sweep entry point for this poller (ADR 0008), used by the script + * server through fabric_port_query() and by fabric_sweep.php. It runs nothing while the plugin is * disabled: core keeps plugin files reachable from the CLI after a disable, * so the enabled state is checked here, not assumed from hooks. */ -function fabric_sweep(?\Somethingwithproof\Fabric\ProcessRunner $runner = null): \Somethingwithproof\Fabric\Sweep { +function fabric_sweep(?\Somethingwithproof\Fabric\ProcessRunner $runner = null, ?float $deadline = null): \Somethingwithproof\Fabric\Sweep { global $config; return new \Somethingwithproof\Fabric\Sweep( @@ -340,6 +410,22 @@ function fabric_sweep(?\Somethingwithproof\Fabric\ProcessRunner $runner = null): $runner ?? new \Somethingwithproof\Fabric\ProcRunner(), fabric_settings(), (int) ($config['poller_id'] ?? 1), - (new \Somethingwithproof\Fabric\Schema(false))->pluginEnabled() + (new \Somethingwithproof\Fabric\Schema(false))->pluginEnabled(), + deadline: $deadline ); } + +/** + * Seconds a sweep started by a script server get may take: Cacti's script + * timeout (Spine's limit for one script server call, default 25) less 5 + * seconds for the cache read and the answer. Spine records NaN for a call + * past its timeout; the PHP + * poller has no such limit and would stall instead, so the bound applies + * to both. A sweep cut short is retried in the next cycle, and the get + * answers from the last stored sample, or U. + */ +function fabric_script_sweep_seconds(): float { + $timeout = (int) read_config_option('script_timeout'); + + return (float) max(0, ($timeout > 0 ? $timeout : 25) - 5); +} diff --git a/templates/fabric-templates.xml b/templates/fabric-templates.xml new file mode 100644 index 0000000..f859ffe --- /dev/null +++ b/templates/fabric-templates.xml @@ -0,0 +1,2470 @@ + + + Fabric Node + + + hash_040103c987bc7327d08cb74aa1b96503f373bd + + + Fabric Port + InfiniBand ports of the fabric nodes mapped to a device, from the Fabric plugin cache + <path_cacti>/resource/script_server/fabric_ports.xml + hash_030103332111d8b54ac8ce939af87a7eac0c06 + + + hash_000103360822ecc397adf7edbccb7d22bcbe2e + Traffic + + + xmit_data + hash_01010355a64e7a843d4601945f276fc5b3be5b + hash_0801033fa2d992cc4dc70c9495f2fb395fb7a7 + + + rcv_data + hash_01010355a64e7a843d4601945f276fc5b3be5b + hash_0801035c4da6609fb80bf7408521d936818cda + + + xmit_pkts + hash_01010355a64e7a843d4601945f276fc5b3be5b + hash_080103da7fca12d019dd1f1d43088be7dba564 + + + rcv_pkts + hash_01010355a64e7a843d4601945f276fc5b3be5b + hash_080103445e0e10ce794df781e2a069b0403855 + + + + + title + 1 + |host_description| - |query_fabricPort| - Traffic + + + + + name + hash_01010355a64e7a843d4601945f276fc5b3be5b + 1 + |host_description| - |query_fabricPort| - Traffic + + + + + hash_000103d981b9667ecd1ec0042dfec812fb3ef4 + Errors + + + symbol_err + hash_0101036518cf6e70bc2d202b8622b6fd384940 + hash_080103d8feb0a6bace476466c09391853b8277 + + + link_err_recov + hash_0101036518cf6e70bc2d202b8622b6fd384940 + hash_0801031596f44564e8d1f4dc7b2e72b4276254 + + + link_downed + hash_0101036518cf6e70bc2d202b8622b6fd384940 + hash_0801038dc42409271f093787a663fd50d4c902 + + + rcv_err + hash_0101036518cf6e70bc2d202b8622b6fd384940 + hash_0801031607505da822ed07880d0e74e344fffa + + + rcv_remote_phys + hash_0101036518cf6e70bc2d202b8622b6fd384940 + hash_080103f17f2687ed6aab36af7de22cb8f12515 + + + rcv_switch_relay + hash_0101036518cf6e70bc2d202b8622b6fd384940 + hash_0801031d46010ab0c4f19cae3cef8f2fe48405 + + + local_link_integ + hash_0101036518cf6e70bc2d202b8622b6fd384940 + hash_080103bf438aab6a729dfc2e7631df0ec8aef5 + + + buffer_overrun + hash_0101036518cf6e70bc2d202b8622b6fd384940 + hash_080103306da2354c30b91ba2b0ed34f82088d8 + + + vl15_dropped + hash_0101036518cf6e70bc2d202b8622b6fd384940 + hash_080103e2eadb6d5d97ab6521be7c34357ba612 + + + + + title + 1 + |host_description| - |query_fabricPort| - Errors + + + + + name + hash_0101036518cf6e70bc2d202b8622b6fd384940 + 1 + |host_description| - |query_fabricPort| - Errors + + + + + hash_0001038bda6165925882420873660160ffe6ff + Congestion + + + xmit_wait + hash_010103880cf69f2b7d05e74bc707e876d21a17 + hash_08010394fd05fa64be09969185da35aac21914 + + + xmit_discards + hash_010103880cf69f2b7d05e74bc707e876d21a17 + hash_080103669230a4bf849b874910b6e35973f9f8 + + + xmit_constraint + hash_010103880cf69f2b7d05e74bc707e876d21a17 + hash_0801034f0869447fd31ee70dc066dc0ad00c80 + + + rcv_constraint + hash_010103880cf69f2b7d05e74bc707e876d21a17 + hash_080103aef73b07a531d7a26c28625065517335 + + + + + title + 1 + |host_description| - |query_fabricPort| - Congestion + + + + + name + hash_010103880cf69f2b7d05e74bc707e876d21a17 + 1 + |host_description| - |query_fabricPort| - Congestion + + + + + hash_000103b43f4a76dd332dff94caa55984c601fb + State + + + active_lanes + hash_0101033bd7cbe3b533f002ef7b04c509fef56f + hash_080103e02ceae4350458fa1256323f3879d7cb + + + speed_rank + hash_0101033bd7cbe3b533f002ef7b04c509fef56f + hash_08010364c667f6de865c096cf59ab47bc1415f + + + degraded + hash_0101033bd7cbe3b533f002ef7b04c509fef56f + hash_08010357eed60118d2fde019194ad54e5e88a2 + + + port_state + hash_0101033bd7cbe3b533f002ef7b04c509fef56f + hash_0801037536da969953330cd1b6bde9b1b573c9 + + + age + hash_0101033bd7cbe3b533f002ef7b04c509fef56f + hash_080103076808a003c3a037a7cfb7b6403b4e44 + + + + + title + 1 + |host_description| - |query_fabricPort| - State + + + + + name + hash_0101033bd7cbe3b533f002ef7b04c509fef56f + 1 + |host_description| - |query_fabricPort| - State + + + + + hash_000103e2b006fc045a23494936c8b508787164 + Alert Rates + + + symbol_err_rate + hash_01010357eca64389327b00c00ae69c15d4206a + hash_08010383915d834b93bf89e7c0e03da5b154ca + + + rcv_err_rate + hash_01010357eca64389327b00c00ae69c15d4206a + hash_080103acd251e07977f2ada5c8c1c0a33008cb + + + link_downed_rate + hash_01010357eca64389327b00c00ae69c15d4206a + hash_080103d546b4d7196d1e2d6384abae98038b9b + + + xmit_discard_rate + hash_01010357eca64389327b00c00ae69c15d4206a + hash_08010370dafcadf14932e26dfca224c9cb7e6b + + + xmit_wait_rate + hash_01010357eca64389327b00c00ae69c15d4206a + hash_080103feef34aa2b9e5a07509f3cec201c8bdc + + + + + title + 1 + |host_description| - |query_fabricPort| - Alert Rates + + + + + name + hash_01010357eca64389327b00c00ae69c15d4206a + 1 + |host_description| - |query_fabricPort| - Alert Rates + + + + + + + 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 + + + + + Fabric Port Traffic + + + + + |host_description| - |query_fabricPort| - Traffic (bytes per second) + + bytes per second + + 1 + + 150 + + 600 + + 1000 + + on + + on + + 2 + + + + + + + + 100 + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + 30 + + + + + + + + 5 + hash_0801033fa2d992cc4dc70c9495f2fb395fb7a7 + 2471A3 + FF + 1 + hash_0501039b55760f76924fd005060c4cca2fb421 + 0 + + + 0 + + Transmitted, data counter times 4 octets + + 0.00 + + + 1 + + + 11 + hash_0801033fa2d992cc4dc70c9495f2fb395fb7a7 + 0 + FF + 1 + hash_0501039b55760f76924fd005060c4cca2fb421 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Current: + + 0.00 + + + 2 + + + 14 + hash_0801033fa2d992cc4dc70c9495f2fb395fb7a7 + 0 + FF + 1 + hash_0501039b55760f76924fd005060c4cca2fb421 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Average: + + 0.00 + + + 3 + + + 12 + hash_0801033fa2d992cc4dc70c9495f2fb395fb7a7 + 0 + FF + 1 + hash_0501039b55760f76924fd005060c4cca2fb421 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Maximum: + on + 0.00 + + + 4 + + + 5 + hash_0801035c4da6609fb80bf7408521d936818cda + 1E8449 + FF + 1 + hash_0501039b55760f76924fd005060c4cca2fb421 + 0 + + + 0 + + Received, data counter times 4 octets + + 0.00 + + + 5 + + + 11 + hash_0801035c4da6609fb80bf7408521d936818cda + 0 + FF + 1 + hash_0501039b55760f76924fd005060c4cca2fb421 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Current: + + 0.00 + + + 6 + + + 14 + hash_0801035c4da6609fb80bf7408521d936818cda + 0 + FF + 1 + hash_0501039b55760f76924fd005060c4cca2fb421 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Average: + + 0.00 + + + 7 + + + 12 + hash_0801035c4da6609fb80bf7408521d936818cda + 0 + FF + 1 + hash_0501039b55760f76924fd005060c4cca2fb421 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Maximum: + on + 0.00 + + + 8 + + + 14 + hash_080103da7fca12d019dd1f1d43088be7dba564 + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Packets transmitted per second, average: + on + 0.00 + + + 9 + + + 14 + hash_080103445e0e10ce794df781e2a069b0403855 + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Packets received per second, average: + on + 0.00 + + + 10 + + + + + First Item Color + The color of the first item + color_id + hash_000103b99cdd277842c2c0d555045a8ab5ef8a + + + + + Fabric Port Errors + + + + + |host_description| - |query_fabricPort| - Link and Receive Errors (per second) + + errors per second + + 1 + + 150 + + 600 + + 1000 + + on + + on + + 2 + + + + + + + + 100 + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + 30 + + + + + + + + 4 + hash_080103d8feb0a6bace476466c09391853b8277 + C0392B + FF + 1 + 0 + 0 + + + 0 + + Symbol errors + + 0.00 + + + 1 + + + 14 + hash_080103d8feb0a6bace476466c09391853b8277 + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Average: + + 0.00 + + + 2 + + + 12 + hash_080103d8feb0a6bace476466c09391853b8277 + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Maximum: + on + 0.00 + + + 3 + + + 4 + hash_0801031596f44564e8d1f4dc7b2e72b4276254 + E67E22 + FF + 1 + 0 + 0 + + + 0 + + Link error recoveries + + 0.00 + + + 4 + + + 14 + hash_0801031596f44564e8d1f4dc7b2e72b4276254 + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Average: + + 0.00 + + + 5 + + + 12 + hash_0801031596f44564e8d1f4dc7b2e72b4276254 + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Maximum: + on + 0.00 + + + 6 + + + 4 + hash_0801038dc42409271f093787a663fd50d4c902 + F1C40F + FF + 1 + 0 + 0 + + + 0 + + Link downed events + + 0.00 + + + 7 + + + 14 + hash_0801038dc42409271f093787a663fd50d4c902 + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Average: + + 0.00 + + + 8 + + + 12 + hash_0801038dc42409271f093787a663fd50d4c902 + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Maximum: + on + 0.00 + + + 9 + + + 4 + hash_0801031607505da822ed07880d0e74e344fffa + 27AE60 + FF + 1 + 0 + 0 + + + 0 + + Receive errors + + 0.00 + + + 10 + + + 14 + hash_0801031607505da822ed07880d0e74e344fffa + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Average: + + 0.00 + + + 11 + + + 12 + hash_0801031607505da822ed07880d0e74e344fffa + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Maximum: + on + 0.00 + + + 12 + + + 4 + hash_080103f17f2687ed6aab36af7de22cb8f12515 + 16A085 + FF + 1 + 0 + 0 + + + 0 + + Receive remote physical errors + + 0.00 + + + 13 + + + 14 + hash_080103f17f2687ed6aab36af7de22cb8f12515 + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Average: + + 0.00 + + + 14 + + + 12 + hash_080103f17f2687ed6aab36af7de22cb8f12515 + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Maximum: + on + 0.00 + + + 15 + + + 4 + hash_0801031d46010ab0c4f19cae3cef8f2fe48405 + 2980B9 + FF + 1 + 0 + 0 + + + 0 + + Receive switch relay errors + + 0.00 + + + 16 + + + 14 + hash_0801031d46010ab0c4f19cae3cef8f2fe48405 + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Average: + + 0.00 + + + 17 + + + 12 + hash_0801031d46010ab0c4f19cae3cef8f2fe48405 + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Maximum: + on + 0.00 + + + 18 + + + 4 + hash_080103bf438aab6a729dfc2e7631df0ec8aef5 + 8E44AD + FF + 1 + 0 + 0 + + + 0 + + Local link integrity errors + + 0.00 + + + 19 + + + 14 + hash_080103bf438aab6a729dfc2e7631df0ec8aef5 + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Average: + + 0.00 + + + 20 + + + 12 + hash_080103bf438aab6a729dfc2e7631df0ec8aef5 + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Maximum: + on + 0.00 + + + 21 + + + 4 + hash_080103306da2354c30b91ba2b0ed34f82088d8 + 7F8C8D + FF + 1 + 0 + 0 + + + 0 + + Excessive buffer overruns + + 0.00 + + + 22 + + + 14 + hash_080103306da2354c30b91ba2b0ed34f82088d8 + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Average: + + 0.00 + + + 23 + + + 12 + hash_080103306da2354c30b91ba2b0ed34f82088d8 + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Maximum: + on + 0.00 + + + 24 + + + 4 + hash_080103e2eadb6d5d97ab6521be7c34357ba612 + 2C3E50 + FF + 1 + 0 + 0 + + + 0 + + VL15 packets dropped + + 0.00 + + + 25 + + + 14 + hash_080103e2eadb6d5d97ab6521be7c34357ba612 + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Average: + + 0.00 + + + 26 + + + 12 + hash_080103e2eadb6d5d97ab6521be7c34357ba612 + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Maximum: + on + 0.00 + + + 27 + + + + + First Item Color + The color of the first item + color_id + hash_000103eb131f2ed6c75e0552a69ea9c2136e33 + + + + + Fabric Port Congestion + + + + + |host_description| - |query_fabricPort| - Congestion and Transmit Discards (per second) + + ticks or packets per second + + 1 + + 150 + + 600 + + 1000 + + on + + on + + 2 + + + + + + + + 100 + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + 30 + + + + + + + + 5 + hash_08010394fd05fa64be09969185da35aac21914 + C0392B + FF + 1 + 0 + 0 + + + 0 + + Transmit wait, ticks with data queued but no credit or arbitration + + 0.00 + + + 1 + + + 14 + hash_08010394fd05fa64be09969185da35aac21914 + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Average: + + 0.00 + + + 2 + + + 12 + hash_08010394fd05fa64be09969185da35aac21914 + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Maximum: + on + 0.00 + + + 3 + + + 4 + hash_080103669230a4bf849b874910b6e35973f9f8 + 7D3C98 + FF + 1 + 0 + 0 + + + 0 + + Transmit discards, packets + + 0.00 + + + 4 + + + 14 + hash_080103669230a4bf849b874910b6e35973f9f8 + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Average: + + 0.00 + + + 5 + + + 12 + hash_080103669230a4bf849b874910b6e35973f9f8 + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Maximum: + on + 0.00 + + + 6 + + + 4 + hash_0801034f0869447fd31ee70dc066dc0ad00c80 + B9770E + FF + 1 + 0 + 0 + + + 0 + + Transmit constraint errors, packets + + 0.00 + + + 7 + + + 14 + hash_0801034f0869447fd31ee70dc066dc0ad00c80 + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Average: + + 0.00 + + + 8 + + + 12 + hash_0801034f0869447fd31ee70dc066dc0ad00c80 + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Maximum: + on + 0.00 + + + 9 + + + 4 + hash_080103aef73b07a531d7a26c28625065517335 + 117A65 + FF + 1 + 0 + 0 + + + 0 + + Receive constraint errors, packets + + 0.00 + + + 10 + + + 14 + hash_080103aef73b07a531d7a26c28625065517335 + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Average: + + 0.00 + + + 11 + + + 12 + hash_080103aef73b07a531d7a26c28625065517335 + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Maximum: + on + 0.00 + + + 12 + + + + + First Item Color + The color of the first item + color_id + hash_000103bc80c3a713636c69ce450676d34b1cf7 + + + + + Fabric Port State + + + + + |host_description| - |query_fabricPort| - Link State + + lanes, rank, or state + + 1 + + 150 + + 600 + + 1000 + + on + + on + + 2 + + + + + + + + 100 + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + 30 + + + + + + + + 5 + hash_080103e02ceae4350458fa1256323f3879d7cb + 2471A3 + FF + 1 + 0 + 0 + + + 0 + + Active lanes + + 0.00 + + + 1 + + + 11 + hash_080103e02ceae4350458fa1256323f3879d7cb + 0 + FF + 1 + 0 + 0 + + + hash_060103d12e4481082abc5c6225a80571377870 + + Current: + on + 0.00 + + + 2 + + + 4 + hash_08010364c667f6de865c096cf59ab47bc1415f + 1E8449 + FF + 1 + 0 + 0 + + + 0 + + Active speed rank, 1 SDR to 9 XDR + + 0.00 + + + 3 + + + 11 + hash_08010364c667f6de865c096cf59ab47bc1415f + 0 + FF + 1 + 0 + 0 + + + hash_060103d12e4481082abc5c6225a80571377870 + + Current: + on + 0.00 + + + 4 + + + 5 + hash_08010357eed60118d2fde019194ad54e5e88a2 + C0392B + FF + 1 + 0 + 0 + + + 0 + + Degraded, 1 when below best and not explained + + 0.00 + + + 5 + + + 11 + hash_08010357eed60118d2fde019194ad54e5e88a2 + 0 + FF + 1 + 0 + 0 + + + hash_060103d12e4481082abc5c6225a80571377870 + + Current: + on + 0.00 + + + 6 + + + 4 + hash_0801037536da969953330cd1b6bde9b1b573c9 + 7F8C8D + FF + 1 + 0 + 0 + + + 0 + + Logical state, 1 Down to 4 Active + + 0.00 + + + 7 + + + 11 + hash_0801037536da969953330cd1b6bde9b1b573c9 + 0 + FF + 1 + 0 + 0 + + + hash_060103d12e4481082abc5c6225a80571377870 + + Current: + on + 0.00 + + + 8 + + + 11 + hash_080103076808a003c3a037a7cfb7b6403b4e44 + 0 + FF + 1 + 0 + 0 + + + hash_060103d12e4481082abc5c6225a80571377870 + + Seconds since the last sample: + on + 0.00 + + + 9 + + + + + First Item Color + The color of the first item + color_id + hash_000103347a1aa184b3f9dad990862b01c94401 + + + + + Fabric Port Alert Rates + + + + + |host_description| - |query_fabricPort| - Alert Rates (per second) + + per second + + 1 + + 150 + + 600 + + 1000 + + on + + on + + 2 + + + + + + + + 100 + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + 30 + + + + + + + + 4 + hash_08010383915d834b93bf89e7c0e03da5b154ca + C0392B + FF + 1 + 0 + 0 + + + 0 + + Symbol errors + + 0.00 + + + 1 + + + 14 + hash_08010383915d834b93bf89e7c0e03da5b154ca + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Average: + + 0.00 + + + 2 + + + 12 + hash_08010383915d834b93bf89e7c0e03da5b154ca + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Maximum: + on + 0.00 + + + 3 + + + 4 + hash_080103acd251e07977f2ada5c8c1c0a33008cb + E67E22 + FF + 1 + 0 + 0 + + + 0 + + Receive errors + + 0.00 + + + 4 + + + 14 + hash_080103acd251e07977f2ada5c8c1c0a33008cb + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Average: + + 0.00 + + + 5 + + + 12 + hash_080103acd251e07977f2ada5c8c1c0a33008cb + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Maximum: + on + 0.00 + + + 6 + + + 4 + hash_080103d546b4d7196d1e2d6384abae98038b9b + 8E44AD + FF + 1 + 0 + 0 + + + 0 + + Link downed events + + 0.00 + + + 7 + + + 14 + hash_080103d546b4d7196d1e2d6384abae98038b9b + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Average: + + 0.00 + + + 8 + + + 12 + hash_080103d546b4d7196d1e2d6384abae98038b9b + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Maximum: + on + 0.00 + + + 9 + + + 4 + hash_08010370dafcadf14932e26dfca224c9cb7e6b + 2980B9 + FF + 1 + 0 + 0 + + + 0 + + Transmit discards + + 0.00 + + + 10 + + + 14 + hash_08010370dafcadf14932e26dfca224c9cb7e6b + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Average: + + 0.00 + + + 11 + + + 12 + hash_08010370dafcadf14932e26dfca224c9cb7e6b + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Maximum: + on + 0.00 + + + 12 + + + 4 + hash_080103feef34aa2b9e5a07509f3cec201c8bdc + 7F8C8D + FF + 1 + 0 + 0 + + + 0 + + Transmit wait ticks + + 0.00 + + + 13 + + + 14 + hash_080103feef34aa2b9e5a07509f3cec201c8bdc + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Average: + + 0.00 + + + 14 + + + 12 + hash_080103feef34aa2b9e5a07509f3cec201c8bdc + 0 + FF + 1 + 0 + 0 + + + hash_0601035a0a9db1ad5e700d03b3cbbedb1e9edb + + Maximum: + on + 0.00 + + + 15 + + + + + First Item Color + The color of the first item + color_id + hash_000103a191b75d520d1a20bfb47d5113bbd36b + + + + + Fabric Port Traffic + + |host_description| - |query_fabricPort| - Traffic + + hash_030103332111d8b54ac8ce939af87a7eac0c06 + + hash_200103d62c52891f4f9688729a5bc9fad91b18 + + 300 + + on + + + + xmit_data + 0 + 100000000000 + 3 + 600 + 0 + + + rcv_data + 0 + 100000000000 + 3 + 600 + 0 + + + xmit_pkts + 0 + 20000000000 + 3 + 600 + 0 + + + rcv_pkts + 0 + 20000000000 + 3 + 600 + 0 + + + + + hash_070103172b4b0eacee4948c6479f587b62e512 + on + + + + hash_07010330fb5d5bcf3d66bb5abe88596f357c26 + on + + + + hash_07010331112c85ae4ff821d3b288336288818c + on + + + + + + Fabric Port Errors + + |host_description| - |query_fabricPort| - Errors + + hash_030103332111d8b54ac8ce939af87a7eac0c06 + + hash_200103d62c52891f4f9688729a5bc9fad91b18 + + 300 + + on + + + + symbol_err + 0 + 1000000 + 3 + 600 + 0 + + + link_err_recov + 0 + 1000000 + 3 + 600 + 0 + + + link_downed + 0 + 1000000 + 3 + 600 + 0 + + + rcv_err + 0 + 1000000 + 3 + 600 + 0 + + + rcv_remote_phys + 0 + 1000000 + 3 + 600 + 0 + + + rcv_switch_relay + 0 + 1000000 + 3 + 600 + 0 + + + local_link_integ + 0 + 1000000 + 3 + 600 + 0 + + + buffer_overrun + 0 + 1000000 + 3 + 600 + 0 + + + vl15_dropped + 0 + 1000000 + 3 + 600 + 0 + + + + + hash_070103172b4b0eacee4948c6479f587b62e512 + on + + + + hash_07010330fb5d5bcf3d66bb5abe88596f357c26 + on + + + + hash_07010331112c85ae4ff821d3b288336288818c + on + + + + + + Fabric Port Congestion + + |host_description| - |query_fabricPort| - Congestion + + hash_030103332111d8b54ac8ce939af87a7eac0c06 + + hash_200103d62c52891f4f9688729a5bc9fad91b18 + + 300 + + on + + + + xmit_wait + 0 + 1000000000000 + 3 + 600 + 0 + + + xmit_discards + 0 + 1000000 + 3 + 600 + 0 + + + xmit_constraint + 0 + 1000000 + 3 + 600 + 0 + + + rcv_constraint + 0 + 1000000 + 3 + 600 + 0 + + + + + hash_070103172b4b0eacee4948c6479f587b62e512 + on + + + + hash_07010330fb5d5bcf3d66bb5abe88596f357c26 + on + + + + hash_07010331112c85ae4ff821d3b288336288818c + on + + + + + + Fabric Port State + + |host_description| - |query_fabricPort| - State + + hash_030103332111d8b54ac8ce939af87a7eac0c06 + + hash_200103d62c52891f4f9688729a5bc9fad91b18 + + 300 + + on + + + + active_lanes + 0 + 12 + 1 + 600 + 0 + + + speed_rank + 0 + 9 + 1 + 600 + 0 + + + degraded + 0 + 1 + 1 + 600 + 0 + + + port_state + 0 + 4 + 1 + 600 + 0 + + + age + 0 + U + 1 + 600 + 0 + + + + + hash_070103172b4b0eacee4948c6479f587b62e512 + on + + + + hash_07010330fb5d5bcf3d66bb5abe88596f357c26 + on + + + + hash_07010331112c85ae4ff821d3b288336288818c + on + + + + + + Fabric Port Alert Rates + + |host_description| - |query_fabricPort| - Alert Rates + + hash_030103332111d8b54ac8ce939af87a7eac0c06 + + hash_200103d62c52891f4f9688729a5bc9fad91b18 + + 300 + + on + + + + symbol_err_rate + 0 + U + 1 + 600 + 0 + + + rcv_err_rate + 0 + U + 1 + 600 + 0 + + + link_downed_rate + 0 + U + 1 + 600 + 0 + + + xmit_discard_rate + 0 + U + 1 + 600 + 0 + + + xmit_wait_rate + 0 + U + 1 + 600 + 0 + + + + + hash_070103172b4b0eacee4948c6479f587b62e512 + on + + + + hash_07010330fb5d5bcf3d66bb5abe88596f357c26 + on + + + + hash_07010331112c85ae4ff821d3b288336288818c + on + + + + + + Fabric Words to Bytes + + + 1 + 6 + CURRENT_DATA_SOURCE,4,* + + + + + Fabric Number + %8.2lf %s + + + Fabric Integer + %5.0lf + + \ No newline at end of file diff --git a/tests/Integration/LifecycleTest.php b/tests/Integration/LifecycleTest.php index 3822106..3c6c04e 100644 --- a/tests/Integration/LifecycleTest.php +++ b/tests/Integration/LifecycleTest.php @@ -29,7 +29,7 @@ // What the seed action leaves: one fabric and one node. const FABRIC_SEEDED = ['plugin_fabric_claim' => 0, 'plugin_fabric_fabric' => 1, 'plugin_fabric_health' => 0, 'plugin_fabric_node' => 1, 'plugin_fabric_node_sweep' => 0, 'plugin_fabric_port' => 0, 'plugin_fabric_relink' => 0, 'plugin_fabric_sample' => 0]; -const FABRIC_HOOKS = ['config_arrays', 'config_settings', 'draw_navigation_text']; +const FABRIC_HOOKS = ['config_arrays', 'config_settings', 'device_remove', 'draw_navigation_text']; beforeEach(function () { lifecycle('reset'); @@ -44,7 +44,7 @@ expect($state['plugin']['status'])->toEqual('4') ->and($state['plugin']['version'])->toEqual(FABRIC_VERSION) - ->and($state['schema'])->toEqual('1') + ->and($state['schema'])->toEqual('2') ->and(array_keys($state['tables']))->toBe(FABRIC_TABLES) ->and($state['tracked'])->toBe(FABRIC_TABLES) ->and(array_keys($state['hooks']))->toBe(FABRIC_HOOKS) @@ -129,7 +129,7 @@ expect($state['result'])->toBeTrue() ->and(array_keys($state['tables']))->toBe(FABRIC_TABLES) ->and($state['tables']['plugin_fabric_node'])->toBe(1) - ->and($state['schema'])->toEqual('1') + ->and($state['schema'])->toEqual('2') ->and($state['plugin']['version'])->toEqual(FABRIC_VERSION); }); @@ -142,7 +142,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 () { @@ -266,3 +266,56 @@ ->and($r['steps']['hostile']['links_skipped'])->toBe(3) ->and($r['steps']['hostile']['kept'])->toBeTrue(); }); + +it('migrates a version 1 sample table to version 2 and keeps its rows', function () { + lifecycle('install'); + lifecycle('seed'); + lifecycle('drop_v2_columns'); + lifecycle('seed_sample'); + lifecycle('set_schema', '1'); + + $state = lifecycle('upgrade'); + $sample = lifecycle('sample')['result']; + + expect($state['result'])->toBeTrue() + ->and($state['schema'])->toEqual('2') + ->and($state['columns'])->toContain('previous_at', 'rates', 'reset', 'discontinuities', 'discontinuity_at') + ->and($state['tables']['plugin_fabric_node'])->toBe(1) + ->and($sample)->toMatchArray([ + 'port_number' => '1', + 'counter_group' => 'basic', + 'observed_at' => '100', + 'attempted_at' => '110', + 'backend' => 'diags', + 'cap_mask' => '7', + 'cap_mask2' => '8', + 'counters' => '{"PortXmitData":"123","PortRcvData":"456"}', + 'error' => '', + 'previous_at' => '0', + 'rates' => '', + 'reset' => '', + 'discontinuities' => '0', + 'discontinuity_at' => '0', + ]); +}); + +it('imports the Cacti objects once, keeps them on a reinstall, and keeps them but not its query file on uninstall', function () { + $installed = lifecycle('install')['objects']; + + expect($installed)->toBe(['host_template' => 1, 'snmp_query' => 1, 'data_template' => 5, 'graph_template' => 5, 'rrd_items' => 27, 'query_file' => true, 'version' => '1']); + + // A template version change imports again, over the same objects. + lifecycle('set_setting', 'fabric_templates_version=0'); + $upgraded = lifecycle('upgrade'); + + expect($upgraded['result'])->toBeTrue() + ->and($upgraded['objects'])->toBe($installed); + + $removed = lifecycle('uninstall')['objects']; + + expect($removed['query_file'])->toBeFalse() + ->and($removed['host_template'])->toBe(1) + ->and($removed['data_template'])->toBe(5); + + expect(lifecycle('install')['objects'])->toBe($installed); +}); diff --git a/tests/Support/FabricGenerator.php b/tests/Support/FabricGenerator.php index 8d6497c..01aea06 100644 --- a/tests/Support/FabricGenerator.php +++ b/tests/Support/FabricGenerator.php @@ -57,6 +57,15 @@ final class FabricGenerator { /** @var array> adapter GUID => port => LID */ public array $portLids = []; + /** + * Counter values that replace the generated ones, in both counter + * groups where the group has the counter, so a test can play a burst, + * a steady count, or a reset. + * + * @var array> "LID:port" => counter => decimal value + */ + public array $counters = []; + public static function forCas(int $cas, int $perSwitch = 32): self { $fabric = new self(); $switches = max(1, (int) ceil($cas / $perSwitch)); @@ -237,6 +246,8 @@ public function perfquery(int $lid, array $ports, bool $extended, ?int $failAt = $out .= sprintf("# Port extended counters: Lid %d port %d (CapMask: 0x%02X CapMask2: 0x%07X)\n", $lid, $port, $capMask, $capMask2); } + $fields = array_replace($fields, array_intersect_key($this->counters[$lid . ':' . $port] ?? [], $fields)); + foreach ($fields as $name => $value) { $out .= $name . ':' . str_repeat('.', 32 - strlen($name)) . $value . "\n"; } diff --git a/tests/Support/FakeTools.php b/tests/Support/FakeTools.php index 5b9bebe..681e0e2 100644 --- a/tests/Support/FakeTools.php +++ b/tests/Support/FakeTools.php @@ -39,10 +39,16 @@ */ final class FakeTools { /** + * Write the tools into $dir. Their fabric, scenario, and call log live + * in $stateDir, by default $dir; a separate one lets the tools sit in a + * root-owned directory, as the plugin requires outside unit tests, + * while the test changes the fabric with state(). + * * @param array $scenario */ - public static function install(string $dir, FabricGenerator $fabric, array $scenario = []): void { - file_put_contents($dir . '/fabric.state', serialize(['fabric' => $fabric, 'scenario' => $scenario])); + public static function install(string $dir, FabricGenerator $fabric, array $scenario = [], ?string $stateDir = null): void { + $stateDir ??= $dir; + self::state($stateDir, $fabric, $scenario); $support = __DIR__; $plugin = dirname(__DIR__, 2); @@ -52,13 +58,22 @@ public static function install(string $dir, FabricGenerator $fabric, array $scen . 'require ' . var_export($plugin . '/include/autoload.php', true) . ";\n" . 'require ' . var_export($support . '/FabricGenerator.php', true) . ";\n" . 'require ' . var_export($support . '/FakeTools.php', true) . ";\n" - . 'exit(\\Somethingwithproof\\Fabric\\Tests\\FakeTools::main(' . var_export($tool, true) . ', __DIR__, array_slice($argv, 1)));' . "\n"; + . 'exit(\\Somethingwithproof\\Fabric\\Tests\\FakeTools::main(' . var_export($tool, true) . ', ' . var_export($stateDir, true) . ', array_slice($argv, 1)));' . "\n"; file_put_contents($dir . '/' . $tool, $script); chmod($dir . '/' . $tool, 0750); } } + /** + * Replace the fabric and scenario the installed tools play. + * + * @param array $scenario + */ + public static function state(string $stateDir, FabricGenerator $fabric, array $scenario = []): void { + file_put_contents($stateDir . '/fabric.state', serialize(['fabric' => $fabric, 'scenario' => $scenario])); + } + /** * Every recorded call: tool, argv, environment. * diff --git a/tests/Unit/BootTest.php b/tests/Unit/BootTest.php index 5f163e8..048c051 100644 --- a/tests/Unit/BootTest.php +++ b/tests/Unit/BootTest.php @@ -38,6 +38,15 @@ ->and(class_exists(Log::class))->toBeTrue(); }); +it('reserves reply time even when the configured script timeout is short', function (string $timeout, float $budget) { + $GLOBALS['__fabric_options']['script_timeout'] = $timeout; + try { + expect(fabric_script_sweep_seconds())->toBe($budget); + } finally { + unset($GLOBALS['__fabric_options']['script_timeout']); + } +})->with([['', 20.0], ['25', 20.0], ['10', 5.0], ['5', 0.0], ['1', 0.0]]); + it('does not refuse or log on a supported runtime', function () { expect(fabric_refuse_unsupported())->toBeFalse() ->and($GLOBALS['__fabric_log'])->toBe([]); @@ -72,5 +81,6 @@ 'config_arrays' => 'fabric_config_arrays', 'config_settings' => 'fabric_config_settings', 'draw_navigation_text' => 'fabric_draw_navigation_text', + 'device_remove' => 'fabric_device_remove', ]); }); diff --git a/tests/Unit/CounterSweepTest.php b/tests/Unit/CounterSweepTest.php index 377d1c8..9331e42 100644 --- a/tests/Unit/CounterSweepTest.php +++ b/tests/Unit/CounterSweepTest.php @@ -121,6 +121,7 @@ function fabric_writes(string $needle): array { $GLOBALS['__fabric_db_exec'] = []; $GLOBALS['__fabric_db_rows'] = []; $GLOBALS['__fabric_log'] = []; + $GLOBALS['__fabric_db_fail'] = []; }); // REQ-SWEEP-003: one command per counter group, switch ports in chunks. @@ -128,6 +129,43 @@ function fabric_writes(string $needle): array { $GLOBALS['__fabric_scratch']->remove(); }); +it('fails a port whose sample write is lost as storage, not as read', function () { + fabric_queue_ports([1 => 0, 2 => 0]); + $GLOBALS['__fabric_db_fail'] = ["counters = VALUES(counters), error = ''"]; + + $result = fabric_sweeper(new ScriptedRunner(FabricGenerator::forCas(1)))->run(fabric_sweep_fabric(), fabric_node('switch', 1), 'test'); + + expect($result?->error)->toBe(CommandError::Storage) + ->and($result?->read)->toBe(0) + ->and($result?->failed)->toBe(2); +}); + +it('starts no tool once the sweep deadline is spent, and caps each run at the time left', function () { + fabric_queue_ports([1 => 0]); + $dir = (string) realpath($GLOBALS['__fabric_scratch']->dir); + $runner = new ScriptedRunner(FabricGenerator::forCas(1)); + $late = new CounterSweep(false, new FixedClock(1_800_000_000), $runner, Settings::fromRow(['fabric_tool_dir' => $dir]), (int) fileowner($dir), microtime(true) - 1); + + expect($late->run(fabric_sweep_fabric(), fabric_node('switch', 1), 'test')?->read)->toBe(0) + ->and($runner->argv)->toBe([]); + + $limits = new class () implements ProcessRunner { + /** @var list */ + public array $timeouts = []; + + public function run(Command $command, float $timeout, int $maxBytes): ProcessResult { + $this->timeouts[] = $timeout; + + return new ProcessResult(0, '', '', false, false, true, 0.0); + } + }; + $settings = Settings::fromRow(['fabric_command_timeout' => 60, 'fabric_tool_dir' => $dir]); + $tools = new \Somethingwithproof\Fabric\ToolRunner($limits, $settings, microtime(true) + 8); + $tools->run((new \Somethingwithproof\Fabric\CommandBuilder($settings, fabric_sweep_fabric()))->counters(1, [1], false)); + + expect($limits->timeouts[0])->toBeLessThanOrEqual(8.0)->toBeGreaterThan(6.0); +}); + it('runs no tool from a tool directory that fails the checks', function () { fabric_queue_ports([1 => 0]); $runner = new ScriptedRunner(FabricGenerator::forCas(1)); @@ -242,6 +280,27 @@ function fabric_writes(string $needle): array { ->and($runner->argv)->toBe([]); }); +it('keeps reading an addressable sibling across sweeps with a port without a LID', function () { + fabric_queue_ports([1 => 3, 2 => 0]); + $rows = []; + $dir = (string) realpath($GLOBALS['__fabric_scratch']->dir); + for ($cycle = 1; $cycle <= 4; $cycle++) { + $GLOBALS['__fabric_db_rows']['FROM plugin_fabric_sample'] = array_values($rows); + $GLOBALS['__fabric_db_exec'] = []; + $runner = new ScriptedRunner(FabricGenerator::forCas(1), capMask: 0); + $sweep = new CounterSweep(false, new FixedClock(1_800_000_000 + $cycle * 300), $runner, Settings::fromRow(['fabric_tool_dir' => $dir, 'fabric_failure_budget' => '1']), (int) fileowner($dir)); + $result = $sweep->run(fabric_sweep_fabric(), fabric_node('ca', 0), 'cycle-' . $cycle); + expect($result?->read)->toBe(1) + ->and($result->failed)->toBe(1) + ->and($runner->argv)->toHaveCount(1); + foreach (fabric_writes('INSERT INTO plugin_fabric_sample') as $write) { + $p = $write['params']; + $rows[$p[1]] = ['port_number' => $p[1], 'counter_group' => $p[2], 'attempted_at' => $p[3]]; + } + expect($rows[2]['attempted_at'])->toBe(1_800_000_000 + $cycle * 300); + } +}); + it('logs the failure with a cleaned stderr excerpt and never the output', function () { fabric_queue_ports([1 => 0, 2 => 0]); $runner = new ScriptedRunner(FabricGenerator::forCas(1), failAt: [1 => 2]); @@ -305,3 +364,55 @@ function fabric_writes(string $needle): array { ->and(fabric_writes('ROLLBACK'))->toHaveCount(1) ->and(fabric_writes('COMMIT'))->toBe([]); }); + +it('resumes with ports left unread by a previous capped sweep', function () { + fabric_queue_ports([1 => 3, 2 => 4]); + $runner = new ScriptedRunner(FabricGenerator::forCas(1), modes: [3 => 'timeout', 4 => 'timeout']); + fabric_sweeper($runner, ['fabric_failure_budget' => '1'])->run(fabric_sweep_fabric(), fabric_node('ca', 0), 'test'); + $attempt = fabric_writes('INSERT INTO plugin_fabric_sample')[0]['params']; + $GLOBALS['__fabric_db_rows']['FROM plugin_fabric_sample'] = [[ + 'port_number' => $attempt[1], 'counter_group' => $attempt[2], 'attempted_at' => $attempt[3], + ]]; + $next = new ScriptedRunner(FabricGenerator::forCas(1)); + fabric_sweeper($next)->run(fabric_sweep_fabric(), fabric_node('ca', 0), 'next'); + expect(array_slice($runner->argv[0], -2))->toBe(['3', '1']) + ->and(array_slice($next->argv[0], -2))->toBe(['4', '2']); +}); + +it('reads extended counters before repeating a newer basic sweep', function () { + fabric_queue_ports([1 => 0, 2 => 0]); + $GLOBALS['__fabric_db_rows']['FROM plugin_fabric_sample'] = [ + ['port_number' => 1, 'counter_group' => 'basic', 'attempted_at' => 100, 'cap_mask' => 0x1600], + ['port_number' => 2, 'counter_group' => 'basic', 'attempted_at' => 100, 'cap_mask' => 0x1600], + ['port_number' => 1, 'counter_group' => 'extended', 'attempted_at' => 50], + ]; + $runner = new ScriptedRunner(FabricGenerator::forCas(1)); + fabric_sweeper($runner)->run(fabric_sweep_fabric(), fabric_node('switch', 1), 'test'); + expect($runner->argv[0])->toContain('-x') + ->and(end($runner->argv[0]))->toBe('2,1') + ->and($runner->argv[1])->not->toContain('-x'); +}); + +it('reserves counter time when topology is due on every script-server call', function () { + fabric_queue_ports([1 => 0]); + $node = ['id' => 9, 'fabric_id' => 1, 'guid' => '0x0002c90300a00000', 'node_type' => 'switch', 'lid' => 1, 'presence' => 'present', 'identity' => 'ok']; + $GLOBALS['__fabric_db_rows']['FROM plugin_fabric_node WHERE host_id'] = [$node]; + $GLOBALS['__fabric_db_rows']['FROM plugin_fabric_node WHERE id = '] = [$node]; + $GLOBALS['__fabric_db_rows']['FROM plugin_fabric_fabric'] = [['id' => 1, 'name' => 'ib0', 'backend' => 'diags', 'poller_id' => 1, 'sweep_interval' => 300, 'adapter' => 'mlx5_0', 'adapter_port' => 1, 'admin_state' => 'enabled']]; + $runner = new class () implements ProcessRunner { + public array $limits = []; + public function run(Command $command, float $timeout, int $maxBytes): ProcessResult { + $this->limits[$command->tool->value][] = $timeout; + return new ProcessResult(null, '', '', true, false, true, $timeout); + } + }; + $dir = (string) realpath($GLOBALS['__fabric_scratch']->dir); + foreach (['ibnetdiscover', 'iblinkinfo', 'perfquery'] as $tool) { + file_put_contents($dir . '/' . $tool, ''); + chmod($dir . '/' . $tool, 0755); + } + $sweep = new \Somethingwithproof\Fabric\Sweep(false, new FixedClock(1_800_000_000), $runner, Settings::fromRow(['fabric_tool_dir' => $dir, 'fabric_command_timeout' => 60]), 1, true, (int) fileowner($dir), microtime(true) + 12); + $sweep->forDevice(7); + expect($runner->limits['ibnetdiscover'][0])->toBeLessThanOrEqual(4.0) + ->and($runner->limits['perfquery'][0])->toBeGreaterThan(8.0); +}); diff --git a/tests/Unit/PortQueryTest.php b/tests/Unit/PortQueryTest.php new file mode 100644 index 0000000..54d773b --- /dev/null +++ b/tests/Unit/PortQueryTest.php @@ -0,0 +1,265 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_fabric, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_fabric + * + * 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\Fabric\CounterDelta; +use Somethingwithproof\Fabric\CounterGroup; +use Somethingwithproof\Fabric\Counters; +use Somethingwithproof\Fabric\Decimal; +use Somethingwithproof\Fabric\FixedClock; +use Somethingwithproof\Fabric\PortQuery; +use Somethingwithproof\Fabric\PortValues; + +/* + * Counter series, rates, discontinuities, and what the Fabric Port data + * query publishes for them (REQ-CTR-001 to REQ-CTR-006, REQ-DISC-001, + * REQ-DISC-002, REQ-IDX-001 to REQ-IDX-003, REQ-ALERT-001, REQ-ALERT-002). + */ + +const FABRIC_T0 = 1_800_000_000; +const FABRIC_NODE = '0x0002c90300a00000'; + +/** + * @param array $values + */ +function fabric_counters(CounterGroup $group, array $values, int $capMask = 0x1600): Counters { + return new Counters($group, 7, 1, $capMask, $group === CounterGroup::Extended ? 2 : null, $values); +} + +/** + * A sample row as SampleRepository stores it, from two consecutive reads. + * + * @param array $now + * @param array|null $before + * + * @return array + */ +function fabric_sample_row(CounterGroup $group, array $now, ?array $before, int $at, int $beforeAt = 0, int $capMask = 0x1600, int $port = 1): array { + $delta = CounterDelta::between($before, $beforeAt, fabric_counters($group, $now, $capMask), $at); + + return [ + 'node_id' => 9, 'port_number' => $port, 'counter_group' => $group->value, 'observed_at' => $at, 'attempted_at' => $at, 'cap_mask' => $capMask, + 'counters' => json_encode($now), 'rates' => $delta->ratesJson(), 'reset' => $delta->resetJson(), 'discontinuities' => $delta->reset === [] ? 0 : 1, 'discontinuity_at' => $delta->reset === [] ? 0 : $at, 'error' => '', + ]; +} + +/** + * Queue one switch node mapped to device 5 with the given ports and samples. + * + * @param list> $ports + * @param list> $samples + */ +function fabric_queue_host(array $ports, array $samples): void { + $GLOBALS['__fabric_db_rows'] = [ + 'FROM plugin_fabric_node WHERE host_id' => [['id' => 9, 'fabric_id' => 1, 'guid' => FABRIC_NODE, 'node_type' => 'switch', 'description' => 'leaf01 | evil', 'host_id' => 5, 'presence' => 'present', 'identity' => 'ok']], + 'FROM plugin_fabric_fabric WHERE id' => [['id' => 1, 'name' => 'ib0', 'backend' => 'diags', 'poller_id' => 1, 'sweep_interval' => 300, 'adapter' => 'mlx5_0', 'adapter_port' => 1, 'admin_state' => 'enabled']], + 'FROM plugin_fabric_port' => $ports, + 'FROM plugin_fabric_sample' => $samples, + ]; +} + +/** + * @return array + */ +function fabric_port_row(int $number, string $width = '4', string $speed = 'edr', string $logical = 'active', string $remote = '0x0002c90300b00010', int $observed = FABRIC_T0): array { + return [ + 'node_id' => 9, 'port_number' => $number, 'remote_guid' => $remote, 'remote_port' => $remote === '' ? 0 : 1, 'presence' => 'present', + 'logical_state' => $logical, 'phys_state' => $logical === 'down' ? 'polling' : 'linkup', 'active_width' => $width, 'active_speed' => $speed, 'best_width' => '4', 'best_speed' => 'edr', + 'enabled_width' => 0, 'enabled_speed' => '', 'has_peer' => $remote === '' ? 0 : 1, 'link_observed_at' => $observed, + ]; +} + +function fabric_query(int $now = FABRIC_T0, bool $downPorts = false, ?Closure $sweep = null): PortQuery { + return new PortQuery(false, new FixedClock($now), $downPorts, $sweep); +} + +beforeEach(function () { + $GLOBALS['__fabric_db_rows'] = []; + $GLOBALS['__fabric_db_exec'] = []; +}); + +it('compares and subtracts 64-bit decimal strings exactly', function () { + expect(Decimal::compare('18446744073709551615', '18446744073709551614'))->toBe(1) + ->and(Decimal::compare('9', '10'))->toBe(-1) + ->and(Decimal::compare('4294967295', '4294967295'))->toBe(0) + ->and(Decimal::difference('18446744073709551615', '18446744073709550615'))->toBe(1000.0) + ->and(Decimal::difference('1000000000', '999999999'))->toBe(1.0) + ->and(Decimal::valid('012'))->toBeFalse() + ->and(Decimal::valid('-1'))->toBeFalse(); +}); + +it('computes rates and flags a decrease as a discontinuity, never a negative rate', function () { + $delta = CounterDelta::between(['PortXmitData' => '1000', 'SymbolErrorCounter' => '5', 'PortXmitWait' => null], FABRIC_T0 - 300, fabric_counters(CounterGroup::Basic, ['PortXmitData' => '61000', 'SymbolErrorCounter' => '2', 'PortXmitWait' => null]), FABRIC_T0); + + expect($delta->rates)->toBe(['PortXmitData' => 200.0, 'SymbolErrorCounter' => null, 'PortXmitWait' => null]) + ->and($delta->reset)->toBe(['SymbolErrorCounter']) + ->and($delta->since)->toBe(FABRIC_T0 - 300); +}); + +it('gives a saturated counter no rate, at the cap and on leaving it', function () { + $capped = CounterDelta::between(['LinkDownedCounter' => '250'], FABRIC_T0 - 300, fabric_counters(CounterGroup::Basic, ['LinkDownedCounter' => '255']), FABRIC_T0); + $held = CounterDelta::between(['LinkDownedCounter' => '255'], FABRIC_T0 - 300, fabric_counters(CounterGroup::Basic, ['LinkDownedCounter' => '255']), FABRIC_T0); + $wide = CounterDelta::between(['LinkDownedCounter' => '255'], FABRIC_T0 - 300, fabric_counters(CounterGroup::Extended, ['LinkDownedCounter' => '555']), FABRIC_T0); + + expect($capped->rates['LinkDownedCounter'])->toBeNull() + ->and($held->rates['LinkDownedCounter'])->toBeNull() + ->and($wide->rates['LinkDownedCounter'])->toBe(1.0) + ->and($capped->reset)->toBe([]); +}); + +it('has no rate without a usable previous sample', function () { + expect(CounterDelta::between(null, 0, fabric_counters(CounterGroup::Basic, ['PortRcvErrors' => '3']), FABRIC_T0)->rates['PortRcvErrors'])->toBeNull() + ->and(CounterDelta::between(['PortRcvErrors' => '1'], FABRIC_T0, fabric_counters(CounterGroup::Basic, ['PortRcvErrors' => '3']), FABRIC_T0)->since)->toBe(0) + ->and(CounterDelta::ratesFromJson('{"a":-1,"b":2,"c":"x"}'))->toBe(['b' => 2.0]); +}); + +it('lists one index per port in GUID and port number order, leaving out down ports without a remote end', function () { + fabric_queue_host([fabric_port_row(0), fabric_port_row(2), fabric_port_row(10), fabric_port_row(3, '', '', 'down', '')], []); + + expect(fabric_query()->answer(5, 'index'))->toBe(FABRIC_NODE . ":2\n" . FABRIC_NODE . ":10\n") + ->and(fabric_query()->answer(5, 'num_indexes'))->toBe('2') + ->and(fabric_query(downPorts: true)->answer(5, 'num_indexes'))->toBe('3') + ->and(fabric_query()->answer(0, 'index'))->toBe(''); +}); + +it('answers query lines with the ! delimiter and keeps fabric text from naming Cacti variables', function () { + fabric_queue_host([fabric_port_row(2)], []); + + expect(fabric_query()->answer(5, 'query', 'fabricNode'))->toBe(FABRIC_NODE . ':2!leaf01 evil (' . FABRIC_NODE . ")\n") + ->and(fabric_query()->answer(5, 'query', 'fabricRemote'))->toBe(FABRIC_NODE . ":2!0x0002c90300b00010:1\n") + ->and(fabric_query()->answer(5, 'query', 'no_such_field'))->toBe(''); +}); + +it('publishes counters, rates, and state from a current sample', function () { + $basic = fabric_sample_row(CounterGroup::Basic, ['SymbolErrorCounter' => '30', 'PortXmitData' => '100', 'PortXmitWait' => '900'], ['SymbolErrorCounter' => '0', 'PortXmitData' => '50', 'PortXmitWait' => '0'], FABRIC_T0 - 10, FABRIC_T0 - 310, 0x1000, 2); + fabric_queue_host([fabric_port_row(2)], [$basic]); + $q = fabric_query(); + + expect($q->answer(5, 'get', 'symbol_err', FABRIC_NODE . ':2'))->toBe('30') + ->and($q->answer(5, 'get', 'symbol_err_rate', FABRIC_NODE . ':2'))->toBe('0.1') + ->and($q->answer(5, 'get', 'xmit_wait_rate', FABRIC_NODE . ':2'))->toBe('3') + ->and($q->answer(5, 'get', 'xmit_data', FABRIC_NODE . ':2'))->toBe('100') + ->and($q->answer(5, 'get', 'active_lanes', FABRIC_NODE . ':2'))->toBe('4') + ->and($q->answer(5, 'get', 'speed_rank', FABRIC_NODE . ':2'))->toBe('6') + ->and($q->answer(5, 'get', 'port_state', FABRIC_NODE . ':2'))->toBe('4') + ->and($q->answer(5, 'get', 'degraded', FABRIC_NODE . ':2'))->toBe('0') + ->and($q->answer(5, 'get', 'age', FABRIC_NODE . ':2'))->toBe('10') + ->and($q->answer(5, 'get', 'fabricPortNum', FABRIC_NODE . ':2'))->toBe('2'); +}); + +it('publishes U, never 0, for unsupported, saturated, reset, stale, and unknown values', function () { + $basic = fabric_sample_row(CounterGroup::Basic, ['SymbolErrorCounter' => '65535', 'PortRcvErrors' => '1', 'PortXmitWait' => null, 'LinkDownedCounter' => '4'], ['SymbolErrorCounter' => '60000', 'PortRcvErrors' => '9', 'LinkDownedCounter' => '4'], FABRIC_T0, FABRIC_T0 - 300, 0x0000, 2); + fabric_queue_host([fabric_port_row(2, '1', 'edr')], [$basic]); + $q = fabric_query(); + $i = FABRIC_NODE . ':2'; + + expect($q->answer(5, 'get', 'xmit_wait', $i))->toBe('U') + ->and($q->answer(5, 'get', 'symbol_err', $i))->toBe('U') + ->and($q->answer(5, 'get', 'symbol_err_rate', $i))->toBe('U') + ->and($q->answer(5, 'get', 'rcv_err', $i))->toBe('U') + ->and($q->answer(5, 'get', 'rcv_err_rate', $i))->toBe('U') + ->and($q->answer(5, 'get', 'link_downed_rate', $i))->toBe('0') + ->and($q->answer(5, 'get', 'degraded', $i))->toBe('U') + ->and($q->answer(5, 'get', 'active_lanes', $i))->toBe('1') + ->and($q->answer(5, 'get', 'no_such_field', $i))->toBe('U') + ->and($q->answer(5, 'get', 'symbol_err', FABRIC_NODE . ':99'))->toBe('U') + ->and($q->answer(5, 'get', 'symbol_err', '../../etc/passwd'))->toBe('U'); + + // Stale: counters, rates, and state are unknown; age stays numeric. + $late = fabric_query(FABRIC_T0 + 3000); + + expect($late->answer(5, 'get', 'link_downed', $i))->toBe('U') + ->and($late->answer(5, 'get', 'link_downed_rate', $i))->toBe('U') + ->and($late->answer(5, 'get', 'active_lanes', $i))->toBe('U') + ->and($late->answer(5, 'get', 'age', $i))->toBe('3000'); +}); + +it('reads data counters from the extended group the port supports, even when its read failed', function () { + $basic = fabric_sample_row(CounterGroup::Basic, ['PortXmitData' => '4294967295', 'SymbolErrorCounter' => '1'], null, FABRIC_T0, 0, 0x1600, 2); + $extended = fabric_sample_row(CounterGroup::Extended, ['PortXmitData' => '98765432109876', 'SymbolErrorCounter' => '7'], null, FABRIC_T0, 0, 0x1600, 2); + fabric_queue_host([fabric_port_row(2)], [$basic, $extended]); + + expect(fabric_query()->answer(5, 'get', 'xmit_data', FABRIC_NODE . ':2'))->toBe('98765432109876') + ->and(fabric_query()->answer(5, 'get', 'symbol_err', FABRIC_NODE . ':2'))->toBe('7'); + + $failed = $extended; + $failed['observed_at'] = 0; + $failed['counters'] = ''; + fabric_queue_host([fabric_port_row(2)], [$basic, $failed]); + + // Not the basic counter at its cap: the data source keeps one width. + expect(fabric_query()->answer(5, 'get', 'xmit_data', FABRIC_NODE . ':2'))->toBe('U') + ->and(fabric_query()->answer(5, 'get', 'age', FABRIC_NODE . ':2'))->toBe('0'); +}); + +it('answers never-sampled ports with U for every value, age included', function () { + fabric_queue_host([fabric_port_row(2, observed: 0)], []); + + foreach (PortValues::names() as $name) { + expect(fabric_query()->answer(5, 'get', $name, FABRIC_NODE . ':2'))->toBe('U'); + } +}); + +it('answers U and no indexes when the fabric record cannot be read, never a default interval', function () { + fabric_queue_host([fabric_port_row(2)], []); + unset($GLOBALS['__fabric_db_rows']['FROM plugin_fabric_fabric WHERE id']); + + expect(fabric_query()->answer(5, 'get', 'age', FABRIC_NODE . ':2'))->toBe('U') + ->and(fabric_query()->answer(5, 'index'))->toBe(''); +}); + +it('starts the sweep once per device, only for get', function () { + fabric_queue_host([fabric_port_row(2)], []); + $swept = []; + $q = fabric_query(sweep: function (int $host) use (&$swept): void { + $swept[] = $host; + }); + + $q->answer(5, 'index'); + $q->answer(5, 'query', 'fabricPort'); + $q->answer(5, 'get', 'age', FABRIC_NODE . ':2'); + $q->answer(5, 'get', 'age', FABRIC_NODE . ':2'); + $q->answer(6, 'get', 'age', FABRIC_NODE . ':2'); + + expect($swept)->toBe([5, 6]); +}); + +it('keeps the data query fields, the query XML, and the data source name limit in step', function () { + $xml = simplexml_load_file(dirname(__DIR__, 2) . '/resource/script_server/fabric_ports.xml'); + assert($xml !== false); + $fields = []; + + foreach ($xml->fields->children() as $name => $field) { + $fields[(string) $field->direction][] = $name; + expect((string) $field->query_name)->toBe($name); + } + + expect($fields['input'])->toBe(PortQuery::INPUT_FIELDS) + ->and($fields['output'])->toBe(PortValues::names()) + ->and((string) $xml->output_delimiter)->toBe(PortQuery::DELIMITER) + ->and((string) $xml->index_order)->toBe(PortQuery::INDEX_FIELD) + ->and((string) $xml->arg_num_indexes)->toBe('num_indexes'); + + foreach (PortValues::names() as $name) { + expect(preg_match('/^[a-z0-9_]{1,19}$/', $name))->toBe(1); + } + + foreach (PortValues::COUNTERS + PortValues::RATE_OF as $counter) { + expect(\Somethingwithproof\Fabric\PerfqueryParser::width(CounterGroup::Basic, $counter))->toBeGreaterThan(0); + } +}); diff --git a/tests/Unit/TemplateInstallerTest.php b/tests/Unit/TemplateInstallerTest.php new file mode 100644 index 0000000..455fdbd --- /dev/null +++ b/tests/Unit/TemplateInstallerTest.php @@ -0,0 +1,201 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_fabric, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_fabric + * + * 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\Fabric\CactiObjectRepository; +use Somethingwithproof\Fabric\PortValues; +use Somethingwithproof\Fabric\TemplateInstaller; +use Somethingwithproof\Fabric\Tests\Scratch; + +require_once dirname(__DIR__) . '/Support/Scratch.php'; + +/* + * The shipped Cacti objects and the one file the plugin writes outside its + * own directory (REQ-OBJ-001, REQ-OBJ-002, REQ-OBJ-004, ADR 0011). + */ + +if (!function_exists('set_config_option')) { + function set_config_option($config_name, $value, $remote = false) { + $GLOBALS['__fabric_options'][$config_name] = $value; + } +} + +if (!function_exists('import_xml_data')) { + function import_xml_data($xml_data, $import_as_new, $profile_id = false, $remove_orphans = false, $replace_svalues = false, $import_hashes = array()) { + $GLOBALS['__fabric_imports'][] = $xml_data; + + return ['host_template' => [['result' => 'success']]]; + } +} + +/** + * A plugin copy and a Cacti tree in scratch, and an installer between them + * whose objects are all found. + */ +function fabric_installer(Scratch $scratch): TemplateInstaller { + $scratch->file('plugin/resource/script_server/fabric_ports.xml', "shipped\n"); + $scratch->file('plugin/templates/fabric-templates.xml', "\n"); + $scratch->file('cacti/lib/utility.php', "file('cacti/lib/import.php', "dir . '/cacti/resource/script_server', 0700, true); + $GLOBALS['__fabric_db_rows'] = ['WHERE hash' => [['id' => 3]]]; + + return new TemplateInstaller($scratch->dir . '/plugin', $scratch->dir . '/cacti', new CactiObjectRepository(false)); +} + +function fabric_target(Scratch $scratch): string { + return $scratch->dir . '/cacti/resource/script_server/fabric_ports.xml'; +} + +beforeEach(function () { + $GLOBALS['__fabric_scratch'] = new Scratch(); + $GLOBALS['__fabric_options'] = []; + $GLOBALS['__fabric_imports'] = []; + $GLOBALS['__fabric_log'] = []; + $GLOBALS['__fabric_db_rows'] = []; +}); + +afterEach(function () { + $GLOBALS['__fabric_scratch']->remove(); +}); + +it('writes the query file where none is, records it, and imports the templates', function () { + $installer = fabric_installer($GLOBALS['__fabric_scratch']); + + expect($installer->install())->toBeTrue() + ->and(file_get_contents(fabric_target($GLOBALS['__fabric_scratch'])))->toBe("shipped\n") + ->and($GLOBALS['__fabric_options'][TemplateInstaller::FILES_SETTING])->toBe(hash('sha256', "shipped\n")) + ->and($GLOBALS['__fabric_imports'])->toBe(["\n"]) + ->and($installer->isCurrent())->toBeTrue() + ->and(glob($GLOBALS['__fabric_scratch']->dir . '/cacti/resource/script_server/.*.tmp'))->toBe([]); +}); + +it('replaces its own unchanged file on upgrade and removes it on uninstall', function () { + $scratch = $GLOBALS['__fabric_scratch']; + $installer = fabric_installer($scratch); + $installer->install(); + $scratch->file('plugin/resource/script_server/fabric_ports.xml', "newer\n"); + + expect($installer->install())->toBeTrue() + ->and(file_get_contents(fabric_target($scratch)))->toBe("newer\n"); + + $installer->uninstall(); + + expect(file_exists(fabric_target($scratch)))->toBeFalse(); +}); + +it('never overwrites or removes a file it did not write, or one changed after', function () { + $scratch = $GLOBALS['__fabric_scratch']; + $installer = fabric_installer($scratch); + $scratch->file('cacti/resource/script_server/fabric_ports.xml', "site file\n"); + + expect($installer->install())->toBeFalse() + ->and(file_get_contents(fabric_target($scratch)))->toBe("site file\n") + ->and($installer->failure())->toContain('was not written by this plugin'); + + $installer->uninstall(); + expect(file_get_contents(fabric_target($scratch)))->toBe("site file\n"); + + // Written by the plugin, then edited by an operator. + unlink(fabric_target($scratch)); + $installer->install(); + file_put_contents(fabric_target($scratch), "edited\n"); + $scratch->file('plugin/resource/script_server/fabric_ports.xml', "newer\n"); + + expect($installer->install())->toBeFalse() + ->and(file_get_contents(fabric_target($scratch)))->toBe("edited\n"); + + $installer->uninstall(); + expect(file_get_contents(fabric_target($scratch)))->toBe("edited\n"); +}); + +it('leaves an identical file it did not write unclaimed, so uninstall keeps it', function () { + $scratch = $GLOBALS['__fabric_scratch']; + $installer = fabric_installer($scratch); + $scratch->file('cacti/resource/script_server/fabric_ports.xml', "shipped\n"); + + expect($installer->install())->toBeTrue() + ->and($GLOBALS['__fabric_options'][TemplateInstaller::FILES_SETTING] ?? '')->toBe(''); + + $installer->uninstall(); + expect(file_exists(fabric_target($scratch)))->toBeTrue(); +}); + +it('refuses a symbolic link at the destination, dangling or not, and never writes through it', function (bool $dangling) { + $scratch = $GLOBALS['__fabric_scratch']; + $installer = fabric_installer($scratch); + $elsewhere = $scratch->dir . '/elsewhere.xml'; + + if (!$dangling) { + file_put_contents($elsewhere, "shipped\n"); + } + + symlink($elsewhere, fabric_target($scratch)); + + expect($installer->install())->toBeFalse() + ->and(is_link(fabric_target($scratch)))->toBeTrue() + ->and($installer->failure())->toContain('symbolic link') + ->and($installer->queryFileProblem())->toContain('symbolic link'); + + if ($dangling) { + expect(file_exists($elsewhere))->toBeFalse(); + } else { + expect(file_get_contents($elsewhere))->toBe("shipped\n"); + } + + $installer->uninstall(); + expect(is_link(fabric_target($scratch)))->toBeTrue(); +})->with(['dangling' => true, 'to a file' => false]); + +it('ships templates whose alertable values are all GAUGE and whose counters are DERIVE (ADR 0011)', function () { + $xml = (string) file_get_contents(dirname(__DIR__, 2) . '/templates/fabric-templates.xml'); + + preg_match_all('#([a-z0-9_]+)\s*([^<]*)\s*([^<]*)\s*(\d)#', $xml, $m, PREG_SET_ORDER); + + $types = []; + + foreach ($m as $match) { + $types[$match[1]] = (int) $match[4]; + expect($match[2])->toBe('0', $match[1]); + } + + ksort($types); + $names = PortValues::names(); + sort($names); + + expect(array_keys($types))->toBe($names); + + foreach ($types as $name => $type) { + // 1 GAUGE, 3 DERIVE. Thold reads only GAUGE values safely (a + // COUNTER or DERIVE that reads U makes Thold 1.8.2 fail). + expect($type)->toBe(PortValues::isCounter($name) ? 3 : 1, $name); + } + + foreach (array_keys(PortValues::RATE_OF + array_flip(PortValues::STATE_VALUES)) as $name) { + expect($types[$name])->toBe(1, $name); + } + + foreach (array_keys(PortValues::templates()) as $name) { + expect($xml)->toMatch('//') + ->and($xml)->toContain('' . $name . ''); + } + + expect($xml)->toContain(TemplateInstaller::hash('host_template', TemplateInstaller::DEVICE_TEMPLATE)) + ->and($xml)->toContain('<path_cacti>/resource/script_server/fabric_ports.xml') + ->and($xml)->not->toMatch('/ + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_fabric, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_fabric + * + * 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. + */ + +if (PHP_SAPI !== 'cli') { + exit(1); +} + + +/* + * Build the Fabric templates in a disposable Cacti database with Cacti's + * own save function, and write Cacti's export of them (get_item_xml with + * dependencies) to templates/fabric-templates.xml. The plugin ships that + * export, not this script's data: + * + * FABRIC_TEST_DATABASE=disposable php plugins/fabric/tests/bin/build-templates.php [export-file] + * + * Hashes come from TemplateInstaller::hash(), so a rebuild updates the rows + * it made and exports the same hashes. Must parse on PHP 8.0. + * + * Data source types follow ADR 0011: counters as received are DERIVE with + * minimum 0, so a decrease is unknown rather than a spike, for graphs only; + * the rates the plugin computes and the state values are GAUGE, the only + * values a Thold threshold should use. The maximums are plausibility + * bounds per second, not reset filters: 10^11 words (4 octets) of data, + * about 1.25 times a 12X XDR link; 2 * 10^10 packets; 10^6 errors or + * events; 10^12 transmit wait ticks. + */ + +chdir(dirname(__DIR__, 4)); + +require('./include/cli_check.php'); +require_once($config['base_path'] . '/lib/functions.php'); +require_once($config['base_path'] . '/lib/export.php'); +require_once($config['base_path'] . '/plugins/fabric/setup.php'); + +if (getenv('FABRIC_TEST_DATABASE') !== 'disposable') { + fwrite(STDERR, "Set FABRIC_TEST_DATABASE=disposable\n"); + exit(2); +} + +if (!fabric_boot()) { + fwrite(STDERR, "PHP 8.2 or later is required\n"); + exit(2); +} + +use Somethingwithproof\Fabric\PortValues as V; +use Somethingwithproof\Fabric\TemplateInstaller as T; + +const FABRIC_GAUGE = 1; +const FABRIC_DERIVE = 3; + +/** Core's "Get Script Server Data (Indexed)" input and its three index fields. */ +const FABRIC_INDEXED_INPUT = '332111d8b54ac8ce939af87a7eac0c06'; +const FABRIC_INDEXED_FIELDS = array('172b4b0eacee4948c6479f587b62e512', '30fb5d5bcf3d66bb5abe88596f357c26', '31112c85ae4ff821d3b288336288818c'); + +/** Data source name => [type, maximum]. */ +function fabric_ds_spec($name) { + $state = array('active_lanes' => '12', 'speed_rank' => '9', 'degraded' => '1', 'port_state' => '4', 'age' => 'U'); + + if (isset($state[$name])) { + return array(FABRIC_GAUGE, $state[$name]); + } + + if (isset(V::RATE_OF[$name])) { + return array(FABRIC_GAUGE, 'U'); + } + + switch ($name) { + case 'xmit_data': + case 'rcv_data': + return array(FABRIC_DERIVE, '100000000000'); + case 'xmit_pkts': + case 'rcv_pkts': + return array(FABRIC_DERIVE, '20000000000'); + case 'xmit_wait': + return array(FABRIC_DERIVE, '1000000000000'); + default: + return array(FABRIC_DERIVE, '1000000'); + } +} + +function fabric_save($table, array $row) { + $id = (int) db_fetch_cell_prepared("SELECT id FROM `$table` WHERE hash = ?", array($row['hash'])); + + $row['id'] = $id > 0 ? $id : 0; + $saved = sql_save($row, $table); + + if (!$saved) { + fwrite(STDERR, "Saving $table {$row['hash']} failed\n"); + exit(1); + } + + return (int) $saved; +} + +function fabric_color($hex) { + $hex = strtoupper($hex); + $id = (int) db_fetch_cell_prepared('SELECT id FROM colors WHERE hex = ?', array($hex)); + + if ($id === 0) { + db_execute_prepared('INSERT INTO colors (hex) VALUES (?)', array($hex)); + $id = (int) db_fetch_cell_prepared('SELECT id FROM colors WHERE hex = ?', array($hex)); + } + + return $id; +} + +function fabric_cdef($name, $rpn) { + $id = fabric_save('cdef', array('hash' => T::hash('cdef', $name), 'name' => $name, 'system' => 0)); + + db_execute_prepared('DELETE FROM cdef_items WHERE cdef_id = ?', array($id)); + fabric_save('cdef_items', array('hash' => T::hash('cdef_item', $name . ':1'), 'cdef_id' => $id, 'sequence' => 1, 'type' => 6, 'value' => $rpn)); + + return $id; +} + +function fabric_gprint($name, $text) { + return fabric_save('graph_templates_gprint', array('hash' => T::hash('gprint', $name), 'name' => $name, 'gprint_text' => $text)); +} + +/** + * A data template on the indexed script server input, one RRD item per + * data source name. + */ +function fabric_data_template($name, $inputId, $title, array $names, array $indexFields) { + $dtId = fabric_save('data_template', array('hash' => T::hash('data_template', $name), 'name' => $name)); + $dtdId = (int) db_fetch_cell_prepared('SELECT id FROM data_template_data WHERE data_template_id = ? AND local_data_id = 0', array($dtId)); + $dtdId = (int) sql_save(array( + 'id' => $dtdId, + 'data_template_id' => $dtId, + 'local_data_id' => 0, + 'local_data_template_data_id' => 0, + 'data_input_id' => $inputId, + 'name' => $title, + 'active' => 'on', + 'rrd_step' => 300, + 'data_source_profile_id' => 1, + ), 'data_template_data'); + + // The index fields are set per data source when Cacti creates one from + // the data query. + foreach ($indexFields as $fieldId) { + db_execute_prepared('REPLACE INTO data_input_data (data_input_field_id, data_template_data_id, t_value, value) VALUES (?, ?, ?, ?)', array($fieldId, $dtdId, 'on', '')); + } + + $rrd = array(); + + foreach ($names as $item) { + $spec = fabric_ds_spec($item); + $rrd[$item] = fabric_save('data_template_rrd', array( + 'hash' => T::hash('data_template_item', $name . ':' . $item), + 'data_template_id' => $dtId, + 'local_data_id' => 0, + 'rrd_maximum' => $spec[1], + 'rrd_minimum' => '0', + 'rrd_heartbeat' => 600, + 'data_source_type_id' => $spec[0], + 'data_source_name' => $item, + 'data_input_field_id' => 0, + )); + } + + return array('id' => $dtId, 'rrd' => $rrd); +} + +/** + * A graph template from a list of drawn items. Each item may carry legends: + * a list of [GPRINT type, label] printed after it; the last legend ends the + * line. + */ +function fabric_graph_template($name, $title, $label, $base, array $items) { + $gtId = fabric_save('graph_templates', array('hash' => T::hash('graph_template', $name), 'name' => $name)); + $gtgId = (int) db_fetch_cell_prepared('SELECT id FROM graph_templates_graph WHERE graph_template_id = ? AND local_graph_id = 0', array($gtId)); + + sql_save(array( + 'id' => $gtgId, + 'graph_template_id' => $gtId, + 'local_graph_id' => 0, + 'local_graph_template_graph_id' => 0, + 'image_format_id' => 1, + 't_title' => '', + 'title' => $title, + 'height' => 150, + 'width' => 600, + 'upper_limit' => '100', + 'lower_limit' => '0', + 'vertical_label' => $label, + 'auto_scale' => 'on', + 'auto_scale_opts' => 2, + 'auto_scale_rigid' => '', + 'base_value' => $base, + 'slope_mode' => 'on', + ), 'graph_templates_graph'); + + db_execute_prepared('DELETE FROM graph_templates_item WHERE graph_template_id = ? AND local_graph_id = 0', array($gtId)); + + $sequence = 0; + $first = 0; + + $add = function (array $row) use (&$sequence, $gtId, $name) { + $sequence++; + + return fabric_save('graph_templates_item', $row + array( + 'hash' => T::hash('graph_template_item', $name . ':' . $sequence), + 'graph_template_id' => $gtId, + 'local_graph_id' => 0, + 'task_item_id' => 0, + 'color_id' => 0, + 'alpha' => 'FF', + 'graph_type_id' => GRAPH_ITEM_TYPE_COMMENT, + 'cdef_id' => 0, + 'consolidation_function_id' => 1, + 'text_format' => '', + 'value' => '', + 'hard_return' => '', + 'gprint_id' => 0, + 'sequence' => $sequence, + )); + }; + + $gprints = array(GRAPH_ITEM_TYPE_GPRINT_LAST, GRAPH_ITEM_TYPE_GPRINT_AVERAGE, GRAPH_ITEM_TYPE_GPRINT_MAX, GRAPH_ITEM_TYPE_GPRINT_MIN); + + foreach ($items as $item) { + $legends = isset($item['legends']) ? $item['legends'] : array(); + $id = $add(array( + 'task_item_id' => $item['rrd'], + 'graph_type_id' => $item['type'], + 'color_id' => isset($item['color']) ? fabric_color($item['color']) : 0, + 'cdef_id' => isset($item['cdef']) ? $item['cdef'] : 0, + 'text_format' => $item['text'], + 'gprint_id' => in_array($item['type'], $gprints, true) ? $item['gprint'] : 0, + 'hard_return' => $legends === array() ? 'on' : '', + )); + + $first = $first === 0 && !in_array($item['type'], $gprints, true) ? $id : $first; + + foreach ($legends as $i => $legend) { + $add(array( + 'task_item_id' => $item['rrd'], + 'graph_type_id' => $legend[0], + 'cdef_id' => isset($item['cdef']) ? $item['cdef'] : 0, + 'text_format' => $legend[1], + 'gprint_id' => $item['gprint'], + 'hard_return' => $i === count($legends) - 1 ? 'on' : '', + )); + } + } + + // One graph template input, for the first item's color: Cacti 1.2.32 + // and later refuse a graph template export with no element. + $inputId = fabric_save('graph_template_input', array( + 'hash' => T::hash('graph_template_input', $name . ':color'), + 'graph_template_id' => $gtId, + 'name' => 'First Item Color', + 'description' => 'The color of the first item', + 'column_name' => 'color_id', + )); + + db_execute_prepared('DELETE FROM graph_template_input_defs WHERE graph_template_input_id = ?', array($inputId)); + db_execute_prepared('INSERT INTO graph_template_input_defs (graph_template_input_id, graph_template_item_id) VALUES (?, ?)', array($inputId, $first)); + + return $gtId; +} + +$words = fabric_cdef('Fabric Words to Bytes', 'CURRENT_DATA_SOURCE,4,*'); +$gNum = fabric_gprint('Fabric Number', '%8.2lf %s'); +$gInt = fabric_gprint('Fabric Integer', '%5.0lf'); + +$stats = array(array(GRAPH_ITEM_TYPE_GPRINT_LAST, 'Current:'), array(GRAPH_ITEM_TYPE_GPRINT_AVERAGE, 'Average:'), array(GRAPH_ITEM_TYPE_GPRINT_MAX, 'Maximum:')); +$now = array(array(GRAPH_ITEM_TYPE_GPRINT_LAST, 'Current:')); + +$indexedInput = (int) db_fetch_cell_prepared('SELECT id FROM data_input WHERE hash = ?', array(FABRIC_INDEXED_INPUT)); +$indexedFields = array(); + +foreach (FABRIC_INDEXED_FIELDS as $hash) { + $indexedFields[] = (int) db_fetch_cell_prepared('SELECT id FROM data_input_fields WHERE hash = ?', array($hash)); +} + +if ($indexedInput === 0 || in_array(0, $indexedFields, true)) { + fwrite(STDERR, "Cacti's script server indexed input is missing\n"); + exit(1); +} + +$suffix = array(V::TRAFFIC => 'Traffic', V::ERRORS => 'Errors', V::CONGESTION => 'Congestion', V::STATE => 'State', V::RATES => 'Alert Rates'); +$dts = array(); + +foreach (V::templates() as $name => $names) { + $dts[$name] = fabric_data_template($name, $indexedInput, '|host_description| - |query_fabricPort| - ' . $suffix[$name], $names, $indexedFields); +} + +$t = $dts[V::TRAFFIC]['rrd']; +$e = $dts[V::ERRORS]['rrd']; +$c = $dts[V::CONGESTION]['rrd']; +$s = $dts[V::STATE]['rrd']; +$r = $dts[V::RATES]['rrd']; + +$palette = array('C0392B', 'E67E22', 'F1C40F', '27AE60', '16A085', '2980B9', '8E44AD', '7F8C8D', '2C3E50'); +$avg = array(array(GRAPH_ITEM_TYPE_GPRINT_AVERAGE, 'Average:'), array(GRAPH_ITEM_TYPE_GPRINT_MAX, 'Maximum:')); + +$errorText = array( + 'symbol_err' => 'Symbol errors', + 'link_err_recov' => 'Link error recoveries', + 'link_downed' => 'Link downed events', + 'rcv_err' => 'Receive errors', + 'rcv_remote_phys' => 'Receive remote physical errors', + 'rcv_switch_relay' => 'Receive switch relay errors', + 'local_link_integ' => 'Local link integrity errors', + 'buffer_overrun' => 'Excessive buffer overruns', + 'vl15_dropped' => 'VL15 packets dropped', +); + +$errorItems = array(); +$i = 0; + +foreach ($errorText as $name => $text) { + $errorItems[] = array('rrd' => $e[$name], 'type' => GRAPH_ITEM_TYPE_LINE1, 'color' => $palette[$i++ % count($palette)], 'text' => $text, 'gprint' => $gNum, 'legends' => $avg); +} + +$graphs = array( + V::TRAFFIC => fabric_graph_template(V::TRAFFIC, '|host_description| - |query_fabricPort| - Traffic (bytes per second)', 'bytes per second', 1000, array( + array('rrd' => $t['xmit_data'], 'type' => GRAPH_ITEM_TYPE_LINE2, 'color' => '2471A3', 'cdef' => $words, 'text' => 'Transmitted, data counter times 4 octets', 'gprint' => $gNum, 'legends' => $stats), + array('rrd' => $t['rcv_data'], 'type' => GRAPH_ITEM_TYPE_LINE2, 'color' => '1E8449', 'cdef' => $words, 'text' => 'Received, data counter times 4 octets', 'gprint' => $gNum, 'legends' => $stats), + array('rrd' => $t['xmit_pkts'], 'type' => GRAPH_ITEM_TYPE_GPRINT_AVERAGE, 'text' => 'Packets transmitted per second, average:', 'gprint' => $gNum), + array('rrd' => $t['rcv_pkts'], 'type' => GRAPH_ITEM_TYPE_GPRINT_AVERAGE, 'text' => 'Packets received per second, average:', 'gprint' => $gNum), + )), + V::ERRORS => fabric_graph_template(V::ERRORS, '|host_description| - |query_fabricPort| - Link and Receive Errors (per second)', 'errors per second', 1000, $errorItems), + V::CONGESTION => fabric_graph_template(V::CONGESTION, '|host_description| - |query_fabricPort| - Congestion and Transmit Discards (per second)', 'ticks or packets per second', 1000, array( + array('rrd' => $c['xmit_wait'], 'type' => GRAPH_ITEM_TYPE_LINE2, 'color' => 'C0392B', 'text' => 'Transmit wait, ticks with data queued but no credit or arbitration', 'gprint' => $gNum, 'legends' => $avg), + array('rrd' => $c['xmit_discards'], 'type' => GRAPH_ITEM_TYPE_LINE1, 'color' => '7D3C98', 'text' => 'Transmit discards, packets', 'gprint' => $gNum, 'legends' => $avg), + array('rrd' => $c['xmit_constraint'], 'type' => GRAPH_ITEM_TYPE_LINE1, 'color' => 'B9770E', 'text' => 'Transmit constraint errors, packets', 'gprint' => $gNum, 'legends' => $avg), + array('rrd' => $c['rcv_constraint'], 'type' => GRAPH_ITEM_TYPE_LINE1, 'color' => '117A65', 'text' => 'Receive constraint errors, packets', 'gprint' => $gNum, 'legends' => $avg), + )), + V::STATE => fabric_graph_template(V::STATE, '|host_description| - |query_fabricPort| - Link State', 'lanes, rank, or state', 1000, array( + array('rrd' => $s['active_lanes'], 'type' => GRAPH_ITEM_TYPE_LINE2, 'color' => '2471A3', 'text' => 'Active lanes', 'gprint' => $gInt, 'legends' => $now), + array('rrd' => $s['speed_rank'], 'type' => GRAPH_ITEM_TYPE_LINE1, 'color' => '1E8449', 'text' => 'Active speed rank, 1 SDR to 9 XDR', 'gprint' => $gInt, 'legends' => $now), + array('rrd' => $s['degraded'], 'type' => GRAPH_ITEM_TYPE_LINE2, 'color' => 'C0392B', 'text' => 'Degraded, 1 when below best and not explained', 'gprint' => $gInt, 'legends' => $now), + array('rrd' => $s['port_state'], 'type' => GRAPH_ITEM_TYPE_LINE1, 'color' => '7F8C8D', 'text' => 'Logical state, 1 Down to 4 Active', 'gprint' => $gInt, 'legends' => $now), + array('rrd' => $s['age'], 'type' => GRAPH_ITEM_TYPE_GPRINT_LAST, 'text' => 'Seconds since the last sample:', 'gprint' => $gInt), + )), + V::RATES => fabric_graph_template(V::RATES, '|host_description| - |query_fabricPort| - Alert Rates (per second)', 'per second', 1000, array( + array('rrd' => $r['symbol_err_rate'], 'type' => GRAPH_ITEM_TYPE_LINE1, 'color' => 'C0392B', 'text' => 'Symbol errors', 'gprint' => $gNum, 'legends' => $avg), + array('rrd' => $r['rcv_err_rate'], 'type' => GRAPH_ITEM_TYPE_LINE1, 'color' => 'E67E22', 'text' => 'Receive errors', 'gprint' => $gNum, 'legends' => $avg), + array('rrd' => $r['link_downed_rate'], 'type' => GRAPH_ITEM_TYPE_LINE1, 'color' => '8E44AD', 'text' => 'Link downed events', 'gprint' => $gNum, 'legends' => $avg), + array('rrd' => $r['xmit_discard_rate'], 'type' => GRAPH_ITEM_TYPE_LINE1, 'color' => '2980B9', 'text' => 'Transmit discards', 'gprint' => $gNum, 'legends' => $avg), + array('rrd' => $r['xmit_wait_rate'], 'type' => GRAPH_ITEM_TYPE_LINE1, 'color' => '7F8C8D', 'text' => 'Transmit wait ticks', 'gprint' => $gNum, 'legends' => $avg), + )), +); + +$queryId = fabric_save('snmp_query', array( + 'hash' => T::hash('data_query', T::QUERY), + 'xml_path' => '/resource/script_server/' . T::QUERY_FILE, + 'name' => T::QUERY, + 'description' => 'InfiniBand ports of the fabric nodes mapped to a device, from the Fabric plugin cache', + 'data_input_id' => $indexedInput, +)); + +foreach ($graphs as $name => $gtId) { + $sqgId = fabric_save('snmp_query_graph', array( + 'hash' => T::hash('data_query_graph', T::QUERY . ':' . $name), + 'snmp_query_id' => $queryId, + 'name' => $suffix[$name], + 'graph_template_id' => $gtId, + )); + + $template = $dts[$name]; + + // Every item of the graph's data template maps to the query field of + // the same name. + db_execute_prepared('DELETE FROM snmp_query_graph_rrd WHERE snmp_query_graph_id = ?', array($sqgId)); + + foreach ($template['rrd'] as $item => $rrdId) { + db_execute_prepared('INSERT INTO snmp_query_graph_rrd (snmp_query_graph_id, data_template_id, data_template_rrd_id, snmp_field_name) VALUES (?, ?, ?, ?)', array($sqgId, $template['id'], $rrdId, $item)); + } + + fabric_save('snmp_query_graph_sv', array( + 'hash' => T::hash('data_query_sv_graph', T::QUERY . ':' . $name . ':title'), + 'snmp_query_graph_id' => $sqgId, + 'sequence' => 1, + 'field_name' => 'title', + 'text' => '|host_description| - |query_fabricPort| - ' . $suffix[$name], + )); + + fabric_save('snmp_query_graph_rrd_sv', array( + 'hash' => T::hash('data_query_sv_data_source', T::QUERY . ':' . $name . ':name'), + 'snmp_query_graph_id' => $sqgId, + 'data_template_id' => $template['id'], + 'sequence' => 1, + 'field_name' => 'name', + 'text' => '|host_description| - |query_fabricPort| - ' . $suffix[$name], + )); +} + +$htId = fabric_save('host_template', array('hash' => T::hash('host_template', T::DEVICE_TEMPLATE), 'name' => T::DEVICE_TEMPLATE)); + +db_execute_prepared('DELETE FROM host_template_graph WHERE host_template_id = ?', array($htId)); +db_execute_prepared('DELETE FROM host_template_snmp_query WHERE host_template_id = ?', array($htId)); +db_execute_prepared('INSERT INTO host_template_snmp_query (host_template_id, snmp_query_id) VALUES (?, ?)', array($htId, $queryId)); + +$xml = get_item_xml('host_template', $htId, true); + +// The export follows the data source profile the data templates use. The +// plugin must not overwrite a site's profile, so the shipped file leaves it +// out and import resolves the profile by its hash, which is Cacti's stock one. +$xml = preg_replace('#\s*.*?#s', '', $xml, -1, $removed); + +if ($removed !== 1) { + fwrite(STDERR, "Expected one data source profile in the export, found $removed\n"); + exit(1); +} + +$file = isset($argv[1]) ? $argv[1] : $config['base_path'] . '/plugins/fabric/templates/' . T::TEMPLATE_FILE; + +file_put_contents($file, $xml); +print "Wrote $file\n"; diff --git a/tests/bin/check-ibsim-fixtures.php b/tests/bin/check-ibsim-fixtures.php new file mode 100644 index 0000000..5036648 --- /dev/null +++ b/tests/bin/check-ibsim-fixtures.php @@ -0,0 +1,138 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_fabric, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_fabric + * + * 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. + */ + +if (PHP_SAPI !== 'cli') { + exit(1); +} + +/* + * Reads the output of the real infiniband-diags tools, run against the + * ibsim simulated fabric (tests/ibsim/run.sh), through the plugin's own + * parsers, and checks the structure: 8 nodes, 4 of them switches, every + * port key :, and a 1X link only on node03 in the + * degraded scenario. LIDs and line order come from OpenSM and vary + * between runs, so they are not compared. ibsim prints "Could be 12X" on + * every link, so below-best is not asserted; the active width is. + * + * php tests/bin/check-ibsim-fixtures.php + * + * Needs no Cacti and no database. Exits 1 on any failed check. + */ + +use Somethingwithproof\Fabric\CounterGroup; +use Somethingwithproof\Fabric\IblinkinfoParser; +use Somethingwithproof\Fabric\IbnetdiscoverParser; +use Somethingwithproof\Fabric\LinkWidth; +use Somethingwithproof\Fabric\NodeType; +use Somethingwithproof\Fabric\PerfqueryParser; +use Somethingwithproof\Fabric\PortRef; + +if (!function_exists('__')) { + function __() { + $args = func_get_args(); + + return count($args) > 2 ? call_user_func_array('sprintf', array_slice($args, 0, -1)) : $args[0]; + } +} + +require dirname(__DIR__, 2) . '/include/autoload.php'; + +$dir = rtrim($argv[1] ?? '', '/'); +$failures = 0; + +function ibsim_check(bool $ok, string $message): void { + global $failures; + + print ($ok ? 'ok ' : 'FAIL ') . $message . PHP_EOL; + $failures += $ok ? 0 : 1; +} + +function ibsim_read(string $file): string { + $data = is_file($file) ? file_get_contents($file) : false; + + if (!is_string($data)) { + throw new RuntimeException("$file is missing"); + } + + return $data; +} + +foreach (['healthy', 'degraded'] as $scenario) { + try { + $topology = (new IbnetdiscoverParser())->parse(ibsim_read("$dir/$scenario/ibnetdiscover.out")); + $links = (new IblinkinfoParser())->parse(ibsim_read("$dir/$scenario/iblinkinfo-line.out")); + $basic = (new PerfqueryParser())->parse(ibsim_read("$dir/$scenario/perfquery-ca.out")); + $extended = (new PerfqueryParser())->parse(ibsim_read("$dir/$scenario/perfquery-ca-x.out")); + $list = (new PerfqueryParser())->parse(ibsim_read("$dir/$scenario/perfquery-sw-list.out")); + } catch (Throwable $e) { + ibsim_check(false, "$scenario: the output parses (" . $e::class . ': ' . $e->getMessage() . ')'); + + continue; + } + + $switches = array_filter($topology->nodes, static fn ($n): bool => $n->type === NodeType::Switch); + $keys = []; + + foreach ($topology->nodes as $node) { + foreach ($node->ports as $port) { + $keys[] = (new PortRef($node->guid, $port->number))->key(); + } + } + + ibsim_check(count($topology->nodes) === 8, "$scenario: ibnetdiscover reads as 8 nodes"); + ibsim_check(count($switches) === 4, "$scenario: 4 of them switches"); + ibsim_check($topology->duplicates === [], "$scenario: no GUID printed twice"); + ibsim_check($topology->local !== null && $topology->local->text === '0x0002c90300bb0000', "$scenario: discovery is from node01"); + ibsim_check($keys !== [] && count(array_unique($keys)) === count($keys) && preg_grep('/^0x[0-9a-f]{16}:\d{1,3}$/', $keys) === $keys, "$scenario: every port has a unique : key"); + + // A switch's node GUID is the switchguid, not a port GUID: every + // switch port in iblinkinfo carries the same GUID, which must be a + // switch node. + $switchGuids = array_map(static fn ($n): string => $n->guid->text, $switches); + $narrow = []; + + foreach ($links->records as $record) { + if ($record->link->activeWidth === LinkWidth::X1) { + $narrow[] = $record; + } + } + + ibsim_check(count($links->records) === 38 && $links->skipped === [], "$scenario: iblinkinfo --line reads as 38 port records, none skipped"); + + $narrowSwitch = array_filter($narrow, static fn ($r): bool => in_array($r->portGuid->text, $switchGuids, true)); + $narrowCa = array_filter($narrow, static fn ($r): bool => !in_array($r->portGuid->text, $switchGuids, true)); + + if ($scenario === 'healthy') { + ibsim_check($narrow === [], 'healthy: no port runs at 1X'); + } else { + $node03 = array_values(array_filter($topology->nodes, static fn ($n): bool => str_contains($n->description, 'node03'))); + + ibsim_check(count($narrow) === 2 && count($narrowSwitch) === 1 && count($narrowCa) === 1, 'degraded: one link runs at 1X, seen from both ends'); + $node03Ports = count($node03) === 1 ? array_map(static fn ($p): string => $p->portGuid->text ?? '', $node03[0]->ports) : []; + $adapterEnd = array_values($narrowCa)[0] ?? null; + + ibsim_check($adapterEnd !== null && in_array($adapterEnd->portGuid->text, $node03Ports, true) && in_array($adapterEnd->remotePortGuid->text ?? '', $switchGuids, true), 'degraded: the 1X link is the node03 adapter link to a switch'); + } + + ibsim_check(count($basic) === 1 && $basic[0]->group === CounterGroup::Basic && isset($basic[0]->values['PortXmitData']), "$scenario: perfquery reads basic counters"); + ibsim_check(count($extended) === 1 && $extended[0]->group === CounterGroup::Extended && isset($extended[0]->values['PortXmitData']), "$scenario: perfquery -x reads extended counters"); + ibsim_check(array_map(static fn ($c): int => $c->port, $list) === [1, 2, 3], "$scenario: a port list reads as ports 1 to 3"); +} + +exit($failures > 0 ? 1 : 0); diff --git a/tests/bin/e2e.php b/tests/bin/e2e.php new file mode 100644 index 0000000..85cb889 --- /dev/null +++ b/tests/bin/e2e.php @@ -0,0 +1,461 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_fabric, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_fabric + * + * 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. + */ + +if (PHP_SAPI !== 'cli') { + exit(1); +} + + +/* + * End to end with Cacti's own poller, Thold, and Maint (REQ-ALERT-001 to + * REQ-ALERT-013, REQ-MAINT-001): fake tools in a root-owned directory, a + * device created for an adapter node, graphs and data sources from the + * Fabric templates, and thresholds made with Thold's own functions. The + * caller runs one phase, then `php poller.php --force`, and so on: + * + * FABRIC_TEST_DATABASE=disposable FABRIC_E2E_TOOLS= php plugins/fabric/tests/bin/e2e.php + * + * Phases: tools writes the fake tools to /tools, for the caller + * to install root-owned in (tests/bin/e2e.sh); setup, then + * degrade, restore, burst, steady, reset, maint, stale, each followed by + * a poller run and the matching check_; graph last. Each prints + * PASS or FAIL lines and exits 1 on a failure. The fake fabric, the tools' + * call log, and this script's state live in . Thold and Maint + * must be installed and enabled first, unchanged. Disposable databases + * only. Must parse on PHP 8.0. + */ + +chdir(dirname(__DIR__, 4)); + +require('./include/cli_check.php'); + +if (getenv('FABRIC_TEST_DATABASE') !== 'disposable') { + fwrite(STDERR, "Set FABRIC_TEST_DATABASE=disposable\n"); + exit(2); +} + +include_once($config['base_path'] . '/plugins/fabric/setup.php'); + +if (!fabric_boot()) { + fwrite(STDERR, "PHP 8.2 or later is required\n"); + exit(2); +} + +require_once($config['base_path'] . '/plugins/fabric/tests/Support/FabricGenerator.php'); +require_once($config['base_path'] . '/plugins/fabric/tests/Support/FakeTools.php'); +require_once($config['base_path'] . '/lib/api_device.php'); +require_once($config['base_path'] . '/lib/data_query.php'); +require_once($config['base_path'] . '/lib/template.php'); +require_once($config['base_path'] . '/lib/api_graph.php'); +require_once($config['base_path'] . '/lib/api_data_source.php'); +require_once($config['base_path'] . '/lib/utility.php'); +require_once($config['base_path'] . '/lib/rrd.php'); + +use Somethingwithproof\Fabric\Tests\FabricGenerator as G; +use Somethingwithproof\Fabric\Tests\FakeTools; +use Somethingwithproof\Fabric\TemplateInstaller as T; + +$phase = isset($argv[1]) ? $argv[1] : ''; +$dir = isset($argv[2]) ? rtrim($argv[2], '/') : ''; +$failures = 0; +$file = $dir . '/e2e.json'; +$tools = (string) getenv('FABRIC_E2E_TOOLS'); +$state = is_file($file) ? json_decode((string) file_get_contents($file), true) : array(); +$adapter = G::CA_BASE; + +function e2e_expect($ok, $message) { + global $failures, $phase; + + print ($ok ? 'PASS ' : 'FAIL ') . $phase . ': ' . $message . PHP_EOL; + $failures += $ok ? 0 : 1; +} + +/** The fabric: one switch, two adapters; the first adapter's port 1 is watched. */ +function e2e_fabric(array $state) { + $gen = G::forCas(2); + + foreach ($state['counters'] ?? array() as $key => $values) { + $gen->counters[$key] = $values; + } + + if (!empty($state['degraded'])) { + $gen->degrade(G::CA_BASE, 1, '1X', 'EDR', '4X', ''); + } + + return $gen; +} + +/** + * Make every sweep due again: Cacti's poller runs here seconds apart, the + * plugin sweeps at most every half interval. + */ +function e2e_due() { + db_execute('UPDATE plugin_fabric_node_sweep SET last_attempt = last_attempt - 400'); + db_execute('UPDATE plugin_fabric_health SET discovery_attempt = discovery_attempt - 400'); + db_execute('UPDATE plugin_fabric_claim SET expires_at = 0'); +} + +function e2e_thold($id) { + return db_fetch_row_prepared('SELECT id, thold_alert, thold_fail_count, lastread, thold_enabled FROM thold_data WHERE id = ?', array($id)); +} + +function e2e_logs($id) { + return (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM plugin_thold_log WHERE threshold_id = ?', array($id)); +} + +/** Create a Thold threshold from a Thold template, as Thold's own pages do. */ +function e2e_threshold($localGraphId, $localDataId, $dsName, $hi, $low) { + $rrd = db_fetch_row_prepared('SELECT id, data_template_id FROM data_template_rrd WHERE local_data_id = ? AND data_source_name = ?', array($localDataId, $dsName)); + + db_execute_prepared("INSERT INTO thold_template (name, suggested_name, data_template_id, data_template_name, data_source_id, data_source_name, data_source_friendly, thold_type, thold_enabled, thold_hi, thold_low, thold_fail_trigger, repeat_alert, data_type) + VALUES (?, ?, ?, '', ?, ?, ?, 0, 'on', ?, ?, 1, 0, 0)", + array('Fabric e2e ' . $dsName, '|data_source_description| ' . $dsName, (int) db_fetch_cell_prepared('SELECT data_template_id FROM data_template_rrd WHERE id = ?', array($rrd['id'])), (int) db_fetch_cell_prepared('SELECT local_data_template_rrd_id FROM data_template_rrd WHERE id = ?', array($rrd['id'])), $dsName, $dsName, $hi, $low)); + + $template = db_fetch_row_prepared('SELECT * FROM thold_template WHERE id = ?', array(db_fetch_insert_id())); + $message = ''; + + thold_create_from_template($localDataId, $localGraphId, $rrd['id'], $template, $message); + + return (int) db_fetch_cell_prepared('SELECT id FROM thold_data WHERE local_data_id = ? AND data_source_name = ?', array($localDataId, $dsName)); +} + +/** Thold still runs: no TypeError, still enabled. */ +function e2e_thold_alive() { + global $config; + + $log = (string) @file_get_contents($config['base_path'] . '/log/cacti.log'); + + e2e_expect(api_plugin_is_enabled('thold') && api_plugin_is_enabled('maint'), 'Thold and Maint are still enabled'); + e2e_expect(preg_match('/TypeError|PHP ERROR|PHP Fatal|Uncaught/', $log) !== 1, 'the Cacti log shows no PHP error'); +} + +foreach (array('thold/thold_functions.php', 'maint/functions.php') as $include) { + if (is_file($config['base_path'] . '/plugins/' . $include)) { + include_once($config['base_path'] . '/plugins/' . $include); + } +} + +switch ($phase) { + case 'tools': + if (!is_dir($dir . '/tools')) { + mkdir($dir . '/tools', 0755); + } + + FakeTools::install($dir . '/tools', e2e_fabric(array()), array(), $dir); + + break; + case 'setup': + e2e_expect(api_plugin_is_enabled('thold') && api_plugin_is_enabled('maint'), 'Thold and Maint are installed and enabled'); + e2e_expect(function_exists('thold_create_from_template') && function_exists('plugin_maint_check_cacti_host'), 'Thold and Maint functions are available'); + + // Inline Thold processing, so a poller run checks thresholds. + set_config_option('thold_daemon_enable', ''); + set_config_option('fabric_tool_dir', $tools); + $state = array('counters' => array(), 'degraded' => false); + FakeTools::state($dir, e2e_fabric($state)); + + db_execute("INSERT INTO plugin_fabric_fabric (name, backend, poller_id, sweep_interval, adapter, adapter_port, admin_state) VALUES ('e2e', 'diags', 1, 300, 'mlx5_0', 1, 'enabled')"); + $fabricId = (int) db_fetch_insert_id(); + $result = fabric_sweep()->forFabric($fabricId, null, true); + + e2e_expect($result !== null, 'the first sweep runs against the fake tools'); + + $nodes = new \Somethingwithproof\Fabric\NodeRepository(false); + $node = null; + + foreach ($nodes->forFabric($fabricId) ?? array() as $n) { + if ($n->guid->text === sprintf('0x%016x', $adapter)) { + $node = $n; + } + } + + e2e_expect($node !== null, 'the adapter node is in the inventory'); + + $clock = new \Somethingwithproof\Fabric\SystemClock(); + $access = new \Somethingwithproof\Fabric\DeviceAccess(static function (int $host): bool { + return true; + }); + $devices = new \Somethingwithproof\Fabric\DeviceProvisioner($nodes, new \Somethingwithproof\Fabric\FabricRepository(false, $clock), new \Somethingwithproof\Fabric\CactiObjectRepository(false), $access, $config['base_path']); + $hostId = $node !== null ? $devices->create($node) : 0; + $index = sprintf('0x%016x', $adapter) . ':1'; + + e2e_expect($hostId > 0, 'a device is created for the adapter node'); + + $indexes = array_column(db_fetch_assoc_prepared('SELECT DISTINCT snmp_index FROM host_snmp_cache WHERE host_id = ? ORDER BY snmp_index', array($hostId)), 'snmp_index'); + e2e_expect($indexes === array($index), 'the data query lists the linked port only, not the down port 2 (' . implode(', ', $indexes) . ')'); + + $queryId = (int) db_fetch_cell_prepared('SELECT id FROM snmp_query WHERE hash = ?', array(T::hash('data_query', T::QUERY))); + $graphs = array(); + + foreach (array('Fabric Port State', 'Fabric Port Alert Rates', 'Fabric Port Traffic', 'Fabric Port Errors') as $name) { + $gt = (int) db_fetch_cell_prepared('SELECT id FROM graph_templates WHERE hash = ?', array(T::hash('graph_template', $name))); + $sqg = (int) db_fetch_cell_prepared('SELECT id FROM snmp_query_graph WHERE hash = ?', array(T::hash('data_query_graph', T::QUERY . ':' . $name))); + $vals = array(); + $made = create_complete_graph_from_template($gt, $hostId, array('snmp_query_id' => $queryId, 'snmp_index_on' => 'fabricPort', 'snmp_index' => $index, 'snmp_query_graph_id' => $sqg), $vals); + + // As cli/add_graphs.php does: the poller polls only what is pushed out. + foreach ($made['local_data_id'] as $localDataId) { + push_out_host($hostId, $localDataId); + } + + $graphs[$name] = array('graph' => (int) $made['local_graph_id'], 'data' => (int) reset($made['local_data_id'])); + e2e_expect($graphs[$name]['graph'] > 0 && $graphs[$name]['data'] > 0, "a $name graph and data source are created from the data query"); + } + + $types = array_column(db_fetch_assoc_prepared('SELECT data_source_name, data_source_type_id FROM data_template_rrd WHERE local_data_id IN (?, ?) ORDER BY data_source_name', array($graphs['Fabric Port State']['data'], $graphs['Fabric Port Alert Rates']['data'])), 'data_source_type_id', 'data_source_name'); + e2e_expect(count($types) === 10 && array_values(array_unique(array_map('intval', $types))) === array(1), 'every thresholdable data source is a GAUGE'); + e2e_expect((int) db_fetch_cell_prepared('SELECT COUNT(*) FROM poller_item WHERE host_id = ?', array($hostId)) === 23, 'the 23 data source items of the four graphs are in the poller cache'); + + $state['host'] = $hostId; + $state['fabric'] = $fabricId; + $state['graphs'] = $graphs; + $state['lanes'] = e2e_threshold($graphs['Fabric Port State']['graph'], $graphs['Fabric Port State']['data'], 'active_lanes', '', '4'); + $state['age'] = e2e_threshold($graphs['Fabric Port State']['graph'], $graphs['Fabric Port State']['data'], 'age', '900', ''); + $state['symbol'] = e2e_threshold($graphs['Fabric Port Alert Rates']['graph'], $graphs['Fabric Port Alert Rates']['data'], 'symbol_err_rate', '0.5', ''); + $lid = sprintf('%d:1', G::forCas(2)->lidOf($adapter, 1)); + $state['lid'] = $lid; + $state['counters'] = array($lid => array('SymbolErrorCounter' => '10')); + + e2e_expect($state['lanes'] > 0 && $state['age'] > 0 && $state['symbol'] > 0, 'Thold creates the three thresholds from its templates'); + + FakeTools::state($dir, e2e_fabric($state)); + e2e_due(); + + break; + case 'check_setup': + $host = db_fetch_row_prepared('SELECT status, availability_method FROM host WHERE id = ?', array($state['host'])); + e2e_expect((int) $host['status'] === 3, 'Cacti marks the created device up with availability checks off (status ' . $host['status'] . '), which Thold requires'); + + $lanes = e2e_thold($state['lanes']); + e2e_expect($lanes['lastread'] === '4' && (int) $lanes['thold_alert'] === 0, 'a 4X link reads 4 lanes and does not breach (lastread ' . $lanes['lastread'] . ')'); + e2e_thold_alive(); + + break; + case 'degrade': + $state['degraded'] = true; + FakeTools::state($dir, e2e_fabric($state)); + e2e_due(); + + break; + case 'check_degrade': + $lanes = e2e_thold($state['lanes']); + e2e_expect($lanes['lastread'] === '1' && (int) $lanes['thold_alert'] !== 0 && e2e_logs($state['lanes']) >= 1, 'a 4X link that falls to 1X fires the lanes threshold (lastread ' . $lanes['lastread'] . ', alert ' . $lanes['thold_alert'] . ')'); + $state['lanes_logs'] = e2e_logs($state['lanes']); + e2e_thold_alive(); + + break; + case 'restore': + $state['degraded'] = false; + FakeTools::state($dir, e2e_fabric($state)); + e2e_due(); + + break; + case 'check_restore': + $lanes = e2e_thold($state['lanes']); + e2e_expect($lanes['lastread'] === '4' && (int) $lanes['thold_alert'] === 0 && e2e_logs($state['lanes']) > $state['lanes_logs'], 'the restored link clears the alert and logs the restoral'); + e2e_thold_alive(); + + break; + case 'burst': + $state['counters'][$state['lid']]['SymbolErrorCounter'] = '5010'; + FakeTools::state($dir, e2e_fabric($state)); + e2e_due(); + + break; + case 'check_burst': + $symbol = e2e_thold($state['symbol']); + e2e_expect((float) $symbol['lastread'] > 0.5 && (int) $symbol['thold_alert'] !== 0, 'a burst of symbol errors fires the rate threshold (lastread ' . $symbol['lastread'] . ')'); + e2e_thold_alive(); + + break; + case 'steady': + e2e_due(); + + break; + case 'check_steady': + $symbol = e2e_thold($state['symbol']); + e2e_expect($symbol['lastread'] === '0' && (int) $symbol['thold_alert'] === 0, 'an unchanged counter reads a rate of 0 and clears the alert (lastread ' . $symbol['lastread'] . ')'); + $state['symbol_logs'] = e2e_logs($state['symbol']); + e2e_thold_alive(); + + break; + case 'reset': + // Another tool resets the counter: it goes down. + $state['counters'][$state['lid']]['SymbolErrorCounter'] = '3'; + FakeTools::state($dir, e2e_fabric($state)); + e2e_due(); + + break; + case 'check_reset': + $symbol = e2e_thold($state['symbol']); + $disc = (int) db_fetch_cell("SELECT MAX(discontinuities) FROM plugin_fabric_sample WHERE counter_group = 'basic'"); + + e2e_expect($disc >= 1, 'the decrease is counted as a discontinuity'); + e2e_expect((int) $symbol['thold_alert'] === 0 && e2e_logs($state['symbol']) === $state['symbol_logs'], 'the reset neither fires nor logs anything for the rate threshold (lastread "' . $symbol['lastread'] . '")'); + e2e_thold_alive(); + + break; + case 'maint': + db_execute("INSERT INTO plugin_maint_schedules (enabled, name, mtype, stime, etime, minterval) VALUES ('on', 'fabric e2e', 1, " . (time() - 60) . ', ' . (time() + 3600) . ', 0)'); + db_execute_prepared('INSERT INTO plugin_maint_hosts (type, host, schedule) VALUES (1, ?, ?)', array($state['host'], db_fetch_insert_id())); + $state['degraded'] = true; + $state['lanes_logs'] = e2e_logs($state['lanes']); + FakeTools::state($dir, e2e_fabric($state)); + e2e_due(); + + break; + case 'check_maint': + $lanes = e2e_thold($state['lanes']); + e2e_expect(plugin_maint_check_cacti_host($state['host']), 'Maint reports the device in maintenance'); + e2e_expect($lanes['lastread'] === '1' && e2e_logs($state['lanes']) === $state['lanes_logs'], 'in maintenance the 1X link is still measured but no alert is logged (lastread ' . $lanes['lastread'] . ')'); + e2e_thold_alive(); + + break; + case 'stale': + // Maintenance over, the fabric disabled: nothing is swept, and the + // last sample ages past the age threshold. + db_execute('DELETE FROM plugin_maint_hosts'); + db_execute('DELETE FROM plugin_maint_schedules'); + db_execute_prepared("UPDATE plugin_fabric_fabric SET admin_state = 'disabled' WHERE id = ?", array($state['fabric'])); + db_execute('UPDATE plugin_fabric_sample SET observed_at = IF(observed_at > 2000, observed_at - 2000, 0), attempted_at = IF(attempted_at > 2000, attempted_at - 2000, 0), previous_at = IF(previous_at > 2000, previous_at - 2000, 0)'); + db_execute('UPDATE plugin_fabric_port SET link_observed_at = IF(link_observed_at > 2000, link_observed_at - 2000, 0)'); + + break; + case 'check_stale': + $age = e2e_thold($state['age']); + $lanes = e2e_thold($state['lanes']); + + e2e_expect((int) $age['lastread'] > 900 && (int) $age['thold_alert'] !== 0, 'a stale port fires the age threshold (lastread ' . $age['lastread'] . ')'); + e2e_expect($lanes['lastread'] === '' || $lanes['lastread'] === null, 'stale link state reads unknown, not a last value (lastread "' . $lanes['lastread'] . '")'); + e2e_thold_alive(); + + break; + case 'thold_idle': + // Thold registers its worker as process thold/master. Wait, bounded, + // until no worker is registered at two checks a second apart, so a + // check phase never reads alert state from before the run. + $idle = 0; + + for ($waited = 0; $waited < 60 && $idle < 2; $waited++) { + $busy = (int) db_fetch_cell("SELECT COUNT(*) FROM processes WHERE tasktype = 'thold' AND taskname = 'master'"); + $idle = $busy === 0 ? $idle + 1 : 0; + + if ($idle < 2) { + sleep(1); + } + } + + e2e_expect($idle >= 2, 'the Thold worker finished within 60 seconds'); + + break; + case 'leftover': + // Rows Cacti's poller left in poller_output, next to the poller items + // of their data sources, for a log check that fails. + foreach (db_fetch_assoc('SELECT po.local_data_id, po.rrd_name, po.time, po.output, pi.rrd_num, pi.rrd_name AS item FROM poller_output AS po LEFT JOIN poller_item AS pi ON pi.local_data_id = po.local_data_id AND pi.rrd_name = po.rrd_name ORDER BY po.local_data_id, po.time') as $row) { + print 'leftover ' . json_encode($row) . PHP_EOL; + } + + break; + case 'graph': + // The Traffic graph against hand-computed values: rebuild its RRD + // file with the data source definitions Cacti created, play known + // counter values into it, and read the graph back through Cacti. + $graph = $state['graphs']['Fabric Port Traffic']; + $path = (string) db_fetch_cell_prepared('SELECT data_source_path FROM data_template_data WHERE local_data_id = ?', array($graph['data'])); + $path = str_replace('', $config['rra_path'], $path); + $tool = read_config_option('path_rrdtool'); + $info = shell_exec(escapeshellarg($tool) . ' info ' . escapeshellarg($path)); + $ds = array(); + + preg_match_all('/^ds\[(\w+)\]\.(type|minimal_heartbeat|min|max) = "?([^"\n]*)"?$/m', (string) $info, $m, PREG_SET_ORDER); + + foreach ($m as $line) { + $ds[$line[1]][$line[2]] = $line[3]; + } + + e2e_expect(isset($ds['rcv_data']) && $ds['rcv_data']['type'] === 'DERIVE' && (float) $ds['rcv_data']['min'] === 0.0, 'Cacti created the data counters as DERIVE with minimum 0'); + + $t0 = (int) (floor(time() / 300) * 300) - 30 * 300; + $args = array('create', $path . '.e2e', '--start', (string) ($t0 - 300), '--step', '300'); + + foreach (array('xmit_data', 'rcv_data', 'xmit_pkts', 'rcv_pkts') as $name) { + $args[] = sprintf('DS:%s:%s:%s:%s:%s', $name, $ds[$name]['type'], $ds[$name]['minimal_heartbeat'], $ds[$name]['min'] === 'NaN' ? 'U' : $ds[$name]['min'], $ds[$name]['max'] === 'NaN' ? 'U' : $ds[$name]['max']); + } + + $args[] = 'RRA:AVERAGE:0.5:1:100'; + exec(escapeshellarg($tool) . ' ' . implode(' ', array_map('escapeshellarg', $args)), $out, $rc); + + // rcv_data grows by 300000 words per step: 1000 words, 4000 octets + // per second. Step 6 goes down, as a reset does: unknown, no spike. + $value = 1000000; + + for ($i = 0; $i <= 10; $i++) { + $value = $i === 6 ? 5 : $value + 300000; + exec(escapeshellarg($tool) . ' update ' . escapeshellarg($path . '.e2e') . ' ' . escapeshellarg(($t0 + $i * 300) . ':0:' . $value . ':0:0')); + } + + rename($path . '.e2e', $path); + + $meta = array(); + // export_csv selects rrdtool xport; without it core draws the graph. + $xport = rrdtool_function_xport($graph['graph'], 0, array('graph_start' => $t0 + 300, 'graph_end' => $t0 + 3000, 'export_csv' => true), $meta); + $xport = is_array($xport) ? $xport : array(); + $column = null; + + foreach ($xport['meta']['legend'] ?? array() as $key => $legend) { + if (strpos($legend, 'Received') === 0) { + $column = $key; + } + } + + $rows = array(); + $reset = null; + + foreach (array_values($xport['data'] ?? array()) as $rowNumber => $row) { + $value = $column !== null && isset($row[$column]) ? $row[$column] : null; + $rows[] = $value; + + // The step that ends at the decrease (update 6). + // Recent RRDtool omits per-row timestamps; its metadata gives + // the first row's time and the constant step. + $timestamp = (int) ($row['timestamp'] ?? ((int) ($xport['meta']['start'] ?? 0) + $rowNumber * (int) ($xport['meta']['step'] ?? 0))); + + if ($timestamp === $t0 + 6 * 300) { + $reset = $value; + } + } + + $numbers = array_values(array_filter($rows, 'is_numeric')); + $spikes = array_filter($numbers, static function ($v) { + return abs((float) $v - 4000) > 0.01; + }); + + e2e_expect($column !== null && count($numbers) >= 5, 'the Traffic graph exports a Received column (' . count($numbers) . ' values, legend ' . json_encode($xport['meta']['legend'] ?? null) . ')'); + e2e_expect($reset !== null && !is_numeric($reset) && count($rows) - count($numbers) === 1, 'the step that ends at the reset is unknown, and it is the only unknown step (' . json_encode($reset) . ')'); + e2e_expect($numbers !== array() && $spikes === array(), 'every Received value is 4000 bytes per second, the counter times 4 octets, and the reset leaves a gap, not a spike (' . implode(', ', array_slice($rows, 0, 12)) . ')'); + + break; + default: + fwrite(STDERR, "Unknown phase\n"); + exit(2); +} + +file_put_contents($file, json_encode($state)); + +exit($failures > 0 ? 1 : 0); diff --git a/tests/bin/e2e.sh b/tests/bin/e2e.sh new file mode 100644 index 0000000..10289cd --- /dev/null +++ b/tests/bin/e2e.sh @@ -0,0 +1,87 @@ +#!/bin/sh +# SPDX-FileCopyrightText: 2026 Thomas Vincent +# SPDX-License-Identifier: GPL-2.0-or-later +# +# End to end with Cacti's poller, Thold, and Maint (tests/bin/e2e.php). +# Run from the Cacti directory, with Thold and Maint unpacked, unchanged, +# in plugins/thold and plugins/maint, and the Fabric plugin enabled. +# Disposable databases only. +# +# sh plugins/fabric/tests/bin/e2e.sh +# +# The plugin runs tools only from a root-owned directory closed to group +# and others, so the fake tools are installed there with install(1), as +# root or through sudo when not root. +set -u +TOOLS=$1 +STATE=$2 +export FABRIC_TEST_DATABASE=disposable FABRIC_E2E_TOOLS="$TOOLS" +fail=0 +as_root="" +[ "$(id -u)" -eq 0 ] || as_root="sudo" + +php cli/plugin_manage.php --plugin=thold --plugin=maint --install --enable || exit 1 + +phase() { + php plugins/fabric/tests/bin/e2e.php "$1" "$STATE" || fail=1 +} + +poll() { + # Rates need at least a second between samples. + sleep 2 + php poller.php --poller=1 --force > /dev/null 2>&1 || { echo "FAIL the poller exited non-zero"; fail=1; } + # Thold checks thresholds in poller_thold.php, which its poller_bottom + # hook starts in the background. Run it in the foreground as well; a + # run refused because the background one holds Thold's process lock + # exits at once, so wait, bounded, until no Thold worker is registered. + php plugins/thold/poller_thold.php --force > /dev/null 2>&1 || { echo "FAIL the Thold worker exited non-zero"; fail=1; } + phase thold_idle +} + +phase tools +# A tool that is not installed could leave an older executable in place, +# which the sweep would then run: stop before setup. +$as_root install -d -o root -g root -m 0755 "$TOOLS" || { echo "FAIL could not create $TOOLS"; exit 1; } +for tool in ibnetdiscover iblinkinfo perfquery; do + $as_root install -o root -g root -m 0755 "$STATE/tools/$tool" "$TOOLS/$tool" || { echo "FAIL could not install the fake $tool"; exit 1; } +done + +phase setup +poll +phase check_setup + +for step in degrade restore burst steady reset maint stale; do + phase "$step" + poll + phase "check_$step" +done + +phase graph + +# The discontinuity is logged as a warning on purpose; anything else at +# warning level or above is a failure. Cacti 1.2.31's poller leaves some of +# these data sources' rows in poller_output each cycle, warns about it, and +# tries to email the primary admin; the 1.2.x branch rewrote that deletion +# and does not. On 1.2.31 only, those warnings are printed as notes, not +# failures, and the rows are listed. The Thold and Maint checks above still +# run in full. +known='counters went down' +if [ "$(cat include/cacti_version)" = '1.2.31' ]; then + known="$known|Poller Output Table not Empty|Data Sources not returning all data|is impacted by lack of complete information|Primary Admin account notifications disabled" + if grep -E "Poller Output Table not Empty|Data Sources not returning all data" log/cacti.log > /dev/null; then + echo "NOTE Cacti 1.2.31 left Fabric rows in poller_output:" + phase leftover + fi +fi +# Cacti 1.2.31 checks RRD file ownership right after an asynchronous create +# when the poller runs as root, as the local replay does; CI does not. +if [ "$(id -u)" = 0 ] && [ "$(cat include/cacti_version)" = '1.2.31' ]; then + known="$known|does not exist for ownership assignment" +fi +if grep -E "FATAL:|ERROR:|WARNING:" log/cacti.log | grep -Ev "$known"; then + echo "FAIL the Cacti log has errors" + fail=1 + phase leftover +fi + +exit $fail diff --git a/tests/bin/lifecycle.php b/tests/bin/lifecycle.php index 66c9ccf..9c25271 100644 --- a/tests/bin/lifecycle.php +++ b/tests/bin/lifecycle.php @@ -58,6 +58,12 @@ db_execute("DELETE FROM settings WHERE name LIKE 'fabric\\_%'"); db_execute("DELETE FROM plugin_db_changes WHERE plugin = 'fabric'"); + // The settings that record the query file as the plugin's are gone, + // so the file goes too; the templates stay, as on a real site. + if (is_file($config['base_path'] . '/resource/script_server/fabric_ports.xml')) { + unlink($config['base_path'] . '/resource/script_server/fabric_ports.xml'); + } + break; case 'install': api_plugin_install('fabric'); @@ -109,6 +115,13 @@ case 'drop_hook': db_execute_prepared("DELETE FROM plugin_hooks WHERE name = 'fabric' AND hook = ?", array($argument)); + break; + case 'drop_v2_columns': + // A version 1 database: the sample table before migration 2. + foreach (array('previous_at', 'rates', 'reset', 'discontinuities', 'discontinuity_at') as $column) { + db_execute('ALTER TABLE plugin_fabric_sample DROP COLUMN `' . $column . '`'); + } + break; case 'drop_table': db_execute('DROP TABLE IF EXISTS `' . preg_replace('/[^a-z_]/', '', $argument) . '`'); @@ -119,6 +132,15 @@ db_execute("INSERT INTO plugin_fabric_fabric (name, backend, poller_id, sweep_interval, adapter, adapter_port, admin_state) VALUES ('seed', 'diags', 1, 300, 'mlx5_0', 1, 'enabled')"); db_execute_prepared("INSERT INTO plugin_fabric_node (fabric_id, guid, node_type, presence, identity) VALUES (?, '0x0002c90300a00000', 'switch', 'present', 'ok')", array(db_fetch_insert_id())); + break; + case 'seed_sample': + $nodeId = (int) db_fetch_cell_prepared("SELECT id FROM plugin_fabric_node WHERE guid = ?", array('0x0002c90300a00000')); + db_execute_prepared("INSERT INTO plugin_fabric_sample (node_id, port_number, counter_group, observed_at, attempted_at, backend, cap_mask, cap_mask2, counters, error) VALUES (?, 1, 'basic', 100, 110, 'diags', 7, 8, ?, '')", array($nodeId, '{"PortXmitData":"123","PortRcvData":"456"}')); + + break; + case 'sample': + $result = db_fetch_row_prepared("SELECT node_id, port_number, counter_group, observed_at, attempted_at, backend, cap_mask, cap_mask2, counters, error, previous_at, rates, reset, discontinuities, discontinuity_at FROM plugin_fabric_sample WHERE port_number = 1 LIMIT 1", array()); + break; case 'sweep_flow': // A whole sweep against MariaDB through the real repositories and @@ -335,4 +357,15 @@ function fabric_sweep_flow(string $dir): array { 'admin' => (int) db_fetch_cell("SELECT COUNT(*) FROM user_auth_realm AS uar INNER JOIN plugin_realms AS pr ON pr.id + 100 = uar.realm_id WHERE pr.plugin = 'fabric' AND uar.user_id = 1"), 'tracked' => array_column(db_fetch_assoc("SELECT `table` FROM plugin_db_changes WHERE plugin = 'fabric' AND method = 'create' ORDER BY `table`"), 'table'), 'tables' => $tables, + 'columns' => array_column(db_fetch_assoc("SELECT COLUMN_NAME AS c FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'plugin_fabric_sample' ORDER BY ORDINAL_POSITION"), 'c'), + // The shipped Cacti objects, counted by name, so a duplicate shows. + 'objects' => array( + 'host_template' => (int) db_fetch_cell("SELECT COUNT(*) FROM host_template WHERE name = 'Fabric Node'"), + 'snmp_query' => (int) db_fetch_cell("SELECT COUNT(*) FROM snmp_query WHERE name = 'Fabric Port'"), + 'data_template' => (int) db_fetch_cell("SELECT COUNT(*) FROM data_template WHERE name LIKE 'Fabric Port %'"), + 'graph_template' => (int) db_fetch_cell("SELECT COUNT(*) FROM graph_templates WHERE name LIKE 'Fabric Port %'"), + 'rrd_items' => (int) db_fetch_cell("SELECT COUNT(*) FROM data_template_rrd AS r INNER JOIN data_template AS t ON t.id = r.data_template_id WHERE t.name LIKE 'Fabric Port %' AND r.local_data_id = 0"), + 'query_file' => is_file($config['base_path'] . '/resource/script_server/fabric_ports.xml'), + 'version' => db_fetch_cell("SELECT value FROM settings WHERE name = 'fabric_templates_version'"), + ), ), JSON_PRETTY_PRINT) . PHP_EOL; diff --git a/tests/bin/page-permissions.php b/tests/bin/page-permissions.php index 8bf9d68..0fd1d1c 100644 --- a/tests/bin/page-permissions.php +++ b/tests/bin/page-permissions.php @@ -88,7 +88,7 @@ $fabric = (int) db_fetch_insert_id(); $devices = array(); $nodes = array(); -$guids = array('open' => '0x0002c90300b00010', 'hidden' => '0x0002c90300b00020', 'unmapped' => '0x0002c90300b00030', 'new' => '0x0002c90300b00040'); +$guids = array('open' => '0x0002c90300b00010', 'hidden' => '0x0002c90300b00020', 'unmapped' => '0x0002c90300b00030', 'new' => '0x0002c90300b00040', 'fresh' => '0x0002c90300b00050'); foreach ($guids as $key => $guid) { $host = 0; @@ -98,11 +98,23 @@ $host = $devices[$key] = (int) db_fetch_insert_id(); } - // The unmapped node went missing; "new" replaced it on the same switch port. + // The unmapped node went missing; "new" replaced it on the same switch + // port. "fresh" is present and unmapped, for device creation. db_execute_prepared("INSERT INTO plugin_fabric_node (fabric_id, guid, node_type, port_count, description, host_id, presence, identity) VALUES (?, ?, 'ca', 1, ?, ?, ?, 'ok')", array($fabric, $guid, '', $host, $key === 'unmapped' ? 'missing' : 'present')); $nodes[$key] = (int) db_fetch_insert_id(); + // Active ports with a remote end, so a mapped device has indexes. + db_execute_prepared("INSERT INTO plugin_fabric_port (node_id, port_number, presence, logical_state, remote_guid, remote_port) VALUES (?, 1, 'present', 'active', '0x0002c90300a00000', 1)", array($nodes[$key])); } +// A Fabric Port Traffic graph on the open device's port 1, as the New +// Graphs page would make it, for the graph link checks. +$traffic = (int) db_fetch_cell_prepared('SELECT id FROM graph_templates WHERE hash = ?', array(md5('plugin_fabric:graph_template:Fabric Port Traffic'))); +$query = (int) db_fetch_cell_prepared('SELECT id FROM snmp_query WHERE hash = ?', array(md5('plugin_fabric:data_query:Fabric Port'))); +db_execute_prepared('INSERT INTO graph_local (host_id, graph_template_id, snmp_query_id, snmp_index) VALUES (?, ?, ?, ?)', array($devices['open'], $traffic, $query, $guids['open'] . ':1')); +$graph = (int) db_fetch_insert_id(); +db_execute_prepared("INSERT INTO graph_templates_graph (local_graph_id, graph_template_id, title_cache) VALUES (?, ?, 'fabric probe graph')", array($graph, $traffic)); +$graphLink = 'graph.php?local_graph_id=' . $graph . '&rra_id=all'; + foreach (array('viewer', 'restricted') as $name) { db_execute_prepared('INSERT INTO user_auth_perms (user_id, item_id, type) VALUES (?, ?, 3)', array($users[$name], $devices['open'])); } @@ -178,6 +190,14 @@ function perm_login($user) { perm_expect(strpos($body, 'login_username') !== false, "anonymous is sent to the login form from $page"); } + if ($page === 'fabric.php' && $allowed && $user !== 'anonymous') { + list(, $nodePage) = perm_http($base . 'fabric.php?node=' . $nodes['open'], $jar); + perm_expect($traffic > 0 && strpos($nodePage, $graphLink) !== false, "$user sees the link to a Traffic graph it may view (permissive graph permissions)"); + + list(, $ranking) = perm_http($base . 'fabric.php?view=congestion', $jar); + perm_expect(strpos($ranking, 'Ports with the Highest Transmit Wait') !== false && strpos($ranking, $guids['hidden']) === false, "$user's congestion ranking loads and leaves out what it may not see"); + } + if ($page === 'fabric.php' && $allowed) { $all = $user === 'admin'; $realm = $user !== 'viewer'; @@ -242,6 +262,116 @@ function perm_login($user) { list(, $health) = perm_http($base . 'fabric_health.php', $jar); perm_expect(strpos($health, '0 identity conflicts and 1 open re-link proposals') !== false, 'restricted admin: health counts leave out the hidden device node'); +// Fabric Admin alone does not grant Cacti's device management or template +// import: no device is created and no template reinstalled. +$hostCount = function () { + return (int) db_fetch_cell('SELECT COUNT(*) FROM host'); +}; +$before = $hostCount(); +list(, $edit) = perm_http($base . 'fabric_admin.php?action=edit_node&id=' . $nodes['fresh'], $jar); +perm_expect(strpos($edit, 'name="host_id"') !== false && strpos($edit, 'create_device') === false, 'restricted admin without device management: no create action on an unmapped node'); +list(, $confirm) = perm_http($base . 'fabric_admin.php?action=create_device&id=' . $nodes['fresh'], $jar); +perm_expect(strpos($confirm, 'Creating the device adds') === false, 'restricted admin without device management: the creation page is denied'); +perm_http($base . 'fabric_admin.php', $jar, array('__csrf_magic' => $token, 'action' => 'create_device_confirm', 'id' => $nodes['fresh'], 'revision' => $node_row($nodes['fresh'])['revision'])); +perm_expect($hostCount() === $before && $host_of($nodes['fresh']) === 0, 'restricted admin without device management: a creation POST creates nothing'); +// The query file goes missing, as when an operator removes it; only the +// health page notices, and only a user who may import templates can put +// it back. +$queryFile = $config['base_path'] . '/resource/script_server/fabric_ports.xml'; +unlink($queryFile); +list(, $health) = perm_http($base . 'fabric_health.php', $jar); +perm_expect(strpos($health, 'is missing or differs') !== false && strpos($health, 'reinstall_templates') === false, 'restricted admin without template import: the missing query file is shown, with no reinstall action'); +perm_http($base . 'fabric_health.php', $jar, array('__csrf_magic' => perm_token($health), 'action' => 'reinstall_templates')); +clearstatcache(); +perm_expect(!is_file($queryFile), 'restricted admin without template import: a reinstall POST installs nothing'); + +unlink($jar); + +// Graph links follow core's graph permissions, not the plugin's: under +// restrictive graph permissions the viewer, who has no grant on the graph +// template, gets no link to the graph. +db_execute("REPLACE INTO settings (name, value) VALUES ('graph_auth_method', '2')"); +// Core caches allowed-graph counts per user for a day. +// A second graph on the device, from a template the viewer is granted, so +// the device stays visible under the restrictive rule. +$errorsTemplate = (int) db_fetch_cell_prepared('SELECT id FROM graph_templates WHERE hash = ?', array(md5('plugin_fabric:graph_template:Fabric Port Errors'))); +db_execute_prepared('INSERT INTO graph_local (host_id, graph_template_id, snmp_query_id, snmp_index) VALUES (?, ?, ?, ?)', array($devices['open'], $errorsTemplate, $query, $guids['open'] . ':1')); +$errorsGraph = (int) db_fetch_insert_id(); +db_execute_prepared("INSERT INTO graph_templates_graph (local_graph_id, graph_template_id, title_cache) VALUES (?, ?, 'fabric probe errors graph')", array($errorsGraph, $errorsTemplate)); +db_execute_prepared('INSERT INTO user_auth_perms (user_id, item_id, type) VALUES (?, ?, 4)', array($users['viewer'], $errorsTemplate)); +db_execute('DELETE FROM user_auth_row_cache'); +$jar = perm_login('viewer'); +list(, $nodePage) = perm_http($base . 'fabric.php?node=' . $nodes['open'], $jar); +include_once('./lib/auth.php'); +set_config_option('graph_auth_method', '2'); +$errorsLink = 'graph.php?local_graph_id=' . $errorsGraph . '&rra_id=all'; +perm_expect(is_device_allowed($devices['open'], $users['viewer']) && strpos($nodePage, $guids['open']) !== false, 'viewer: the node of a device core allows under restrictive graph permissions is shown'); +perm_expect(!is_graph_allowed($graph, $users['viewer']) && strpos($nodePage, $graphLink) === false, 'viewer: no link to a graph whose template restrictive graph permissions deny, as core decides'); +perm_expect(is_graph_allowed($errorsGraph, $users['viewer']) && strpos($nodePage, $errorsLink) !== false, 'viewer: a link to the graph whose template is granted, as core decides'); +unlink($jar); +db_execute("REPLACE INTO settings (name, value) VALUES ('graph_auth_method', '1')"); +db_execute_prepared('DELETE FROM user_auth_perms WHERE user_id = ? AND type = 4', array($users['viewer'])); +db_execute_prepared('DELETE FROM graph_templates_graph WHERE local_graph_id = ?', array($errorsGraph)); +db_execute_prepared('DELETE FROM graph_local WHERE id = ?', array($errorsGraph)); + +// A full administrator creates a device for the fresh node: a GET shows +// what will be added and changes nothing; the POST creates the device on +// the fabric's poller, maps the node, and adds the data query. +$jar = perm_login('admin'); + +// The template reinstall needs template import, which the admin holds. +list(, $health) = perm_http($base . 'fabric_health.php', $jar); +perm_expect(strpos($health, 'reinstall_templates') !== false && strpos($health, 'Cacti Objects') !== false, 'admin: the health page offers the reinstall while the query file is missing'); +perm_http($base . 'fabric_health.php?action=reinstall_templates', $jar); +clearstatcache(); +perm_expect(!is_file($queryFile), 'admin: a reinstall sent as GET has no effect'); +perm_http($base . 'fabric_health.php', $jar, array('__csrf_magic' => perm_token($health), 'action' => 'reinstall_templates')); +clearstatcache(); +perm_expect(is_file($queryFile) && (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM graph_templates WHERE hash = ?', array(md5('plugin_fabric:graph_template:Fabric Port Traffic'))) === 1, 'admin: a reinstall POST restores the query file without duplicating the templates'); + + +$before = $hostCount(); +list(, $confirm) = perm_http($base . 'fabric_admin.php?action=create_device&id=' . $nodes['fresh'], $jar); +perm_expect(strpos($confirm, 'Creating the device adds') !== false && $hostCount() === $before, 'admin: the creation page shows the plan and creates nothing'); +perm_http($base . 'fabric_admin.php?action=create_device_confirm&id=' . $nodes['fresh'], $jar); +perm_expect($hostCount() === $before, 'admin: a creation sent as GET has no effect'); +perm_http($base . 'fabric_admin.php', $jar, array('__csrf_magic' => perm_token($confirm), 'action' => 'create_device_confirm', 'id' => $nodes['fresh'], 'revision' => $node_row($nodes['fresh'])['revision'])); +$created = $host_of($nodes['fresh']); +$row = db_fetch_row_prepared('SELECT hostname, poller_id, availability_method, snmp_version FROM host WHERE id = ?', array($created)); +perm_expect($created > 0 && $hostCount() === $before + 1 && is_array($row) && $row['hostname'] === '0002c90300b00050.fabric.invalid' && (int) $row['poller_id'] === 1 && (int) $row['availability_method'] === 0 && (int) $row['snmp_version'] === 0, 'admin: a creation POST makes one device with a reserved host name, no checks, and the fabric poller'); +perm_expect((int) db_fetch_cell_prepared('SELECT COUNT(*) FROM host_snmp_query WHERE host_id = ? AND snmp_query_id = ? AND reindex_method = 2', array($created, $query)) === 1, 'admin: the created device has the Fabric Port data query with Index Count Changed, whatever the site default'); +$cached = function () use ($created, $query) { + return (int) db_fetch_cell_prepared('SELECT COUNT(DISTINCT snmp_index) FROM host_snmp_cache WHERE host_id = ? AND snmp_query_id = ?', array($created, $query)); +}; +perm_expect($cached() === 1, 'admin: the created device lists the node\'s port (' . $cached() . ' indexes)'); +list(, $again) = perm_http($base . 'fabric_admin.php', $jar, array('__csrf_magic' => perm_token($confirm), 'action' => 'create_device_confirm', 'id' => $nodes['fresh'], 'revision' => $node_row($nodes['fresh'])['revision'])); +perm_expect($hostCount() === $before + 1, 'admin: a second creation for a mapped node creates nothing'); + +// Mapping to a device another poller polls is refused. +db_execute("REPLACE INTO poller (id, name, hostname, disabled) VALUES (3, 'fabric-other', 'other.invalid', 'on')"); +db_execute("INSERT INTO host (description, hostname, poller_id) VALUES ('Other poller', 'other.invalid', 3)"); +$other = (int) db_fetch_insert_id(); +list(, $list) = perm_http($base . 'fabric_admin.php', $jar); +perm_http($base . 'fabric_admin.php', $jar, array('__csrf_magic' => perm_token($list), 'action' => 'save_node', 'id' => $nodes['fresh'], 'revision' => $node_row($nodes['fresh'])['revision'], 'host_id' => $other)); +perm_expect($host_of($nodes['fresh']) === $created, 'admin: mapping a node to a device on another poller is refused'); +db_execute_prepared('DELETE FROM host WHERE id = ?', array($other)); +db_execute('DELETE FROM poller WHERE id = 3'); + +// Unmapping the last node empties the device's port list, which an empty +// script query would not do on Cacti 1.2.31; the device itself stays. +list(, $list) = perm_http($base . 'fabric_admin.php', $jar); +perm_http($base . 'fabric_admin.php', $jar, array('__csrf_magic' => perm_token($list), 'action' => 'save_node', 'id' => $nodes['fresh'], 'revision' => $node_row($nodes['fresh'])['revision'], 'host_id' => 0)); +perm_expect($host_of($nodes['fresh']) === 0 && $cached() === 0 && $hostCount() === $before + 1, 'admin: unmapping the last node of a device clears its port list and keeps the device (' . $cached() . ' indexes)'); +list(, $list) = perm_http($base . 'fabric_admin.php', $jar); +perm_http($base . 'fabric_admin.php', $jar, array('__csrf_magic' => perm_token($list), 'action' => 'save_node', 'id' => $nodes['fresh'], 'revision' => $node_row($nodes['fresh'])['revision'], 'host_id' => $created)); +perm_expect($host_of($nodes['fresh']) === $created && $cached() === 1, 'admin: mapping the node again lists its port again'); + +// Deleting the device in Cacti clears the mapping through the device_remove hook. +include_once('./lib/api_device.php'); +api_device_remove($created); +perm_expect($host_of($nodes['fresh']) === 0, 'deleting a mapped device in Cacti unmaps its node'); + + unlink($jar); $jar = perm_login('admin'); @@ -323,12 +453,12 @@ function perm_login($user) { // The export is Fabric Admin only and holds every record. list($code, $export) = perm_http($base . 'fabric_admin.php?action=export', $jar); $document = json_decode($export, true); -perm_expect($code === 200 && is_array($document) && count($document['fabrics']) === 1 && count($document['nodes']) === 4 && strpos($export, ' perm_token($confirm), 'action' => 'delete_fabric_confirm', 'id' => $fabric)); -perm_expect($exists() && strpos($busy, 'A sweep of this fabric is running') !== false && (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM plugin_fabric_node WHERE fabric_id = ?', array($fabric)) === 4, 'a fabric delete is refused while a sweep of it holds a claim, and nothing is removed'); +perm_expect($exists() && strpos($busy, 'A sweep of this fabric is running') !== false && (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM plugin_fabric_node WHERE fabric_id = ?', array($fabric)) === 5, 'a fabric delete is refused while a sweep of it holds a claim, and nothing is removed'); db_execute_prepared("UPDATE plugin_fabric_claim SET expires_at = 0 WHERE scope = 'topology' AND claim_key = ?", array($fabric)); perm_http($base . 'fabric_admin.php', $jar, array('__csrf_magic' => perm_token($confirm), 'action' => 'delete_fabric_confirm', 'id' => $fabric)); diff --git a/tests/bin/php-guard-check.php b/tests/bin/php-guard-check.php index 81e2e23..e442a16 100644 --- a/tests/bin/php-guard-check.php +++ b/tests/bin/php-guard-check.php @@ -113,7 +113,7 @@ function guard_call_shims() { if ($supported) { guard_expect($state['status'] == 1, 'install and enable succeed (status ' . $state['status'] . ')'); guard_expect($state['tables'] === 8, 'all eight plugin tables exist (' . $state['tables'] . ')'); - guard_expect($state['hooks'] === 3 && $state['realms'] === 2, 'hooks and realms are registered'); + guard_expect($state['hooks'] === 4 && $state['realms'] === 2, 'hooks and realms are registered'); } else { guard_expect($state['status'] == 2, 'plugin is left as needing configuration, not enabled (status ' . $state['status'] . ')'); guard_expect($state['tables'] === 0 && $state['hooks'] === 0 && $state['realms'] === 0, 'no tables, hooks, or realms were created'); diff --git a/tests/bin/scale.php b/tests/bin/scale.php new file mode 100644 index 0000000..b42c213 --- /dev/null +++ b/tests/bin/scale.php @@ -0,0 +1,256 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_fabric, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_fabric + * + * 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. + */ + +if (PHP_SAPI !== 'cli') { + exit(1); +} + + +/* + * Scale measurements at the documented fabric sizes (#49, docs/PLAN.md + * "Performance"), with the fabric generator and the fake tools, through + * the production sweep, repositories, data query, and pages: + * + * FABRIC_TEST_DATABASE=disposable FABRIC_E2E_TOOLS= \ + * php plugins/fabric/tests/bin/scale.php ... + * + * For each size: the topology import, counter sweeps of a sample of nodes, + * the data query's index and get answers for a switch device, the + * inventory page. For the first size only, every graph of every port of + * that switch is created and Cacti's poller timed over them, for measured + * object counts and poll times. Prints one JSON + * line per size. The fake tools are PHP scripts, so tool time is PHP start + * up, not fabric round trips: the sweep figures measure the plugin's own + * work, never a fabric's. Disposable databases only. Must parse on PHP 8.0. + */ + +chdir(dirname(__DIR__, 4)); + +require('./include/cli_check.php'); + +if (getenv('FABRIC_TEST_DATABASE') !== 'disposable') { + fwrite(STDERR, "Set FABRIC_TEST_DATABASE=disposable\n"); + exit(2); +} + +include_once($config['base_path'] . '/plugins/fabric/setup.php'); + +if (!fabric_boot()) { + exit(2); +} + +require_once($config['base_path'] . '/plugins/fabric/tests/Support/FabricGenerator.php'); +require_once($config['base_path'] . '/plugins/fabric/tests/Support/FakeTools.php'); +require_once($config['base_path'] . '/lib/api_device.php'); +require_once($config['base_path'] . '/lib/data_query.php'); +require_once($config['base_path'] . '/lib/template.php'); +require_once($config['base_path'] . '/lib/api_graph.php'); +require_once($config['base_path'] . '/lib/api_data_source.php'); +require_once($config['base_path'] . '/lib/utility.php'); + +use Somethingwithproof\Fabric\Tests\FabricGenerator as G; +use Somethingwithproof\Fabric\Tests\FakeTools; + +$stateDir = rtrim($argv[1], '/'); +$sizes = array_map('intval', array_slice($argv, 2)); +$sample = 25; + +set_config_option('fabric_tool_dir', (string) getenv('FABRIC_E2E_TOOLS')); + +foreach ($sizes as $adapters) { + db_execute('DELETE FROM plugin_fabric_fabric'); + foreach (array('node', 'port', 'sample', 'node_sweep', 'health', 'claim', 'relink') as $t) { + db_execute("DELETE FROM plugin_fabric_$t"); + } + + $gen = G::forCas($adapters); + FakeTools::state($stateDir, $gen); + @unlink($stateDir . '/calls.log'); + + db_execute("INSERT INTO plugin_fabric_fabric (name, backend, poller_id, sweep_interval, adapter, adapter_port, admin_state) VALUES ('scale', 'diags', 1, 300, 'mlx5_0', 1, 'enabled')"); + $fabricId = (int) db_fetch_insert_id(); + $clock = new \Somethingwithproof\Fabric\SystemClock(); + $nodes = new \Somethingwithproof\Fabric\NodeRepository(false); + + // The first sweep with a node GUID runs the topology (ibnetdiscover, + // iblinkinfo, and the import) and that node's counters. + $switch = \Somethingwithproof\Fabric\Guid::fromString(sprintf('0x%016x', G::SWITCH_BASE)); + $t = microtime(true); + fabric_sweep()->forFabric($fabricId, $switch, true); + $first = microtime(true) - $t; + + $all = $nodes->forFabric($fabricId) ?? array(); + $ports = (int) db_fetch_cell('SELECT COUNT(*) FROM plugin_fabric_port'); + $sampled = array_slice(array_values(array_filter($all, static function ($n) { + return $n->type === \Somethingwithproof\Fabric\NodeType::Adapter; + })), 0, $sample); + $health = (new \Somethingwithproof\Fabric\FabricHealthRepository(false))->find($fabricId); + // Link discovery adds every switch port. Only each adapter's linked + // port has a GUID in ibnetdiscover and can be joined to link discovery. + $expectedPorts = $adapters + 36 * (count($gen->nodes) - $adapters); + + if ($health === null || ($health['discovery_error'] ?? 'missing') !== '' || ($health['links_error'] ?? 'missing') !== '' + || (int) ($health['discovery_success'] ?? 0) === 0 || (int) ($health['links_success'] ?? 0) === 0 + || count($all) !== count($gen->nodes) || $ports !== $expectedPorts + || count($sampled) !== min($sample, $adapters)) { + throw new RuntimeException('Scale measurement refused: topology import is incomplete: ' . json_encode(array('health' => $health, 'nodes' => count($all), 'ports' => $ports, 'expected_ports' => $expectedPorts, 'sampled' => count($sampled)))); + } + + $t = microtime(true); + + // Not forced, as the poller sweeps: a forced run repeats the topology. + foreach ($sampled as $node) { + fabric_sweep()->forFabric($fabricId, $node->guid, false); + } + + $perNode = $sampled === array() ? 0.0 : (microtime(true) - $t) / count($sampled); + $sweeps = (new \Somethingwithproof\Fabric\NodeSweepRepository(false))->all(); + $measured = array_filter($all, static function ($n) use ($switch, $sampled) { + return $n->guid->equals($switch) || in_array($n, $sampled, true); + }); + + foreach ($measured as $node) { + $result = $sweeps[$node->id] ?? array(); + + if (($result['outcome'] ?? '') !== 'completed' || ($result['error'] ?? 'missing') !== '' + || (int) ($result['ports_total'] ?? 0) === 0 + || (int) $result['ports_read'] !== (int) $result['ports_total'] + || (int) $result['ports_failed'] !== 0 || (int) $result['ports_skipped'] !== 0) { + throw new RuntimeException('Scale measurement refused: incomplete counter sweep for node ' . $node->id); + } + } + + // One switch mapped to a device: the data query answers from the cache. + db_execute("INSERT INTO host (description, hostname, poller_id, availability_method, snmp_version, status) VALUES ('scale switch', 'scale.invalid', 1, 0, 0, 3)"); + $host = (int) db_fetch_insert_id(); + db_execute_prepared('UPDATE plugin_fabric_node SET host_id = ? WHERE guid = ?', array($host, $switch->text)); + + $query = new \Somethingwithproof\Fabric\PortQuery(false, $clock, false, null); + $t = microtime(true); + $index = $query->answer($host, 'index'); + $tIdx = microtime(true) - $t; + $keys = array_filter(explode("\n", $index)); + $t = microtime(true); + + foreach ($keys as $key) { + foreach (\Somethingwithproof\Fabric\PortValues::names() as $name) { + $query->answer($host, 'get', $name, $key); + } + } + + $gets = count($keys) * count(\Somethingwithproof\Fabric\PortValues::names()); + $tGet = $gets > 0 ? (microtime(true) - $t) / $gets : 0.0; + + // The inventory overview, rendered as for an administrator. + $page = new \Somethingwithproof\Fabric\InventoryPage(new \Somethingwithproof\Fabric\FabricRepository(false, $clock), $nodes, new \Somethingwithproof\Fabric\SampleRepository(false), $clock, static function (int $h): bool { + return true; + }, true); + ob_start(); + $t = microtime(true); + $page->renderList(); + $tPage = microtime(true) - $t; + $bytes = strlen((string) ob_get_clean()); + + // Measured Cacti objects and a poller run, on the first size only. + $objects = null; + + if ($adapters === $sizes[0]) { + $queryId = (int) db_fetch_cell_prepared('SELECT id FROM snmp_query WHERE hash = ?', array(\Somethingwithproof\Fabric\TemplateInstaller::hash('data_query', 'Fabric Port'))); + api_device_dq_add($host, $queryId, DATA_QUERY_AUTOINDEX_INDEX_NUM_CHANGE); + $indexes = array_column(db_fetch_assoc_prepared('SELECT DISTINCT snmp_index FROM host_snmp_cache WHERE host_id = ?', array($host)), 'snmp_index'); + + foreach ($indexes as $index) { + foreach (array_keys(\Somethingwithproof\Fabric\PortValues::templates()) as $name) { + $gt = (int) db_fetch_cell_prepared('SELECT id FROM graph_templates WHERE hash = ?', array(\Somethingwithproof\Fabric\TemplateInstaller::hash('graph_template', $name))); + $sqg = (int) db_fetch_cell_prepared('SELECT id FROM snmp_query_graph WHERE hash = ?', array(\Somethingwithproof\Fabric\TemplateInstaller::hash('data_query_graph', 'Fabric Port:' . $name))); + $vals = array(); + $made = create_complete_graph_from_template($gt, $host, array('snmp_query_id' => $queryId, 'snmp_index_on' => 'fabricPort', 'snmp_index' => $index, 'snmp_query_graph_id' => $sqg), $vals); + + foreach ($made['local_data_id'] as $localDataId) { + push_out_host($host, $localDataId); + } + } + } + + // Availability checks are off, as on a created device, so the poller + // polls every item instead of skipping a host it reads as down. + db_execute('UPDATE plugin_fabric_node_sweep SET last_attempt = 0'); + $log = $config['base_path'] . '/log/cacti.log'; + clearstatcache(true, $log); + $at = is_file($log) ? (int) filesize($log) : 0; + exec(escapeshellarg(PHP_BINARY) . ' ' . escapeshellarg($config['base_path'] . '/poller.php') . ' --poller=1 --force 2>&1', $output, $status); + + if ($status !== 0) { + throw new RuntimeException('Scale poller failed: ' . implode("\n", $output)); + } + + $stats = ''; + + foreach (array_reverse(explode("\n", (string) file_get_contents($log, false, null, $at))) as $line) { + if (strpos($line, 'SYSTEM STATS:') !== false) { + $stats = trim(substr($line, strpos($line, 'SYSTEM STATS:') + 13)); + + break; + } + } + + if ($stats === '') { + throw new RuntimeException('Scale poller did not append SYSTEM STATS to the log'); + } + + $objects = array( + 'ports' => count($indexes), + 'graphs' => (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM graph_local WHERE host_id = ?', array($host)), + 'data_sources' => (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM data_local WHERE host_id = ?', array($host)), + 'rrd_items' => (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM data_template_rrd AS r INNER JOIN data_local AS l ON l.id = r.local_data_id WHERE l.host_id = ?', array($host)), + 'poller_items' => (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM poller_item WHERE host_id = ?', array($host)), + 'poller_stats' => $stats, + ); + + foreach (db_fetch_assoc_prepared('SELECT id FROM graph_local WHERE host_id = ?', array($host)) as $g) { + db_execute_prepared('DELETE FROM graph_templates_item WHERE local_graph_id = ?', array($g['id'])); + db_execute_prepared('DELETE FROM graph_templates_graph WHERE local_graph_id = ?', array($g['id'])); + } + + api_device_remove($host); + } + + $calls = FakeTools::calls($stateDir); + $tools = array_count_values(array_column($calls, 'tool')); + + print json_encode(array( + 'adapters' => $adapters, + 'nodes' => count($all), + 'ports' => $ports, + 'topology_and_one_node' => round($first, 3), + 'counter_sweep_per_node' => round($perNode, 3), + 'sampled_nodes' => count($sampled), + 'tool_runs' => $tools, + 'samples' => (int) db_fetch_cell('SELECT COUNT(*) FROM plugin_fabric_sample'), + 'index_answer' => round($tIdx, 4), + 'index_rows' => count($keys), + 'get_answer_ms' => round($tGet * 1000, 3), + 'overview_render' => round($tPage, 3), + 'overview_bytes' => $bytes, + 'memory_peak_mb' => round(memory_get_peak_usage(true) / 1048576, 1), + 'cacti_objects' => $objects, + )) . PHP_EOL; + + db_execute_prepared('DELETE FROM host WHERE id = ?', array($host)); +} diff --git a/tests/bootstrap-unit.php b/tests/bootstrap-unit.php index a87cd97..644f5a7 100644 --- a/tests/bootstrap-unit.php +++ b/tests/bootstrap-unit.php @@ -96,6 +96,13 @@ function db_execute_prepared($sql, $params = [], $log = true, $db_conn = false, $GLOBALS['__fabric_db_exec'][] = ['sql' => $sql, 'params' => $params]; $GLOBALS['__fabric_insert_id'] = str_starts_with(ltrim($sql), 'INSERT') ? count($GLOBALS['__fabric_db_exec']) : 0; + // A test makes writes containing a needle fail, as a lost database would. + foreach ($GLOBALS['__fabric_db_fail'] ?? [] as $needle) { + if (str_contains($sql, $needle)) { + return false; + } + } + return true; } } diff --git a/tests/fixtures/ibsim/degraded/iblinkinfo-line.out b/tests/fixtures/ibsim/degraded/iblinkinfo-line.out new file mode 100644 index 0000000..1617110 --- /dev/null +++ b/tests/fixtures/ibsim/degraded/iblinkinfo-line.out @@ -0,0 +1,38 @@ +0x0002c90300bb0009 " node04 mlx5_0" 10 1[ ] ==( 4X 2.5 Gbps Active/ LinkUp)==> 0x0002c90300aa0003 4 3[ ] "leaf2 MQM8700" (Could be 12X Could be 10.0 Gbps) +0x0002c90300aa0003 " leaf2 MQM8700" 4 1[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300bb0002 6 2[ ] "node01 mlx5_0" (Could be 12X ) +0x0002c90300aa0003 " leaf2 MQM8700" 4 2[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300bb0005 8 2[ ] "node02 mlx5_0" (Could be 12X ) +0x0002c90300aa0003 " leaf2 MQM8700" 4 3[ ] ==( 4X 2.5 Gbps Active/ LinkUp)==> 0x0002c90300bb0009 10 1[ ] "node04 mlx5_0" (Could be 12X Could be 10.0 Gbps) +0x0002c90300aa0003 " leaf2 MQM8700" 4 4[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0003 " leaf2 MQM8700" 4 5[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300aa0000 1 2[ ] "spine1 MQM8700" (Could be 12X ) +0x0002c90300aa0003 " leaf2 MQM8700" 4 6[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300aa0001 2 2[ ] "spine2 MQM8700" (Could be 12X ) +0x0002c90300aa0003 " leaf2 MQM8700" 4 7[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0003 " leaf2 MQM8700" 4 8[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0001 " spine2 MQM8700" 2 1[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300aa0002 3 6[ ] "leaf1 MQM8700" (Could be 12X ) +0x0002c90300aa0001 " spine2 MQM8700" 2 2[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300aa0003 4 6[ ] "leaf2 MQM8700" (Could be 12X ) +0x0002c90300aa0001 " spine2 MQM8700" 2 3[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0001 " spine2 MQM8700" 2 4[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0001 " spine2 MQM8700" 2 5[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0001 " spine2 MQM8700" 2 6[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0001 " spine2 MQM8700" 2 7[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0001 " spine2 MQM8700" 2 8[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0000 " spine1 MQM8700" 1 1[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300aa0002 3 5[ ] "leaf1 MQM8700" (Could be 12X ) +0x0002c90300aa0000 " spine1 MQM8700" 1 2[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300aa0003 4 5[ ] "leaf2 MQM8700" (Could be 12X ) +0x0002c90300aa0000 " spine1 MQM8700" 1 3[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0000 " spine1 MQM8700" 1 4[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0000 " spine1 MQM8700" 1 5[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0000 " spine1 MQM8700" 1 6[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0000 " spine1 MQM8700" 1 7[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0000 " spine1 MQM8700" 1 8[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300bb0007 " node03 mlx5_0" 9 1[ ] ==( 1X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300aa0002 3 3[ ] "leaf1 MQM8700" (Could be 12X ) +0x0002c90300bb0004 " node02 mlx5_0" 7 1[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300aa0002 3 2[ ] "leaf1 MQM8700" (Could be 12X ) +0x0002c90300bb0005 " node02 mlx5_0" 8 2[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300aa0003 4 2[ ] "leaf2 MQM8700" (Could be 12X ) +0x0002c90300aa0002 " leaf1 MQM8700" 3 1[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300bb0001 5 1[ ] "node01 mlx5_0" (Could be 12X ) +0x0002c90300aa0002 " leaf1 MQM8700" 3 2[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300bb0004 7 1[ ] "node02 mlx5_0" (Could be 12X ) +0x0002c90300aa0002 " leaf1 MQM8700" 3 3[ ] ==( 1X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300bb0007 9 1[ ] "node03 mlx5_0" (Could be 12X ) +0x0002c90300aa0002 " leaf1 MQM8700" 3 4[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0002 " leaf1 MQM8700" 3 5[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300aa0000 1 1[ ] "spine1 MQM8700" (Could be 12X ) +0x0002c90300aa0002 " leaf1 MQM8700" 3 6[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300aa0001 2 1[ ] "spine2 MQM8700" (Could be 12X ) +0x0002c90300aa0002 " leaf1 MQM8700" 3 7[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0002 " leaf1 MQM8700" 3 8[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300bb0001 " node01 mlx5_0" 5 1[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300aa0002 3 1[ ] "leaf1 MQM8700" (Could be 12X ) +0x0002c90300bb0002 " node01 mlx5_0" 6 2[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300aa0003 4 1[ ] "leaf2 MQM8700" (Could be 12X ) diff --git a/tests/fixtures/ibsim/degraded/ibnetdiscover.out b/tests/fixtures/ibsim/degraded/ibnetdiscover.out new file mode 100644 index 0000000..93d4031 --- /dev/null +++ b/tests/fixtures/ibsim/degraded/ibnetdiscover.out @@ -0,0 +1,72 @@ +# +# Topology file: generated on Sun Nov 15 15:17:41 2026 +# +# Initiated from node 0002c90300bb0000 port 0002c90300bb0001 + +vendid=0x0 +devid=0xd2f2 +sysimgguid=0x2c90300aa0003 +switchguid=0x2c90300aa0003(2c90300aa0003) +Switch 8 "S-0002c90300aa0003" # "leaf2 MQM8700" base port 0 lid 4 lmc 0 +[1] "H-0002c90300bb0000"[2](2c90300bb0002) # "node01 mlx5_0" lid 6 4xQDR +[2] "H-0002c90300bb0003"[2](2c90300bb0005) # "node02 mlx5_0" lid 8 4xQDR +[3] "H-0002c90300bb0008"[1](2c90300bb0009) # "node04 mlx5_0" lid 10 4xSDR +[5] "S-0002c90300aa0000"[2] # "spine1 MQM8700" lid 1 4xQDR +[6] "S-0002c90300aa0001"[2] # "spine2 MQM8700" lid 2 4xQDR + +vendid=0x0 +devid=0xd2f2 +sysimgguid=0x2c90300aa0001 +switchguid=0x2c90300aa0001(2c90300aa0001) +Switch 8 "S-0002c90300aa0001" # "spine2 MQM8700" base port 0 lid 2 lmc 0 +[1] "S-0002c90300aa0002"[6] # "leaf1 MQM8700" lid 3 4xQDR +[2] "S-0002c90300aa0003"[6] # "leaf2 MQM8700" lid 4 4xQDR + +vendid=0x0 +devid=0xd2f2 +sysimgguid=0x2c90300aa0000 +switchguid=0x2c90300aa0000(2c90300aa0000) +Switch 8 "S-0002c90300aa0000" # "spine1 MQM8700" base port 0 lid 1 lmc 0 +[1] "S-0002c90300aa0002"[5] # "leaf1 MQM8700" lid 3 4xQDR +[2] "S-0002c90300aa0003"[5] # "leaf2 MQM8700" lid 4 4xQDR + +vendid=0x0 +devid=0xd2f2 +sysimgguid=0x2c90300aa0002 +switchguid=0x2c90300aa0002(2c90300aa0002) +Switch 8 "S-0002c90300aa0002" # "leaf1 MQM8700" base port 0 lid 3 lmc 0 +[1] "H-0002c90300bb0000"[1](2c90300bb0001) # "node01 mlx5_0" lid 5 4xQDR +[2] "H-0002c90300bb0003"[1](2c90300bb0004) # "node02 mlx5_0" lid 7 4xQDR +[3] "H-0002c90300bb0006"[1](2c90300bb0007) # "node03 mlx5_0" lid 9 1xQDR +[5] "S-0002c90300aa0000"[1] # "spine1 MQM8700" lid 1 4xQDR +[6] "S-0002c90300aa0001"[1] # "spine2 MQM8700" lid 2 4xQDR + +vendid=0x0 +devid=0xd2f2 +sysimgguid=0x2c90300bb0008 +caguid=0x2c90300bb0008 +Ca 1 "H-0002c90300bb0008" # "node04 mlx5_0" +[1](2c90300bb0009) "S-0002c90300aa0003"[3] # lid 10 lmc 0 "leaf2 MQM8700" lid 4 4xSDR + +vendid=0x0 +devid=0xd2f2 +sysimgguid=0x2c90300bb0006 +caguid=0x2c90300bb0006 +Ca 1 "H-0002c90300bb0006" # "node03 mlx5_0" +[1](2c90300bb0007) "S-0002c90300aa0002"[3] # lid 9 lmc 0 "leaf1 MQM8700" lid 3 1xQDR + +vendid=0x0 +devid=0xd2f2 +sysimgguid=0x2c90300bb0003 +caguid=0x2c90300bb0003 +Ca 2 "H-0002c90300bb0003" # "node02 mlx5_0" +[1](2c90300bb0004) "S-0002c90300aa0002"[2] # lid 7 lmc 0 "leaf1 MQM8700" lid 3 4xQDR +[2](2c90300bb0005) "S-0002c90300aa0003"[2] # lid 8 lmc 0 "leaf2 MQM8700" lid 4 4xQDR + +vendid=0x2c9 +devid=0xd2f2 +sysimgguid=0x2c90300bb0000 +caguid=0x2c90300bb0000 +Ca 2 "H-0002c90300bb0000" # "node01 mlx5_0" +[1](2c90300bb0001) "S-0002c90300aa0002"[1] # lid 5 lmc 0 "leaf1 MQM8700" lid 3 4xQDR +[2](2c90300bb0002) "S-0002c90300aa0003"[1] # lid 6 lmc 0 "leaf2 MQM8700" lid 4 4xQDR diff --git a/tests/fixtures/ibsim/degraded/perfquery-ca-x.out b/tests/fixtures/ibsim/degraded/perfquery-ca-x.out new file mode 100644 index 0000000..01fb59f --- /dev/null +++ b/tests/fixtures/ibsim/degraded/perfquery-ca-x.out @@ -0,0 +1,11 @@ +# Port extended counters: Lid 10 port 1 (CapMask: 0x1200 CapMask2: 0x0000000) +PortSelect:......................1 +CounterSelect:...................0x0000 +PortXmitData:....................1944 +PortRcvData:.....................2016 +PortXmitPkts:....................27 +PortRcvPkts:.....................28 +PortUnicastXmitPkts:.............0 +PortUnicastRcvPkts:..............0 +PortMulticastXmitPkts:...........0 +PortMulticastRcvPkts:............0 diff --git a/tests/fixtures/ibsim/degraded/perfquery-ca.out b/tests/fixtures/ibsim/degraded/perfquery-ca.out new file mode 100644 index 0000000..03d116f --- /dev/null +++ b/tests/fixtures/ibsim/degraded/perfquery-ca.out @@ -0,0 +1,22 @@ +# Port counters: Lid 10 port 1 (CapMask: 0x1200) +PortSelect:......................1 +CounterSelect:...................0x0000 +SymbolErrorCounter:..............0 +LinkErrorRecoveryCounter:........0 +LinkDownedCounter:...............0 +PortRcvErrors:...................0 +PortRcvRemotePhysicalErrors:.....0 +PortRcvSwitchRelayErrors:........0 +PortXmitDiscards:................0 +PortXmitConstraintErrors:........0 +PortRcvConstraintErrors:.........0 +CounterSelect2:..................0x00 +LocalLinkIntegrityErrors:........0 +ExcessiveBufferOverrunErrors:....0 +QP1Dropped:......................0 +VL15Dropped:.....................0 +PortXmitData:....................1800 +PortRcvData:.....................1872 +PortXmitPkts:....................25 +PortRcvPkts:.....................26 +PortXmitWait:....................0 diff --git a/tests/fixtures/ibsim/degraded/perfquery-sw-list.out b/tests/fixtures/ibsim/degraded/perfquery-sw-list.out new file mode 100644 index 0000000..ccf1d96 --- /dev/null +++ b/tests/fixtures/ibsim/degraded/perfquery-sw-list.out @@ -0,0 +1,66 @@ +# Port counters: Lid 2 port 1 (CapMask: 0x1300) +PortSelect:......................1 +CounterSelect:...................0x0000 +SymbolErrorCounter:..............0 +LinkErrorRecoveryCounter:........0 +LinkDownedCounter:...............0 +PortRcvErrors:...................0 +PortRcvRemotePhysicalErrors:.....0 +PortRcvSwitchRelayErrors:........0 +PortXmitDiscards:................0 +PortXmitConstraintErrors:........0 +PortRcvConstraintErrors:.........0 +CounterSelect2:..................0x00 +LocalLinkIntegrityErrors:........0 +ExcessiveBufferOverrunErrors:....0 +QP1Dropped:......................0 +VL15Dropped:.....................0 +PortXmitData:....................6912 +PortRcvData:.....................6984 +PortXmitPkts:....................96 +PortRcvPkts:.....................97 +PortXmitWait:....................0 +# Port counters: Lid 2 port 2 (CapMask: 0x1300) +PortSelect:......................2 +CounterSelect:...................0x0000 +SymbolErrorCounter:..............0 +LinkErrorRecoveryCounter:........0 +LinkDownedCounter:...............0 +PortRcvErrors:...................0 +PortRcvRemotePhysicalErrors:.....0 +PortRcvSwitchRelayErrors:........0 +PortXmitDiscards:................0 +PortXmitConstraintErrors:........0 +PortRcvConstraintErrors:.........0 +CounterSelect2:..................0x00 +LocalLinkIntegrityErrors:........0 +ExcessiveBufferOverrunErrors:....0 +QP1Dropped:......................0 +VL15Dropped:.....................0 +PortXmitData:....................864 +PortRcvData:.....................864 +PortXmitPkts:....................12 +PortRcvPkts:.....................12 +PortXmitWait:....................0 +# Port counters: Lid 2 port 3 (CapMask: 0x1300) +PortSelect:......................3 +CounterSelect:...................0x0000 +SymbolErrorCounter:..............0 +LinkErrorRecoveryCounter:........0 +LinkDownedCounter:...............0 +PortRcvErrors:...................0 +PortRcvRemotePhysicalErrors:.....0 +PortRcvSwitchRelayErrors:........0 +PortXmitDiscards:................0 +PortXmitConstraintErrors:........0 +PortRcvConstraintErrors:.........0 +CounterSelect2:..................0x00 +LocalLinkIntegrityErrors:........0 +ExcessiveBufferOverrunErrors:....0 +QP1Dropped:......................0 +VL15Dropped:.....................0 +PortXmitData:....................0 +PortRcvData:.....................0 +PortXmitPkts:....................0 +PortRcvPkts:.....................0 +PortXmitWait:....................0 diff --git a/tests/fixtures/ibsim/healthy/iblinkinfo-line.out b/tests/fixtures/ibsim/healthy/iblinkinfo-line.out new file mode 100644 index 0000000..8762ed6 --- /dev/null +++ b/tests/fixtures/ibsim/healthy/iblinkinfo-line.out @@ -0,0 +1,38 @@ +0x0002c90300bb0009 " node04 mlx5_0" 10 1[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300aa0003 4 3[ ] "leaf2 MQM8700" (Could be 12X ) +0x0002c90300aa0003 " leaf2 MQM8700" 4 1[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300bb0002 6 2[ ] "node01 mlx5_0" (Could be 12X ) +0x0002c90300aa0003 " leaf2 MQM8700" 4 2[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300bb0005 8 2[ ] "node02 mlx5_0" (Could be 12X ) +0x0002c90300aa0003 " leaf2 MQM8700" 4 3[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300bb0009 10 1[ ] "node04 mlx5_0" (Could be 12X ) +0x0002c90300aa0003 " leaf2 MQM8700" 4 4[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0003 " leaf2 MQM8700" 4 5[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300aa0000 1 2[ ] "spine1 MQM8700" (Could be 12X ) +0x0002c90300aa0003 " leaf2 MQM8700" 4 6[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300aa0001 2 2[ ] "spine2 MQM8700" (Could be 12X ) +0x0002c90300aa0003 " leaf2 MQM8700" 4 7[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0003 " leaf2 MQM8700" 4 8[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0001 " spine2 MQM8700" 2 1[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300aa0002 3 6[ ] "leaf1 MQM8700" (Could be 12X ) +0x0002c90300aa0001 " spine2 MQM8700" 2 2[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300aa0003 4 6[ ] "leaf2 MQM8700" (Could be 12X ) +0x0002c90300aa0001 " spine2 MQM8700" 2 3[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0001 " spine2 MQM8700" 2 4[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0001 " spine2 MQM8700" 2 5[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0001 " spine2 MQM8700" 2 6[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0001 " spine2 MQM8700" 2 7[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0001 " spine2 MQM8700" 2 8[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0000 " spine1 MQM8700" 1 1[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300aa0002 3 5[ ] "leaf1 MQM8700" (Could be 12X ) +0x0002c90300aa0000 " spine1 MQM8700" 1 2[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300aa0003 4 5[ ] "leaf2 MQM8700" (Could be 12X ) +0x0002c90300aa0000 " spine1 MQM8700" 1 3[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0000 " spine1 MQM8700" 1 4[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0000 " spine1 MQM8700" 1 5[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0000 " spine1 MQM8700" 1 6[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0000 " spine1 MQM8700" 1 7[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0000 " spine1 MQM8700" 1 8[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300bb0007 " node03 mlx5_0" 9 1[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300aa0002 3 3[ ] "leaf1 MQM8700" (Could be 12X ) +0x0002c90300bb0004 " node02 mlx5_0" 7 1[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300aa0002 3 2[ ] "leaf1 MQM8700" (Could be 12X ) +0x0002c90300bb0005 " node02 mlx5_0" 8 2[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300aa0003 4 2[ ] "leaf2 MQM8700" (Could be 12X ) +0x0002c90300aa0002 " leaf1 MQM8700" 3 1[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300bb0001 5 1[ ] "node01 mlx5_0" (Could be 12X ) +0x0002c90300aa0002 " leaf1 MQM8700" 3 2[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300bb0004 7 1[ ] "node02 mlx5_0" (Could be 12X ) +0x0002c90300aa0002 " leaf1 MQM8700" 3 3[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300bb0007 9 1[ ] "node03 mlx5_0" (Could be 12X ) +0x0002c90300aa0002 " leaf1 MQM8700" 3 4[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0002 " leaf1 MQM8700" 3 5[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300aa0000 1 1[ ] "spine1 MQM8700" (Could be 12X ) +0x0002c90300aa0002 " leaf1 MQM8700" 3 6[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300aa0001 2 1[ ] "spine2 MQM8700" (Could be 12X ) +0x0002c90300aa0002 " leaf1 MQM8700" 3 7[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300aa0002 " leaf1 MQM8700" 3 8[ ] ==( Down/ Polling)==> [ ] "" ( ) +0x0002c90300bb0001 " node01 mlx5_0" 5 1[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300aa0002 3 1[ ] "leaf1 MQM8700" (Could be 12X ) +0x0002c90300bb0002 " node01 mlx5_0" 6 2[ ] ==( 4X 10.0 Gbps Active/ LinkUp)==> 0x0002c90300aa0003 4 1[ ] "leaf2 MQM8700" (Could be 12X ) diff --git a/tests/fixtures/ibsim/healthy/ibnetdiscover.out b/tests/fixtures/ibsim/healthy/ibnetdiscover.out new file mode 100644 index 0000000..aaca2eb --- /dev/null +++ b/tests/fixtures/ibsim/healthy/ibnetdiscover.out @@ -0,0 +1,72 @@ +# +# Topology file: generated on Sun Nov 15 15:17:36 2026 +# +# Initiated from node 0002c90300bb0000 port 0002c90300bb0001 + +vendid=0x0 +devid=0xd2f2 +sysimgguid=0x2c90300aa0003 +switchguid=0x2c90300aa0003(2c90300aa0003) +Switch 8 "S-0002c90300aa0003" # "leaf2 MQM8700" base port 0 lid 4 lmc 0 +[1] "H-0002c90300bb0000"[2](2c90300bb0002) # "node01 mlx5_0" lid 6 4xQDR +[2] "H-0002c90300bb0003"[2](2c90300bb0005) # "node02 mlx5_0" lid 8 4xQDR +[3] "H-0002c90300bb0008"[1](2c90300bb0009) # "node04 mlx5_0" lid 10 4xQDR +[5] "S-0002c90300aa0000"[2] # "spine1 MQM8700" lid 1 4xQDR +[6] "S-0002c90300aa0001"[2] # "spine2 MQM8700" lid 2 4xQDR + +vendid=0x0 +devid=0xd2f2 +sysimgguid=0x2c90300aa0001 +switchguid=0x2c90300aa0001(2c90300aa0001) +Switch 8 "S-0002c90300aa0001" # "spine2 MQM8700" base port 0 lid 2 lmc 0 +[1] "S-0002c90300aa0002"[6] # "leaf1 MQM8700" lid 3 4xQDR +[2] "S-0002c90300aa0003"[6] # "leaf2 MQM8700" lid 4 4xQDR + +vendid=0x0 +devid=0xd2f2 +sysimgguid=0x2c90300aa0000 +switchguid=0x2c90300aa0000(2c90300aa0000) +Switch 8 "S-0002c90300aa0000" # "spine1 MQM8700" base port 0 lid 1 lmc 0 +[1] "S-0002c90300aa0002"[5] # "leaf1 MQM8700" lid 3 4xQDR +[2] "S-0002c90300aa0003"[5] # "leaf2 MQM8700" lid 4 4xQDR + +vendid=0x0 +devid=0xd2f2 +sysimgguid=0x2c90300aa0002 +switchguid=0x2c90300aa0002(2c90300aa0002) +Switch 8 "S-0002c90300aa0002" # "leaf1 MQM8700" base port 0 lid 3 lmc 0 +[1] "H-0002c90300bb0000"[1](2c90300bb0001) # "node01 mlx5_0" lid 5 4xQDR +[2] "H-0002c90300bb0003"[1](2c90300bb0004) # "node02 mlx5_0" lid 7 4xQDR +[3] "H-0002c90300bb0006"[1](2c90300bb0007) # "node03 mlx5_0" lid 9 4xQDR +[5] "S-0002c90300aa0000"[1] # "spine1 MQM8700" lid 1 4xQDR +[6] "S-0002c90300aa0001"[1] # "spine2 MQM8700" lid 2 4xQDR + +vendid=0x0 +devid=0xd2f2 +sysimgguid=0x2c90300bb0008 +caguid=0x2c90300bb0008 +Ca 1 "H-0002c90300bb0008" # "node04 mlx5_0" +[1](2c90300bb0009) "S-0002c90300aa0003"[3] # lid 10 lmc 0 "leaf2 MQM8700" lid 4 4xQDR + +vendid=0x0 +devid=0xd2f2 +sysimgguid=0x2c90300bb0006 +caguid=0x2c90300bb0006 +Ca 1 "H-0002c90300bb0006" # "node03 mlx5_0" +[1](2c90300bb0007) "S-0002c90300aa0002"[3] # lid 9 lmc 0 "leaf1 MQM8700" lid 3 4xQDR + +vendid=0x0 +devid=0xd2f2 +sysimgguid=0x2c90300bb0003 +caguid=0x2c90300bb0003 +Ca 2 "H-0002c90300bb0003" # "node02 mlx5_0" +[1](2c90300bb0004) "S-0002c90300aa0002"[2] # lid 7 lmc 0 "leaf1 MQM8700" lid 3 4xQDR +[2](2c90300bb0005) "S-0002c90300aa0003"[2] # lid 8 lmc 0 "leaf2 MQM8700" lid 4 4xQDR + +vendid=0x2c9 +devid=0xd2f2 +sysimgguid=0x2c90300bb0000 +caguid=0x2c90300bb0000 +Ca 2 "H-0002c90300bb0000" # "node01 mlx5_0" +[1](2c90300bb0001) "S-0002c90300aa0002"[1] # lid 5 lmc 0 "leaf1 MQM8700" lid 3 4xQDR +[2](2c90300bb0002) "S-0002c90300aa0003"[1] # lid 6 lmc 0 "leaf2 MQM8700" lid 4 4xQDR diff --git a/tests/fixtures/ibsim/healthy/perfquery-ca-x.out b/tests/fixtures/ibsim/healthy/perfquery-ca-x.out new file mode 100644 index 0000000..01fb59f --- /dev/null +++ b/tests/fixtures/ibsim/healthy/perfquery-ca-x.out @@ -0,0 +1,11 @@ +# Port extended counters: Lid 10 port 1 (CapMask: 0x1200 CapMask2: 0x0000000) +PortSelect:......................1 +CounterSelect:...................0x0000 +PortXmitData:....................1944 +PortRcvData:.....................2016 +PortXmitPkts:....................27 +PortRcvPkts:.....................28 +PortUnicastXmitPkts:.............0 +PortUnicastRcvPkts:..............0 +PortMulticastXmitPkts:...........0 +PortMulticastRcvPkts:............0 diff --git a/tests/fixtures/ibsim/healthy/perfquery-ca.out b/tests/fixtures/ibsim/healthy/perfquery-ca.out new file mode 100644 index 0000000..03d116f --- /dev/null +++ b/tests/fixtures/ibsim/healthy/perfquery-ca.out @@ -0,0 +1,22 @@ +# Port counters: Lid 10 port 1 (CapMask: 0x1200) +PortSelect:......................1 +CounterSelect:...................0x0000 +SymbolErrorCounter:..............0 +LinkErrorRecoveryCounter:........0 +LinkDownedCounter:...............0 +PortRcvErrors:...................0 +PortRcvRemotePhysicalErrors:.....0 +PortRcvSwitchRelayErrors:........0 +PortXmitDiscards:................0 +PortXmitConstraintErrors:........0 +PortRcvConstraintErrors:.........0 +CounterSelect2:..................0x00 +LocalLinkIntegrityErrors:........0 +ExcessiveBufferOverrunErrors:....0 +QP1Dropped:......................0 +VL15Dropped:.....................0 +PortXmitData:....................1800 +PortRcvData:.....................1872 +PortXmitPkts:....................25 +PortRcvPkts:.....................26 +PortXmitWait:....................0 diff --git a/tests/fixtures/ibsim/healthy/perfquery-sw-list.out b/tests/fixtures/ibsim/healthy/perfquery-sw-list.out new file mode 100644 index 0000000..ccf1d96 --- /dev/null +++ b/tests/fixtures/ibsim/healthy/perfquery-sw-list.out @@ -0,0 +1,66 @@ +# Port counters: Lid 2 port 1 (CapMask: 0x1300) +PortSelect:......................1 +CounterSelect:...................0x0000 +SymbolErrorCounter:..............0 +LinkErrorRecoveryCounter:........0 +LinkDownedCounter:...............0 +PortRcvErrors:...................0 +PortRcvRemotePhysicalErrors:.....0 +PortRcvSwitchRelayErrors:........0 +PortXmitDiscards:................0 +PortXmitConstraintErrors:........0 +PortRcvConstraintErrors:.........0 +CounterSelect2:..................0x00 +LocalLinkIntegrityErrors:........0 +ExcessiveBufferOverrunErrors:....0 +QP1Dropped:......................0 +VL15Dropped:.....................0 +PortXmitData:....................6912 +PortRcvData:.....................6984 +PortXmitPkts:....................96 +PortRcvPkts:.....................97 +PortXmitWait:....................0 +# Port counters: Lid 2 port 2 (CapMask: 0x1300) +PortSelect:......................2 +CounterSelect:...................0x0000 +SymbolErrorCounter:..............0 +LinkErrorRecoveryCounter:........0 +LinkDownedCounter:...............0 +PortRcvErrors:...................0 +PortRcvRemotePhysicalErrors:.....0 +PortRcvSwitchRelayErrors:........0 +PortXmitDiscards:................0 +PortXmitConstraintErrors:........0 +PortRcvConstraintErrors:.........0 +CounterSelect2:..................0x00 +LocalLinkIntegrityErrors:........0 +ExcessiveBufferOverrunErrors:....0 +QP1Dropped:......................0 +VL15Dropped:.....................0 +PortXmitData:....................864 +PortRcvData:.....................864 +PortXmitPkts:....................12 +PortRcvPkts:.....................12 +PortXmitWait:....................0 +# Port counters: Lid 2 port 3 (CapMask: 0x1300) +PortSelect:......................3 +CounterSelect:...................0x0000 +SymbolErrorCounter:..............0 +LinkErrorRecoveryCounter:........0 +LinkDownedCounter:...............0 +PortRcvErrors:...................0 +PortRcvRemotePhysicalErrors:.....0 +PortRcvSwitchRelayErrors:........0 +PortXmitDiscards:................0 +PortXmitConstraintErrors:........0 +PortRcvConstraintErrors:.........0 +CounterSelect2:..................0x00 +LocalLinkIntegrityErrors:........0 +ExcessiveBufferOverrunErrors:....0 +QP1Dropped:......................0 +VL15Dropped:.....................0 +PortXmitData:....................0 +PortRcvData:.....................0 +PortXmitPkts:....................0 +PortRcvPkts:.....................0 +PortXmitWait:....................0 diff --git a/tests/ibsim/run.sh b/tests/ibsim/run.sh new file mode 100644 index 0000000..9ca3b68 --- /dev/null +++ b/tests/ibsim/run.sh @@ -0,0 +1,193 @@ +#!/bin/sh +# SPDX-FileCopyrightText: 2026 Thomas Vincent +# SPDX-License-Identifier: GPL-2.0-or-later +# +# Runs inside the pinned Ubuntu container (see the ibsim-fabric job). Starts the +# linux-rdma ibsim fabric simulator and OpenSM under the libumad2sim LD_PRELOAD +# shim, then runs the real ibnetdiscover, iblinkinfo and perfquery against the +# simulated fabric and writes their raw output to $2. +# +# sh run.sh +# +# Needs root only for apt-get; no extra Linux capabilities, no /dev/infiniband. +# Every stage has its own bound and prints its elapsed time, so a stall names +# the stage and shows the simulator and OpenSM logs: package install +# (APT_LIMIT each step), the simulator start, OpenSM reaching +# MASTER (OSM_LIMIT), the local port going Active (PORT_LIMIT), and each tool +# (TOOL_LIMIT; a tool that times out stops the run). The worst case stays +# under the job's docker wait. The simulator and OpenSM also run under a +# watchdog: they are stopped with SIGKILL, which timeout cannot pass on to its +# child. tests/bin/check-ibsim-fixtures.php then reads the output through the +# plugin's own parsers. +set -eu +export DEBIAN_FRONTEND=noninteractive +REPO=$1 +OUT=$2 +TOPO_DIR=$REPO/tests/ibsim/topo + +# Exact archive versions, so a fixture change is a deliberate bump. Ubuntu +# removes superseded security builds from the archive; bump these together +# with the image digest when `apt-get install` reports a missing version. +APT_LIMIT=150 +OSM_LIMIT=60 +PORT_LIMIT=30 +TOOL_LIMIT=20 +DOG_LIMIT=$((3 + OSM_LIMIT + PORT_LIMIT + 7 + 13 * (TOOL_LIMIT + 2) + 30)) + +T0=$(date +%s) +log() { echo "[$(( $(date +%s) - T0 ))s] $*"; } + +# die [log file...]: stop with the stage named and the logs shown. +die() { + msg=$1; shift + echo "FAIL $msg after $(( $(date +%s) - T0 ))s" >&2 + for f in "$@"; do + [ -f "$f" ] || continue + echo "--- last lines of $f" >&2 + tail -n 25 "$f" >&2 + done + exit 1 +} + +# wait_for : poll once a second until the command +# succeeds; non-zero when the limit passes first. +wait_for() { + end=$(( $(date +%s) + $1 )); shift + until "$@"; do + [ "$(date +%s)" -lt "$end" ] || return 1 + sleep 1 + done +} + +log "apt-get update" +timeout -k 5 "$APT_LIMIT" apt-get update -qq >/tmp/apt.log 2>&1 || + die "apt-get update did not finish within ${APT_LIMIT}s" /tmp/apt.log +log "apt-get install" +timeout -k 5 "$APT_LIMIT" apt-get install -y -qq --no-install-recommends \ + ibsim-utils=0.10-2build1 \ + infiniband-diags=50.0-2ubuntu0.2 \ + libibumad3=50.0-2ubuntu0.2 \ + opensm=3.3.23-2 >/tmp/apt.log 2>&1 || + die "apt-get install of the pinned packages failed or took over ${APT_LIMIT}s" /tmp/apt.log + +SO=$(find /usr/lib -name libumad2sim.so | head -n 1) +[ -n "$SO" ] || die "libumad2sim.so not found" +log "packages installed; shim $SO" + +fail=0 +check() { # check + desc=$1; shift + if "$@"; then echo "ok $desc"; else echo "FAIL $desc"; fail=1; fi +} + +run_scenario() { + sc=$1 + d=$OUT/$sc + rm -rf "$d"; mkdir -p "$d/osm" + # Attach at node01, as the plugin's poller attaches at a compute node. + export SIM_HOST=node01 + # Use ibsim's loopback UDP transport. On hosted runners the first write + # to its abstract Unix datagram socket can stall before OpenSM attaches. + export IBSIM_SERVER_NAME=127.0.0.1 + log "$sc: starting ibsim" + ibsim -r -s "$TOPO_DIR/$sc.net" --no-console >"$d/ibsim.log" 2>&1 & + sim_pid=$! + (sleep "$DOG_LIMIT"; kill -9 "$sim_pid" 2>/dev/null) & + sim_dog=$! + # ibsim prints no ready line; give it a moment, then require it to still + # be running. OpenSM reaching MASTER below proves it answers. + sleep 3 + kill -0 "$sim_pid" 2>/dev/null || die "$sc: ibsim exited at start" "$d/ibsim.log" + + log "$sc: starting OpenSM under the shim" + OSM_TMP_DIR=$d/osm OSM_CACHE_DIR=$d/osm LD_PRELOAD=$SO \ + opensm -V -f "$d/osm.log" >"$d/opensm.out" 2>&1 & + osm_pid=$! + (sleep "$DOG_LIMIT"; kill -9 "$osm_pid" 2>/dev/null) & + osm_dog=$! + stop() { kill -9 "$osm_pid" "$sim_pid" "$osm_dog" "$sim_dog" 2>/dev/null || true; } + + osm_master() { + kill -0 "$osm_pid" 2>/dev/null || return 2 + grep -q 'Entering MASTER state' "$d/opensm.out" "$d/osm.log" 2>/dev/null + } + wait_for "$OSM_LIMIT" osm_master || { + kill -0 "$osm_pid" 2>/dev/null && why="did not reach MASTER within ${OSM_LIMIT}s" || why="exited before reaching MASTER" + stop + die "$sc: OpenSM $why" "$d/opensm.out" "$d/osm.log" "$d/ibsim.log" + } + log "$sc: OpenSM is MASTER" + + export LD_PRELOAD=$SO + port_active() { timeout -k 2 5 ibstat 2>/dev/null | grep -q 'State: Active'; } + wait_for "$PORT_LIMIT" port_active || { + stop + die "$sc: the local port did not go Active within ${PORT_LIMIT}s of MASTER" "$d/osm.log" "$d/ibsim.log" + } + log "$sc: local port Active" + + tool() { # tool (stdout, stderr, command and rc kept) + n=$1; shift + echo "$*" >"$d/$n.cmd" + rc=0 + timeout -k 2 "$TOOL_LIMIT" "$@" >"$d/$n.out" 2>"$d/$n.err" || rc=$? + echo "rc=$rc" >>"$d/$n.cmd" + if [ "$rc" -eq 124 ] || [ "$rc" -eq 137 ]; then + stop + die "$sc: '$*' did not finish within ${TOOL_LIMIT}s" "$d/$n.err" "$d/osm.log" "$d/ibsim.log" + fi + return 0 + } + tool ibstat ibstat + tool ibnetdiscover ibnetdiscover + tool ibnetdiscover-p ibnetdiscover -p + tool ibnetdiscover-l ibnetdiscover -l + tool iblinkinfo iblinkinfo + tool iblinkinfo-line iblinkinfo --line + for t in ibnetdiscover iblinkinfo perfquery; do tool "$t-version" "$t" -V; done + + # LIDs come from the SM and change between runs: take them from the topology. + ca_lid=$(awk '$1 == "CA" && /node04/ {print $2}' "$d/ibnetdiscover-p.out") + sw_lid=$(awk '$1 == "SW" && /leaf1/ {print $2; exit}' "$d/ibnetdiscover-p.out") + tool perfquery-ca perfquery "$ca_lid" 1 + tool perfquery-ca-x perfquery -x "$ca_lid" 1 + tool perfquery-sw perfquery "$sw_lid" 1 + tool perfquery-sw-list perfquery "$sw_lid" 1-3 + + # OpenSM does not exit on SIGTERM under the shim (it logs "exiting" and + # lingers), so a `wait` here hangs. SIGKILL both; nothing is left to flush. + stop + sleep 1 + unset LD_PRELOAD + log "$sc: tools done" + + # Smoke assertions on the raw output, so the job proves the simulation is + # real before any plugin parser is involved. Counts are structural (node + # and link counts), not LIDs or line order, which vary between runs. + check "$sc: every tool exited 0" \ + sh -c "! grep -L '^rc=0' $d/*.cmd | grep -q ." + check "$sc: 8 nodes in --list" test "$(wc -l <"$d/ibnetdiscover-l.out")" -eq 8 + check "$sc: 4 switchguid lines" test "$(grep -c '^switchguid=' "$d/ibnetdiscover.out")" -eq 4 + check "$sc: 4 caguid lines" test "$(grep -c '^caguid=' "$d/ibnetdiscover.out")" -eq 4 + check "$sc: discovery initiated from node01" \ + grep -q '^# Initiated from node 0002c90300bb0000' "$d/ibnetdiscover.out" + check "$sc: iblinkinfo --line has 38 port rows" test "$(wc -l <"$d/iblinkinfo-line.out")" -eq 38 + check "$sc: perfquery returned PortXmitData" grep -q '^PortXmitData:' "$d/perfquery-ca.out" + check "$sc: perfquery -x returned 64-bit PortXmitData" grep -q '^PortXmitData:' "$d/perfquery-ca-x.out" + check "$sc: perfquery port list returned 3 ports" \ + test "$(grep -c '^# Port counters' "$d/perfquery-sw-list.out")" -eq 3 +} + +run_scenario healthy +run_scenario degraded + +# Scenario-specific: the 4X to 1X link on node03 must be visible, and only there. +check "healthy: no 1X link" test "$(grep -c ' 1X ' "$OUT/healthy/iblinkinfo-line.out")" -eq 0 +check "degraded: node03 link is 1X in both directions" \ + test "$(grep -c ' 1X ' "$OUT/degraded/iblinkinfo-line.out")" -eq 2 + +# A switch's ports all print one PortGUID in iblinkinfo --line. +check "switch ports share one PortGUID" \ + test "$(grep -E '^0x[0-9a-f]+ " +leaf1 MQM8700"' "$OUT/healthy/iblinkinfo-line.out" | awk '{print $1}' | sort -u | wc -l)" -eq 1 + +exit "$fail" diff --git a/tests/ibsim/topo/degraded.net b/tests/ibsim/topo/degraded.net new file mode 100644 index 0000000..b6b20c4 --- /dev/null +++ b/tests/ibsim/topo/degraded.net @@ -0,0 +1,47 @@ +# SPDX-FileCopyrightText: 2026 Thomas Vincent +# SPDX-License-Identifier: GPL-2.0-or-later +# +# 2 spines, 2 leaves, 4 HCAs (node01, node02 dual-port; node03, node04 single-port). +# First record is the SM/attachment point (node01), as on a real compute node. +# Switch ports all report the switch GUID as PortGUID (ibsim hard-wires this). +vendid=0x2c9 +devid=0xd2f2 +speed=4 +switchguid=0x0002c90300aa0000 +caguid=0x0002c90300bb0000 + +Hca 2 "node01" # "node01 mlx5_0" +[1] "leaf1"[1] +[2] "leaf2"[1] + +Hca 2 "node02" # "node02 mlx5_0" +[1] "leaf1"[2] +[2] "leaf2"[2] + +Hca 1 "node03" # "node03 mlx5_0" +[1] "leaf1"[3] w=1 + +Hca 1 "node04" # "node04 mlx5_0" +[1] "leaf2"[3] s=1 + +Switch 8 "spine1" # "spine1 MQM8700" base port 0 lid 1 lmc 0 +[1] "leaf1"[5] +[2] "leaf2"[5] + +Switch 8 "spine2" # "spine2 MQM8700" base port 0 lid 2 lmc 0 +[1] "leaf1"[6] +[2] "leaf2"[6] + +Switch 8 "leaf1" # "leaf1 MQM8700" base port 0 lid 3 lmc 0 +[1] "node01"[1] +[2] "node02"[1] +[3] "node03"[1] w=1 +[5] "spine1"[1] +[6] "spine2"[1] + +Switch 8 "leaf2" # "leaf2 MQM8700" base port 0 lid 4 lmc 0 +[1] "node01"[2] +[2] "node02"[2] +[3] "node04"[1] s=1 +[5] "spine1"[2] +[6] "spine2"[2] diff --git a/tests/ibsim/topo/healthy.net b/tests/ibsim/topo/healthy.net new file mode 100644 index 0000000..e30851c --- /dev/null +++ b/tests/ibsim/topo/healthy.net @@ -0,0 +1,47 @@ +# SPDX-FileCopyrightText: 2026 Thomas Vincent +# SPDX-License-Identifier: GPL-2.0-or-later +# +# 2 spines, 2 leaves, 4 HCAs (node01, node02 dual-port; node03, node04 single-port). +# First record is the SM/attachment point (node01), as on a real compute node. +# Switch ports all report the switch GUID as PortGUID (ibsim hard-wires this). +vendid=0x2c9 +devid=0xd2f2 +speed=4 +switchguid=0x0002c90300aa0000 +caguid=0x0002c90300bb0000 + +Hca 2 "node01" # "node01 mlx5_0" +[1] "leaf1"[1] +[2] "leaf2"[1] + +Hca 2 "node02" # "node02 mlx5_0" +[1] "leaf1"[2] +[2] "leaf2"[2] + +Hca 1 "node03" # "node03 mlx5_0" +[1] "leaf1"[3] + +Hca 1 "node04" # "node04 mlx5_0" +[1] "leaf2"[3] + +Switch 8 "spine1" # "spine1 MQM8700" base port 0 lid 1 lmc 0 +[1] "leaf1"[5] +[2] "leaf2"[5] + +Switch 8 "spine2" # "spine2 MQM8700" base port 0 lid 2 lmc 0 +[1] "leaf1"[6] +[2] "leaf2"[6] + +Switch 8 "leaf1" # "leaf1 MQM8700" base port 0 lid 3 lmc 0 +[1] "node01"[1] +[2] "node02"[1] +[3] "node03"[1] +[5] "spine1"[1] +[6] "spine2"[1] + +Switch 8 "leaf2" # "leaf2 MQM8700" base port 0 lid 4 lmc 0 +[1] "node01"[2] +[2] "node02"[2] +[3] "node04"[1] +[5] "spine1"[2] +[6] "spine2"[2]