diff --git a/.gitattributes b/.gitattributes index 385524c..198814a 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,12 @@ * text=auto eol=lf *.rrd binary + +# Left out of release archives (git archive, GitHub source downloads); see +# docs/release.md. +/.github export-ignore +/tests export-ignore +/phpstan.neon export-ignore +/phpunit.xml export-ignore +/phpunit-integration.xml export-ignore +/.editorconfig export-ignore +/.gitattributes export-ignore diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..c97a095 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,31 @@ +# Changelog + +All notable changes are recorded here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html). The version in `INFO` is the version of the next release; a release is a signed tag of that version (see [docs/release.md](docs/release.md)). + +## [0.1.0] - Unreleased + +Phase 1, Lustre observation. Not released: pilots on real filesystems, the external security review, and live scale measurements are still open. + +### Added + +- Plugin install, upgrade, and uninstall through Cacti's plugin API, with a refusal on PHP below 8.2 that leaves Cacti working (milestone 2). +- Registry of filesystems, nodes, and the networks each poller may reach; a background reader per poller that reads Lustre servers over SSH through a fixed forced-command script, `node/pfs-read.sh` (milestone 2). +- A cache of target inventory, condition, capacity, and counters with their freshness, and a health page (milestone 2). +- One Cacti device per filesystem with OST and MDT script server data queries, device, data, and graph templates, five overview graphs, and per-target graphs on demand; counters as DERIVE data sources that read unknown across a reset (milestone 3). +- A per-filesystem summary data source for Thold: fill and imbalance, target counts, capacity totals, filesystem throughput and metadata rates, and data age (milestones 3 and 4). +- Device permissions on every page and admin action, and a `graph_buttons` link from a device's graphs to its filesystem view (milestone 3). +- End-to-end tests with unchanged Thold and Maint releases, target churn and reindex, backup and restore, failure scenarios, and a scale harness (milestone 4). +- Operator guide, alerting guide, release process, security self-review, and pilot plan (milestone 4). + +### Changed + +- An absent counter line counts as zero in the filesystem sums for a target that is present, in service, and reported its other values in the same read; the per-target value stays unknown ([ADR 0013](docs/decisions/0013-absent-counter-lines-count-as-zero-in-sums.md)). + +### Fixed + +- A target that a complete read left out serves unknown on its per-target data source at once, instead of its last value until that value went stale. +- The Fill graph did not draw `age`, so Cacti stored no value for it and Thold could not threshold it. + +### Known issues + +- Thold 1.8.2 thresholds on counter data sources (`read_bytes`, `write_bytes`, `md_ops`) are not supported: an unknown counter interval makes Thold's poller hook fail and Cacti disables Thold ([docs/alerting.md](docs/alerting.md#counters-and-thold-182)). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f6981c5..9cfb18c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,6 +1,6 @@ # Contributing -This project is in development; milestone 2 (foundation) is merged and there is no release. Most useful contributions right now are evidence for the research issues in milestone 1 and review of the requirements and open decisions. +This project is in development; milestones 2 and 3 are merged, milestone 4 is code complete pending pilots and an external security review, and there is no release. Most useful contributions right now are evidence for the research issues in milestone 1 and review of the requirements and open decisions. ## Before you start diff --git a/INFO b/INFO index 8716314..53d0ff6 100644 --- a/INFO +++ b/INFO @@ -18,7 +18,7 @@ ; remote collector; remote_collect:1 alone skips it (docs/research/cacti-core.md). [info] name = pfs -version = 0.1.0-dev +version = 0.1.0 longname = Parallel Filesystems author = "Thomas Vincent (somethingwithproof)" email = thomasvincent@gmail.com diff --git a/README.md b/README.md index a5f56a1..e4cac53 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ A Cacti 1.2 plugin that brings parallel filesystem health and load into Cacti: capacity and fill imbalance across targets, per-target throughput, and metadata operation rates. Lustre is the first backend. GPFS (IBM Storage Scale) and BeeGFS follow behind a backend interface. The data lands in ordinary Cacti devices, data sources, and graphs, so Thold and Maint alert on and suppress it unchanged. -> **Status: in development, no release yet.** Milestones 2 (foundation) and 3 (Lustre observation) are merged on `main`. The code installs, upgrades, and uninstalls through Cacti's plugin API and refuses PHP below 8.2. It keeps a registry of filesystems, nodes, and the networks each poller may reach. A background reader on each poller reads its Lustre nodes over SSH through a fixed forced-command script ([node/pfs-read.sh](node/pfs-read.sh)) and caches target inventory, condition, capacity, and counter values with their freshness, plus a per-filesystem summary. Each filesystem becomes a Cacti device with two script server data queries (OSTs and MDTs), the "Parallel Filesystem" device, data, and graph templates, five overview graphs, and per-target graphs on demand. Counters are DERIVE data sources that read unknown across a reset. The view page follows Cacti's device permissions. Thold rate alerts (high thresholds only) and Maint suppression are not yet validated; that is milestone 4. Milestone 1 research is written up from documentation and source; checks that need a real file system are still open, and the plugin has not run against a real Lustre node: the end-to-end run uses fixture node output. The rest of this README describes the design, not shipped behavior. +> **Status: milestone 4, code complete for phase 1, not released.** Milestones 2 (foundation), 3 (Lustre observation), and 4 (alerting and release preparation) are done on `main` or in review. The plugin installs, upgrades, and uninstalls through Cacti's plugin API and refuses PHP below 8.2. A background reader on each poller reads Lustre servers over SSH through a fixed forced-command script ([node/pfs-read.sh](node/pfs-read.sh)) and caches inventory, condition, capacity, and counters with their freshness. Each filesystem becomes a Cacti device with OST and MDT data queries, five overview graphs, per-target graphs on demand, and a summary data source for Thold. Thold v1.8.2 and Maint v1.3, unchanged, alert on and suppress the summary gauges in the end-to-end run; Thold thresholds on counters are not supported with Thold 1.8.2 ([docs/alerting.md](docs/alerting.md)). Every test so far runs on fixture node output in a disposable Cacti: the plugin has not run against a real Lustre node. Still open before a release: pilots on real filesystems ([pilot plan](docs/pilot-plan.md)), the external security review ([self-review](docs/security-review.md)), and scale measurements on documented hardware ([scale](docs/research/scale.md)). Version 0.1.0 is prepared in `INFO` and [CHANGELOG.md](CHANGELOG.md) but not tagged. ## Why @@ -38,6 +38,7 @@ Out of scope: any write, clear, reset, or tuning operation on a node or filesyst ## Design - [docs/PLAN.md](docs/PLAN.md) is the full plan: architecture, upstream facts it depends on (with sources and what is still unverified), counter semantics, state model, security boundaries, performance arithmetic, testing, and risks. +- [docs/operator-guide.md](docs/operator-guide.md) covers install, the graphs and values, upgrade, backup and restore, uninstall, and troubleshooting; [docs/alerting.md](docs/alerting.md) covers Thold and Maint. - [docs/node-setup.md](docs/node-setup.md) describes how to prepare a Lustre server and a poller for the reader. - [docs/decisions/](docs/decisions/) holds architecture decision records for choices already made. - [docs/REQUIREMENTS.md](docs/REQUIREMENTS.md) maps every requirement ID to its issue. diff --git a/REUSE.toml b/REUSE.toml index 1daa9f9..6d8cd7d 100644 --- a/REUSE.toml +++ b/REUSE.toml @@ -7,6 +7,7 @@ version = 1 [[annotations]] path = [ "README.md", + "CHANGELOG.md", "CONTRIBUTING.md", "SECURITY.md", "docs/**", diff --git a/docs/PLAN.md b/docs/PLAN.md index 7764b9b..09a170b 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -1,6 +1,6 @@ # Cacti 1.2 Parallel Filesystem Plugin Plan -Status: in development, plan revision 2 (2026-11-15), after the milestone 1 documentation and source research in [docs/research](research/README.md). Revision 1 was 2026-11-14. Milestone 2 (foundation) is merged on `main`: the plugin lifecycle and PHP guard, realms and pages, the filesystem, node, and network registry, the Lustre backend and forced-command node reader, the observation cache and measurement state model, the health page, and the test harness. Milestone 3 (Lustre observation) is merged too: a Cacti device per filesystem, OST and MDT data queries, the templates, five overview graphs, and per-target graphs on demand, with the differences from this plan listed in the milestone 3 implementation notes. Milestone 4 and later are not done: Thold and Maint integration is not validated, and there is no release. Sections below describe the design; where they differ from what is merged, the milestone table shows which milestone delivers it. Statements about Lustre, GPFS, BeeGFS, RRDtool, Cacti core, Thold, and Maint describe upstream behavior and cite the source that was checked, at a pinned tag or commit where one exists. Anything that could not be verified is listed under [Assumptions to confirm](#assumptions-to-confirm) and tracked as a research issue; the design does not treat it as fact. Items that need a real Lustre, Storage Scale, or BeeGFS system, a Cacti remote collector, or accounts are marked *live*; none of those checks has run. Owner is not assigned; size estimates are in [estimates](research/estimates.md). +Status: in development, plan revision 2 (2026-11-15), after the milestone 1 documentation and source research in [docs/research](research/README.md). Revision 1 was 2026-11-14. Milestone 2 (foundation) is merged on `main`: the plugin lifecycle and PHP guard, realms and pages, the filesystem, node, and network registry, the Lustre backend and forced-command node reader, the observation cache and measurement state model, the health page, and the test harness. Milestone 3 (Lustre observation) is merged too: a Cacti device per filesystem, OST and MDT data queries, the templates, five overview graphs, and per-target graphs on demand, with the differences from this plan listed in the milestone 3 implementation notes. Milestone 4 (alerting and phase 1 release preparation) is code complete on its branch: Thold and Maint run end to end on the summary gauges, with the differences listed in the milestone 4 implementation notes; pilots, the external security review, and live scale measurements remain, and there is no release. Sections below describe the design; where they differ from what is merged, the milestone table shows which milestone delivers it. Statements about Lustre, GPFS, BeeGFS, RRDtool, Cacti core, Thold, and Maint describe upstream behavior and cite the source that was checked, at a pinned tag or commit where one exists. Anything that could not be verified is listed under [Assumptions to confirm](#assumptions-to-confirm) and tracked as a research issue; the design does not treat it as fact. Items that need a real Lustre, Storage Scale, or BeeGFS system, a Cacti remote collector, or accounts are marked *live*; none of those checks has run. Owner is not assigned; size estimates are in [estimates](research/estimates.md). `plugin_pfs` brings parallel filesystem health and load into Cacti 1.2 as ordinary Cacti devices, data sources, and graphs: capacity and fill imbalance across targets, per-target throughput, and metadata operation rates. Lustre is the phase 1 backend. GPFS (IBM Storage Scale) and BeeGFS follow behind a backend interface. @@ -246,7 +246,7 @@ Lustre stats counters are cumulative since initialization or the last clear (see - Cumulative counters (byte sums, sample counts, operation counts) are stored raw as DERIVE with minimum 0 and a generous per-counter maximum. RRDtool computes the rate, and a decrease becomes an unknown interval; the maximum also makes an implausibly large interval unknown, which drops real traffic above it, so it is a plausibility bound and not a reset filter (measured offline in [counter-reset](research/counter-reset.md)). Thold computes its own rate and sees a negative value on a reset ([thold-counters](research/thold-counters.md)). - The reader also detects a decrease and publishes unknown for that interval. A reset followed by a value larger than the last pre-reset value (a long outage, then heavy traffic) cannot be seen by a minimum of 0 alone. - Capacity and inode counts are GAUGE. -- A counter line that is absent from a stats file that was read successfully means zero samples on `v2_17_0`. The source shows the same rule at `v2_15_8`, `v2_16_1`, and `v2_17_0`; the plugin applies it only after fixtures from real nodes confirm it for each matrix release (*live*). A failed read is unknown. +- A counter line that is absent from a stats file that was read successfully means zero samples on `v2_17_0`. The source shows the same rule at `v2_15_8`, `v2_16_1`, and `v2_17_0`. Decided in [ADR 0013](decisions/0013-absent-counter-lines-count-as-zero-in-sums.md): the OST sums count such a line as 0 only for an OST that is present, in service, current, and reported other values in the same read, and not on the read that cleared a counter which had counted; `md_ops` leaves an absent operation out of its member set, since an MDT has no condition flags; the target's own value stays unknown, and a missing, stale, or failed target keeps the sum unknown. Fixtures from real nodes still have to confirm the rule for each matrix release (*live*). A failed read is unknown. - A filesystem aggregate across targets is unknown for any interval in which a contributing target is missing or reset. A partial sum would draw an outage as a throughput drop. The number of contributors is published beside the aggregate. - The plugin never clears a counter. GPFS `reset` and Lustre stats writes affect every other consumer on that node. @@ -289,7 +289,7 @@ Thold thresholds and Maint device schedules apply with no change to either plugi Stated limits: - **Sampling alignment.** Cacti polls on its own interval and the reader reads nodes on its own. Thold durations should be at least one poll interval. -- **Rates.** Thold can compute a rate from a DERIVE data source, with one negative sample on a reset, and an endpoint-difference rate (a lower bound) if a reset is hidden by a larger later value ([thold-counters](research/thold-counters.md)). Decided in [ADR 0012](decisions/0012-thold-rate-alerts-high-thresholds-only.md) (#8): rate alerts on DERIVE data sources are supported for high thresholds with a duration of at least two polls; low-threshold rate alerts are unsupported in phase 1, because a reset can reach Thold as a negative rate. +- **Rates.** Superseded in practice by the milestone 4 finding below: with Thold 1.8.2, a threshold on a DERIVE data source that reads `U` once crashes Thold's poller output hook. Thold can compute a rate from a DERIVE data source, with one negative sample on a reset, and an endpoint-difference rate (a lower bound) if a reset is hidden by a larger later value ([thold-counters](research/thold-counters.md)). Decided in [ADR 0012](decisions/0012-thold-rate-alerts-high-thresholds-only.md) (#8): rate alerts on DERIVE data sources are supported for high thresholds with a duration of at least two polls; low-threshold rate alerts are unsupported in phase 1, because a reset can reach Thold as a negative rate. - **Resets.** A counter reset yields one unknown interval, which does not trigger a threshold. - **Summary only.** Alerts see the summary and per-target gauges, not distributions. @@ -303,6 +303,15 @@ Alternatives considered: **Maintenance.** Device maintenance works through Maint with no change to Maint or Thold: Thold calls `plugin_maint_check_cacti_host()` directly, and the plugin uses the same guarded call. Measurements continue during maintenance; only notifications are suppressed. Maint declares `remote_collect:0`, so its hooks do not run on a remote collector; whether Thold on a collector can still load Maint's functions and apply maintenance there was not checked and is an integration check (*live*). +Milestone 4 implementation notes, where the build differs from or adds to the text above: + +- **Counter thresholds are not supported with Thold 1.8.2.** Thold stores a `U` from a DERIVE data source as its previous raw value and on the next numeric value throws a PHP `TypeError` in the `poller_output` hook; Cacti then disables Thold. The plugin serves `U` for every reset and contributor change by design, so ADR 0012's supported rate alerts would disable Thold at the first reset. The end-to-end run checks a two-poll high rate threshold only before any `U` and then removes it. Thold's unreleased development branch changes this path. Whether to amend ADR 0012, report it to Thold, or add plugin-computed rate gauges is an owner decision ([alerting](alerting.md), [thold-counters](research/thold-counters.md#milestone-4-end-to-end-run)). +- **Absent counter lines in sums** count as zero only for a present, in-service OST whose other values are current in the same read ([ADR 0013](decisions/0013-absent-counter-lines-count-as-zero-in-sums.md)). The per-target series stays unknown. A read without `snapshot_time` is not complete, so nothing in it counts as absent. +- **A missing target serves `U` at once.** Milestone 3 served a missing or conflicting target's last gauge until it went stale (up to two intervals), which drew an outage as a flat line. The data query now serves `U` for any target that is not present; its index and data source stay. +- **`age` is drawn on the Fill graph.** Cacti creates in an RRD file only the values some graph item uses; `age` was not drawn, so it had no RRD value and no threshold could be made on it. The Fill graph now prints it. +- **`targets_missing` and `age` are the outage alerts.** Sums go unknown on a missing target, and in Thold 1.8.2 an unknown value is never a breach, so outages are alerted on through these two gauges. +- **Release archive.** `.gitattributes` leaves tests and CI files out of `git archive`; the archive prefix must be `pfs/` ([release](release.md)). + ## Remote operation (phase 2) When nodes are reachable only from a Cacti remote data collector, that collector runs the reader and the script server input (ADR 0004): diff --git a/docs/alerting.md b/docs/alerting.md new file mode 100644 index 0000000..3f7a4ea --- /dev/null +++ b/docs/alerting.md @@ -0,0 +1,51 @@ +# Alerting with Thold and Maint + +The plugin has no alert engine. Thold thresholds and Maint schedules work on the plugin's data sources unchanged ([ADR 0002](decisions/0002-alert-through-cacti-data-sources.md)). This page says what to threshold, what was tested, and the limits. + +## What to threshold + +Use the **Parallel Filesystem Summary** values. Each overview graph has its own summary data source, so create the threshold from the graph that draws the value: + +| Value | Graph | Example threshold | Notes | +|---|---|---|---| +| `fill_spread_pct` | Imbalance | High 20 (percentage points) | Fullest minus emptiest OST | +| `fill_max_pct` | Fill | High 90 | Fullest OST | +| `targets_missing` | Fill or Imbalance | High 0.5 | Targets left out of the summary: missing, or no current capacity reading | +| `targets_unhealthy` | Fill | High 0.5 | Targets whose condition flags are not in service; unknown when no target's condition is known | +| `age` | Fill | High 3 x the poll interval | Seconds since the oldest observation behind the summary; numeric whenever the filesystem was ever observed, so it keeps rising while a node is silent | +| `kbytes_avail` | Capacity | Low, in kilobytes | Unknown while any OST is missing, so it does not alert on an outage | +| `read_bytes`, `write_bytes`, `md_ops` | Throughput, Metadata Operations | Not with Thold 1.8.2; see below | Counters (DERIVE) | + +Per-target gauges (capacity, inodes) can be thresholded the same way from per-target graphs. + +## Durations + +- Set the threshold's fail trigger to at least one poll. The reader and the Cacti poller run on their own schedules, so a value can be one interval old when Cacti polls it. +- A value that is unknown (`U`) never breaches a high or low threshold. In Thold 1.8.2's source an unknown value takes the not-breached path, so a breached threshold logs a restoral on a gap (read in `thold_check_threshold()`, not exercised end to end). A missing target shows up in `targets_missing` while the summary is current. When reads stop and the summary goes stale, every value but `age` is served as `U`, `targets_missing` included, so `age` is the one that alerts on a read outage; alert on these rather than on a gap. +- A counter reset produces one unknown interval on the counter's graph. + +## Maintenance + +Put the filesystem's device in a Maint schedule. Thold checks the device with Maint's own function, so during the schedule a breach is neither counted nor notified, and Thold logs nothing for it. Collection continues: the reader reads, the poller polls, and the RRD files record the values. When the schedule ends, a breach that is still there counts from zero and notifies after the threshold's fail trigger. + +## Counters and Thold 1.8.2 + +Do not create Thold thresholds on the counter values (`read_bytes`, `write_bytes`, `md_ops`, or per-target counters) with Thold 1.8.2. + +The plugin serves `U` for a counter interval it cannot trust: a reset, a target joining or leaving the sum, or a read that is not current. Thold 1.8.2 stores that `U` as the previous raw value of a DERIVE data source, and on the next numeric value its rate calculation throws a PHP `TypeError` inside Cacti's poller output processing. Cacti then disables the Thold plugin, and that poll's output processing stops. This was observed in the end-to-end run (log line in [research/thold-counters.md](research/thold-counters.md#milestone-4-end-to-end-run)). While no `U` reaches it, a high rate threshold with a two-poll fail trigger behaves as [ADR 0012](decisions/0012-thold-rate-alerts-high-thresholds-only.md) expects: one poll above the threshold breaches without notifying, and the second notifies. + +Thold's development branch at `dc76952` (not released) changes this path: an unknown rate starts a fresh baseline and preserves the alert state instead of logging a restoral. Rate thresholds should be reconsidered once a Thold release includes that change; whether to amend ADR 0012 is an owner decision. + +## What was tested + +`tests/bin/alert-replay.sh` runs against Thold v1.8.2 (`1eb406bd0f81f3204358cce7bd43c8bb5adc8e4a`) and Maint v1.3 (`cd62de9cc323a4f5a8ac80a8d9dda3c7fa16c470`), unchanged, on a disposable Cacti 1.2.31 and the 1.2.x branch, with fixture node output and real poller runs. Thresholds are saved through Thold's own `save_thold()`; the Maint schedule is the two rows Maint's schedule page saves. + +| Scenario | Threshold | Result | +|---|---|---| +| Fill imbalance, then balance | `fill_spread_pct` above 20, 1 poll | Notifies once, then logs a restoral | +| An OST disappears, then returns | `targets_missing` above 0.5, 1 poll | Notifies, then restores | +| The OSS stops answering for 40 seconds | `age` above 30, 1 poll | Notifies while `age` stays numeric, restores when the node answers | +| Write rate far above the threshold for two polls | `write_bytes` above 1 GB/s, 2 polls | First poll breaches without notifying, second notifies, then restores | +| Imbalance inside a Maint schedule, for two polls | `fill_spread_pct` | No count and no log entry while the RRD records the value; notifies on the poll after the schedule ends | + +Not tested: notification delivery (no mail server), Thold's daemon mode, and Maint on a remote data collector (*live*). diff --git a/docs/decisions/0013-absent-counter-lines-count-as-zero-in-sums.md b/docs/decisions/0013-absent-counter-lines-count-as-zero-in-sums.md new file mode 100644 index 0000000..ef7c137 --- /dev/null +++ b/docs/decisions/0013-absent-counter-lines-count-as-zero-in-sums.md @@ -0,0 +1,35 @@ +# 0013. Count an absent counter line as zero in filesystem sums, for healthy targets only + +Status: Accepted (2026-11-15). Owner decision for #50. + +## Context + +Lustre leaves a counter out of a target's `stats` or `md_stats` file until the counter first counts. The source shows this at `v2_15_8`, `v2_16_1`, and `v2_17_0` ([counter semantics](../PLAN.md#counter-semantics)): an OST that has never been written prints `read_bytes` but no `write_bytes` line. In milestone 3 an absent line was unknown, and because a filesystem sum needs every target, one idle OST made `write_bytes` for the whole filesystem `U` for as long as it stayed idle. The same held for `md_ops` when an MDT had never seen one of the allowlisted operations, which is common for rare operations and certain on a release that lacks one. + +An absent line is not the only way a value goes missing. A section can fail to read, be cut off, or not be printed at all because the node is down or the target moved. Those must stay unknown, or an outage would draw as a throughput drop. + +## Decision + +- **OST sums.** In the filesystem-wide OST counter sums (`read_bytes`, `write_bytes`), a counter whose line is absent counts as 0 only when all of these hold for that target in the same read: + - the node printed the target's stats section completely (its `snapshot_time` line is present and the section was not marked failed or truncated); + - the target is present and its condition is in service; + - the target reported at least one other known value in that read; + - the observation is current; + - the counter did not have a value before under a different or the same `start_time`, and its node did not change: a counter that had counted and is now absent was cleared, so that read is a reset and unknown, and only later reads under the new `start_time` count as 0. +- **`md_ops`.** The zero rule does not apply to MDTs: the read script reads no condition flags for an MDT, so its condition is never in service. `md_ops` sums the operations each MDT printed; an operation that is absent is left out of the sum's member set. While the set of printed operations stays the same the sum is unchanged by this, and when an operation first appears the member set changes and that interval is unknown once. +- **Everything else stays unknown.** A target that is missing, stale, unhealthy, of unknown condition, or whose read failed keeps the sum `U`, as before. A line that is present but malformed is unknown, never zero. +- **Per-target values stay unknown.** The target's own data source still serves `U` for the absent counter. Only the filesystem sum treats it as zero, so the per-target graph shows that the counter was never printed. +- **Continuity.** The reader records the absent line as its own continuity state (`absent`), not as a value. When the counter first appears, its interval continues from zero only if the node printed the same `start_time` as before and the same node answered; otherwise the interval is a reset and is unknown once. + +## Consequences + +- An idle OST no longer hides the filesystem throughput, and a rarely used metadata operation does not hide the metadata rate. +- The member set of a sum includes an absent-but-healthy target, so the first write to an idle OST does not change the set and does not cost an unknown interval when its `start_time` is printed. +- On a release that lacks an allowlisted metadata operation, the operation is left out of `md_ops`, which gives the same sum as counting it as zero; the first time a rare operation is printed costs one unknown interval. +- A stats clear that removes a counter line which had counted is a reset, not a zero, so the sum is unknown for that read rather than undercounting the target. + +## Alternatives rejected + +- **Absent means unknown everywhere.** Correct but useless on a real filesystem, where some OST is always idle. +- **Absent means zero everywhere, per target too.** A per-target graph would draw a never-written OST as measured zero traffic, which a broken read can mimic. +- **Zero for any present target.** A degraded or unknown-condition target may be mid-failover or mid-recovery, where a missing line is not evidence of no traffic. diff --git a/docs/decisions/README.md b/docs/decisions/README.md index ec53c95..c1c03a9 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -16,5 +16,6 @@ Each record captures one architecture decision: its context, the decision, its c | [0010](0010-one-device-per-filesystem.md) | Model each filesystem as one Cacti device with targets as data query indexes | Accepted | | [0011](0011-overview-graphs-by-default-targets-on-demand.md) | Create overview graphs by default and per-target graphs on demand | Accepted | | [0012](0012-thold-rate-alerts-high-thresholds-only.md) | Allow Thold rate alerts on counters for high thresholds only | Accepted | +| [0013](0013-absent-counter-lines-count-as-zero-in-sums.md) | Count an absent counter line as zero in filesystem sums, for healthy targets only | Accepted | Open decisions are tracked as issues labelled `type: decision`. diff --git a/docs/node-setup.md b/docs/node-setup.md index d80e6d0..f430eab 100644 --- a/docs/node-setup.md +++ b/docs/node-setup.md @@ -1,6 +1,6 @@ # Node setup -How a Lustre server is prepared so that the plugin's reader can read it ([ADR 0009](decisions/0009-read-nodes-through-a-forced-ssh-command.md)). Nothing here has run on a real Lustre node yet; the live checks are in [#20](https://github.com/somethingwithproof/plugin_pfs/issues/20). +How a Lustre server is prepared so that the plugin's reader can read it ([ADR 0009](decisions/0009-read-nodes-through-a-forced-ssh-command.md)). Nothing here has run on a real Lustre node yet; the live checks are in [#20](https://github.com/somethingwithproof/plugin_pfs/issues/20) and the pilot plan ([pilot-plan.md](pilot-plan.md)). Installing the plugin in Cacti is in [operator-guide.md](operator-guide.md). ## On each Lustre server @@ -15,6 +15,40 @@ How a Lustre server is prepared so that the plugin's reader can read it ([ADR 00 `restrict` turns off forwarding, agent forwarding, X11, and the pseudo-terminal. sshd runs the forced command in place of whatever the client asks for, so the client cannot run anything else. 4. On Lustre 2.17 the OST `stats` and `recovery_status` files are in debugfs, which only root can read by default. Without root, or a debugfs mount whose mode lets the account read them, those targets report capacity and condition but their counters stay unknown. Which to allow is a site decision ([node-privileges](research/node-privileges.md)). +## What the reader account needs, by node type + +The reader account needs read access to the files below and nothing else: no sudo rule, no group membership beyond its own, no write access anywhere on Lustre, and no login shell use other than the forced command. Derived from Lustre source ([node-privileges](research/node-privileges.md)); not yet confirmed on a real node. + +| Node type | Files the script reads | Readable by an unprivileged account | +|---|---|---| +| OSS (2.15, 2.16) | `osd-*/-OST*/kbytes*`, `files*` and `obdfilter/-OST*/degraded`, `no_precreate`, `no_create`, `readonly` under `/sys/fs/lustre`; `obdfilter/-OST*/stats` and `recovery_status` under `/proc/fs/lustre` | Yes | +| OSS (2.17) | The same sysfs files; `stats` and `recovery_status` under `/sys/kernel/debug/lustre` | Sysfs yes; debugfs only for root by default | +| MDS (all three) | `osd-*/-MDT*/kbytes*`, `files*` under `/sys/fs/lustre`; `mdt/-MDT*/md_stats` under `/proc/fs/lustre` | Yes | +| Any | `version` under `/sys/fs/lustre` | Yes | + +If the site grants debugfs access on 2.17 OSSs, prefer a debugfs mount whose `gid` and `mode` let a dedicated group read it over running the script as root, and note that this opens all of debugfs to that group. + +## Confirm nothing more is granted + +On each server, as root: + +```sh +id pfsread # only its own group, plus any debugfs group you chose +sudo -l -U pfsread # "not allowed to run sudo" +grep -n pfsread /etc/sudoers /etc/sudoers.d/* 2>/dev/null # nothing +cat ~pfsread/.ssh/authorized_keys # exactly one line, starting with restrict,command="/usr/local/libexec/pfs-read.sh" +ls -l /usr/local/libexec/pfs-read.sh # root-owned, 0755, not writable by pfsread +sshd -T -C user=pfsread,host=cacti,addr= | grep -Ei 'permituserenvironment|authorizedkeyscommand|forcecommand' +``` + +From the poller, as the poller user, using the configured key: + +```sh +ssh -F /dev/null -i /etc/cacti/pfs/id_ed25519 -o UserKnownHostsFile=/etc/cacti/pfs/known_hosts -o HostKeyAlias= pfsread@
'id; cat /etc/shadow' +``` + +The answer must be the framed output of the read script (`#pfs-read 1` ... `#pfs-read end`) and nothing from the requested command. Anything else means the forced command is not in effect; fix it before adding the node to the registry. Check that `PermitUserEnvironment` is `no` and that no `Match` block or `AuthorizedKeysCommand` gives the account another key or command. + ## On each Cacti poller that reads nodes 1. Put the private key at the path in **SSH Key File** (default `/etc/cacti/pfs/id_ed25519`), readable only by the poller user. The plugin never creates, copies, or prints it. The health page warns when other users can read it. diff --git a/docs/operator-guide.md b/docs/operator-guide.md new file mode 100644 index 0000000..9b03f77 --- /dev/null +++ b/docs/operator-guide.md @@ -0,0 +1,111 @@ +# Operator guide + +How to install, run, upgrade, back up, and remove the plugin, and what its graphs and values mean. Node preparation is in [node-setup.md](node-setup.md); alerting with Thold and Maint is in [alerting.md](alerting.md). + +Status: phase 1 is code complete and has run only against fixture node output in a disposable Cacti. No pilot on a real Lustre filesystem has reported yet ([#57](https://github.com/somethingwithproof/plugin_pfs/issues/57)); treat every number below as a fixture result until one has. + +## Requirements + +| Component | Requirement | +|---|---| +| Cacti | 1.2.31 or later, no core patches | +| PHP | 8.2 or later on every Cacti host that runs the web UI or a poller. On PHP 8.0 or 8.1 the plugin refuses to enable and Cacti keeps working | +| Lustre | Servers reached over SSH with the forced-command read script; releases checked from source are 2.15.8, 2.16.1, and 2.17.0 | +| Poller host | `ssh` client, a private key for the reader, and a known hosts file | + +## Install + +1. Unpack the release so that the plugin directory is `/plugins/pfs`. The directory must be named `pfs`; a GitHub source archive unpacks as `plugin_pfs-` and has to be renamed. +2. In Cacti, open Configuration, Plugins, and install and enable Parallel Filesystems. The install creates the plugin tables, registers its hooks and two realms, imports the device, data, and graph templates, and copies the two data query files into Cacti (next section). +3. Give users the realms they need under User Management: **Parallel Filesystem View** for the filesystem page, **Parallel Filesystem Admin** for the registry and health pages. The view realm sees inventory and freshness only. Both follow Cacti's device permissions. +4. Open Console, Parallel Filesystem Health. Every warning there names what to fix. A fresh install normally shows the missing SSH key and known hosts files until the next steps are done. +5. Prepare the nodes and the poller as in [node-setup.md](node-setup.md). +6. In Parallel Filesystem Admin, allow the networks each poller may reach, add the filesystem, then its nodes (endpoint, port, login name, role). A node whose endpoint resolves outside the allowed networks is not saved. +7. Wait one poller interval. The reader runs from Cacti's `poller_bottom` hook on each poller and fills the inventory. Review the proposed targets on the filesystem page; an ignored target drops out of the data queries and the summary. +8. Create the filesystem's device from the admin page (or map the filesystem onto an existing device). The plugin lists what it will add before it adds it: the device, both data queries, and five overview graphs. Per-target graphs are created on demand from Cacti's New Graphs page. + +### Data query files + +Cacti reads a data query XML only from inside `/resource`, so the install copies `resource/script_server/pfs_osts.xml` and `pfs_mdts.xml` from the plugin into `/resource/script_server/`. It refuses a symbolic link at either destination and writes each file through a temporary file in the same directory. It records the SHA-256 only of a file it wrote: a file that is already there with the same content, such as a copy made with the steps below, is used but stays yours, and uninstall leaves it. The install never replaces a file it did not write or that was changed since, and uninstall removes only the files it wrote, while unchanged. + +If the web server user cannot write that directory, the health page says so and the data queries cannot list targets. Copy the files once as a user who can, keeping them readable by the web server and poller users: + +```sh +cd +install -m 0644 plugins/pfs/resource/script_server/pfs_osts.xml resource/script_server/ +install -m 0644 plugins/pfs/resource/script_server/pfs_mdts.xml resource/script_server/ +``` + +Then use **Install the Templates Again** on the health page. The warning clears when both copies match the plugin's. Because these copies are yours, the plugin does not update or remove them: repeat the copy after an upgrade that changes either file (the health page warns when they differ), and remove them yourself after uninstalling. + +## What the graphs and values mean + +Each filesystem is one Cacti device. Its targets (OSTs and MDTs) are the indexes of two script server data queries. Every value comes from the reader's cache; no graph, page, or data source contacts a node. + +| Graph | Values | Unknown when | +|---|---|---| +| Fill (overview) | Maximum, mean, and minimum OST used percentage, spread (maximum minus minimum), targets total, missing, and unhealthy | No OST has a current capacity reading | +| Capacity (overview) | Filesystem total and available kilobytes | Any OST is missing or stale, so the total would be partial | +| Throughput (overview) | Filesystem read and write bytes per second | Any OST is missing, stale, unhealthy without its counter, or reset in the interval | +| Metadata (overview) | Filesystem metadata operations per second, all allowlisted operations together | Any MDT is missing, stale, or reset in the interval | +| Data age (overview) | Seconds since the oldest observation behind the summary, and contributor counts | Never observed | +| OST Capacity, Inodes, Throughput (per target) | Used and available, inodes, read and write bytes per second and operations per second | The target is missing, stale, or the node did not print the value | +| MDT Capacity, Operations (per target) | Used and available, inodes, operations per second by operation | Same | + +Rules behind the table: + +- **Used percentage** follows `lfs df`: used over used plus available, rounded up. +- **Unknown is a gap, never zero.** A missing target, a failed read, or a value the node did not print is drawn as a gap. +- **Counters** are stored raw as DERIVE with minimum 0. A reset (a decrease, a changed `start_time`, a different node answering after failover, or an unknown previous value) makes exactly one interval unknown. +- **Freshness.** A value is current while its age is at most one and a half intervals, delayed up to three, and stale after that. Gauges are served while current or delayed; counters only while current, so a missed read is a gap and not a flat line followed by a doubled rate. +- **Idle targets.** Lustre does not print a counter that has never counted since its start time. The filesystem sums count it as zero for a target that is present, in service, and reported its other values in that read; the per-target graph still shows a gap ([ADR 0013](decisions/0013-absent-counter-lines-count-as-zero-in-sums.md)). +- **Target set changes.** When a target joins or leaves a sum, that sum is unknown for one poll, so its whole history is not drawn as one interval. +- **Missing targets** keep their index, data sources, and history until an administrator ignores them in the registry. + +## Upgrade + +1. Back up first (below). +2. Replace the `plugins/pfs` directory with the new release. Keep the directory name. +3. Open Configuration, Plugins. Cacti shows the new version, and the plugin brings its schema, hooks, realms, templates, and data query files up to date when Cacti next loads its configuration (opening the Plugins page does). An interrupted upgrade finishes on the next load. The reader does not run while the schema is behind; it logs that the upgrade has to be finished. +4. Check the health page and the Cacti log. A template or query file problem is reported there, not silently skipped. + +Downgrading to an older plugin version is refused when the database schema is newer than the code; restore the backup taken before the upgrade instead. + +## Back up and restore + +Back up these together, at the same moment: + +| What | Where | +|---|---| +| Plugin tables | Every table named `plugin_pfs_*` in the Cacti database (`mysqldump cacti $(mysql -N -e "SHOW TABLES LIKE 'plugin\_pfs\_%'" cacti)`), or the whole Cacti database | +| Cacti objects | The Cacti database: the filesystem devices, their data sources and graphs, the templates, and the plugin settings in `settings` (`pfs_*`) | +| RRD files | `/rra`, or your RRD directory | +| Node access | On each poller, the SSH key file and known hosts file from the plugin settings. On each node, the reader account, its `authorized_keys` line, and `/usr/local/libexec/pfs-read.sh` | +| Query file copies | `/resource/script_server/pfs_osts.xml` and `pfs_mdts.xml`, if you copied them by hand | + +To restore, stop the pollers, restore the database and the RRD directory from the same backup, restore the key and known hosts files, then start the pollers. The reader resumes on the next run without creating duplicate data sources: the device, its data sources, and the RRD files are matched by their stored ids and paths. The first poll after the restore draws one unknown counter interval, because the reader cannot trust a rate across the gap. If the restored schema is older than the installed code, the plugin detects it and upgrades it as in the upgrade steps. The restore is exercised by `tests/bin/restore-flow.php`. + +## Uninstall + +1. Optional: export the registry from Parallel Filesystem Admin. +2. Disable, then uninstall the plugin in Configuration, Plugins. +3. Uninstall removes the plugin's hooks and realms and the data query file copies it wrote and that are unchanged. Removing the `poller_bottom` hook stops the reader, so nothing collects node values after uninstall: existing graphs keep their history but stop updating, and their newest values become unknown. The imported templates stay in Cacti, like any imported template, and so do the devices, data sources, and graphs made from them. With **Keep Plugin Tables on Uninstall** checked (the default) the tables stay; clear it to drop them. Devices, data sources, graphs, and RRD files you created stay in Cacti and are yours to remove. +4. On each node, remove the reader's `authorized_keys` line, the read script, and the account. Storage nodes are never contacted by the uninstall. + +## Troubleshooting + +Start with the health page; it names the node, the poller, and the cause. Then the Cacti log, filtered on `PFS`. + +| Symptom | Cause and fix | +|---|---| +| A node shows "host key is not in the known hosts file, or it changed" | Add or correct the key under the endpoint name exactly as registered. Check a changed key out of band before trusting it; the reader never accepts one on its own | +| "answered without the fixed read script framing" | The key is not limited to the forced command, or the command is not `pfs-read.sh`. Fix the `authorized_keys` line | +| "printed N parameters the plugin does not read" | The node runs something other than the shipped script. Reinstall `node/pfs-read.sh` | +| "resolves outside the networks allowed" | Allow the network for that poller in the admin page, or correct the endpoint | +| A node read is recorded as failed or partial | Unreachable, timed out, or the answer was larger than **Maximum Response**. Its targets keep their last values until those go stale, then read unknown | +| "The reader on poller N has not completed a run" | The poller is not running `poller_bottom`, PHP is below 8.2 on that poller, or **PHP Binary Path** in Cacti's settings is empty. The log says which | +| The data queries list no targets | The query file copies are missing or differ (see Data query files), or the reader has not completed a read yet | +| Counters on a per-target graph are always a gap | The reader account cannot read the OST `stats` file. On Lustre 2.17 it is in debugfs ([node-setup.md](node-setup.md)) | +| Filesystem throughput is a gap but per-target throughput draws | A target is missing, stale, unhealthy, or just reset; the targets missing and unhealthy counts on the Fill graph say which | +| The overview graphs are created but empty | The device is polled by a different poller than the one that reads its nodes; the health page warns about the mismatch | +| The poller log shows `Plugin 'thold': Uncaught TypeError` and Thold is disabled | A Thold threshold on a counter value saw an unknown interval; delete the threshold, re-enable Thold on the Plugins page, and see [alerting.md](alerting.md#counters-and-thold-182) | diff --git a/docs/pilot-plan.md b/docs/pilot-plan.md new file mode 100644 index 0000000..4cc2dd3 --- /dev/null +++ b/docs/pilot-plan.md @@ -0,0 +1,50 @@ +# Phase 1 pilot plan + +Plan for [#57](https://github.com/somethingwithproof/plugin_pfs/issues/57) (REQ-PILOT-001, REQ-PILOT-002). Fixtures and the container runs cannot show what a real filesystem does; pilots can. Nothing below has run yet. + +## Pilots + +| Pilot | Filesystem | Purpose | +|---|---|---| +| A | A Lustre test filesystem, at least 2 OSS and 1 MDS, one of the matrix releases (2.15, 2.16, or 2.17) | First contact: node setup, read script, values against `lfs df` and server counters, failure drills | +| B | A multi-server, production-like Lustre filesystem, ideally another release than pilot A, with failover pairs | Scale, failover, long-running counters, alert noise | + +Each pilot needs a site contact with root on the servers for setup, a Cacti 1.2.31 or later install on PHP 8.2 or later, and agreement to share a redacted report. + +## Before the pilot + +1. Install the plugin from the release candidate, following [operator-guide.md](operator-guide.md) and [node-setup.md](node-setup.md) as written. Record every step that was unclear or wrong; that record closes the acceptance criterion of #53. +2. Record the site profile: Lustre release and build, OSS and MDS counts, OSTs per OSS, failover pairs, how debugfs access was granted (or not), Cacti version, poller type (`cmd.php` or Spine), poller interval, and hardware of the Cacti host and database. +3. Confirm the reader account can read only what [node-privileges](research/node-privileges.md) lists; record `sudo -l -U pfsread` (or equivalent) and the `authorized_keys` line. + +## Checks + +Run each check at least once; repeat the comparisons at three times of day. + +| # | Check | Method | Pass when | +|---|---|---|---| +| 1 | Fill agrees with `lfs df` | On a client, `lfs df` and `lfs df -i` at the same minute as a reader run; compare each OST's used percentage, the summary maximum, minimum, and spread | Each OST within 1 percentage point; summary values match the same rounding | +| 2 | Throughput agrees with the servers | `lctl get_param obdfilter.*.stats` twice, 300 s apart, on each OSS; compute read and write bytes per second; compare with the per-OST and filesystem graphs for the same interval | Within 2 percent per OST and for the sum | +| 3 | Metadata rate agrees | `lctl get_param mdt.*.md_stats` twice, 300 s apart; compare with the MDT and filesystem metadata graphs | Within 2 percent | +| 4 | Idle targets | Find an OST with no `write_bytes` line; confirm the filesystem write rate still draws and the per-OST graph shows a gap ([ADR 0013](decisions/0013-absent-counter-lines-count-as-zero-in-sums.md)) | As described | +| 5 | Absent counter rule | For each release in the pilot, confirm from real output that a counter that has never counted is left out of `stats` and `md_stats` (the source says so) | Confirmed, or ADR 0013 is reopened | +| 6 | Node down | Stop sshd or block the poller on one OSS for two intervals | Health page names the node; targets go delayed then stale; sums read unknown; `age` and `targets_missing` alert in Thold; recovery is automatic | +| 7 | Failover | Fail an OST over to its partner | One unknown interval on its counters; capacity continues; no duplicate data source | +| 8 | Counter clear | With the site's agreement, clear one OST's stats (`lctl set_param obdfilter..stats=clear`) | One unknown interval; no spike | +| 9 | Thold and Maint | The thresholds in [alerting.md](alerting.md) on gauges only; a Maint schedule over a planned change | Alerts and restorals as tested; nothing notified during the schedule | +| 10 | Scale | Reader run time, poll cycle time, and page times from Cacti's own statistics over a week | Reader within its budget; poll cycle within the interval; pages under two seconds | +| 11 | Privilege | Confirm the reader account could not read or run anything beyond the allowlist | No extra access found | + +## Report + +Each pilot report, attached to #57, lists: + +- the site profile above, with names and addresses redacted; +- the result of each check, with the commands and outputs used to compare; +- every defect found, its severity, and its disposition (fixed, with the commit; deferred, with the issue; or not a defect, with the reason); +- install guide problems, for #53; +- measurements, for [research/scale.md](research/scale.md). + +## Exit + +#57 closes when both pilot reports are attached, checks 1 to 3 pass on both, and every defect has a disposition. A failed check reopens the design question it touches before the phase 1 release. diff --git a/docs/release.md b/docs/release.md new file mode 100644 index 0000000..7ed5911 --- /dev/null +++ b/docs/release.md @@ -0,0 +1,38 @@ +# Release process + +How a version of the plugin is cut. No release has been made; 0.1.0 is prepared but not tagged. + +## Versioning + +- [Semantic Versioning](https://semver.org/spec/v2.0.0.html). Phase 1 is 0.1.0. Until 1.0.0, a minor version may change the schema or templates; the upgrade path handles both. +- `INFO` carries the version of the next release. `plugin_pfs_version()` reads it, and Cacti shows it on the Plugins page. +- [CHANGELOG.md](../CHANGELOG.md) follows Keep a Changelog. Each release section is dated when it is tagged; until then it reads "Unreleased". + +## Archive layout + +The release archive unpacks to a directory named `pfs`, which is what Cacti expects under `plugins/`: + +``` +pfs/ + INFO LICENSE LICENSES/ README.md CHANGELOG.md SECURITY.md CONTRIBUTING.md CODE_OF_CONDUCT.md REUSE.toml + setup.php index.php pfs.php pfs_admin.php pfs_health.php poller_pfs.php + include/ lib/ scripts/ resource/script_server/ templates/ locales/ node/ docs/ +``` + +Tests, CI configuration, and analysis configuration are left out by `export-ignore` in `.gitattributes`. + +## Steps + +1. On a branch, set the version in `INFO`, date the CHANGELOG section, and regenerate `locales/po/cacti.pot` with `sh locales/build_gettext.sh`. Do this on every version change, not only when strings change: the template's `Project-Id-Version` header carries the version from `INFO`, so `sh locales/build_gettext.sh --check` in CI fails until it is regenerated. +2. Merge after CI passes on every matrix entry. The end-to-end runs in `tests/bin` (device flow, target churn, restore, failure, scale, and the Thold and Maint replay) are not in CI yet; run them against a disposable Cacti 1.2.31 and the 1.2.x branch and attach the output to the release pull request. +3. Tag the merge commit with a signed tag, `git tag -s v -m "plugin_pfs "`. +4. Build the archive from the tag and check its contents and its REUSE compliance: + + ```sh + git archive --format=tar.gz --prefix=pfs/ -o pfs-.tar.gz v + tar -tzf pfs-.tar.gz | head + ``` + +5. Publish the archive and its SHA-256 on the GitHub release for the tag, with the CHANGELOG section as the notes. + +A GitHub source download unpacks as `plugin_pfs-/` and must be renamed to `pfs`; the operator guide says so. diff --git a/docs/research/scale.md b/docs/research/scale.md index 73605e3..f3487f5 100644 --- a/docs/research/scale.md +++ b/docs/research/scale.md @@ -35,10 +35,52 @@ Counts follow from the schema and code; none was observed in a database. Poll values per cycle equal the `poller_item` count: 4,500 and 18,000. At a 300-second interval that is 15 and 60 values per second on average, matching the plan. -## Reader cost (plan's assumption, still unmeasured) +## Reader cost (plan's assumption; parsing and caching measured below, SSH still unmeasured) The plan assumes 16 targets per server, 125 node reads per cycle for 2,000 targets, two seconds per read, and a concurrency of eight, giving about 30 seconds. These are assumptions, not measurements; the number of targets per server on real sites and the read latency of the chosen node source ([node-privileges.md](node-privileges.md)) are *live*. +## Container measurement (milestone 4) + +Run 2026-11-15 with `tests/bin/scale-replay.sh` (driver `tests/bin/scale-flow.php`) for [#52](https://github.com/somethingwithproof/plugin_pfs/issues/52). + +**Machine caveat.** One container on a developer laptop: Apple M3 Max, 14 CPUs and 16 GiB given to the OrbStack Linux VM, PHP 8.2.35 CLI, MariaDB in a second container on the same host, Cacti 1.2.31 with `cmd.php`, one process, no boost, no Spine. Node answers are generated fixtures served in process, so no SSH, network, or Lustre time is included. These numbers show how the plugin's own work grows with the target count on this machine; they are not a capacity claim and do not replace the live check in #23. + +Each filesystem has N OSTs on N/16 OSS nodes (16 OSTs per OSS) and one MDS with one MDT. One per-target capacity graph is created for every OST, which is one of the three per-OST graphs; graphing throughput and inodes as well would roughly triple the data source, `poller_item`, and RRD counts. + +Each target count is measured alone: after its counts are taken, the replay removes that filesystem with its device, data sources, and graphs before building the next one, so the 2,000 OST poller runs do not also poll the 500 OST filesystem. The figures below are from that isolated run; an earlier run that left the 500 OST filesystem in place gave the same row counts and readings within a few tenths of a second, except the first 2,000 OST poller run (6 s then, 7 s now). + +| Measurement | 500 OSTs | 2,000 OSTs | +|---|---|---| +| Nodes read | 33 | 126 | +| Reader run, steady state (s) | 0.40 | 0.96 | +| Reader run, first (s) | 0.70 | 1.12 | +| Reader peak memory (MiB) | 18 | 42 | +| Create the device and index both queries (s) | 0.91 | 1.15 | +| Indexes in `host_snmp_cache` | 501 | 2,001 | +| Data query `index`, first call, empty cache (ms) | 8.2 | 30.4 | +| Data query `query` for one field, cached (ms) | 2.5 | 10.1 | +| Data query `get`, per call, cached (ms) | 0.090 | 0.342 | +| Summary script, per call, cached (ms) | 0.076 | 0.067 | +| Summary script, new instance with an empty cache, same process (ms) | 0.101 | 0.097 | +| Create one capacity graph per OST (s) | 25.7 | 156.5 | +| Forced poller run, first, creating RRD files (s, whole seconds) | 2 | 7 | +| Forced poller run, second (s, whole seconds) | 1 | 3 | +| `data_local` | 505 | 2,005 | +| `data_template_rrd` | 1,580 | 6,080 | +| `graph_local` | 505 | 2,005 | +| `poller_item` | 1,505 | 6,005 | +| `host_snmp_cache` | 1,002 | 4,002 | +| RRD files on disk after two polls | 505 | 2,004 | +| Plugin observation rows | 4,525 | 18,025 | + +Readings: + +- The 5 extra data sources and graphs are the overview graphs' summary data sources; each per-target capacity data source has 3 items, so `poller_item` is 3 per OST plus 5. +- The summary script answers in under 0.1 ms per call at 2,000 targets, against the plan's 50 ms budget for it. The data query `get` stays under 0.4 ms per call once its 30 second cache is filled; the first `index` call, which loads every target, takes about 30 ms. +- Creating graphs is the largest cost and is Cacti's own: about 0.08 s per graph at 2,000 targets, against 0.05 s at 500. Operators who graph every OST should expect minutes, once. +- One RRD file of the 2,005 was missing after two polls at 2,000 targets, in both runs, including the isolated one; at 500 targets every file existed. Which data source lacks its file was not recorded, and the cause is not known. Rerun with the file list before relying on the count. +- Reader time excludes SSH. With real nodes the reader's time is dominated by the slowest node and the parallelism setting, not by parsing. + ## Limits - The script server cost per call, the poll cycle time, Cacti page response times at these row counts, and database sizes are not known. diff --git a/docs/research/thold-counters.md b/docs/research/thold-counters.md index aa37f65..ccfd1e1 100644 --- a/docs/research/thold-counters.md +++ b/docs/research/thold-counters.md @@ -57,3 +57,21 @@ Maint suppresses Thold notifications for a device through the guarded function c | Issue | Check | What it settles | |---|---|---| | [#22](https://github.com/somethingwithproof/plugin_pfs/issues/22) | Install Thold and Maint on a Cacti 1.2.31 test instance, create a DERIVE fixture data source and thresholds, feed the sequences above through the poller | The values Thold stores and alerts on, end to end; Maint suppression | + +## Milestone 4 end-to-end run + +Run 2026-11-15 with `tests/bin/alert-replay.sh` on a disposable Cacti 1.2.31 (PHP 8.2.35, `cmd.php`), Thold v1.8.2 (`1eb406bd0f81f3204358cce7bd43c8bb5adc8e4a`) and Maint v1.3 (`cd62de9cc323a4f5a8ac80a8d9dda3c7fa16c470`), unchanged, with the plugin's summary data source fed from fixture reads. Results for gauges and for a rate threshold that sees no unknown value are in [alerting.md](../alerting.md#what-was-tested). + +**Unknown values break Thold 1.8.2 on DERIVE data sources.** In the first run a high threshold on the summary `write_bytes` (DERIVE) saw the `U` the plugin serves for the poll after a target left the sum. Thold's `thold_poller_output()` stored `U` as the threshold's `oldvalue` (a `varchar`), and on the next numeric value `thold_get_currentval()` computed `value - 'U'`: + +``` +ERROR PHP ERROR in Plugin 'thold': Uncaught TypeError: Unsupported operand types: string - string in /work/cacti/plugins/thold/thold_functions.php:812 + #0 /work/cacti/plugins/thold/includes/polling.php(157): thold_get_currentval(...) + #1 /work/cacti/lib/plugins.php(288): thold_poller_output(Array) + #3 /work/cacti/lib/poller.php(816): api_plugin_hook_function('poller_output', Array) + #4 /work/cacti/poller.php(782): process_poller_output(...) +``` + +Cacti's error handler then disabled the Thold plugin (`api_plugin_disable_all()` for a fatal error in a plugin file), and that poll's output processing stopped. Every later Thold check in the run was skipped. The same applies to any DERIVE or COUNTER data source with a Thold threshold that reads `U` once, which the plugin does by design on a reset or a change of contributors (ADR 0012). Thold's development branch at `dc76952ee52e8b4877b2d5b830caab1f7c43dde9` (2026-11-09, not released) treats an unknown or stale counter sample as a fresh baseline and keeps the alert state; it was read, not run. + +Also seen in the run: Thold's first rate after a threshold is created divides the raw counter by the data source step (no previous value), which a two-poll fail trigger absorbs. In Thold 1.8.2's source a non-numeric value takes the not-breached branch of `thold_check_threshold()`, so an unknown value restores a breached threshold; this was read, not exercised. diff --git a/docs/security-review.md b/docs/security-review.md new file mode 100644 index 0000000..1010eff --- /dev/null +++ b/docs/security-review.md @@ -0,0 +1,91 @@ +# Phase 1 security self-review + +Review for [#56](https://github.com/somethingwithproof/plugin_pfs/issues/56) (REQ-SEC-020, REQ-SEC-021), done 2026-11-15 by the author against the code at milestone 4. It is a self-review: it does not replace the external review the issue asks for, and it does not claim the plugin has no other weaknesses. Report vulnerabilities privately as described in [SECURITY.md](../SECURITY.md). + +## Scope and trust boundaries + +| Boundary | Who is on each side | What crosses it | +|---|---|---| +| Storage node to poller | A Lustre server (root on it is trusted for its own data) and the Cacti poller user | The output of the fixed read script, over SSH | +| Poller to Cacti database | The poller user and the database | Parsed values, inventory, node health | +| Cacti user to plugin pages | Any logged-in Cacti user and the web server | Page requests and form posts | +| Plugin to Cacti install | The web server or CLI user that installs the plugin and Cacti's `resource/` tree | Two copied data query files, imported templates | +| Script server to cache | Cacti's poller and script server, with arguments from Cacti's command line | Host ids, target names, field names; numbers back | + +The plugin never writes to a node, never runs a command a user supplies, and has no network listener of its own. + +## Findings by area + +### Node access and the forced command + +- The poller connects with a dedicated key whose `authorized_keys` line forces `pfs-read.sh` and sets `restrict` ([node-setup.md](node-setup.md)). The client sends no command; sshd runs the forced command whatever is asked. +- `pfs-read.sh` takes no arguments (exits 64 if given any), ignores `SSH_ORIGINAL_COMMAND`, sets `PATH`, `LC_ALL`, and `umask`, reads only an allowlist of globs under the Lustre sysfs, procfs, and debugfs roots, skips symbolic links and anything that is not a regular file, caps each file at 64 KiB and the whole answer at 4 MiB, and writes nothing. +- The reader runs `ssh` from an argument array through `proc_open()` with no shell, a two-variable environment, stdin from `/dev/null`, `-F /dev/null` before every option, `BatchMode`, `StrictHostKeyChecking=yes`, a plugin-owned known hosts file with `HostKeyAlias` set to the registered endpoint, no agent, no forwarding, no proxy or local command, and `--` before the address. A missing or changed host key is a failed read; the reader never accepts a key. +- Endpoints, login names, and ports are validated against fixed patterns before they are saved and again when a node is loaded; the endpoint must resolve only to addresses inside the networks allowed for that poller. +- The private key path, known hosts path, and ssh path are settings restricted to absolute paths of a fixed character set. The plugin never creates, copies, or prints the key; the health page warns when the key file is readable by others. + +No issue found. Residual: framing is in-band. A line inside a parameter file that starts with `== `, `!! `, or `#pfs-read` would be read as framing. The files are produced by the Lustre kernel modules and are not writable by unprivileged users on the node, so this needs root on the node, which already controls its data. An external reviewer should confirm that no allowlisted file can carry text from an unprivileged source, for example a client-supplied name in `recovery_status`. + +### Input parsing + +- The parser accepts only the protocol header, section headers, and the end marker; an answer without the end marker, or with anything after it, is rejected as incomplete. Unframed output is rejected and reported on the health page. +- Each value is matched by an anchored, bounded regular expression; a malformed number, a counter printed twice, or a section printed twice is unknown, never zero. At most 50,000 sections are read per answer; the response size is capped by **Maximum Response** before parsing, and a larger answer is discarded unread. +- Target names must match the Lustre `-OST|MDT` pattern and the registered filesystem; anything else is counted and ignored. Unknown parameter paths are counted and ignored. +- The failure run in `tests/bin/failure-replay.sh` exercises unreachable, changed host key, a hung node, an oversized answer, and unframed output through the production reader; each is recorded as a failed read and leaves the cached values unchanged. + +No issue found. + +### Output escaping + +- Every page cell goes through `html_escape()` (`Format::row`, `Format::header`); node versions, names, and errors are shown only after pattern checks. The hostile-string fixture (`tests/fixtures/lustre/hostile.txt`) runs through the page suite. +- The registry export is served as `application/json` with `Content-Disposition: attachment` and `X-Content-Type-Options: nosniff`. +- The script server functions answer only numbers, `U`, target names that matched the pattern, or nothing; arguments are checked against fixed lists and never echoed. +- Log lines name nodes by id and registered name; ssh's error text is classified and dropped, not logged. + +No issue found. + +### Permissions + +- Two realms: **Parallel Filesystem View** (`pfs.php`) and **Parallel Filesystem Admin** (`pfs_admin.php`, `pfs_health.php`). Every page checks its realm, and every page and admin action on a record tied to a device checks `is_device_allowed()` before reading or writing it; lists and the export are filtered the same way. This was tightened in milestone 3 after a coordinator audit, and a restricted-admin case is in the permission suite (`tests/bin/device-permissions.php`). +- State-changing actions are POST only, behind Cacti's CSRF protection; the page suite checks that GET does not change state. +- Realms are granted only from the Plugins page (install and `check_config`); a repair triggered by any page load never grants a realm. + +No issue found. + +### File writes into Cacti + +- Install copies two fixed file names into `/resource/script_server/` and records the SHA-256 of each file it wrote. A file already there with the right content is used but not recorded, so uninstall never removes a copy an administrator made. It never replaces a file it did not write or that changed since, and uninstall removes only recorded files whose hash still matches. No path comes from user input. +- A symbolic link at either destination, dangling or not, is refused before anything is written. Each file is copied to a temporary file in the same directory, its hash is checked, and it is renamed into place; `rename()` replaces the path itself and does not follow a link. Uninstall does not remove a link. `tests/Unit/QueryFilesTest.php` covers both kinds of link, an administrator's copy, and replacement of the plugin's own copy. +- Templates are imported through Cacti's own import code from the shipped XML; the export test checks it carries no data source profile and no third-party attribution. +- The reader writes only to the plugin's own tables; Cacti writes the RRD files. + +Residual: an account that can write `resource/script_server/` can still replace a file between the install's checks and Cacti reading it; that account can already change any data query Cacti loads from there, so this gives it nothing new. + +### Database access + +- SQL is in `Schema` and the `*Repository` classes, plus three statements in `include/unbooted-uninstall.php`, and every statement goes through Cacti's `*_prepared` functions with values bound (checked by search at this review; no test enforces it). Table and column names are constants. + +No issue found. + +## Confirmed issues fixed in this review + +None in this pass. The device-permission gap found in milestone 3 was fixed then. + +## For the external reviewer + +1. The forced-command setup on a real Lustre server: that `restrict` and the forced command hold under the site's sshd configuration (`Match` blocks, `PermitUserEnvironment`, `AuthorizedKeysCommand`), and that the reader account can read nothing else of value. +2. The allowlisted files on 2.15, 2.16, and 2.17: who can influence their content, and the in-band framing residual above. +3. Debugfs access: whatever the site does to let the reader read OST `stats` (a debugfs mount option, group, or a privileged helper) and whether it widens access. +4. `SshNodeSource::argv()` and `ProcRunner`: option injection through any setting or node field, and the child's environment and file descriptors. +5. `LustreBackend::parse()` with crafted input: memory and time at the size limits. +6. The permission suite results (`tests/bin/page-permissions.php`, `tests/bin/device-permissions.php`) and the realm and `is_device_allowed()` checks in `pfs.php`, `pfs_admin.php`, and `pfs_health.php`. +7. The query file copy and uninstall removal, including the symbolic link refusal and the temporary file and rename. +8. Remote data collectors are phase 2 and out of scope here; `remote_agent` actions do not exist yet. + +## Owners + +| Item | Owner | State | +|---|---|---| +| External review | Project owner to arrange | Open (#56) | +| Framing residual | External reviewer | Recorded | +| Symbolic link residual | External reviewer | Recorded | diff --git a/lib/Continuity.php b/lib/Continuity.php index 0f30bc4..2012cc3 100644 --- a/lib/Continuity.php +++ b/lib/Continuity.php @@ -22,9 +22,12 @@ /** * Counter continuity of one cached value (REQ-STATE-004). Reset means the * interval that ends at this observation contains a reset, so its rate is - * unknown. + * unknown. Absent means the node printed the counter's stats section and the + * counter's line was not in it, which Lustre does for a counter that has not + * counted since its start time; the value itself stays unknown (ADR 0013). */ enum Continuity: string { case Continuous = 'continuous'; case Reset = 'reset'; + case Absent = 'absent'; } diff --git a/lib/LustreBackend.php b/lib/LustreBackend.php index b52a7e1..db60e91 100644 --- a/lib/LustreBackend.php +++ b/lib/LustreBackend.php @@ -192,7 +192,7 @@ public function parse(string $output): NodeReport { $version = null; $rejected = 0; - /** @var array, flags: array, start: ?string, recovery: ?string}> $targets */ + /** @var array, flags: array, start: ?string, recovery: ?string, absent: list}> $targets */ $targets = []; foreach ($paths as $i => $path) { @@ -231,7 +231,7 @@ public function parse(string $output): NodeReport { } $name = $id->name(); - $targets[$name] ??= ['id' => $id, 'values' => [], 'flags' => [], 'start' => null, 'recovery' => null]; + $targets[$name] ??= ['id' => $id, 'values' => [], 'flags' => [], 'start' => null, 'recovery' => null, 'absent' => []]; switch ($match['kind']) { case 'capacity': @@ -252,6 +252,11 @@ public function parse(string $output): NodeReport { foreach (self::OST_COUNTERS as $counter => [$samples, $sum]) { $targets[$name]['values'][$samples] = $stats['counters'][$counter]['samples'] ?? null; $targets[$name]['values'][$sum] = $stats['counters'][$counter]['sum'] ?? null; + + if (!array_key_exists($counter, $stats['counters']) && $stats['complete']) { + $targets[$name]['absent'][] = $samples; + $targets[$name]['absent'][] = $sum; + } } $targets[$name]['start'] = $stats['start']; @@ -262,6 +267,10 @@ public function parse(string $output): NodeReport { foreach (self::MDT_OPS as $counter => $value) { $targets[$name]['values'][$value] = $stats['counters'][$counter]['samples'] ?? null; + + if (!array_key_exists($counter, $stats['counters']) && $stats['complete']) { + $targets[$name]['absent'][] = $value; + } } $targets[$name]['start'] = $stats['start']; @@ -285,7 +294,7 @@ public function parse(string $output): NodeReport { } } - $reports[$name] = new TargetReport($target['id'], $values, $target['start'], self::condition($target['flags']), $target['recovery']); + $reports[$name] = new TargetReport($target['id'], $values, $target['start'], self::condition($target['flags']), $target['recovery'], $target['absent']); } ksort($reports); @@ -308,14 +317,14 @@ private function classify(string $path): ?array { } /** - * @param array, flags: array, start: ?string, recovery: ?string}> $targets + * @param array, flags: array, start: ?string, recovery: ?string, absent: list}> $targets */ private function noteTarget(string $path, array &$targets): void { $match = $this->classify($path); $id = $match === null ? null : TargetId::parse($match['target']); if ($id !== null && ($match['type'] === null || $id->type === $match['type'])) { - $targets[$id->name()] ??= ['id' => $id, 'values' => [], 'flags' => [], 'start' => null, 'recovery' => null]; + $targets[$id->name()] ??= ['id' => $id, 'values' => [], 'flags' => [], 'start' => null, 'recovery' => null, 'absent' => []]; } } @@ -343,14 +352,17 @@ private static function version(array $lines): ?string { * A stats file: snapshot_time, optional start_time and elapsed_time, then * " samples []" with optional min, max, sum, and sum * of squares. A counter printed twice, or a line that does not match the - * format, leaves that counter unknown. + * format, leaves that counter unknown. complete is true when the section + * carried its snapshot_time line, so a counter missing from it was left + * out by Lustre rather than lost in transit. * * @param list $lines * - * @return array{start: ?string, counters: array} + * @return array{start: ?string, complete: bool, counters: array} */ private static function stats(array $lines): array { $start = null; + $snapshot = false; $counters = []; $broken = []; @@ -366,6 +378,8 @@ private static function stats(array $lines): array { $start = $m[2]; } + $snapshot = $snapshot || $m[1] === 'snapshot_time'; + continue; } @@ -382,8 +396,9 @@ private static function stats(array $lines): array { } // A line that looks like a counter we want but does not parse - // makes that counter unknown rather than silently absent. - if (preg_match('/^([a-z_]{1,32})\s/', $line, $m) === 1) { + // makes that counter unknown rather than silently absent. The + // line is trimmed, so a bare name ends the line. + if (preg_match('/^([a-z_]{1,32})(?:\s|$)/', $line, $m) === 1) { $broken[$m[1]] = true; } } @@ -392,7 +407,7 @@ private static function stats(array $lines): array { $counters[$name] = ['samples' => null, 'sum' => null]; } - return ['start' => $start, 'counters' => $counters]; + return ['start' => $start, 'complete' => $snapshot, 'counters' => $counters]; } /** diff --git a/lib/Reader.php b/lib/Reader.php index f6a0e18..2b7a2cf 100644 --- a/lib/Reader.php +++ b/lib/Reader.php @@ -322,7 +322,9 @@ private function observationsFor(TargetUpdate $update, array $specs, array $prev $value = $update->report->values[$name] ?? null; $start = $update->report->startMarker; - $continuity = ResetDetector::continuity($prior, $value, $start, $update->sourceNodeId, $spec->kind); + $continuity = $value === null && $spec->kind === ValueKind::Counter && in_array($name, $update->report->absent, true) + ? ResetDetector::absent($prior, $start, $update->sourceNodeId) + : ResetDetector::continuity($prior, $value, $start, $update->sourceNodeId, $spec->kind); $epoch = ($prior->epoch ?? 0) + ($continuity === Continuity::Reset ? 1 : 0); $out[] = new Observation($targetId, $name, $value, $now, $now, $update->sourceNodeId, $filesystem->interval, $continuity, $spec->kind === ValueKind::Counter ? $start : null, $epoch); diff --git a/lib/ResetDetector.php b/lib/ResetDetector.php index 162aae5..8ce7741 100644 --- a/lib/ResetDetector.php +++ b/lib/ResetDetector.php @@ -29,6 +29,18 @@ * 5), or the previous value was unknown, so no rate can be trusted across it. * A reset hidden by a later, larger value with no start_time is not * detectable; that limit is documented in the research. + * + * A counter Lustre left out of its stats section (Continuity::Absent) has not + * counted since its start time, so its first printed value continues from + * zero when the start time is printed, unchanged, and the node is the same; + * without a start time to compare there is no way to rule out a clear, and + * the interval is a reset (ADR 0013). + * + * Entering absence is checked the same way (absent()): a counter that had a + * value and is now left out was cleared, as is one whose start time or node + * changed, so that interval is a reset and not a zero. Only a counter that + * was already without a value under the same start time and node, or that + * has no earlier observation, is Absent. */ final class ResetDetector { public static function continuity(?Observation $previous, ?float $value, ?string $start, int $sourceNodeId, ValueKind $kind): Continuity { @@ -36,6 +48,12 @@ public static function continuity(?Observation $previous, ?float $value, ?string return Continuity::Continuous; } + if ($previous->continuity === Continuity::Absent) { + return $start !== null && $start === $previous->startMarker && $previous->sourceNodeId === $sourceNodeId + ? Continuity::Continuous + : Continuity::Reset; + } + return match (true) { $previous->value === null => Continuity::Reset, $value < $previous->value => Continuity::Reset, @@ -44,4 +62,17 @@ public static function continuity(?Observation $previous, ?float $value, ?string default => Continuity::Continuous, }; } + + /** + * Continuity of a counter Lustre left out of a complete stats section. + */ + public static function absent(?Observation $previous, ?string $start, int $sourceNodeId): Continuity { + if ($previous === null) { + return Continuity::Absent; + } + + return $previous->value === null && $start !== null && $start === $previous->startMarker && $previous->sourceNodeId === $sourceNodeId + ? Continuity::Absent + : Continuity::Reset; + } } diff --git a/lib/SummaryCalculator.php b/lib/SummaryCalculator.php index 10679f5..0903257 100644 --- a/lib/SummaryCalculator.php +++ b/lib/SummaryCalculator.php @@ -31,6 +31,12 @@ * capacity totals need every OST, and the aggregate counters need every OST * (or MDT) present with a current, continuous value. * + * A counter Lustre left out of a target's stats section has not counted + * since its start time. In a sum it counts as zero, but only for a target + * that is present, in service, and reported other values in the same read; + * a missing, stale, or failed target still makes the sum unknown (ADR 0013). + * The target's own value stays unknown. + * * An aggregate counter is a sum of counters, so its member set must not * change between two published values: a target joining would add its whole * history to the sum. Each counter's member set is kept as a hash, and a @@ -182,7 +188,7 @@ private static function sum(array $targets, array $metrics, \Closure $current): foreach ($metrics as $metric) { $observation = $target->value($metric); - $value = $observation?->published(); + $value = self::absentAsZero($target, $observation, $current) ? 0.0 : $observation?->published(); if ($value === null || !$current($observation)) { continue; @@ -215,6 +221,31 @@ private static function sum(array $targets, array $metrics, \Closure $current): return ['value' => $complete ? $total : null, 'members' => $members, 'contributors' => $contributors]; } + /** + * Whether an absent counter counts as zero: the observation says Lustre + * left the line out, it is current, and the target is present, in + * service, and has a known value from the same read. + * + * @param \Closure(?Observation): bool $current + */ + private static function absentAsZero(SummaryTarget $target, ?Observation $observation, \Closure $current): bool { + if ($observation === null || $observation->continuity !== Continuity::Absent || !$current($observation)) { + return false; + } + + if ($target->presence !== Presence::Present || $target->condition !== Condition::InService) { + return false; + } + + foreach ($target->values as $other) { + if ($other->value !== null && $other->observedAt === $observation->observedAt) { + return true; + } + } + + return false; + } + /** * @param array{value: ?float, members: list, contributors: int} $sum * diff --git a/lib/TargetQuery.php b/lib/TargetQuery.php index abfab2c..bc74b8f 100644 --- a/lib/TargetQuery.php +++ b/lib/TargetQuery.php @@ -146,7 +146,10 @@ private function value(string $field, Target $target, Filesystem $filesystem, ar $observation = $values[$target->id][$field] ?? null; $value = $observation?->published(); - if ($observation === null || $value === null) { + // A target that a complete read left out, or that two nodes + // reported, keeps its index and data source but serves U: its last + // value would otherwise draw on for up to two intervals. + if ($target->presence !== Presence::Present || $observation === null || $value === null) { return 'U'; } diff --git a/lib/TargetReport.php b/lib/TargetReport.php index 5cbd084..4d5b702 100644 --- a/lib/TargetReport.php +++ b/lib/TargetReport.php @@ -24,11 +24,16 @@ * * $values holds every value the backend declares for the target's type; a * value the node did not print, or printed in a form the parser rejects, is - * null (unknown), never zero (REQ-BACKEND-003). + * null (unknown), never zero (REQ-BACKEND-003). $absent names the counters + * whose stats section the node printed without that counter's line: Lustre + * omits a counter that has not counted since its start time, so the summary + * may count it as zero for a healthy target (ADR 0013). The value itself + * stays null. */ final readonly class TargetReport { /** * @param array $values value name => value + * @param list $absent counter value names absent from a printed stats section */ public function __construct( public TargetId $id, @@ -36,6 +41,7 @@ public function __construct( public ?string $startMarker, public Condition $condition, public ?string $recovery, + public array $absent = [], ) { } } diff --git a/lib/TemplateInstaller.php b/lib/TemplateInstaller.php index 1654c24..5b7aa32 100644 --- a/lib/TemplateInstaller.php +++ b/lib/TemplateInstaller.php @@ -135,7 +135,7 @@ public function uninstall(): void { foreach ($written as $file => $hash) { $target = $this->queryTarget($file); - if ($target !== null && is_file($target) && hash_file('sha256', $target) === $hash) { + if ($target !== null && !is_link($target) && is_file($target) && hash_file('sha256', $target) === $hash) { @unlink($target); } } @@ -201,11 +201,21 @@ public function queryFileProblems(): array { } /** + * Copy the data query files into Cacti's resource tree. + * + * Ownership is recorded only for a file this method wrote, as soon as it is + * written: a file that is + * already there with the right content, for example one an administrator + * copied by hand, is used but not recorded, so uninstall never removes + * it. A file is replaced only when the plugin wrote it and nobody changed + * it since. The destination must not be a symbolic link, dangling or not; + * each file is written to a temporary file in the same directory and + * renamed into place, and rename() replaces a path without following it. + * * @return string|null the reason, or null when every file is in place */ private function installQueryFiles(): ?string { $written = $this->written(); - $changed = false; foreach (self::QUERIES as [, $file]) { $source = $this->querySource($file); @@ -215,37 +225,73 @@ private function installQueryFiles(): ?string { return sprintf('The data query file %s cannot be installed: the source or the Cacti resource directory is missing', $file); } + clearstatcache(true, $target); + + if (is_link($target)) { + return sprintf('%s is a symbolic link; it was left as it is. Replace it with a copy of plugins/pfs/resource/script_server/%s', $target, $file); + } + $want = (string) hash_file('sha256', $source); - if (is_file($target)) { - $have = (string) hash_file('sha256', $target); + if (file_exists($target)) { + $have = is_file($target) ? (string) hash_file('sha256', $target) : ''; + $ours = ($written[$file] ?? null) === $have; if ($have === $want) { - $written[$file] ??= $want; - continue; } - if (($written[$file] ?? null) !== $have) { + if (!$ours) { 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/pfs/resource/script_server/%s', $target, $file); } } - if (!is_writable(dirname($target)) || @copy($source, $target) === false || hash_file('sha256', $target) !== $want) { + if (!$this->writeQueryFile($source, $target, $want)) { return sprintf('Could not write %s. Copy plugins/pfs/resource/script_server/%s there as the web server user, then reinstall the templates from the health page', $target, $file); } + // Saved at once: a later file that fails must not leave this one + // written but unrecorded, or a retry would find it identical and + // take it for an administrator's copy. $written[$file] = $want; - $changed = true; - } - - if ($changed || $written !== $this->written()) { set_config_option(self::FILES_SETTING, (string) json_encode($written)); } return null; } + /** + * Write $source to $target through a temporary file in the target's + * directory, checking the copy's hash before the rename. + */ + private function writeQueryFile(string $source, string $target, string $want): bool { + $dir = dirname($target); + + if (!is_dir($dir) || !is_writable($dir)) { + return false; + } + + // tempnam() falls back to the system temporary directory when it + // cannot create the file here, and a rename from there is not atomic. + $temp = @tempnam($dir, '.pfs-'); + + if ($temp === false || realpath(dirname($temp)) !== realpath($dir)) { + if (is_string($temp)) { + @unlink($temp); + } + + return false; + } + + $ok = @copy($source, $temp) && hash_file('sha256', $temp) === $want && @chmod($temp, 0644) && @rename($temp, $target); + + if (!$ok) { + @unlink($temp); + } + + return $ok; + } + /** * @return string|null the reason, or null when every object imported */ diff --git a/locales/po/cacti.pot b/locales/po/cacti.pot index 808b9ad..bb49d1a 100644 --- a/locales/po/cacti.pot +++ b/locales/po/cacti.pot @@ -6,7 +6,7 @@ #, fuzzy msgid "" msgstr "" -"Project-Id-Version: pfs 0.1.0-dev\n" +"Project-Id-Version: pfs 0.1.0\n" "Report-Msgid-Bugs-To: https://github.com/somethingwithproof/plugin_pfs/issues\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: Thomas Vincent \n" diff --git a/templates/pfs-templates.xml b/templates/pfs-templates.xml index 5b9618e..54dfbc5 100644 --- a/templates/pfs-templates.xml +++ b/templates/pfs-templates.xml @@ -433,6 +433,25 @@ 19 + + 11 + hash_080103daf82948cb2dfd865880d08160a7848a + 0 + FF + 1 + 0 + 0 + + + hash_0601030292662719dc838b36ba4253137dbf08 + + Seconds since the oldest observation: + on + 0.00 + + + 20 + diff --git a/tests/Unit/LustreBackendTest.php b/tests/Unit/LustreBackendTest.php index 5014f72..5b9b7f8 100644 --- a/tests/Unit/LustreBackendTest.php +++ b/tests/Unit/LustreBackendTest.php @@ -18,8 +18,14 @@ */ use Somethingwithproof\Pfs\Condition; +use Somethingwithproof\Pfs\Continuity; use Somethingwithproof\Pfs\LustreBackend; +use Somethingwithproof\Pfs\Observation; +use Somethingwithproof\Pfs\Presence; use Somethingwithproof\Pfs\ReadError; +use Somethingwithproof\Pfs\Review; +use Somethingwithproof\Pfs\SummaryCalculator; +use Somethingwithproof\Pfs\SummaryTarget; use Somethingwithproof\Pfs\TargetType; use Somethingwithproof\Pfs\ValueKind; use Somethingwithproof\Pfs\ValueSpec; @@ -58,6 +64,8 @@ function pfs_fixture(string $name): string { ->and($ost1->values['read_ops'])->toBe(10.0) ->and($ost1->values['write_ops'])->toBeNull() ->and($ost1->values['write_bytes'])->toBeNull() + ->and($ost1->absent)->toBe(['write_ops', 'write_bytes']) + ->and($ost0->absent)->toBe([]) ->and($ost1->condition)->toBe(Condition::Degraded) ->and($ost1->recovery)->toBe('RECOVERING'); }); @@ -71,6 +79,8 @@ function pfs_fixture(string $name): string { ->and($mdt->values['md_open'])->toBe(50000.0) ->and($mdt->values['md_par_rename_file'])->toBe(12.0) ->and($mdt->values['md_mkdir'])->toBeNull() + ->and($mdt->absent)->toContain('md_mkdir') + ->and($mdt->absent)->not->toContain('md_open') ->and($mdt->values)->not->toHaveKey('weird_new_op') ->and($mdt->values)->not->toHaveKey('read_bytes') ->and($mdt->condition)->toBe(Condition::Unknown); @@ -92,9 +102,44 @@ function pfs_fixture(string $name): string { ->and($ost->values['kbytes_free'])->toBeNull() ->and($ost->values['read_bytes'])->toBeNull() ->and($ost->values['read_ops'])->toBeNull() + ->and($ost->absent)->toBe([]) ->and($ost->startMarker)->toBeNull(); }); +it('does not call a counter absent when its stats section has no snapshot_time line', function () { + $output = "#pfs-read 1\n== obdfilter/scratch-OST0000/stats\nread_bytes 10 samples [bytes] 4096 4096 40960 167772160\n#pfs-read end\n"; + $ost = (new LustreBackend())->parse($output)->targets['scratch-OST0000'] ?? throw new LogicException('no target'); + + expect($ost->values['write_bytes'])->toBeNull() + ->and($ost->absent)->toBe([]); +}); + +it('keeps a bare counter name with no values unknown, never absent', function () { + $output = "#pfs-read 1\n" + . "== obdfilter/scratch-OST0000/degraded\n0\n\n" + . "== obdfilter/scratch-OST0000/stats\n" + . "snapshot_time 1731600000.123456789 secs.nsecs\n" + . "start_time 1731000000.000000001 secs.nsecs\n" + . "read_bytes 10 samples [bytes] 4096 4096 40960 167772160\n" + . "write_bytes \n\n" + . "== mdt/scratch-MDT0000/md_stats\n" + . "snapshot_time 1731600000.000000001 secs.nsecs\n" + . "open 70 samples [usecs] 1 900 700 7000\n" + . "close\n\n" + . "#pfs-read end\n"; + $report = (new LustreBackend())->parse($output); + $ost = $report->targets['scratch-OST0000'] ?? throw new LogicException('no OST'); + $mdt = $report->targets['scratch-MDT0000'] ?? throw new LogicException('no MDT'); + + expect($ost->values['read_bytes'])->toBe(40960.0) + ->and($ost->values['write_bytes'])->toBeNull() + ->and($ost->absent)->not->toContain('write_bytes') + ->and($ost->absent)->not->toContain('write_ops') + ->and($mdt->values['md_open'])->toBe(70.0) + ->and($mdt->values['md_close'])->toBeNull() + ->and($mdt->absent)->not->toContain('md_close'); +}); + it('rejects an answer without the end marker as incomplete', function () { $report = (new LustreBackend())->parse(pfs_fixture('incomplete.txt')); @@ -180,3 +225,39 @@ function pfs_fixture(string $name): string { ->and($kinds['read_bytes'])->toBe(ValueKind::Counter) ->and($kinds['md_open'])->toBe(ValueKind::Counter); }); + +it('parses the generated fixtures the end-to-end flows and the scale harness use', function () { + require_once __DIR__ . '/../bin/lustre-fixture.php'; + + $oss = (new LustreBackend())->parse(pfs_fixture_oss('scratch', [0 => ['used' => 40, 'read' => 4096, 'write' => 8192], 1 => ['used' => 90, 'read' => 4096, 'write' => null, 'degraded' => 1]])); + $mds = (new LustreBackend())->parse(pfs_fixture_mds('scratch', [0 => ['open' => 10, 'close' => 9]])); + + expect($oss->usable() && !$oss->partial && $mds->usable() && !$mds->partial)->toBeTrue() + ->and($oss->targets['scratch-OST0000']->values['kbytes_avail'])->toBe(600000000.0) + ->and($oss->targets['scratch-OST0000']->values['write_bytes'])->toBe(8192.0) + ->and($oss->targets['scratch-OST0000']->condition)->toBe(Condition::InService) + ->and($oss->targets['scratch-OST0001']->absent)->toBe(['write_ops', 'write_bytes']) + ->and($oss->targets['scratch-OST0001']->condition)->toBe(Condition::Degraded) + ->and($mds->targets['scratch-MDT0000']->values['md_open'])->toBe(10.0) + ->and($mds->targets['scratch-MDT0000']->absent)->toContain('md_mkdir'); +}); + +it('marks the operations a 2.15 MDT does not print as absent, so md_ops still sums', function () { + $mdt = (new LustreBackend())->parse(pfs_fixture('mds-2.15.txt'))->targets['scratch-MDT0000']; + + expect($mdt->values['md_open'])->toBe(50000.0) + ->and($mdt->values['md_par_rename_file'])->toBeNull() + ->and($mdt->absent)->toContain('md_par_rename_file', 'md_par_rename_dir', 'md_rename_trylocks', 'md_migrate') + ->and($mdt->absent)->not->toContain('md_open'); + + $observations = []; + + foreach ($mdt->values as $metric => $value) { + $observations[$metric] = new Observation(1, $metric, $value, 1000, 1000, 1, 300, in_array($metric, $mdt->absent, true) ? Continuity::Absent : Continuity::Continuous); + } + + $summary = SummaryCalculator::calculate([new SummaryTarget($mdt->id, Review::Accepted, Presence::Present, Condition::InService, $observations)], null, 300, 1000); + + expect($summary->value('md_ops'))->toBe(50000.0 + 49990.0 + 120000.0 + 3000.0 + 7.0) + ->and($summary->value('mdt_contributors'))->toBe(1.0); +}); diff --git a/tests/Unit/QueryFilesTest.php b/tests/Unit/QueryFilesTest.php new file mode 100644 index 0000000..38e5d56 --- /dev/null +++ b/tests/Unit/QueryFilesTest.php @@ -0,0 +1,130 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_pfs, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_pfs + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * The data query files the install copies into Cacti's resource tree: + * ownership is recorded only for files the plugin wrote, and a symbolic + * link at the destination is refused, dangling or not. + */ + +use Somethingwithproof\Pfs\CactiObjectRepository; +use Somethingwithproof\Pfs\TemplateInstaller; +use Somethingwithproof\Pfs\Tests\Scratch; + +require_once dirname(__DIR__) . '/Support/Scratch.php'; + +beforeEach(function () { + $GLOBALS['__pfs_options'] = []; + $this->scratch = new Scratch(); + $this->plugin = $this->scratch->dir . '/plugin'; + $this->cacti = $this->scratch->dir . '/cacti'; + $this->dest = $this->cacti . '/resource/script_server'; + + foreach (TemplateInstaller::QUERIES as [, $file]) { + $this->scratch->file('plugin/resource/script_server/' . $file, "$file\n", 0644); + } + + mkdir($this->dest, 0700, true); + + $this->installer = new TemplateInstaller($this->plugin, $this->cacti, new CactiObjectRepository(false)); + $this->copy = fn (): ?string => (new ReflectionMethod(TemplateInstaller::class, 'installQueryFiles'))->invoke($this->installer); +}); + +afterEach(function () { + $this->scratch->remove(); + $GLOBALS['__pfs_options'] = []; +}); + +it('copies the files, records what it wrote, and removes them on uninstall', function () { + expect(($this->copy)())->toBeNull() + ->and(file_get_contents($this->dest . '/pfs_osts.xml'))->toBe("pfs_osts.xml\n") + ->and(array_keys(json_decode($GLOBALS['__pfs_options'][TemplateInstaller::FILES_SETTING], true)))->toBe(['pfs_osts.xml', 'pfs_mdts.xml']) + ->and(glob($this->dest . '/.pfs-*'))->toBe([]); + + $this->installer->uninstall(); + + expect(file_exists($this->dest . '/pfs_osts.xml'))->toBeFalse() + ->and(file_exists($this->dest . '/pfs_mdts.xml'))->toBeFalse(); +}); + +it('uses an identical file an administrator copied without taking it over, so uninstall keeps it', function () { + copy($this->plugin . '/resource/script_server/pfs_osts.xml', $this->dest . '/pfs_osts.xml'); + + expect(($this->copy)())->toBeNull() + ->and(json_decode($GLOBALS['__pfs_options'][TemplateInstaller::FILES_SETTING], true))->toHaveKeys(['pfs_mdts.xml'])->not->toHaveKey('pfs_osts.xml'); + + $this->installer->uninstall(); + + expect(file_exists($this->dest . '/pfs_osts.xml'))->toBeTrue() + ->and(file_exists($this->dest . '/pfs_mdts.xml'))->toBeFalse(); +}); + +it('keeps owning a file it wrote when a later file fails, so a retry and uninstall still treat it as its own', function () { + file_put_contents($this->dest . '/pfs_mdts.xml', "local\n"); + + expect(($this->copy)())->toContain('pfs_mdts.xml exists and was not written by this plugin') + ->and(json_decode($GLOBALS['__pfs_options'][TemplateInstaller::FILES_SETTING], true))->toHaveKey('pfs_osts.xml'); + + // The operator clears the conflict and installs again. + unlink($this->dest . '/pfs_mdts.xml'); + + expect(($this->copy)())->toBeNull() + ->and(array_keys(json_decode($GLOBALS['__pfs_options'][TemplateInstaller::FILES_SETTING], true)))->toBe(['pfs_osts.xml', 'pfs_mdts.xml']); + + $this->installer->uninstall(); + + expect(file_exists($this->dest . '/pfs_osts.xml'))->toBeFalse() + ->and(file_exists($this->dest . '/pfs_mdts.xml'))->toBeFalse(); +}); + +it('leaves a different file it did not write alone', function () { + file_put_contents($this->dest . '/pfs_osts.xml', "local\n"); + + expect(($this->copy)())->toContain('was not written by this plugin') + ->and(file_get_contents($this->dest . '/pfs_osts.xml'))->toBe("local\n"); +}); + +it('refuses a symbolic link at the destination, dangling or not, and writes nothing through it', function () { + $elsewhere = $this->scratch->dir . '/elsewhere.xml'; + symlink($elsewhere, $this->dest . '/pfs_osts.xml'); + + expect(($this->copy)())->toContain('is a symbolic link') + ->and(file_exists($elsewhere))->toBeFalse() + ->and(is_link($this->dest . '/pfs_osts.xml'))->toBeTrue(); + + $existing = $this->scratch->file('existing.xml', "pfs_osts.xml\n", 0644); + unlink($this->dest . '/pfs_osts.xml'); + symlink($existing, $this->dest . '/pfs_osts.xml'); + + expect(($this->copy)())->toContain('is a symbolic link'); + + $this->installer->uninstall(); + + expect(is_file($existing))->toBeTrue(); +}); + +it('replaces a file it wrote when the shipped version changes', function () { + expect(($this->copy)())->toBeNull(); + + file_put_contents($this->plugin . '/resource/script_server/pfs_osts.xml', "v2\n"); + + expect(($this->copy)())->toBeNull() + ->and(file_get_contents($this->dest . '/pfs_osts.xml'))->toBe("v2\n") + ->and(substr(sprintf('%o', fileperms($this->dest . '/pfs_osts.xml')), -4))->toBe('0644'); +}); diff --git a/tests/Unit/StateTest.php b/tests/Unit/StateTest.php index 96ff278..6bc7c1b 100644 --- a/tests/Unit/StateTest.php +++ b/tests/Unit/StateTest.php @@ -107,6 +107,35 @@ function pfs_target(string $name, int $source, Presence $presence = Presence::Pr ->and((new Observation(1, 'read_bytes', 10.0, 100, 100, 3, 300))->published())->toBe(10.0); }); + it('continues from an absent counter line only with the same start time and source', function () { + $absent = new Observation(1, 'write_bytes', null, 100, 100, 3, 300, Continuity::Absent, '1731000000.000000001', 0); + + expect(ResetDetector::continuity($absent, 4096.0, '1731000000.000000001', 3, ValueKind::Counter))->toBe(Continuity::Continuous) + ->and(ResetDetector::continuity($absent, 4096.0, '1731599000.000000001', 3, ValueKind::Counter))->toBe(Continuity::Reset) + ->and(ResetDetector::continuity($absent, 4096.0, '1731000000.000000001', 4, ValueKind::Counter))->toBe(Continuity::Reset) + ->and(ResetDetector::continuity($absent, 4096.0, null, 3, ValueKind::Counter))->toBe(Continuity::Reset); + }); + + it('treats a counter that goes absent after a value, or under a new start time or node, as a reset', function () { + $start = '1731000000.000000001'; + $cleared = '1731599000.000000001'; + $counted = new Observation(1, 'write_bytes', 10000.0, 100, 100, 3, 300, Continuity::Continuous, $start, 0); + $absent = new Observation(1, 'write_bytes', null, 100, 100, 3, 300, Continuity::Absent, $start, 0); + + // A stats clear: the counter had a value, now the line is gone and + // the start time is new. Only from the next read on is it absent. + $reset = new Observation(1, 'write_bytes', null, 400, 400, 3, 300, ResetDetector::absent($counted, $cleared, 3), $cleared, 1); + + expect($reset->continuity)->toBe(Continuity::Reset) + ->and(ResetDetector::absent($counted, $start, 3))->toBe(Continuity::Reset) + ->and(ResetDetector::absent($reset, $cleared, 3))->toBe(Continuity::Absent) + ->and(ResetDetector::absent($absent, $start, 3))->toBe(Continuity::Absent) + ->and(ResetDetector::absent($absent, $cleared, 3))->toBe(Continuity::Reset) + ->and(ResetDetector::absent($absent, $start, 4))->toBe(Continuity::Reset) + ->and(ResetDetector::absent($absent, null, 3))->toBe(Continuity::Reset) + ->and(ResetDetector::absent(null, $start, 3))->toBe(Continuity::Absent); + }); + it('never treats a gauge as reset', function () use ($previous) { expect(ResetDetector::continuity($previous, 1.0, null, 9, ValueKind::Gauge))->toBe(Continuity::Continuous); }); diff --git a/tests/Unit/SummaryTest.php b/tests/Unit/SummaryTest.php index 04cf48d..35cc34e 100644 --- a/tests/Unit/SummaryTest.php +++ b/tests/Unit/SummaryTest.php @@ -52,6 +52,19 @@ function sum_target(string $name, array $values, int $at = SUM_T, Presence $pres return new SummaryTarget(TargetId::parse($name), $review, $presence, $condition, $observations); } +/** + * The target with $metric recorded as a counter line Lustre left out of a + * stats section in the same read as its other values. + */ +function sum_absent(SummaryTarget $target, string $metric): SummaryTarget { + $at = max(array_map(static fn (Observation $o): int => $o->observedAt, $target->values)); + $values = $target->values; + + $values[$metric] = new Observation(1, $metric, null, $at, $at, 1, 300, Continuity::Absent); + + return new SummaryTarget($target->id, $target->review, $target->presence, $target->condition, $values); +} + function sum_ost(string $name, float $used, float $read = 1000.0, float $write = 500.0, array $extra = []): array { return ['kbytes_total' => 1000.0, 'kbytes_free' => 1000.0 - $used, 'kbytes_avail' => 1000.0 - $used, 'files_total' => 100.0, 'files_free' => 90.0, 'read_bytes' => $read, 'write_bytes' => $write] + $extra; } @@ -138,18 +151,75 @@ function sum_ost(string $name, float $used, float $read = 1000.0, float $write = ->and($s->value('fill_max_pct'))->toBe(30.0); }); - it('keeps an absent counter line unknown, so a sum that needs it is unknown', function () { + it('keeps a counter with no observation or a rejected line unknown, so a sum that needs it is unknown', function () { $ost1 = sum_ost('scratch-OST0001', 300.0); unset($ost1['write_bytes']); + $rejected = sum_ost('scratch-OST0001', 300.0, 1000.0, 0.0); + $rejected['write_bytes'] = null; + + foreach ([$ost1, $rejected] as $values) { + $s = SummaryCalculator::calculate([ + sum_target('scratch-OST0000', sum_ost('scratch-OST0000', 200.0)), + sum_target('scratch-OST0001', $values), + ], null, 300, SUM_T); + + expect($s->value('write_bytes'))->toBeNull() + ->and($s->value('read_bytes'))->toBe(2000.0) + ->and($s->value('ost_contributors'))->toBe(1.0); + } + }); + it('counts an absent counter line as zero for a present, in-service OST that reported its other values', function () { $s = SummaryCalculator::calculate([ sum_target('scratch-OST0000', sum_ost('scratch-OST0000', 200.0)), - sum_target('scratch-OST0001', $ost1), + sum_absent(sum_target('scratch-OST0001', sum_ost('scratch-OST0001', 300.0)), 'write_bytes'), ], null, 300, SUM_T); - expect($s->value('write_bytes'))->toBeNull() + expect($s->value('write_bytes'))->toBe(500.0) ->and($s->value('read_bytes'))->toBe(2000.0) - ->and($s->value('ost_contributors'))->toBe(1.0); + ->and($s->value('ost_contributors'))->toBe(2.0) + ->and($s->members['write_bytes'])->toBe(sha1("scratch-OST0000:write_bytes\nscratch-OST0001:write_bytes")); + }); + + it('keeps the sum unknown when the OST with an absent line is missing, unhealthy, stale, or reported nothing else', function () { + $healthy = sum_target('scratch-OST0000', sum_ost('scratch-OST0000', 200.0)); + $cases = [ + 'missing' => sum_absent(sum_target('scratch-OST0001', sum_ost('scratch-OST0001', 300.0), SUM_T, Presence::Missing), 'write_bytes'), + 'degraded' => sum_absent(sum_target('scratch-OST0001', sum_ost('scratch-OST0001', 300.0), SUM_T, Presence::Present, Condition::Degraded), 'write_bytes'), + 'unknown' => sum_absent(sum_target('scratch-OST0001', sum_ost('scratch-OST0001', 300.0), SUM_T, Presence::Present, Condition::Unknown), 'write_bytes'), + 'stale' => sum_absent(sum_target('scratch-OST0001', sum_ost('scratch-OST0001', 300.0), SUM_T - 600), 'write_bytes'), + 'read lost' => sum_absent(sum_target('scratch-OST0001', array_map(static fn (): ?float => null, sum_ost('scratch-OST0001', 300.0))), 'write_bytes'), + ]; + + foreach ($cases as $case => $target) { + $s = SummaryCalculator::calculate([$healthy, $target], null, 300, SUM_T); + + expect($s->value('write_bytes'))->toBeNull($case); + } + }); + + it('leaves an absent metadata operation out of md_ops instead of counting it, since an MDT is never in service', function () { + $mdt = sum_absent(sum_target('scratch-MDT0000', ['kbytes_total' => 100.0, 'kbytes_free' => 50.0, 'kbytes_avail' => 50.0, 'md_open' => 7.0], SUM_T, Presence::Present, Condition::Unknown), 'md_close'); + $s = SummaryCalculator::calculate([$mdt], null, 300, SUM_T); + + expect($s->value('md_ops'))->toBe(7.0) + ->and($s->members['md_ops'])->toBe(sha1('scratch-MDT0000:md_open')); + }); + + it('keeps the sum unknown when a counter with a value is cleared and goes absent', function () { + // 1000 + 10000, then OST0001's stats are cleared: its write line is + // gone under a new start time. Zero for it would publish 12000 after + // 11000 and hide the clear, so the reset interval is unknown. + $before = SummaryCalculator::calculate([ + sum_target('scratch-OST0000', sum_ost('scratch-OST0000', 200.0, 1000.0, 1000.0)), + sum_target('scratch-OST0001', sum_ost('scratch-OST0001', 300.0, 1000.0, 10000.0)), + ], null, 300, SUM_T); + $cleared = sum_target('scratch-OST0001', array_merge(sum_ost('scratch-OST0001', 300.0, 1000.0), ['write_bytes' => null]), SUM_T + 300, Presence::Present, Condition::InService, ['write_bytes']); + $after = SummaryCalculator::calculate([sum_target('scratch-OST0000', sum_ost('scratch-OST0000', 200.0, 1000.0, 12000.0), SUM_T + 300), $cleared], $before, 300, SUM_T + 300); + + expect($before->value('write_bytes'))->toBe(11000.0) + ->and($cleared->value('write_bytes')?->continuity)->toBe(Continuity::Reset) + ->and($after->value('write_bytes'))->toBeNull(); }); it('publishes unknown once when the members of a counter sum change', function () { diff --git a/tests/Unit/TemplatesTest.php b/tests/Unit/TemplatesTest.php index 7da4a81..b4bfe3f 100644 --- a/tests/Unit/TemplatesTest.php +++ b/tests/Unit/TemplatesTest.php @@ -40,7 +40,7 @@ function tpl_xml(): string { /** * Every data source item in the export: name => [type id, minimum, maximum]. * - * @return list + * @return list */ function tpl_items(): array { // Export tags are hash_, a two digit object type (08 is a data source @@ -52,7 +52,7 @@ function tpl_items(): array { preg_match('#(.*?)#', $match[3], $min); preg_match('#(.*?)#', $match[3], $max); preg_match('#(.*?)#', $match[3], $type); - $items[] = ['name' => $match[2], 'type' => $type[1] ?? '', 'min' => $min[1] ?? '', 'max' => $max[1] ?? '']; + $items[] = ['hash' => $match[1], 'name' => $match[2], 'type' => $type[1] ?? '', 'min' => $min[1] ?? '', 'max' => $max[1] ?? '']; } return $items; @@ -113,6 +113,20 @@ function tpl_items(): array { } }); +// Cacti creates and updates only the data source items some graph item +// references, so a summary value no graph draws never reaches its RRD or +// Thold. +it('draws every summary value on some graph', function () { + preg_match_all('#(hash_08\d{4}[0-9a-f]{32})#', tpl_xml(), $m); + $drawn = array_flip($m[1]); + + foreach (tpl_items() as $item) { + if (in_array($item['name'], Summary::names(), true)) { + expect(isset($drawn[$item['hash']]))->toBeTrue($item['name'] . ' is not on any graph'); + } + } +}); + it('ships no profile, no core attribution, and the query paths under the resource tree', function () { $xml = tpl_xml(); diff --git a/tests/bin/alert-flow.php b/tests/bin/alert-flow.php new file mode 100644 index 0000000..5ade261 --- /dev/null +++ b/tests/bin/alert-flow.php @@ -0,0 +1,444 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_pfs, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_pfs + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * Thold alerting and Maint suppression on the plugin's summary data source, + * end to end, with Thold and Maint installed unchanged at plugins/thold and + * plugins/maint (issue #51, REQ-ALERT-010, REQ-ALERT-011, REQ-MAINT-001). + * + * tests/bin/alert-replay.sh drives it: for each step in turn it runs + * + * PFS_TEST_DATABASE=disposable php plugins/pfs/tests/bin/alert-flow.php + * php poller.php --force + * php plugins/thold/poller_thold.php + * + * Each step first checks what Thold made of the poll before it, then has the + * reader read the next fixture answer (FixtureNodeSource, no SSH). The + * thresholds are created through Thold's own save_thold(), as its edit page + * does; the maintenance schedule is the two rows Maint's page saves. + * + * Every check prints PASS or FAIL; EVIDENCE lines show the Thold state and + * log rows each check relied on. Must parse on PHP 8.0. State between steps + * is kept in Cacti's settings table under pfs_alert_*. + */ + +chdir(dirname(__DIR__, 4)); + +require('./include/cli_check.php'); +require_once($config['base_path'] . '/lib/api_device.php'); +require_once($config['base_path'] . '/lib/api_graph.php'); +require_once($config['base_path'] . '/lib/template.php'); +require_once($config['base_path'] . '/lib/data_query.php'); +require_once($config['base_path'] . '/lib/utility.php'); +require_once($config['base_path'] . '/lib/rrd.php'); +require_once($config['base_path'] . '/plugins/pfs/setup.php'); +require_once($config['base_path'] . '/plugins/pfs/tests/bin/lustre-fixture.php'); + +use Somethingwithproof\Pfs\AccessMethod; +use Somethingwithproof\Pfs\FixedClock; +use Somethingwithproof\Pfs\FixtureNodeSource; +use Somethingwithproof\Pfs\NodeSources; +use Somethingwithproof\Pfs\TemplateInstaller; + +const ALERT_STEPS = array('setup', 'warmup', 'baseline', 'burst', 'burst2', 'rated', 'calm', 'imbalance', 'balanced', 'lost', 'returned', 'silent', 'answering', 'maint', 'maint2', 'unmaint', 'final'); + +// Thold's log statuses (plugins/thold/includes/settings.php), defined there +// only while Thold's config hook runs. +const ALERT_NOTIFY = 4; +const ALERT_RESTORE = 5; + +if (isset($argv[1]) && $argv[1] === 'list') { + print implode(' ', ALERT_STEPS) . PHP_EOL; + exit(0); +} + +if (getenv('PFS_TEST_DATABASE') !== 'disposable' || !isset($argv[1]) || !in_array($argv[1], ALERT_STEPS, true)) { + fwrite(STDERR, 'Set PFS_TEST_DATABASE=disposable and pass one of: ' . implode(' ', ALERT_STEPS) . PHP_EOL); + exit(2); +} + +if (!pfs_boot()) { + fwrite(STDERR, "PHP 8.2 or later is required\n"); + exit(2); +} + +require_once($config['base_path'] . '/plugins/thold/thold_functions.php'); +require_once($config['base_path'] . '/plugins/thold/includes/arrays.php'); + +$failures = 0; + +/** The thresholds: summary value => [high threshold, fail trigger in polls]. */ +const ALERT_THOLDS = array( + 'fill_spread_pct' => array('20', 1), + 'targets_missing' => array('0.5', 1), + 'age' => array('30', 1), + 'write_bytes' => array('1000000000', 2), +); + +function alert_expect($ok, $message) { + global $failures; + + print ($ok ? 'PASS ' : 'FAIL ') . $message . PHP_EOL; + $failures += $ok ? 0 : 1; +} + +function alert_state($name, $value = null) { + if ($value !== null) { + db_execute_prepared('REPLACE INTO settings (name, value) VALUES (?, ?)', array('pfs_alert_' . $name, (string) $value)); + } + + return (string) db_fetch_cell_prepared('SELECT value FROM settings WHERE name = ?', array('pfs_alert_' . $name)); +} + +/** Two healthy OSTs at 40 and 45 percent; $write is the per-OST write total. */ +function alert_osts($write, array $change = array()) { + $osts = array( + 0 => array('used' => 40, 'read' => 1000000, 'write' => $write), + 1 => array('used' => 45, 'read' => 1000000, 'write' => $write), + ); + + foreach ($change as $index => $fields) { + if ($fields === null) { + unset($osts[$index]); + } else { + $osts[$index] = array_merge($osts[$index], $fields); + } + } + + return $osts; +} + +/** + * Read the fixture answers now. $oss null means the OSS does not answer; + * the write counters keep growing between steps so a rate is drawn. + */ +function alert_read($oss) { + $source = new FixtureNodeSource(array()); + $sources = new NodeSources(); + + if ($oss !== null) { + $source->answer((int) alert_state('oss'), pfs_fixture_oss('scratch', $oss)); + } + + $source->answer((int) alert_state('mds'), pfs_fixture_mds('scratch', array(0 => array('open' => 100, 'close' => 90)))); + $sources->register(AccessMethod::Ssh, $source); + + // Steps are seconds apart, not an interval: make both nodes due again, + // as they are when the next interval starts. + db_execute('UPDATE plugin_pfs_node_health SET last_attempt = last_attempt - 3600'); + + $run = pfs_reader_with(1, $sources, new FixedClock(time()))->run(1, 240, 4); + alert_expect($run->nodesRead + $run->nodesFailed === 2, 'the reader read both nodes (' . $run->nodesRead . ' answered, ' . $run->nodesFailed . ' failed)'); + + return $run; +} + +/** The write total the next healthy read reports: 1 MB more per OST each step. */ +function alert_write($extra = 0) { + $write = (int) alert_state('write') + 1000000 + $extra; + alert_state('write', $write); + + return $write; +} + +function alert_thold($name) { + return db_fetch_row_prepared('SELECT id, thold_alert, thold_fail_count, lastread, oldvalue FROM thold_data WHERE id = ?', array((int) alert_state('thold_' . $name))); +} + +/** Thold log rows for one threshold since the given log id. */ +function alert_log($name, $after) { + return db_fetch_assoc_prepared('SELECT id, status, current, description FROM plugin_thold_log WHERE threshold_id = ? AND id > ? ORDER BY id', array((int) alert_state('thold_' . $name), (int) $after)); +} + +function alert_statuses($rows) { + return array_map('intval', array_column($rows, 'status')); +} + +/** Print the Thold state of every threshold, and remember the newest log id. */ +function alert_evidence($step) { + foreach (array_keys(ALERT_THOLDS) as $name) { + $t = alert_thold($name); + + if (!is_array($t) || !isset($t['id'])) { + continue; + } + + print "EVIDENCE $step $name alert=" . $t['thold_alert'] . ' fail_count=' . $t['thold_fail_count'] . " lastread='" . $t['lastread'] . "'" . PHP_EOL; + } + + foreach (db_fetch_assoc_prepared('SELECT l.id, l.status, l.current, t.data_source_name FROM plugin_thold_log l INNER JOIN thold_data t ON t.id = l.threshold_id WHERE l.id > ? ORDER BY l.id', array((int) alert_state('log'))) as $row) { + print "EVIDENCE $step log id=" . $row['id'] . ' ' . $row['data_source_name'] . ' status=' . $row['status'] . " current='" . $row['current'] . "'" . PHP_EOL; + } +} + +/** Log rows since the step started, by threshold. */ +function alert_since($name) { + return alert_statuses(alert_log($name, (int) alert_state('log'))); +} + +/** + * Check a threshold after a poll: $alert is whether it is breached now, + * $logged the Thold log statuses that poll added for it. + */ +function alert_check($step, $name, $alert, array $logged) { + $t = alert_thold($name); + $got = alert_since($name); + + alert_expect(((int) $t['thold_alert'] !== 0) === $alert && $got === $logged, "$step: $name " . ($alert ? 'breached' : 'normal') . ' with log ' . json_encode($logged) . ' (alert=' . $t['thold_alert'] . ', fail_count=' . $t['thold_fail_count'] . ', log ' . json_encode($got) . ')'); +} + +function alert_quiet($step, array $names) { + foreach ($names as $name) { + alert_check($step, $name, false, array()); + } +} + +/** Create one threshold the way Thold's edit page saves it. */ +function alert_create_thold($hostId, $name, $hi, $trigger) { + $row = db_fetch_row_prepared('SELECT dtr.id AS dtr, dtr.local_data_id, gti.local_graph_id + FROM data_template_rrd dtr + INNER JOIN data_local dl ON dl.id = dtr.local_data_id + INNER JOIN graph_templates_item gti ON gti.task_item_id = dtr.id + WHERE dl.host_id = ? AND dtr.data_source_name = ? + ORDER BY gti.local_graph_id LIMIT 1', array($hostId, $name)); + + if (!is_array($row) || !isset($row['dtr'])) { + return 0; + } + + $_REQUEST = array(); + $fields = array( + 'host_id' => $hostId, 'local_data_id' => $row['local_data_id'], 'local_graph_id' => $row['local_graph_id'], + 'data_template_rrd_id' => $row['dtr'], 'thold_type' => '0', 'thold_hi' => $hi, 'thold_low' => '', + 'thold_fail_trigger' => (string) $trigger, 'thold_warning_hi' => '', 'thold_warning_low' => '', + 'thold_warning_fail_trigger' => '', 'repeat_alert' => '0', 'data_type' => '0', 'cdef' => '0', + 'thold_per_enabled' => 'on', 'name' => 'pfs ' . $name, 'notify_alert' => '0', 'notify_warning' => '0', + 'bl_type' => '0', 'syslog_facility' => '0', 'syslog_priority' => '0', 'time_fail_trigger' => '', + 'time_fail_length' => '', 'time_warning_fail_trigger' => '', 'time_warning_fail_length' => '', + 'bl_ref_time_range' => '', 'bl_fail_trigger' => '', 'decimals' => '2', + ); + + foreach ($fields as $field => $value) { + set_request_var($field, $value); + } + + $id = save_thold(); + + return is_numeric($id) ? (int) $id : 0; +} + +function alert_rrd($localDataId, $name) { + $path = get_data_source_path($localDataId, true); + $out = (string) shell_exec('rrdtool lastupdate ' . escapeshellarg($path) . ' 2>&1'); + $rows = preg_split('/\R/', trim($out)); + + if (count($rows) < 3) { + return array(0, 'none'); + } + + $names = preg_split('/\s+/', trim($rows[0])); + $values = preg_split('/\s+/', trim(substr($rows[2], strpos($rows[2], ':') + 1))); + $map = array_combine($names, $values); + + return array((int) $rows[2], isset($map[$name]) ? $map[$name] : 'none'); +} + +$step = $argv[1]; + +if ($step !== 'setup') { + alert_evidence($step); +} + +switch ($step) { + case 'setup': + alert_expect(api_plugin_is_enabled('thold') && api_plugin_is_enabled('maint'), 'Thold and Maint are installed and enabled'); + + $repo = new \Somethingwithproof\Pfs\FilesystemRepository(false, new \Somethingwithproof\Pfs\SystemClock()); + + foreach ($repo->all() as $old) { + $repo->delete($old->id); + } + + // A 60 second interval keeps the staleness wait short: the summary is + // current up to 90 seconds old (ADR 0012). + db_execute("INSERT INTO plugin_pfs_filesystem (name, backend, poller_id, expected_interval, admin_state) VALUES ('scratch', 'lustre', 1, 60, 'enabled')"); + $fsId = (int) db_fetch_insert_id(); + + foreach (array('oss01' => 'oss', 'mds01' => 'mds') as $name => $role) { + db_execute_prepared("INSERT INTO plugin_pfs_node (filesystem_id, name, role, poller_id, endpoint, port, ssh_user, access_method, admin_state) VALUES (?, ?, ?, 1, '10.20.0.1', 22, 'pfsread', 'ssh', 'enabled')", array($fsId, $name, $role)); + alert_state(substr($name, 0, 3), (int) db_fetch_insert_id()); + } + + alert_state('write', 1000000); + alert_state('log', 0); + alert_read(alert_osts(alert_write())); + + $hostId = pfs_provisioner()->create($repo->find($fsId)); + alert_expect($hostId > 0, 'the filesystem device was created'); + alert_state('host', $hostId); + alert_state('fs', $fsId); + + foreach (ALERT_THOLDS as $name => $spec) { + $id = alert_create_thold($hostId, $name, $spec[0], $spec[1]); + alert_expect($id > 0, "Thold saved a high threshold on $name above " . $spec[0] . ' after ' . $spec[1] . ' poll(s)'); + alert_state('thold_' . $name, $id); + } + + alert_read(alert_osts(alert_write())); + + break; + case 'warmup': + $hostId = (int) alert_state('host'); + alert_expect((int) db_fetch_cell_prepared('SELECT status FROM host WHERE id = ?', array($hostId)) === 3, 'the filesystem device is up, so Thold checks its thresholds'); + alert_expect(is_numeric(alert_thold('fill_spread_pct')['lastread']) && is_numeric(alert_thold('age')['lastread']), 'Thold read the summary values from the poll'); + alert_read(alert_osts(alert_write())); + + break; + case 'baseline': + // Thold's first rate reading after it starts is against no previous + // value; the fail trigger of two polls keeps that from alerting. + alert_quiet($step, array_keys(ALERT_THOLDS)); + // 10 TB more per OST within one poll: far above 1 GB/s. + alert_read(alert_osts(alert_write(10000000000000))); + + break; + case 'burst': + $t = alert_thold('write_bytes'); + alert_expect((int) $t['thold_alert'] !== 0 && (int) $t['thold_fail_count'] === 1 && alert_since('write_bytes') === array(), 'burst: one poll above the rate threshold breaches it without notifying (fail_count=' . $t['thold_fail_count'] . ', log ' . json_encode(alert_since('write_bytes')) . ')'); + alert_read(alert_osts(alert_write(10000000000000))); + + break; + case 'burst2': + alert_check($step, 'write_bytes', true, array(ALERT_NOTIFY)); + alert_read(alert_osts(alert_write())); + + break; + case 'rated': + alert_check($step, 'write_bytes', false, array(ALERT_RESTORE)); + + // Thold 1.8.2 keeps the U a counter data source reads after a reset + // or a change of contributing targets as its previous value, and its + // next rate calculation throws a TypeError in the poller, after + // which Cacti disables Thold (docs/alerting.md). The rest of this + // replay changes the target set, so the rate threshold goes first. + thold_api_thold_remove((int) alert_state('thold_write_bytes')); + alert_expect((int) db_fetch_cell_prepared('SELECT COUNT(*) FROM thold_data WHERE id = ?', array((int) alert_state('thold_write_bytes'))) === 0, 'rated: the rate threshold is removed before the target set changes'); + alert_read(alert_osts(alert_write())); + + break; + case 'calm': + alert_quiet($step, array('fill_spread_pct', 'targets_missing', 'age')); + alert_read(alert_osts(alert_write(), array(0 => array('used' => 90), 1 => array('used' => 10)))); + + break; + case 'imbalance': + alert_check($step, 'fill_spread_pct', true, array(ALERT_NOTIFY)); + alert_quiet($step, array('targets_missing', 'age')); + alert_read(alert_osts(alert_write())); + + break; + case 'balanced': + alert_check($step, 'fill_spread_pct', false, array(ALERT_RESTORE)); + alert_read(alert_osts(alert_write(), array(1 => null))); + + break; + case 'lost': + alert_check($step, 'targets_missing', true, array(ALERT_NOTIFY)); + alert_quiet($step, array('fill_spread_pct', 'age')); + alert_read(alert_osts(alert_write())); + + break; + case 'returned': + alert_check($step, 'targets_missing', false, array(ALERT_RESTORE)); + // The OSS stops answering; the replay waits 40 seconds before polling. + alert_read(null); + + break; + case 'silent': + alert_check($step, 'age', true, array(ALERT_NOTIFY)); + alert_expect(is_numeric(alert_thold('age')['lastread']), 'silent: age stays numeric while the node is silent (REQ-ALERT-003)'); + alert_read(alert_osts(alert_write())); + + break; + case 'answering': + alert_check($step, 'age', false, array(ALERT_RESTORE)); + + // A one-off Maint schedule for the filesystem device, from a minute + // ago to an hour from now, as Maint's schedule page saves it. + db_execute_prepared("INSERT INTO plugin_maint_schedules (enabled, name, mtype, stime, etime, minterval) VALUES ('on', 'pfs replay', 1, ?, ?, 0)", array(time() - 60, time() + 3600)); + $schedule = (int) db_fetch_insert_id(); + db_execute_prepared('INSERT INTO plugin_maint_hosts (type, host, schedule) VALUES (1, ?, ?)', array((int) alert_state('host'), $schedule)); + alert_state('schedule', $schedule); + include_once($config['base_path'] . '/plugins/maint/functions.php'); + alert_expect(plugin_maint_check_cacti_host((int) alert_state('host')), 'Maint reports the filesystem device in maintenance'); + alert_read(alert_osts(alert_write(), array(0 => array('used' => 90), 1 => array('used' => 10)))); + + break; + case 'maint': + case 'maint2': + alert_check($step, 'fill_spread_pct', true, array()); + + $t = alert_thold('fill_spread_pct'); + [$at, $spread] = alert_rrd((int) db_fetch_cell_prepared('SELECT local_data_id FROM thold_data WHERE id = ?', array($t['id'])), 'fill_spread_pct'); + alert_expect((int) $t['thold_fail_count'] === 0 && $spread === '80' && $at >= (int) alert_state('maint_at'), "$step: in maintenance the breach is not counted or notified while the RRD still records it (fill_spread_pct=$spread at $at)"); + alert_state('maint_at', $at + 1); + + if ($step === 'maint2') { + db_execute_prepared('DELETE FROM plugin_maint_hosts WHERE schedule = ?', array((int) alert_state('schedule'))); + db_execute_prepared('DELETE FROM plugin_maint_schedules WHERE id = ?', array((int) alert_state('schedule'))); + } + + alert_read(alert_osts(alert_write(), array(0 => array('used' => 90), 1 => array('used' => 10)))); + + break; + case 'unmaint': + alert_check($step, 'fill_spread_pct', true, array(ALERT_NOTIFY)); + alert_read(alert_osts(alert_write())); + + break; + case 'final': + alert_check($step, 'fill_spread_pct', false, array(ALERT_RESTORE)); + alert_quiet($step, array('targets_missing', 'age')); + + foreach (db_fetch_assoc('SELECT l.id, l.status, l.current, t.data_source_name, l.description FROM plugin_thold_log l INNER JOIN thold_data t ON t.id = l.threshold_id ORDER BY l.id') as $row) { + print 'EVIDENCE log ' . $row['id'] . ' ' . $row['data_source_name'] . ' status=' . $row['status'] . " current='" . $row['current'] . "' " . $row['description'] . PHP_EOL; + } + + // Leave the registry as the setup found it, for the suites after + // this one: no thresholds, filesystem, nodes, or health rows. + foreach (db_fetch_assoc('SELECT id FROM thold_data') as $row) { + thold_api_thold_remove((int) $row['id']); + } + + $repo = new \Somethingwithproof\Pfs\FilesystemRepository(false, new \Somethingwithproof\Pfs\SystemClock()); + + foreach ($repo->all() as $old) { + $repo->delete($old->id); + } + + db_execute("DELETE FROM settings WHERE name LIKE 'pfs\\_alert\\_%'"); + + break; +} + +if ($step !== 'final') { + alert_state('log', (int) db_fetch_cell('SELECT COALESCE(MAX(id), 0) FROM plugin_thold_log')); +} + +exit($failures > 0 ? 1 : 0); diff --git a/tests/bin/alert-replay.sh b/tests/bin/alert-replay.sh new file mode 100644 index 0000000..8ad40a2 --- /dev/null +++ b/tests/bin/alert-replay.sh @@ -0,0 +1,64 @@ +#!/bin/sh +# SPDX-FileCopyrightText: 2026 Thomas Vincent +# SPDX-License-Identifier: GPL-2.0-or-later +# +# This file is part of plugin_pfs, a plugin for Cacti. +# https://github.com/somethingwithproof/plugin_pfs +# +# This program is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by the Free +# Software Foundation; either version 2 of the License, or (at your option) +# any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +# more details. + +# Thold and Maint end to end (tests/bin/alert-flow.php). Run from the root +# of a disposable Cacti install with the plugin installed and enabled, and +# unchanged Thold and Maint releases at plugins/thold and plugins/maint: +# +# PFS_TEST_DATABASE=disposable sh plugins/pfs/tests/bin/alert-replay.sh +# +# Installs and enables Thold and Maint, then runs each step, a forced +# poll, and the Thold check. Exits non-zero when any check failed. +set -u + +[ "${PFS_TEST_DATABASE:-}" = disposable ] || { echo "Set PFS_TEST_DATABASE=disposable" >&2; exit 2; } +[ -f plugins/thold/setup.php ] && [ -f plugins/maint/setup.php ] || { echo "plugins/thold and plugins/maint are required" >&2; exit 2; } + +php cli/plugin_manage.php --plugin=thold --plugin=maint --install --enable || exit 1 + +fail=0 + +steps=$(php plugins/pfs/tests/bin/alert-flow.php list) || { echo "alert-flow.php list failed" >&2; exit 1; } +[ -n "$steps" ] || { echo "alert-flow.php list printed no steps" >&2; exit 1; } + +for step in $steps; do + echo "== step $step" + php plugins/pfs/tests/bin/alert-flow.php "$step" || fail=1 + [ "$step" = final ] && break + + # The OSS stays silent long enough for the summary age to pass the + # 30 second threshold. + [ "$step" = returned ] && sleep 40 + + # RRDtool refuses a second update in the same second, and the steps + # run faster than that. + sleep 1 + php poller.php --poller=1 --force > /tmp/pfs-alert-poll.txt 2>&1 || { fail=1; tail -5 /tmp/pfs-alert-poll.txt; } + + # poller_bottom starts poller_thold.php in the background. Wait for it, + # then run it in the foreground: a run that finds nothing new to check + # changes nothing, because Thold clears each threshold's check flag. + for _ in $(seq 1 60); do + [ "$(php -r 'chdir("."); include("./include/cli_check.php"); print db_fetch_cell("SELECT COUNT(*) FROM processes WHERE tasktype = \"thold\"");')" = 0 ] && break + sleep 1 + done + + php plugins/thold/poller_thold.php > /tmp/pfs-alert-thold.txt 2>&1 || { fail=1; cat /tmp/pfs-alert-thold.txt; } +done + +echo "alert replay fail=$fail" +exit $fail diff --git a/tests/bin/build-templates.php b/tests/bin/build-templates.php index 9a4d123..49e3433 100644 --- a/tests/bin/build-templates.php +++ b/tests/bin/build-templates.php @@ -315,6 +315,9 @@ function pfs_graph_template($name, $title, $label, $base, array $items, $upper = array('rrd' => $s['targets_total'], 'type' => GRAPH_ITEM_TYPE_GPRINT_LAST, 'text' => 'Targets:', 'gprint' => $gCount), array('rrd' => $s['targets_missing'], 'type' => GRAPH_ITEM_TYPE_GPRINT_LAST, 'text' => 'Left out of the summary:', 'gprint' => $gCount), array('rrd' => $s['targets_unhealthy'], 'type' => GRAPH_ITEM_TYPE_GPRINT_LAST, 'text' => 'Unhealthy:', 'gprint' => $gCount), + // Cacti stores only the data source items a graph references, so age + // must appear on a graph for Thold to see it. + array('rrd' => $s['age'], 'type' => GRAPH_ITEM_TYPE_GPRINT_LAST, 'text' => 'Seconds since the oldest observation:', 'gprint' => $gCount), ), '100', true), pfs_graph_template('Parallel Filesystem Imbalance', '|host_description| - Imbalance (fullest minus emptiest OST)', 'percentage points', 1000, array( array('rrd' => $s['fill_spread_pct'], 'type' => GRAPH_ITEM_TYPE_AREA, 'color' => '7D3C98', 'text' => 'Spread', 'gprint' => $gPct, 'legends' => $last), diff --git a/tests/bin/failure-flow.php b/tests/bin/failure-flow.php new file mode 100644 index 0000000..251cba5 --- /dev/null +++ b/tests/bin/failure-flow.php @@ -0,0 +1,191 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_pfs, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_pfs + * + * 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. + */ + +/* + * Phase 1 failure qualification (issue #55, REQ-FAIL-001, REQ-FAIL-002), + * through the production reader and SSH node source, with a stand-in for the + * ssh client whose behaviour each scenario sets. Driven by + * tests/bin/failure-replay.sh: + * + * setup a filesystem whose node is read through the stand-in + * arm choose what the stand-in does and make the node due + * (php plugins/pfs/poller_pfs.php --poller=1 --force, timed) + * check the state the reader recorded for that mode + * cleanup remove the filesystem and restore the settings + * + * Modes: ok, unreachable, hostkey, slow, oversized, unframed, dbloss. The + * stand-in and its fixture live in PFS_FAULT_DIR. Must parse on PHP 8.0. + */ + +chdir(dirname(__DIR__, 4)); + +require('./include/cli_check.php'); +require_once($config['base_path'] . '/lib/api_device.php'); +require_once($config['base_path'] . '/lib/utility.php'); +require_once($config['base_path'] . '/plugins/pfs/setup.php'); +require_once($config['base_path'] . '/plugins/pfs/tests/bin/lustre-fixture.php'); + +$called_by_script_server = true; +require_once($config['base_path'] . '/plugins/pfs/scripts/ss_pfs_targets.php'); +require_once($config['base_path'] . '/plugins/pfs/scripts/ss_pfs_summary.php'); + +const FAULT_MODES = array('ok', 'unreachable', 'hostkey', 'slow', 'oversized', 'unframed', 'dbloss'); + +/** What the node health records for each failing mode. */ +const FAULT_ERRORS = array('unreachable' => 'unreachable', 'hostkey' => 'host_key', 'slow' => 'timeout', 'oversized' => 'too_large', 'unframed' => 'unframed'); + +$dir = (string) getenv('PFS_FAULT_DIR'); +$step = isset($argv[1]) ? $argv[1] : ''; +$mode = isset($argv[2]) ? $argv[2] : ''; + +if (getenv('PFS_TEST_DATABASE') !== 'disposable' || $dir === '' || !is_dir($dir) || !in_array($step, array('setup', 'arm', 'check', 'cleanup'), true) || (in_array($step, array('arm', 'check'), true) && !in_array($mode, FAULT_MODES, true))) { + fwrite(STDERR, "Set PFS_TEST_DATABASE=disposable and PFS_FAULT_DIR, and pass setup, arm , check , or cleanup\n"); + exit(2); +} + +if (!pfs_boot()) { + fwrite(STDERR, "PHP 8.2 or later is required\n"); + exit(2); +} + +$failures = 0; + +function fault_expect($ok, $message) { + global $failures; + + print ($ok ? 'PASS ' : 'FAIL ') . $message . PHP_EOL; + $failures += $ok ? 0 : 1; +} + +function fault_state($name, $value = null) { + if ($value !== null) { + db_execute_prepared('REPLACE INTO settings (name, value) VALUES (?, ?)', array('pfs_fault_' . $name, (string) $value)); + } + + return (string) db_fetch_cell_prepared('SELECT value FROM settings WHERE name = ?', array('pfs_fault_' . $name)); +} + +function fault_health() { + $row = db_fetch_row_prepared('SELECT outcome, error, last_attempt, last_success, duration FROM plugin_pfs_node_health WHERE node_id = ?', array((int) fault_state('node'))); + + return is_array($row) ? $row : array(); +} + +function fault_observed() { + return (int) db_fetch_cell_prepared("SELECT MAX(o.observed_at) FROM plugin_pfs_observation o INNER JOIN plugin_pfs_target t ON t.id = o.target_id WHERE t.filesystem_id = ?", array((int) fault_state('fs'))); +} + +switch ($step) { + case 'setup': + foreach (array('pfs_ssh_binary', 'pfs_ssh_key_file', 'pfs_ssh_known_hosts', 'pfs_read_timeout', 'pfs_max_response') as $name) { + fault_state('saved_' . $name, json_encode(db_fetch_cell_prepared('SELECT value FROM settings WHERE name = ?', array($name)))); + } + + file_put_contents("$dir/answer.txt", pfs_fixture_oss('fault', array(0 => array('used' => 40, 'read' => 1000, 'write' => 1000), 1 => array('used' => 50, 'read' => 1000, 'write' => 1000)))); + file_put_contents("$dir/big.txt", "#pfs-read 1\n== version\n" . str_repeat(str_repeat('x', 1023) . "\n", 200) . "#pfs-read end\n"); + file_put_contents("$dir/id_ed25519", "not a key; the stand-in never reads it\n"); + file_put_contents("$dir/known_hosts", "127.0.0.1 ssh-ed25519 AAAA\n"); + chmod("$dir/id_ed25519", 0600); + + // The stand-in for ssh: what it does is chosen by the mode file. + file_put_contents("$dir/ssh", "#!/bin/sh\n" . + "case \"\$(cat '$dir/mode')\" in\n" . + "ok) cat '$dir/answer.txt' ;;\n" . + "unreachable) echo 'ssh: connect to host 127.0.0.1 port 22: No route to host' >&2; exit 255 ;;\n" . + "hostkey) echo '@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@' >&2; echo '@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @' >&2; exit 255 ;;\n" . + "slow) sleep 30; cat '$dir/answer.txt' ;;\n" . + "oversized) cat '$dir/big.txt' ;;\n" . + "unframed) echo 'Welcome to oss01'; echo 'Last login: never' ;;\n" . + "dbloss) sleep 5; cat '$dir/answer.txt' ;;\n" . + "esac\n"); + chmod("$dir/ssh", 0755); + file_put_contents("$dir/mode", "ok\n"); + + foreach (array('pfs_ssh_binary' => "$dir/ssh", 'pfs_ssh_key_file' => "$dir/id_ed25519", 'pfs_ssh_known_hosts' => "$dir/known_hosts", 'pfs_read_timeout' => '3', 'pfs_max_response' => '64') as $name => $value) { + db_execute_prepared('REPLACE INTO settings (name, value) VALUES (?, ?)', array($name, $value)); + } + + db_execute("INSERT INTO plugin_pfs_filesystem (name, backend, poller_id, expected_interval, admin_state) VALUES ('fault', 'lustre', 1, 300, 'enabled')"); + $fsId = (int) db_fetch_insert_id(); + db_execute("INSERT INTO plugin_pfs_node (filesystem_id, name, role, poller_id, endpoint, port, ssh_user, access_method, admin_state) VALUES ($fsId, 'fault-oss', 'oss', 1, '127.0.0.1', 22, 'pfsread', 'ssh', 'enabled')"); + fault_state('node', (int) db_fetch_insert_id()); + fault_state('fs', $fsId); + db_execute("INSERT IGNORE INTO plugin_pfs_network (poller_id, cidr, created_at) VALUES (1, '127.0.0.0/8', UNIX_TIMESTAMP())"); + fault_expect($fsId > 0, 'a filesystem whose node is read through the ssh stand-in'); + + break; + case 'arm': + file_put_contents("$dir/mode", "$mode\n"); + db_execute('UPDATE plugin_pfs_node_health SET last_attempt = last_attempt - 3600'); + fault_state('before', fault_observed()); + + break; + case 'check': + $health = fault_health(); + $fs = (new \Somethingwithproof\Pfs\FilesystemRepository(false, new \Somethingwithproof\Pfs\SystemClock()))->find((int) fault_state('fs')); + print 'EVIDENCE ' . $mode . ' health ' . json_encode($health) . PHP_EOL; + + if ($mode === 'ok') { + fault_expect(isset($health['outcome']) && $health['error'] === '' && fault_observed() > (int) fault_state('before'), 'ok: the production reader read the node through the stand-in and cached its values'); + + if ((int) fault_state('host') === 0) { + $hostId = pfs_provisioner()->create($fs); + fault_state('host', $hostId); + fault_expect($hostId > 0, 'ok: the filesystem device was created'); + } + + fault_expect(ss_pfs_targets((int) fault_state('host'), 'ost', 'get', 'kbytes_total', 'fault-OST0000') === '1000000000', 'ok: the data query serves the value'); + } elseif ($mode === 'dbloss') { + // The reader's database connection was killed while it waited + // for the node. Whatever it managed to write, the next run must + // read normally and nothing may read as zero. + $lease = db_fetch_row('SELECT holder, expires_at FROM plugin_pfs_reader WHERE poller_id = 1'); + print 'EVIDENCE dbloss lease ' . json_encode($lease) . PHP_EOL; + fault_expect(ss_pfs_targets((int) fault_state('host'), 'ost', 'get', 'kbytes_total', 'fault-OST0000') !== '0', 'dbloss: no value reads as zero after the reader lost its database connection'); + } else { + $t = db_fetch_row_prepared("SELECT presence FROM plugin_pfs_target WHERE filesystem_id = ? AND name = 'fault-OST0000'", array((int) fault_state('fs'))); + fault_expect(isset($health['error']) && $health['error'] === FAULT_ERRORS[$mode], "$mode: the node read is recorded as failed with error " . FAULT_ERRORS[$mode] . ' (' . json_encode($health) . ')'); + fault_expect(fault_observed() === (int) fault_state('before') && is_array($t) && $t['presence'] === 'present', "$mode: the cached values and the inventory are left as they were, not zeroed or marked missing"); + fault_expect(ss_pfs_targets((int) fault_state('host'), 'ost', 'get', 'kbytes_total', 'fault-OST0000') === '1000000000', "$mode: the last good gauge is still served while it is current"); + + $clock = new \Somethingwithproof\Pfs\SystemClock(); + $warnings = \Somethingwithproof\Pfs\HealthWarnings::production($clock)->for(pfs_settings(), (new \Somethingwithproof\Pfs\NodeRepository(false, $clock))->all(), (new \Somethingwithproof\Pfs\NodeHealthRepository(false))->all(), (new \Somethingwithproof\Pfs\ReaderRepository(false, $clock))->all(), array($fs->id => $fs)); + print 'EVIDENCE ' . $mode . ' warnings ' . json_encode($warnings) . PHP_EOL; + } + + break; + case 'cleanup': + foreach (array('pfs_ssh_binary', 'pfs_ssh_key_file', 'pfs_ssh_known_hosts', 'pfs_read_timeout', 'pfs_max_response') as $name) { + $saved = json_decode(fault_state('saved_' . $name), true); + + if (is_string($saved)) { + db_execute_prepared('REPLACE INTO settings (name, value) VALUES (?, ?)', array($name, $saved)); + } else { + db_execute_prepared('DELETE FROM settings WHERE name = ?', array($name)); + } + } + + (new \Somethingwithproof\Pfs\FilesystemRepository(false, new \Somethingwithproof\Pfs\SystemClock()))->delete((int) fault_state('fs')); + db_execute("DELETE FROM plugin_pfs_network WHERE cidr = '127.0.0.0/8'"); + db_execute("DELETE FROM settings WHERE name LIKE 'pfs\\_fault\\_%'"); + + break; +} + +exit($failures > 0 ? 1 : 0); diff --git a/tests/bin/failure-replay.sh b/tests/bin/failure-replay.sh new file mode 100644 index 0000000..2a82c7f --- /dev/null +++ b/tests/bin/failure-replay.sh @@ -0,0 +1,171 @@ +#!/bin/sh +# SPDX-FileCopyrightText: 2026 Thomas Vincent +# SPDX-License-Identifier: GPL-2.0-or-later +# +# This file is part of plugin_pfs, a plugin for Cacti. +# https://github.com/somethingwithproof/plugin_pfs +# +# This program is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by the Free +# Software Foundation; either version 2 of the License, or (at your option) +# any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +# more details. + +# Failure qualification (tests/bin/failure-flow.php). Run as root from the +# root of a disposable Cacti install with the plugin enabled: +# +# PFS_TEST_DATABASE=disposable PFS_TEST_MYSQL_DEFAULTS= \ +# sh plugins/pfs/tests/bin/failure-replay.sh +# +# Each scenario runs the production reader (poller_pfs.php) against a +# stand-in for ssh and prints how long the reader and the Cacti poller took. +# Exits non-zero on a failure. +set -u + +[ "${PFS_TEST_DATABASE:-}" = disposable ] || { echo "Set PFS_TEST_DATABASE=disposable" >&2; exit 2; } +[ -r "${PFS_TEST_MYSQL_DEFAULTS:-}" ] || { echo "Set PFS_TEST_MYSQL_DEFAULTS to a readable client defaults file" >&2; exit 2; } + +CLIENT=$(command -v mariadb || command -v mysql) +DB=$(php -r 'chdir("."); include("./include/cli_check.php"); print $database_default;') +case "$DB" in + '' | *[!A-Za-z0-9_]*) echo "Cannot read a plain database name from include/config.php" >&2; exit 2 ;; +esac +PFS_FAULT_DIR=$(mktemp -d) +export PFS_FAULT_DIR +fail=0 + +# The last update time of an RRD file, or nothing when rrdtool fails or does +# not print a numeric time. +rrd_last() { + last=$("$RRDTOOL" lastupdate "$1" 2> /dev/null) || return 0 + last=$(printf '%s\n' "$last" | tail -1 | cut -d: -f1) + case "$last" in + '' | *[!0-9]*) ;; + *) printf '%s\n' "$last" ;; + esac +} + +flow() { + php plugins/pfs/tests/bin/failure-flow.php "$@" || fail=1 +} + +reader() { + start=$(date +%s) + php plugins/pfs/poller_pfs.php --poller=1 --force || fail=1 + echo "TIMING $1 reader $(( $(date +%s) - start )) s" +} + +flow setup + +for mode in ok unreachable hostkey slow oversized unframed ok; do + echo "== $mode" + flow arm "$mode" + reader "$mode" + flow check "$mode" +done + +# The Cacti poller with a node that hangs: poller_bottom starts the reader +# in the background, so the poller is not held up by the node. +echo "== slow node under the Cacti poller" +flow arm slow +start=$(date +%s) +php poller.php --poller=1 --force > "$PFS_FAULT_DIR/poll.txt" 2>&1 || fail=1 +took=$(( $(date +%s) - start )) +echo "TIMING slow poller $took s" +[ "$took" -lt 25 ] && echo "PASS the Cacti poller finished in $took s while the node hung for 30" || { echo "FAIL the Cacti poller took $took s"; fail=1; } +for _ in $(seq 1 30); do + [ "$(php -r 'chdir("."); include("./include/cli_check.php"); print db_fetch_cell("SELECT COUNT(*) FROM processes WHERE tasktype = \"pfs\"");')" = 0 ] && break + sleep 1 +done +flow check slow + +# The database connection drops while the reader waits for a node. +echo "== database connection lost mid-read" +flow arm dbloss +php plugins/pfs/poller_pfs.php --poller=1 --force > "$PFS_FAULT_DIR/dbloss.txt" 2>&1 & +pid=$! +sleep 2 +# Nothing else uses the disposable database now, so every other connection +# to it is the reader's, which is waiting on the node. +killed=0 +if kill -0 "$pid" 2> /dev/null; then + for id in $("$CLIENT" --defaults-file="$PFS_TEST_MYSQL_DEFAULTS" -N -e "SELECT ID FROM information_schema.PROCESSLIST WHERE DB = '$DB' AND ID <> CONNECTION_ID()"); do + "$CLIENT" --defaults-file="$PFS_TEST_MYSQL_DEFAULTS" -e "KILL $id" && killed=$((killed + 1)) + done +fi +wait "$pid" +status=$? +echo "EVIDENCE dbloss killed $killed reader connection(s) on $DB; reader exit $status output: $(tr '\n' ' ' < "$PFS_FAULT_DIR/dbloss.txt" | cut -c1-400)" +[ "$killed" -gt 0 ] && echo "PASS the reader's database connection was killed mid-read" || { echo "FAIL no reader connection to $DB was killed, so the scenario proves nothing"; fail=1; } +flow check dbloss +echo "== after the database came back" +flow arm ok +reader after-dbloss +flow check ok + +# An RRD file the poller cannot write. Root ignores file modes, so the +# poller runs as www-data with that one file left owned by root, read-only. +echo "== RRD file the poller cannot write" +if id www-data > /dev/null 2>&1; then + # shellcheck disable=SC2046 # the id and the path, split on purpose + set -- $(php -r 'chdir("."); include("./include/cli_check.php"); include_once("./lib/rrd.php"); $id = db_fetch_cell("SELECT dl.id FROM data_local dl INNER JOIN host h ON h.id = dl.host_id WHERE h.hostname LIKE \"fault.%\" AND dl.snmp_query_id = 0 ORDER BY dl.id LIMIT 1"); print $id . " " . get_data_source_path($id, true);') + rrd_id=${1:-0} + rrd=${2:-} + # The executable Cacti itself runs, which need not be on PATH. + RRDTOOL=$(php -r 'chdir("."); include("./include/cli_check.php"); print read_config_option("path_rrdtool");') + php poller.php --poller=1 --force > /dev/null 2>&1 || fail=1 + if [ "$rrd_id" -gt 0 ] && [ -f "$rrd" ] && [ -x "$RRDTOOL" ]; then + chown -R www-data rra log + chown root "$rrd" && chmod 0444 "$rrd" + su -s /bin/sh www-data -c "test -w '$rrd'" && denied=no || denied=yes + before=$(rrd_last "$rrd") + sleep 2 + # The poller writes its output until it exits, so a separate marker + # made before the poll tells which RRD files it updated. + touch "$PFS_FAULT_DIR/rrd-mark" + su -s /bin/sh www-data -c 'php poller.php --poller=1 --force' > "$PFS_FAULT_DIR/rrd.txt" 2>&1 + status=$? + after=$(rrd_last "$rrd") + others=$(find rra -name '*.rrd' -newer "$PFS_FAULT_DIR/rrd-mark" ! -path "$rrd" | wc -l) + chown -R root rra log + chmod 0644 "$rrd" + echo "EVIDENCE rrd poller exit $status, other files updated in that poll: $others" + [ "$status" -eq 0 ] || { echo "FAIL the Cacti poller failed:"; tail -5 "$PFS_FAULT_DIR/rrd.txt"; fail=1; } + [ "$others" -gt 0 ] && echo "PASS the poll updated the other RRD files" || { echo "FAIL the poll updated no other RRD file"; fail=1; } + if [ -z "$before" ] || [ -z "$after" ]; then + echo "FAIL could not read the RRD file's last update before and after the poll ($before, $after)" + fail=1 + elif [ "$before" = "$after" ]; then + echo "PASS the unwritable RRD file was not updated ($before)" + else + echo "FAIL the unwritable RRD file changed ($before, $after)" + fail=1 + fi + # Cacti does not always log the refused update, so the permission is + # checked directly and the log line is evidence only. + grep "RRDtool did not acknowledge the update for local_data_id: $rrd_id\$" log/cacti.log | tail -1 | sed 's/^/EVIDENCE rrd log: /' + if [ "$denied" = yes ]; then + echo "PASS the poller user could not write the RRD file, so the unchanged file is the refused update" + else + echo "FAIL the poller user could write the RRD file, so the scenario proves nothing" + fail=1 + fi + else + echo "FAIL no summary RRD file of the fault device to make unwritable, or no rrdtool ($rrd_id, $rrd, $RRDTOOL)" + fail=1 + fi + flow arm ok + reader after-rrd + flow check ok +else + echo "SKIP no unprivileged www-data user to run the poller as" +fi + +flow cleanup +[ -n "$PFS_FAULT_DIR" ] && rm -rf "$PFS_FAULT_DIR" +echo "failure replay fail=$fail" +exit $fail diff --git a/tests/bin/lustre-fixture.php b/tests/bin/lustre-fixture.php new file mode 100644 index 0000000..4fbfd60 --- /dev/null +++ b/tests/bin/lustre-fixture.php @@ -0,0 +1,105 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_pfs, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_pfs + * + * 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. + */ + +/* + * Generated Lustre read-script answers for the end-to-end flows and the + * scale harness, in the format of tests/fixtures/lustre/oss-2.15.txt. There + * is no Lustre simulator; these reproduce what a node prints, not how a + * filesystem behaves. + * + * Must parse on PHP 8.0, like the other tests/bin scripts. + */ + +/** + * One OSS answer. $osts maps an OST index to its state: + * used percent used, 0 to 100 (lfs df: used over used plus available) + * read read_bytes stats sum; null leaves the line out + * write write_bytes stats sum; null leaves the line out, as Lustre does + * for an OST that has not written since its start time + * degraded 1 to set the degraded flag + * start the stats start_time + */ +function pfs_fixture_oss($fs, array $osts, $version = '2.15.5') { + $out = array('#pfs-read 1', '== version', $version, ''); + + foreach ($osts as $index => $ost) { + $name = sprintf('%s-OST%04x', $fs, $index); + $total = 1000000000; + $avail = (int) round($total * (100 - $ost['used']) / 100); + + foreach (array('kbytestotal' => $total, 'kbytesfree' => $avail, 'kbytesavail' => $avail, 'filestotal' => 65536000, 'filesfree' => 60000000) as $item => $value) { + array_push($out, "== osd-ldiskfs/$name/$item", (string) $value, ''); + } + + foreach (array('degraded', 'no_precreate', 'no_create', 'readonly') as $flag) { + array_push($out, "== obdfilter/$name/$flag", ($flag === 'degraded' && !empty($ost['degraded'])) ? '1' : '0', ''); + } + + $out[] = "== obdfilter/$name/stats"; + $out[] = 'snapshot_time 1731600000.123456789 secs.nsecs'; + $out[] = 'start_time ' . (isset($ost['start']) ? $ost['start'] : '1731000000.000000001') . ' secs.nsecs'; + $out[] = 'elapsed_time 600000.123456788 secs.nsecs'; + + foreach (array('read' => 'read_bytes', 'write' => 'write_bytes') as $key => $counter) { + if (isset($ost[$key])) { + $bytes = (int) $ost[$key]; + $samples = max(1, intdiv($bytes, 1048576)); + $out[] = sprintf('%-25s %d samples [bytes] 4096 1048576 %d %d', $counter, $samples, $bytes, $bytes * 4096); + } + } + + array_push($out, 'statfs 300 samples [usecs] 0 9 400 900', ''); + } + + $out[] = '#pfs-read end'; + + return implode("\n", $out) . "\n"; +} + +/** + * One MDS answer. $mdts maps an MDT index to its md_stats counters + * (operation => samples); an operation left out is not printed, as on a + * release that lacks it. + */ +function pfs_fixture_mds($fs, array $mdts, $version = '2.15.5') { + $out = array('#pfs-read 1', '== version', $version, ''); + + foreach ($mdts as $index => $ops) { + $name = sprintf('%s-MDT%04x', $fs, $index); + + foreach (array('kbytestotal' => 200000000, 'kbytesfree' => 150000000, 'kbytesavail' => 140000000, 'filestotal' => 100000000, 'filesfree' => 90000000) as $item => $value) { + array_push($out, "== osd-ldiskfs/$name/$item", (string) $value, ''); + } + + $out[] = "== mdt/$name/md_stats"; + $out[] = 'snapshot_time 1731600000.000000001 secs.nsecs'; + $out[] = 'start_time 1730000000.000000001 secs.nsecs'; + $out[] = 'elapsed_time 1600000.000000000 secs.nsecs'; + + foreach ($ops as $op => $samples) { + $out[] = sprintf('%-25s %d samples [usecs] 1 900 %d %d', $op, (int) $samples, (int) $samples * 10, (int) $samples * 100); + } + + $out[] = ''; + } + + $out[] = '#pfs-read end'; + + return implode("\n", $out) . "\n"; +} diff --git a/tests/bin/restore-flow.php b/tests/bin/restore-flow.php new file mode 100644 index 0000000..ba4479a --- /dev/null +++ b/tests/bin/restore-flow.php @@ -0,0 +1,204 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_pfs, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_pfs + * + * 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. + */ + +/* + * Backup and restore of a filesystem device (issue #54, REQ-DR-001). Driven + * by tests/bin/restore-replay.sh: + * + * setup a filesystem with its device and a per-target graph, read + * (poll, then dump the database and copy the RRD directory) + * snapshot record the device's objects and RRD files in a state file + * (change things after the backup, then restore the dump and the copy) + * verify the restored objects match the snapshot, the reader resumes, + * (poll) + * resumed the poll wrote into the restored RRD files, nothing duplicated + * + * State that must survive the restore is kept in the file named by + * PFS_RESTORE_STATE, not in the database. Must parse on PHP 8.0. + */ + +chdir(dirname(__DIR__, 4)); + +require('./include/cli_check.php'); +require_once($config['base_path'] . '/lib/api_device.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/template.php'); +require_once($config['base_path'] . '/lib/data_query.php'); +require_once($config['base_path'] . '/lib/utility.php'); +require_once($config['base_path'] . '/lib/rrd.php'); +require_once($config['base_path'] . '/plugins/pfs/setup.php'); +require_once($config['base_path'] . '/plugins/pfs/tests/bin/lustre-fixture.php'); + +use Somethingwithproof\Pfs\AccessMethod; +use Somethingwithproof\Pfs\FixedClock; +use Somethingwithproof\Pfs\FixtureNodeSource; +use Somethingwithproof\Pfs\NodeSources; +use Somethingwithproof\Pfs\TemplateInstaller; + +$stateFile = (string) getenv('PFS_RESTORE_STATE'); + +if (getenv('PFS_TEST_DATABASE') !== 'disposable' || $stateFile === '' || !isset($argv[1]) || !in_array($argv[1], array('setup', 'snapshot', 'drift', 'verify', 'resumed'), true)) { + fwrite(STDERR, "Set PFS_TEST_DATABASE=disposable and PFS_RESTORE_STATE, and pass setup, snapshot, drift, verify, or resumed\n"); + exit(2); +} + +if (!pfs_boot()) { + fwrite(STDERR, "PHP 8.2 or later is required\n"); + exit(2); +} + +$failures = 0; + +function restore_expect($ok, $message) { + global $failures; + + print ($ok ? 'PASS ' : 'FAIL ') . $message . PHP_EOL; + $failures += $ok ? 0 : 1; +} + +function restore_state(array $add = array()) { + global $stateFile; + + $state = is_file($stateFile) ? json_decode((string) file_get_contents($stateFile), true) : array(); + $state = array_merge(is_array($state) ? $state : array(), $add); + + if ($add !== array()) { + file_put_contents($stateFile, json_encode($state)); + } + + return $state; +} + +function restore_read($fsName, $write) { + $state = restore_state(); + $source = new FixtureNodeSource(array()); + $sources = new NodeSources(); + $source->answer((int) $state['oss'], pfs_fixture_oss($fsName, array(0 => array('used' => 40, 'read' => $write, 'write' => $write), 1 => array('used' => 60, 'read' => $write, 'write' => $write)))); + $source->answer((int) $state['mds'], pfs_fixture_mds($fsName, array(0 => array('open' => 100, 'close' => 90)))); + $sources->register(AccessMethod::Ssh, $source); + + db_execute('UPDATE plugin_pfs_node_health SET last_attempt = last_attempt - 3600'); + + return pfs_reader_with(1, $sources, new FixedClock(time()))->run(1, 240, 4); +} + +/** What a backup must bring back for the device: objects by id and the RRD files. */ +function restore_inventory($hostId) { + $ds = db_fetch_assoc_prepared('SELECT id, data_template_id, snmp_index FROM data_local WHERE host_id = ? ORDER BY id', array($hostId)); + + return array( + 'filesystem' => db_fetch_assoc("SELECT id, name, host_id FROM plugin_pfs_filesystem ORDER BY id"), + 'targets' => array_column(db_fetch_assoc('SELECT name FROM plugin_pfs_target ORDER BY name'), 'name'), + 'data_local' => $ds, + 'graph_local' => array_column(db_fetch_assoc_prepared('SELECT id FROM graph_local WHERE host_id = ? ORDER BY id', array($hostId)), 'id'), + 'poller_item' => (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM poller_item WHERE host_id = ?', array($hostId)), + 'rrd_files' => array_map(function ($row) { return basename(get_data_source_path((int) $row['id'], true)); }, $ds), + ); +} + +$step = $argv[1]; + +switch ($step) { + case 'setup': + $repo = new \Somethingwithproof\Pfs\FilesystemRepository(false, new \Somethingwithproof\Pfs\SystemClock()); + + foreach ($repo->all() as $old) { + $repo->delete($old->id); + } + + db_execute("INSERT INTO plugin_pfs_filesystem (name, backend, poller_id, expected_interval, admin_state) VALUES ('keep', 'lustre', 1, 300, 'enabled')"); + $fsId = (int) db_fetch_insert_id(); + $ids = array(); + + foreach (array('oss' => 'oss', 'mds' => 'mds') as $name => $role) { + db_execute_prepared("INSERT INTO plugin_pfs_node (filesystem_id, name, role, poller_id, endpoint, port, ssh_user, access_method, admin_state) VALUES (?, ?, ?, 1, '10.20.0.4', 22, 'pfsread', 'ssh', 'enabled')", array($fsId, 'keep-' . $name, $role)); + $ids[$name] = (int) db_fetch_insert_id(); + } + + restore_state(array('oss' => $ids['oss'], 'mds' => $ids['mds'], 'fs' => $fsId)); + restore_read('keep', 1000000); + restore_read('keep', 2000000); + + $hostId = pfs_provisioner()->create($repo->find($fsId)); + $queryId = (int) db_fetch_cell_prepared('SELECT id FROM snmp_query WHERE hash = ?', array(TemplateInstaller::hash('data_query', 'Parallel Filesystem OSTs'))); + $gt = (int) db_fetch_cell_prepared('SELECT id FROM graph_templates WHERE hash = ?', array(TemplateInstaller::hash('graph_template', 'Parallel Filesystem OST Throughput'))); + $sqg = (int) db_fetch_cell_prepared('SELECT id FROM snmp_query_graph WHERE snmp_query_id = ? AND graph_template_id = ?', array($queryId, $gt)); + $empty = array(); + $graph = create_complete_graph_from_template($gt, $hostId, array('snmp_query_id' => $queryId, 'snmp_index_on' => 'pfsName', 'snmp_query_graph_id' => $sqg, 'snmp_index' => 'keep-OST0000'), $empty); + push_out_host($hostId, 0); + + restore_state(array('host' => $hostId, 'ost_ds' => (int) array_values($graph['local_data_id'])[0])); + restore_expect($hostId > 0 && isset($graph['local_graph_id']), 'a filesystem device with a per-target graph exists before the backup'); + restore_read('keep', 3000000); + + break; + case 'snapshot': + $state = restore_state(); + $inv = restore_inventory((int) $state['host']); + $last = (string) shell_exec('rrdtool lastupdate ' . escapeshellarg(get_data_source_path((int) $state['ost_ds'], true)) . ' 2>&1'); + restore_expect(strpos($last, 'read_bytes') !== false, 'the poll before the backup wrote the per-target RRD file'); + restore_state(array('inventory' => $inv)); + + break; + case 'drift': + // Changes made after the backup, which the restore must undo. + $state = restore_state(); + db_execute_prepared('DELETE FROM plugin_pfs_target WHERE filesystem_id = ?', array((int) $state['fs'])); + api_device_remove((int) $state['host']); + restore_expect((int) db_fetch_cell_prepared('SELECT COUNT(*) FROM host WHERE id = ?', array((int) $state['host'])) === 0, 'after the backup the device and the inventory were removed'); + + break; + case 'verify': + $state = restore_state(); + $inv = restore_inventory((int) $state['host']); + restore_expect($inv === $state['inventory'], 'the restore brought back the filesystem, inventory, device objects, and RRD file names exactly: ' . json_encode(array_diff_key($inv, array('data_local' => 1)))); + + foreach ($inv['data_local'] as $row) { + if (!is_file(get_data_source_path((int) $row['id'], true))) { + restore_expect(false, 'restored RRD file for data source ' . $row['id'] . ' exists'); + } + } + + $schema = new \Somethingwithproof\Pfs\Schema(false); + restore_expect($schema->isCurrent(), 'the restored plugin schema is current, so the reader runs'); + + $run = restore_read('keep', 4000000); + restore_expect($run->nodesRead === 2, 'the reader resumed on the restored registry'); + restore_state(array('restored_at' => time())); + + break; + case 'resumed': + $state = restore_state(); + $inv = restore_inventory((int) $state['host']); + $dups = (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM (SELECT COUNT(*) AS n FROM data_local WHERE host_id = ? AND snmp_query_id > 0 GROUP BY data_template_id, snmp_query_id, snmp_index HAVING n > 1) d', array((int) $state['host'])); + restore_expect($inv === $state['inventory'] && $dups === 0, 'the poll after the restore added no data source, graph, or poller item: ' . json_encode(array('duplicates' => $dups, 'same' => $inv === $state['inventory']))); + + $out = (string) shell_exec('rrdtool lastupdate ' . escapeshellarg(get_data_source_path((int) $state['ost_ds'], true)) . ' 2>&1'); + $rows = preg_split('/\R/', trim($out)); + restore_expect(count($rows) >= 3 && (int) $rows[2] >= (int) $state['restored_at'], 'the poll after the restore wrote into the restored RRD file: ' . (isset($rows[2]) ? $rows[2] : $out)); + + $repo = new \Somethingwithproof\Pfs\FilesystemRepository(false, new \Somethingwithproof\Pfs\SystemClock()); + $repo->delete((int) $state['fs']); + @unlink($stateFile); + + break; +} + +exit($failures > 0 ? 1 : 0); diff --git a/tests/bin/restore-replay.sh b/tests/bin/restore-replay.sh new file mode 100644 index 0000000..610ae23 --- /dev/null +++ b/tests/bin/restore-replay.sh @@ -0,0 +1,90 @@ +#!/bin/sh +# SPDX-FileCopyrightText: 2026 Thomas Vincent +# SPDX-License-Identifier: GPL-2.0-or-later +# +# This file is part of plugin_pfs, a plugin for Cacti. +# https://github.com/somethingwithproof/plugin_pfs +# +# 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. + +# Backup and restore qualification (tests/bin/restore-flow.php). Run from +# the root of a disposable Cacti install with the plugin enabled: +# +# PFS_TEST_DATABASE=disposable PFS_TEST_MYSQL_DEFAULTS= \ +# sh plugins/pfs/tests/bin/restore-replay.sh +# +# The defaults file names the server and user; a password comes from +# MYSQL_PWD, never the command line. Dumps the whole Cacti database and +# copies the RRD directory, changes both, restores them, and checks that the +# plugin resumes without duplicating anything. Exits non-zero on a failure. +set -u + +[ "${PFS_TEST_DATABASE:-}" = disposable ] || { echo "Set PFS_TEST_DATABASE=disposable" >&2; exit 2; } +[ -r "${PFS_TEST_MYSQL_DEFAULTS:-}" ] || { echo "Set PFS_TEST_MYSQL_DEFAULTS to a readable client defaults file" >&2; exit 2; } + +DB=${PFS_TEST_MYSQL_DB:-cacti} +DUMP=$(command -v mariadb-dump || command -v mysqldump) +CLIENT=$(command -v mariadb || command -v mysql) +SCRATCH=$(mktemp -d) +export PFS_RESTORE_STATE="$SCRATCH/state.json" +fail=0 + +flow() { + php plugins/pfs/tests/bin/restore-flow.php "$1" || fail=1 +} + +# The poller starts background jobs (automation, maintenance, boost) that +# keep using the database after it returns. Wait for them, so the backup is +# consistent and the restore does not drop tables under them. +settle() { + for _ in $(seq 1 120); do + busy=0 + for f in /proc/[0-9]*/cmdline; do + case $(tr '\0' ' ' < "$f" 2>/dev/null) in + *poller_*.php* | *cmd.php* | *script_server.php*) busy=1 ;; + esac + done + [ "$busy" -eq 0 ] && return 0 + sleep 1 + done + echo "background poller jobs did not finish" + fail=1 +} + +poll() { + php poller.php --poller=1 --force > "$SCRATCH/poll.txt" 2>&1 || { fail=1; tail -5 "$SCRATCH/poll.txt"; } + settle +} + +flow setup +poll +flow snapshot + +echo "== backup" +"$DUMP" --defaults-file="$PFS_TEST_MYSQL_DEFAULTS" --single-transaction --routines "$DB" > "$SCRATCH/cacti.sql" || fail=1 +tar -C rra -cf "$SCRATCH/rra.tar" . || fail=1 + +flow drift +poll + +echo "== restore" +"$CLIENT" --defaults-file="$PFS_TEST_MYSQL_DEFAULTS" -e "DROP DATABASE \`$DB\`; CREATE DATABASE \`$DB\`" || fail=1 +"$CLIENT" --defaults-file="$PFS_TEST_MYSQL_DEFAULTS" "$DB" < "$SCRATCH/cacti.sql" || fail=1 +find rra -mindepth 1 -delete +tar -C rra -xf "$SCRATCH/rra.tar" || fail=1 + +flow verify +poll +flow resumed + +[ -n "$SCRATCH" ] && rm -rf "$SCRATCH" +echo "restore replay fail=$fail" +exit $fail diff --git a/tests/bin/scale-flow.php b/tests/bin/scale-flow.php new file mode 100644 index 0000000..6d405de --- /dev/null +++ b/tests/bin/scale-flow.php @@ -0,0 +1,216 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_pfs, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_pfs + * + * 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. + */ + +/* + * Scale harness (issue #52): one filesystem with N OSTs, 16 per OSS as the + * plan assumes, and one MDT, read from generated fixtures. Driven by + * tests/bin/scale-replay.sh: + * + * php plugins/pfs/tests/bin/scale-flow.php build + * (time one forced Cacti poller run) + * php plugins/pfs/tests/bin/scale-flow.php after + * php plugins/pfs/tests/bin/scale-flow.php remove + * + * build prints the reader's time and memory, the data query reindex time, + * the script server functions' time per call, and the time to create one + * per-target graph for every OST. after prints the Cacti row and RRD file + * counts. remove deletes the filesystem's device with its data sources and + * graphs, then the filesystem, so the next target count is measured alone. + * Results are for the machine the run is on; nothing here is a + * capacity claim. Must parse on PHP 8.0. + */ + +chdir(dirname(__DIR__, 4)); + +require('./include/cli_check.php'); +require_once($config['base_path'] . '/lib/api_device.php'); +require_once($config['base_path'] . '/lib/api_data_source.php'); +require_once($config['base_path'] . '/lib/api_graph.php'); +require_once($config['base_path'] . '/lib/template.php'); +require_once($config['base_path'] . '/lib/data_query.php'); +require_once($config['base_path'] . '/lib/utility.php'); +require_once($config['base_path'] . '/plugins/pfs/setup.php'); +require_once($config['base_path'] . '/plugins/pfs/tests/bin/lustre-fixture.php'); + +$called_by_script_server = true; +require_once($config['base_path'] . '/plugins/pfs/scripts/ss_pfs_targets.php'); +require_once($config['base_path'] . '/plugins/pfs/scripts/ss_pfs_summary.php'); + +use Somethingwithproof\Pfs\AccessMethod; +use Somethingwithproof\Pfs\FixedClock; +use Somethingwithproof\Pfs\FixtureNodeSource; +use Somethingwithproof\Pfs\NodeSources; +use Somethingwithproof\Pfs\TemplateInstaller; + +$step = isset($argv[1]) ? $argv[1] : ''; +$n = isset($argv[2]) ? (int) $argv[2] : 0; + +if (getenv('PFS_TEST_DATABASE') !== 'disposable' || !in_array($step, array('build', 'after', 'remove'), true) || $n < 16 || $n > 20000) { + fwrite(STDERR, "Set PFS_TEST_DATABASE=disposable and pass build, after, or remove, and a target count of 16 to 20000\n"); + exit(2); +} + +if (!pfs_boot()) { + fwrite(STDERR, "PHP 8.2 or later is required\n"); + exit(2); +} + +// A Lustre filesystem name is at most eight characters. +$name = 'sc' . $n; + +function scale_metric($label, $value) { + print "METRIC $label $value" . PHP_EOL; +} + +/** Average milliseconds per call of $fn over $calls calls. */ +function scale_time($calls, $fn) { + $start = hrtime(true); + + for ($i = 0; $i < $calls; $i++) { + $fn($i); + } + + return round((hrtime(true) - $start) / 1e6 / $calls, 3); +} + +function scale_read($name, array $nodes, $mds, $n, $at) { + $source = new FixtureNodeSource(array()); + $sources = new NodeSources(); + + foreach ($nodes as $i => $nodeId) { + $osts = array(); + + for ($t = $i * 16; $t < min($n, ($i + 1) * 16); $t++) { + $osts[$t] = array('used' => 30 + ($t % 40), 'read' => 1000000 * ($at % 100000), 'write' => 1000000 * ($at % 100000)); + } + + $source->answer($nodeId, pfs_fixture_oss($name, $osts)); + } + + $source->answer($mds, pfs_fixture_mds($name, array(0 => array('open' => 100, 'close' => 90)))); + $sources->register(AccessMethod::Ssh, $source); + db_execute('UPDATE plugin_pfs_node_health SET last_attempt = last_attempt - 3600'); + + $start = hrtime(true); + $run = pfs_reader_with(1, $sources, new FixedClock($at))->run(1, 600, 8); + + return array($run, round((hrtime(true) - $start) / 1e9, 2)); +} + +$fs = null; + +foreach ((new \Somethingwithproof\Pfs\FilesystemRepository(false, new \Somethingwithproof\Pfs\SystemClock()))->all() as $f) { + $fs = $f->name === $name ? $f : $fs; +} + +if ($step === 'build') { + db_execute_prepared("INSERT INTO plugin_pfs_filesystem (name, backend, poller_id, expected_interval, admin_state) VALUES (?, 'lustre', 1, 300, 'enabled')", array($name)); + $fsId = (int) db_fetch_insert_id(); + $nodes = array(); + + for ($i = 0; $i < (int) ceil($n / 16); $i++) { + db_execute_prepared("INSERT INTO plugin_pfs_node (filesystem_id, name, role, poller_id, endpoint, port, ssh_user, access_method, admin_state) VALUES (?, ?, 'oss', 1, '10.20.0.9', 22, 'pfsread', 'ssh', 'enabled')", array($fsId, sprintf('%s-oss%03d', $name, $i))); + $nodes[$i] = (int) db_fetch_insert_id(); + } + + db_execute_prepared("INSERT INTO plugin_pfs_node (filesystem_id, name, role, poller_id, endpoint, port, ssh_user, access_method, admin_state) VALUES (?, ?, 'mds', 1, '10.20.0.9', 22, 'pfsread', 'ssh', 'enabled')", array($fsId, $name . '-mds')); + $mds = (int) db_fetch_insert_id(); + + scale_metric("$n nodes", count($nodes) + 1); + $now = time(); + [$run, $first] = scale_read($name, $nodes, $mds, $n, $now - 300); + $peakFirst = memory_get_peak_usage(true); + [$run, $second] = scale_read($name, $nodes, $mds, $n, $now); + scale_metric("$n reader_first_run_s", $first); + scale_metric("$n reader_run_s", $second); + scale_metric("$n reader_nodes_read", $run->nodesRead); + scale_metric("$n reader_peak_memory_mib", round(max($peakFirst, memory_get_peak_usage(true)) / 1048576, 1)); + + $fs = (new \Somethingwithproof\Pfs\FilesystemRepository(false, new \Somethingwithproof\Pfs\SystemClock()))->find($fsId); + $start = hrtime(true); + $host = pfs_provisioner()->create($fs); + scale_metric("$n device_create_and_index_s", round((hrtime(true) - $start) / 1e9, 2)); + $indexes = (int) db_fetch_cell_prepared('SELECT COUNT(DISTINCT snmp_index) FROM host_snmp_cache WHERE host_id = ?', array($host)); + scale_metric("$n indexes", $indexes); + + if ($run->nodesRead !== count($nodes) + 1 || $indexes !== $n + 1) { + fwrite(STDERR, "FAIL expected $n OSTs and one MDT indexed from " . (count($nodes) + 1) . " nodes\n"); + exit(1); + } + + // The script server keeps one process, so the functions are timed the + // same way: repeated calls in one process. The first call of each + // fills the query's 30 second cache. + $t = pfs_target_query(); + scale_metric("$n targets_index_first_ms", scale_time(1, function () use ($t, $host) { $t->answer($host, 'ost', 'index'); })); + scale_metric("$n targets_get_ms_per_call", scale_time(2000, function ($i) use ($t, $host, $name, $n) { $t->answer($host, 'ost', 'get', 'kbytes_total', sprintf('%s-OST%04x', $name, $i % $n)); })); + scale_metric("$n targets_query_ms", scale_time(5, function () use ($t, $host) { $t->answer($host, 'ost', 'query', 'kbytes_total'); })); + scale_metric("$n summary_ms_per_call", scale_time(200, function () use ($host) { ss_pfs_summary($host); })); + scale_metric("$n summary_fresh_process_ms", scale_time(1, function () use ($host) { pfs_summary_script()->answer($host); })); + + $queryId = (int) db_fetch_cell_prepared('SELECT id FROM snmp_query WHERE hash = ?', array(TemplateInstaller::hash('data_query', 'Parallel Filesystem OSTs'))); + $gt = (int) db_fetch_cell_prepared('SELECT id FROM graph_templates WHERE hash = ?', array(TemplateInstaller::hash('graph_template', 'Parallel Filesystem OST Capacity'))); + $sqg = (int) db_fetch_cell_prepared('SELECT id FROM snmp_query_graph WHERE snmp_query_id = ? AND graph_template_id = ?', array($queryId, $gt)); + $start = hrtime(true); + + for ($i = 0; $i < $n; $i++) { + $empty = array(); + create_complete_graph_from_template($gt, $host, array('snmp_query_id' => $queryId, 'snmp_index_on' => 'pfsName', 'snmp_query_graph_id' => $sqg, 'snmp_index' => sprintf('%s-OST%04x', $name, $i)), $empty); + } + + push_out_host($host, 0); + scale_metric("$n capacity_graphs_create_s", round((hrtime(true) - $start) / 1e9, 1)); +} elseif ($step === 'remove') { + if ($fs === null) { + fwrite(STDERR, "FAIL no filesystem $name to remove\n"); + exit(1); + } + + if ($fs->hostId > 0) { + api_device_remove_multi(array($fs->hostId), 2); + } + + $gone = (new \Somethingwithproof\Pfs\FilesystemRepository(false, new \Somethingwithproof\Pfs\SystemClock()))->delete($fs->id); + $left = (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM poller_item WHERE host_id = ?', array($fs->hostId)); + + if (!$gone || $left > 0) { + fwrite(STDERR, "FAIL $name was not removed ($left poller items left)\n"); + exit(1); + } + + print "REMOVED $name and its device\n"; +} else { + $host = $fs === null ? 0 : $fs->hostId; + + foreach (array('data_local' => 'SELECT COUNT(*) FROM data_local WHERE host_id = ?', 'data_template_rrd' => 'SELECT COUNT(*) FROM data_template_rrd r INNER JOIN data_local d ON d.id = r.local_data_id WHERE d.host_id = ?', 'graph_local' => 'SELECT COUNT(*) FROM graph_local WHERE host_id = ?', 'poller_item' => 'SELECT COUNT(*) FROM poller_item WHERE host_id = ?', 'host_snmp_cache' => 'SELECT COUNT(*) FROM host_snmp_cache WHERE host_id = ?') as $table => $sql) { + scale_metric("$n rows_$table", (int) db_fetch_cell_prepared($sql, array($host))); + } + + $files = 0; + + foreach (db_fetch_assoc_prepared('SELECT id FROM data_local WHERE host_id = ?', array($host)) as $row) { + $files += is_file(get_data_source_path((int) $row['id'], true)) ? 1 : 0; + } + + scale_metric("$n rrd_files", $files); + scale_metric("$n plugin_observation_rows", (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM plugin_pfs_observation o INNER JOIN plugin_pfs_target t ON t.id = o.target_id WHERE t.filesystem_id = ?', array($fs === null ? 0 : $fs->id))); + print 'NOTE the per-target capacity graph is one of three OST graphs; an operator who graphs all three multiplies the data source rows and RRD files by three' . PHP_EOL; +} + +exit(0); diff --git a/tests/bin/scale-replay.sh b/tests/bin/scale-replay.sh new file mode 100644 index 0000000..20f2503 --- /dev/null +++ b/tests/bin/scale-replay.sh @@ -0,0 +1,70 @@ +#!/bin/sh +# SPDX-FileCopyrightText: 2026 Thomas Vincent +# SPDX-License-Identifier: GPL-2.0-or-later +# +# This file is part of plugin_pfs, a plugin for Cacti. +# https://github.com/somethingwithproof/plugin_pfs +# +# 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. + +# Scale measurements (tests/bin/scale-flow.php). Run from the root of a +# disposable Cacti install with the plugin enabled: +# +# PFS_TEST_DATABASE=disposable sh plugins/pfs/tests/bin/scale-replay.sh [N ...] +# +# For each target count (default 500 and 2000) it builds the filesystem, +# times two forced poller runs with cmd.php, prints METRIC lines, and removes +# the filesystem and its device again, so each count is measured alone. +# Exits non-zero when a step or a poller run fails. +set -u + +[ "${PFS_TEST_DATABASE:-}" = disposable ] || { echo "Set PFS_TEST_DATABASE=disposable" >&2; exit 2; } +[ "$#" -gt 0 ] || set -- 500 2000 + +echo "METRIC host_cpus $(nproc 2>/dev/null || echo unknown)" +echo "METRIC host_memory_kib $(awk '/MemTotal/ {print $2}' /proc/meminfo 2>/dev/null || echo unknown)" +echo "METRIC php $(php -r 'print PHP_VERSION;')" + +# The filesystem being measured, removed again on any exit before its own +# removal step, so a failed run leaves nothing behind for the next one. +built= +out= +cleanup() { + status=$? + trap - EXIT + [ -n "$out" ] && rm -f "$out" + if [ -n "$built" ]; then + php plugins/pfs/tests/bin/scale-flow.php remove "$built" || status=1 + fi + exit $status +} +trap cleanup EXIT +trap 'exit 130' INT TERM + +for n in "$@"; do + built=$n + php plugins/pfs/tests/bin/scale-flow.php build "$n" || exit 1 + for run in 1 2; do + start=$(date +%s) + out=$(mktemp) + if ! php poller.php --poller=1 --force > "$out" 2>&1; then + echo "FAIL poller run $run for $n targets:" >&2 + tail -20 "$out" >&2 + exit 1 + fi + rm -f "$out" + out= + echo "METRIC $n poller_run_${run}_s $(( $(date +%s) - start ))" + done + php plugins/pfs/tests/bin/scale-flow.php after "$n" || exit 1 + built= + php plugins/pfs/tests/bin/scale-flow.php remove "$n" || exit 1 +done diff --git a/tests/bin/target-flow.php b/tests/bin/target-flow.php new file mode 100644 index 0000000..480edc0 --- /dev/null +++ b/tests/bin/target-flow.php @@ -0,0 +1,282 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_pfs, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_pfs + * + * 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. + */ + +/* + * Target churn on a filesystem device across polls (issues #43, #46, #47): + * an OST disappears, a new one appears, the old one returns, and Cacti + * reindexes the device after each change. Run between real poller runs: + * + * PFS_TEST_DATABASE=disposable php plugins/pfs/tests/bin/target-flow.php setup + * php poller.php --force + * ... remove, poll, add, poll, return, poll, check + * + * Checks that no data source or poller item is duplicated, that a missing + * OST keeps its data source and serves U, that a release which does not + * print some metadata operations still has a filesystem metadata rate, and + * that a missing OST exports from its RRD as a gap, not as zero. + * + * Must parse on PHP 8.0. State between phases is kept in Cacti's settings + * table under pfs_churn_*. + */ + +chdir(dirname(__DIR__, 4)); + +require('./include/cli_check.php'); +require_once($config['base_path'] . '/lib/api_device.php'); +require_once($config['base_path'] . '/lib/api_graph.php'); +require_once($config['base_path'] . '/lib/template.php'); +require_once($config['base_path'] . '/lib/data_query.php'); +require_once($config['base_path'] . '/lib/utility.php'); +require_once($config['base_path'] . '/lib/rrd.php'); +require_once($config['base_path'] . '/plugins/pfs/setup.php'); +require_once($config['base_path'] . '/plugins/pfs/tests/bin/lustre-fixture.php'); + +$called_by_script_server = true; +require_once($config['base_path'] . '/plugins/pfs/scripts/ss_pfs_targets.php'); +require_once($config['base_path'] . '/plugins/pfs/scripts/ss_pfs_summary.php'); + +use Somethingwithproof\Pfs\AccessMethod; +use Somethingwithproof\Pfs\FixedClock; +use Somethingwithproof\Pfs\FixtureNodeSource; +use Somethingwithproof\Pfs\NodeSources; +use Somethingwithproof\Pfs\TemplateInstaller; + +if (getenv('PFS_TEST_DATABASE') !== 'disposable' || !isset($argv[1]) || !in_array($argv[1], array('setup', 'remove', 'add', 'return', 'check'), true)) { + fwrite(STDERR, "Set PFS_TEST_DATABASE=disposable and pass setup, remove, add, return, or check\n"); + exit(2); +} + +if (!pfs_boot()) { + fwrite(STDERR, "PHP 8.2 or later is required\n"); + exit(2); +} + +$failures = 0; +$mds215 = str_replace('scratch-MDT', 'churn-MDT', (string) file_get_contents($config['base_path'] . '/plugins/pfs/tests/fixtures/lustre/mds-2.15.txt')); + +function churn_expect($ok, $message) { + global $failures; + + print ($ok ? 'PASS ' : 'FAIL ') . $message . PHP_EOL; + $failures += $ok ? 0 : 1; +} + +function churn_state($name, $value = null) { + if ($value !== null) { + db_execute_prepared('REPLACE INTO settings (name, value) VALUES (?, ?)', array('pfs_churn_' . $name, (string) $value)); + } + + return (string) db_fetch_cell_prepared('SELECT value FROM settings WHERE name = ?', array('pfs_churn_' . $name)); +} + +/** + * Wait for the reader the last forced poll started in the background + * (poller_bottom). Run beside it, it would find the churn nodes due once + * this flow moves their last attempt back, try them over SSH, and hold the + * lease the fixture read needs. + */ +function churn_settle() { + for ($i = 0; $i < 60; $i++) { + $busy = (int) db_fetch_cell("SELECT COUNT(*) FROM processes WHERE tasktype = 'pfs'") > 0; + + foreach (glob('/proc/[0-9]*/cmdline') ?: array() as $file) { + $busy = $busy || strpos((string) @file_get_contents($file), 'poller_pfs.php') !== false; + } + + if (!$busy) { + return; + } + + sleep(1); + } + + churn_expect(false, 'the background reader finished within 60 seconds'); +} + +/** Read the OSTs given (index => used percent) and the 2.15 MDS answer now. */ +function churn_read(array $used, $at) { + global $mds215; + + $osts = array(); + + foreach ($used as $index => $pct) { + $osts[$index] = array('used' => $pct, 'read' => 1000000 * ($at % 100000), 'write' => 2000000 * ($at % 100000)); + } + + $source = new FixtureNodeSource(array()); + $sources = new NodeSources(); + $source->answer((int) churn_state('oss'), pfs_fixture_oss('churn', $osts)); + $source->answer((int) churn_state('mds'), $mds215); + $sources->register(AccessMethod::Ssh, $source); + + churn_settle(); + db_execute('UPDATE plugin_pfs_node_health SET last_attempt = last_attempt - 3600'); + + $run = pfs_reader_with(1, $sources, new FixedClock($at))->run(1, 240, 4); + churn_expect($run->startedAt > 0, 'the fixture read ran, not skipped for a lease another run held'); + + return $run; +} + +/** Rerun both data queries on the device, as a reindex does. */ +function churn_reindex($hostId) { + foreach (db_fetch_assoc_prepared('SELECT snmp_query_id FROM host_snmp_query WHERE host_id = ?', array($hostId)) as $row) { + run_data_query($hostId, (int) $row['snmp_query_id']); + } +} + +function churn_indexes($hostId) { + return 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'); +} + +/** + * Data query data sources per (template, query, index) and poller items per + * (data source, field); each should be one. The overview graphs' summary + * data sources share a template and have no index, so they are left out. + */ +function churn_duplicates($hostId) { + $ds = (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM (SELECT data_template_id, snmp_index, COUNT(*) AS n FROM data_local WHERE host_id = ? AND snmp_query_id > 0 GROUP BY data_template_id, snmp_query_id, snmp_index HAVING n > 1) d', array($hostId)); + $pi = (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM (SELECT local_data_id, rrd_name, COUNT(*) AS n FROM poller_item WHERE host_id = ? GROUP BY local_data_id, rrd_name, rrd_path HAVING n > 1) p', array($hostId)); + + return array('data_sources' => $ds, 'poller_items' => $pi); +} + +function churn_graph($hostId, $index) { + $queryId = (int) db_fetch_cell_prepared('SELECT id FROM snmp_query WHERE hash = ?', array(TemplateInstaller::hash('data_query', 'Parallel Filesystem OSTs'))); + $gt = (int) db_fetch_cell_prepared('SELECT id FROM graph_templates WHERE hash = ?', array(TemplateInstaller::hash('graph_template', 'Parallel Filesystem OST Capacity'))); + $sqg = (int) db_fetch_cell_prepared('SELECT id FROM snmp_query_graph WHERE snmp_query_id = ? AND graph_template_id = ?', array($queryId, $gt)); + $empty = array(); + $graph = create_complete_graph_from_template($gt, $hostId, array('snmp_query_id' => $queryId, 'snmp_index_on' => 'pfsName', 'snmp_query_graph_id' => $sqg, 'snmp_index' => $index), $empty); + + return isset($graph['local_data_id']) ? (int) array_values($graph['local_data_id'])[0] : 0; +} + +function churn_counts($hostId) { + return array( + 'data_local' => (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM data_local WHERE host_id = ?', array($hostId)), + 'graph_local' => (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM graph_local WHERE host_id = ?', array($hostId)), + 'poller_item' => (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM poller_item WHERE host_id = ?', array($hostId)), + ); +} + +$step = $argv[1]; +$hostId = (int) churn_state('host'); +$now = time(); + +if ($step === 'setup') { + db_execute("INSERT INTO plugin_pfs_filesystem (name, backend, poller_id, expected_interval, admin_state) VALUES ('churn', 'lustre', 1, 300, 'enabled')"); + $fsId = (int) db_fetch_insert_id(); + + foreach (array('oss' => 'oss', 'mds' => 'mds') as $name => $role) { + db_execute_prepared("INSERT INTO plugin_pfs_node (filesystem_id, name, role, poller_id, endpoint, port, ssh_user, access_method, admin_state) VALUES (?, ?, ?, 1, '10.20.0.3', 22, 'pfsread', 'ssh', 'enabled')", array($fsId, 'churn-' . $name, $role)); + churn_state($name, (int) db_fetch_insert_id()); + } + + churn_read(array(0 => 40, 1 => 50), $now - 300); + churn_read(array(0 => 40, 1 => 50), $now); + + $repo = new \Somethingwithproof\Pfs\FilesystemRepository(false, new \Somethingwithproof\Pfs\SystemClock()); + $hostId = pfs_provisioner()->create($repo->find($fsId)); + churn_state('host', $hostId); + churn_state('fs', $fsId); + + churn_state('ds0', churn_graph($hostId, 'churn-OST0000')); + churn_state('ds1', churn_graph($hostId, 'churn-OST0001')); + push_out_host($hostId, 0); + + churn_expect($hostId > 0 && (int) churn_state('ds1') > 0 && churn_indexes($hostId) === array('churn-MDT0000', 'churn-OST0000', 'churn-OST0001'), 'the churn device indexes two OSTs and one MDT, with a capacity graph per OST'); + + $summary = ss_pfs_summary($hostId); + churn_expect(preg_match('/(^| )md_ops:[0-9]/', $summary) === 1, 'a 2.15 MDT that does not print the newer operations still has a metadata rate: ' . $summary); + churn_state('counts', json_encode(churn_counts($hostId))); +} elseif ($step === 'remove') { + churn_read(array(0 => 40), $now); + churn_reindex($hostId); + + churn_expect(churn_indexes($hostId) === array('churn-MDT0000', 'churn-OST0000', 'churn-OST0001'), 'a missing OST keeps its index after a reindex: ' . implode(', ', churn_indexes($hostId))); + churn_expect(json_encode(churn_counts($hostId)) === churn_state('counts'), 'the reindex added or dropped no data source, graph, or poller item: ' . json_encode(churn_counts($hostId))); + churn_expect(ss_pfs_targets($hostId, 'ost', 'get', 'kbytes_total', 'churn-OST0001') === 'U', 'the missing OST serves U'); + churn_state('missing_from', $now); +} elseif ($step === 'add') { + churn_read(array(0 => 40, 2 => 30), $now); + churn_reindex($hostId); + + churn_expect(churn_indexes($hostId) === array('churn-MDT0000', 'churn-OST0000', 'churn-OST0001', 'churn-OST0002'), 'a new OST is indexed beside the missing one: ' . implode(', ', churn_indexes($hostId))); + churn_state('ds2', churn_graph($hostId, 'churn-OST0002')); + push_out_host($hostId, 0); + churn_expect(churn_duplicates($hostId) === array('data_sources' => 0, 'poller_items' => 0), 'adding a graph for the new OST duplicated nothing: ' . json_encode(churn_duplicates($hostId))); + churn_state('counts', json_encode(churn_counts($hostId))); +} elseif ($step === 'return') { + churn_read(array(0 => 40, 1 => 55, 2 => 30), $now); + churn_reindex($hostId); + push_out_host($hostId, 0); + + $ds1 = (int) db_fetch_cell_prepared("SELECT id FROM data_local WHERE host_id = ? AND snmp_index = 'churn-OST0001' ORDER BY id LIMIT 1", array($hostId)); + churn_expect($ds1 === (int) churn_state('ds1') && json_encode(churn_counts($hostId)) === churn_state('counts') && churn_duplicates($hostId) === array('data_sources' => 0, 'poller_items' => 0), 'the returning OST resumes on its original data source with nothing duplicated: ' . json_encode(array(churn_counts($hostId), churn_duplicates($hostId)))); + churn_expect(ss_pfs_targets($hostId, 'ost', 'get', 'kbytes_total', 'churn-OST0001') === '1000000000', 'the returning OST serves values again'); +} else { + $path = get_data_source_path((int) churn_state('ds1'), true); + $last = (string) shell_exec('rrdtool lastupdate ' . escapeshellarg($path) . ' 2>&1'); + churn_expect(strpos($last, 'kbytes_total') !== false && preg_match('/:\s.*1000000000/', $last) === 1, 'the poller kept writing the returning OST into its original RRD file'); + + // The poller writes at wall-clock time, seconds apart, so a gap cannot + // span an RRD step in this run. Replay the values the plugin served for + // this OST at 300 second steps into a copy of the RRD file Cacti + // created: present, missing (the U the script served), present. + $copy = sys_get_temp_dir() . '/pfs-churn-gap-' . getmypid() . '.rrd'; + $base = (int) (floor($now / 300) * 300) + 3000; + $info = (string) shell_exec('rrdtool info ' . escapeshellarg($path)); + preg_match_all('/^ds\[([a-z_0-9]+)\]\.type/m', $info, $m); + $names = $m[1]; + $ok = copy($path, $copy); + $plan = array('1000000000', '1000000000', 'U', 'U', 'U', '1000000000', '1000000000'); + + foreach ($plan as $i => $value) { + $values = array(); + + foreach ($names as $name) { + $values[] = $name === 'kbytes_total' ? $value : 'U'; + } + + shell_exec('rrdtool update ' . escapeshellarg($copy) . ' --template ' . escapeshellarg(implode(':', $names)) . ' ' . escapeshellarg(($base + 300 * ($i + 1)) . ':' . implode(':', $values)) . ' 2>&1'); + } + + $xport = (string) shell_exec('rrdtool xport --start ' . ($base + 300) . ' --end ' . ($base + 2100) . ' --step 300 ' . escapeshellarg('DEF:t=' . $copy . ':kbytes_total:AVERAGE') . ' XPORT:t 2>&1'); + @unlink($copy); + + // rrdtool 1.8 leaves the element out of each row unless asked, so + // rows are taken in order from the start time. + preg_match_all('#(?:\d+)?([^<]+)#', $xport, $rows, PREG_SET_ORDER); + $series = array(); + + foreach ($rows as $i => $row) { + $series[$base + 300 * ($i + 1)] = is_numeric($row[1]) && strtolower($row[1]) !== 'nan' ? (float) $row[1] : 'gap'; + } + + print 'EVIDENCE xport ' . ($series === array() ? substr($xport, 0, 400) : json_encode($series)) . PHP_EOL; + $gaps = count(array_filter($series, function ($v) { return $v === 'gap'; })); + $zeros = count(array_filter($series, function ($v) { return $v === 0.0; })); + churn_expect($ok && $gaps >= 3 && $zeros === 0 && in_array(1000000000.0, $series, true), "a missing OST exports from its RRD as a gap, not zero ($gaps gap steps, $zeros zero steps)"); + + $repo = new \Somethingwithproof\Pfs\FilesystemRepository(false, new \Somethingwithproof\Pfs\SystemClock()); + $repo->delete((int) churn_state('fs')); + db_execute("DELETE FROM settings WHERE name LIKE 'pfs\\_churn\\_%'"); +} + +exit($failures > 0 ? 1 : 0); diff --git a/tests/bootstrap-unit.php b/tests/bootstrap-unit.php index d254469..2c513a0 100644 --- a/tests/bootstrap-unit.php +++ b/tests/bootstrap-unit.php @@ -70,6 +70,12 @@ function read_config_option($config_name, $force = false) { } } +if (!function_exists('set_config_option')) { + function set_config_option($config_name, $value, $remote = false) { + $GLOBALS['__pfs_options'][$config_name] = $value; + } +} + // Repositories in unit tests talk to these stubs. A test reads the // statements from $GLOBALS['__pfs_db_exec'] and queues query results in // $GLOBALS['__pfs_db_rows'] (keyed by a substring of the SQL). diff --git a/tests/fixtures/lustre/mds-2.15.txt b/tests/fixtures/lustre/mds-2.15.txt new file mode 100644 index 0000000..635cf2d --- /dev/null +++ b/tests/fixtures/lustre/mds-2.15.txt @@ -0,0 +1,30 @@ +#pfs-read 1 +== version +2.15.8 + +== osd-ldiskfs/scratch-MDT0000/kbytestotal +200000000 + +== osd-ldiskfs/scratch-MDT0000/kbytesfree +150000000 + +== osd-ldiskfs/scratch-MDT0000/kbytesavail +140000000 + +== osd-ldiskfs/scratch-MDT0000/filestotal +100000000 + +== osd-ldiskfs/scratch-MDT0000/filesfree +90000000 + +== mdt/scratch-MDT0000/md_stats +snapshot_time 1731600000.000000001 secs.nsecs +start_time 1730000000.000000001 secs.nsecs +elapsed_time 1600000.000000000 secs.nsecs +open 50000 samples [usecs] 1 3000 900000 90000000 +close 49990 samples [usecs] 1 900 300000 10000000 +getattr 120000 samples [usecs] 1 400 500000 9000000 +statfs 3000 samples [usecs] 1 10 9000 90000 +crossdir_rename 7 samples [usecs] 10 900 3000 900000 + +#pfs-read end