diff --git a/.github/workflows/plugin-ci-workflow.yml b/.github/workflows/plugin-ci-workflow.yml index 2be1d15..dce47e4 100644 --- a/.github/workflows/plugin-ci-workflow.yml +++ b/.github/workflows/plugin-ci-workflow.yml @@ -377,6 +377,191 @@ jobs: exit 1 fi + # The milestone 3 and 4 end-to-end runs (tests/bin) against real poller + # runs: device flow, target churn and reindex, backup and restore, the Thold + # and Maint replay, and failure qualification. One PHP version per Cacti + # ref keeps the job time down; the scale harness stays a manual run + # (docs/release.md). + end-to-end: + name: End to end on Cacti ${{ matrix.cacti }} + runs-on: ubuntu-latest + timeout-minutes: 30 + + strategy: + fail-fast: false + matrix: + cacti: ['release/1.2.31', '1.2.x'] + + services: + mariadb: + image: mariadb:11.8@sha256:6422478cb8e159f080fb1d8ccf65101e26fe51385787fde7d16c3b165a331f15 + env: + MYSQL_ROOT_PASSWORD: cactiroot + MYSQL_DATABASE: cacti + MYSQL_USER: cactiuser + MYSQL_PASSWORD: cactiuser + ports: + - 3306:3306 + options: >- + --health-cmd="mariadb-admin ping" + --health-interval=10s + --health-timeout=5s + --health-retries=3 + + steps: + - name: Checkout Cacti + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + repository: Cacti/cacti + ref: ${{ matrix.cacti }} + path: cacti + + - name: Checkout pfs plugin + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + path: cacti/plugins/pfs + + # Thold and Maint run unchanged, at the releases docs/alerting.md names. + - name: Checkout Thold v1.8.2 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + repository: Cacti/plugin_thold + ref: 1eb406bd0f81f3204358cce7bd43c8bb5adc8e4a + path: cacti/plugins/thold + + - name: Checkout Maint v1.3 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + repository: Cacti/plugin_maint + ref: cd62de9cc323a4f5a8ac80a8d9dda3c7fa16c470 + path: cacti/plugins/maint + + - name: Install PHP 8.2 + uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 + with: + php-version: '8.2' + extensions: intl, mysql, gd, ldap, gmp, xml, json, mbstring, openssl, snmp + ini-values: "post_max_size=256M, max_execution_time=60, date.timezone=America/New_York" + coverage: none + + - name: Install system dependencies + run: | + sudo apt-get update + sudo apt-get install -y rrdtool mariadb-client + + - name: Initialize Cacti database + run: | + echo -e "[client]\nuser = root\npassword = cactiroot\nhost = 127.0.0.1\n" > ~/.my.cnf + chmod 600 ~/.my.cnf + mariadb -e "CREATE USER IF NOT EXISTS 'cactiuser'@'127.0.0.1' IDENTIFIED BY 'cactiuser';" + mariadb -e "GRANT ALL PRIVILEGES ON cacti.* TO 'cactiuser'@'127.0.0.1';" + mariadb -e "GRANT SELECT ON mysql.time_zone_name TO 'cactiuser'@'127.0.0.1';" + mariadb -e "FLUSH PRIVILEGES;" + mariadb cacti < cacti/cacti.sql + mariadb -e "INSERT INTO settings (name, value) VALUES ('path_php_binary', '$(command -v php)')" cacti + sed -r "s/localhost/127.0.0.1/g" cacti/include/config.php.dist > cacti/include/config.php + + - name: Install Cacti via CLI + working-directory: cacti + run: php cli/install_cacti.php --accept-eula --install --force + + - name: Install and enable the plugin + working-directory: cacti + run: php plugins/pfs/tests/bin/php-guard-check.php + + - name: Device flow + working-directory: cacti + env: + PFS_TEST_DATABASE: disposable + # RRDtool refuses a second update to a file in the same second, and + # the flows run faster than that, so each forced poll waits a second. + run: | + set -eu + php plugins/pfs/tests/bin/device-flow.php setup + sleep 1 + php poller.php --poller=1 --force > /dev/null + php plugins/pfs/tests/bin/device-flow.php check + sleep 1 + php poller.php --poller=1 --force > /dev/null + php plugins/pfs/tests/bin/device-flow.php later + + - name: Target churn and reindex + working-directory: cacti + env: + PFS_TEST_DATABASE: disposable + run: | + set -eu + for phase in setup remove add return; do + php plugins/pfs/tests/bin/target-flow.php "$phase" + sleep 1 + php poller.php --poller=1 --force > /dev/null + done + php plugins/pfs/tests/bin/target-flow.php check + + - name: Backup and restore + working-directory: cacti + env: + PFS_TEST_DATABASE: disposable + run: PFS_TEST_MYSQL_DEFAULTS="$HOME/.my.cnf" sh plugins/pfs/tests/bin/restore-replay.sh + + # The poller logs a failed ownership change for each RRD file it has not + # created yet; that line is not a fault of the flows. + - name: Check the flows' log for errors + working-directory: cacti + run: | + if [ -f log/cacti.log ]; then + # Cacti 1.2.31 leaves incomplete poller-output rows when a + # multi-item source returns U. The churn replay checks those + # gaps; keep the diagnostics visible and restrict this allowance + # to the affected core release and the plugin's templates. + core_warnings='^$' + if [ "$(cat include/cacti_version)" = '1.2.31' ]; then + core_warnings="^[^ ]+ [0-9:]+ - POLLER: Poller\\[1\\] PID\\[[0-9]+\\] WARNING: (Poller Output Table not Empty\\. Issues: [0-9]+, DS\\[[0-9, ]+\\]|There are [0-9]+ Data Sources not returning all data leaving rows in the poller output table\\. Details to follow\\.|Data Template 'Parallel Filesystem [^']+' is impacted by lack of complete information)\$" + grep -E "$core_warnings" log/cacti.log || true + fi + if grep -E "FATAL:|ERROR:|WARNING:" log/cacti.log | grep -v "does not exist for ownership assignment" | grep -vE "$core_warnings" | grep -vE '^[^ ]+ [0-9:]+ - SYSTEM WARNING: Primary Admin account notifications disabled! Unable to send administrative Email\.$'; then + exit 1 + fi + mv log/cacti.log log/flows.log + fi + + - name: Thold and Maint replay + working-directory: cacti + env: + PFS_TEST_DATABASE: disposable + run: | + sh plugins/pfs/tests/bin/alert-replay.sh + if grep -E "PHP ERROR|DISABLING PLUGIN|TypeError|Fatal" log/cacti.log; then + exit 1 + fi + mv log/cacti.log log/alert.log + + # Provokes failed reads, a lost database connection, and slow nodes, so + # its log is printed, not checked. Not root here, so the RRD permission + # scenario is skipped; the container run covers it. + - name: Failure qualification + working-directory: cacti + env: + PFS_TEST_DATABASE: disposable + run: | + PFS_TEST_MYSQL_DEFAULTS="$HOME/.my.cnf" sh plugins/pfs/tests/bin/failure-replay.sh + if [ -f log/cacti.log ]; then mv log/cacti.log log/failure.log; fi + + - name: Show the end-to-end logs + if: always() + working-directory: cacti + run: | + for f in log/flows.log log/alert.log log/failure.log log/cacti.log; do + if [ -f "$f" ]; then + echo "== $f" + cat "$f" + fi + done + workflow-lint: name: Workflow lint runs-on: ubuntu-latest @@ -412,6 +597,7 @@ jobs: - entry-point-lint - integration-test - php-guard + - end-to-end - workflow-lint - reuse runs-on: ubuntu-latest diff --git a/CHANGELOG.md b/CHANGELOG.md index c97a095..220b976 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,7 +12,9 @@ Phase 1, Lustre observation. Not released: pilots on real filesystems, the exter - 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). +- A per-filesystem summary data source for Thold: fill and imbalance, target counts, capacity totals, filesystem throughput and metadata counters, and data age (milestones 3 and 4). +- Summary rate gauges, `read_bytes_rate`, `write_bytes_rate`, and `md_ops_rate`, computed by the reader so Thold can alert on rates without a counter data source ([ADR 0012 amendment](docs/decisions/0012-thold-rate-alerts-high-thresholds-only.md#amendment-2026-11-15)). +- An uninstall setting, off by default, that deletes the devices the plugin created, with their graphs and data sources, through Cacti's device delete; mapped existing devices always stay. The devices the plugin created are recorded one row each in `plugin_pfs_created_devices`, which outlives an uninstall that drops the other tables while it lists a device still in Cacti (REQ-LIFE-005, [#31](https://github.com/somethingwithproof/plugin_pfs/issues/31)). - 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). @@ -23,9 +25,12 @@ Phase 1, Lustre observation. Not released: pilots on real filesystems, the exter ### Fixed +- Upgrade instructions now call out recreating the Throughput and Metadata graphs to add the rate gauges, and preserving any needed history first. +- A rate gauge was served from a counter read that was no longer current while the capacity read the summary time comes from still was; each rate now also needs its own counter read to be current. +- Uninstall now clears mappings for remotely soft-deleted devices before it forgets their ownership, and stops if mapping reads or writes fail. - 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)). +- 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. Threshold the rate gauges instead ([docs/alerting.md](docs/alerting.md#counters-and-thold-182)). diff --git a/docs/PLAN.md b/docs/PLAN.md index 09a170b..16e547b 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -283,13 +283,14 @@ The "Parallel Filesystem Summary" data source returns, from the reader's cache: | `targets_missing` | Targets in inventory with no recent observation | `U` | | `targets_unhealthy` | Targets with a non-healthy condition flag | `U` | | `age` | Seconds since the oldest contributing observation | Always numeric once observed | +| `read_bytes_rate`, `write_bytes_rate`, `md_ops_rate` | Per-second rates of the aggregate counters, computed by the reader (GAUGE) | `U`, and `U` across a reset or member change | Thold thresholds and Maint device schedules apply with no change to either plugin (ADR 0002). 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.** 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. +- **Rates.** Amended in [ADR 0012](decisions/0012-thold-rate-alerts-high-thresholds-only.md#amendment-2026-11-15) after the milestone 4 run: rate alerts use the summary's rate gauges, and thresholds on DERIVE data sources are unsupported with Thold 1.8.2, because a threshold on a DERIVE data source that reads `U` once crashes Thold's poller output hook. The original reasoning follows. 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. @@ -305,7 +306,7 @@ Alternatives considered: 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)). +- **Counter thresholds are not supported with Thold 1.8.2; rate gauges replace them.** 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. The summary therefore carries `read_bytes_rate`, `write_bytes_rate`, and `md_ops_rate`: GAUGE values the reader computes from consecutive sums with the same unknown rules, printed on the Throughput and Metadata Operations graphs so Cacti stores them. The end-to-end run thresholds `write_bytes_rate` through a counter reset with Thold still enabled ([ADR 0012 amendment](decisions/0012-thold-rate-alerts-high-thresholds-only.md#amendment-2026-11-15), [alerting](alerting.md), [thold-counters](research/thold-counters.md#milestone-4-end-to-end-run)). The rate's time base is the read time all summed values share, so a sum whose values were read in different runs has no rate; per-target rate gauges are not provided. - **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. diff --git a/docs/alerting.md b/docs/alerting.md index 3f7a4ea..d1f2bf9 100644 --- a/docs/alerting.md +++ b/docs/alerting.md @@ -14,7 +14,9 @@ Use the **Parallel Filesystem Summary** values. Each overview graph has its own | `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) | +| `read_bytes_rate`, `write_bytes_rate` | Throughput | High, in bytes per second, 2 polls | Filesystem read and write rates the reader computes; unknown for two or three polls after a reset | +| `md_ops_rate` | Metadata Operations | High, in operations per second, 2 polls | Filesystem metadata operation rate, computed the same way | +| `read_bytes`, `write_bytes`, `md_ops` | Throughput, Metadata Operations | None with Thold 1.8.2; use the rates above | Counters (DERIVE), for graphs only | Per-target gauges (capacity, inodes) can be thresholded the same way from per-target graphs. @@ -22,7 +24,8 @@ Per-target gauges (capacity, inodes) can be thresholded the same way from per-ta - 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. +- A counter reset produces one unknown interval on the counter's graph, and two or three unknown polls on the matching rate gauge. +- Rate thresholds should be high thresholds with a fail trigger of at least two polls. Low rate thresholds ("write rate fell below") are not supported in phase 1, because an unknown poll after a reset restores them ([ADR 0012](decisions/0012-thold-rate-alerts-high-thresholds-only.md#amendment-2026-11-15)). ## Maintenance @@ -30,11 +33,13 @@ Put the filesystem's device in a Maint schedule. Thold checks the device with Ma ## 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. +Do not create Thold thresholds on the counter values (`read_bytes`, `write_bytes`, `md_ops`, or per-target counters) with Thold 1.8.2. Threshold the rate gauges instead. -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. +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)). -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. +The rate gauges avoid this: the reader computes the rate, Cacti stores it as a GAUGE, and Thold compares the level without computing anything. A reset makes the gauge `U` for two or three polls, which Thold reads as not breached and which the end-to-end run passes through with Thold still enabled. Thold's development branch at `dc76952` (not released) guards the DERIVE path; counter thresholds can be reconsidered once a release includes that change. + +If Thold was disabled by this error: delete the counter threshold, re-enable Thold on the Plugins page, and create the threshold on the rate gauge. ## What was tested @@ -45,7 +50,8 @@ Thold's development branch at `dc76952` (not released) changes this path: an unk | 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 | +| Write rate far above the threshold for two polls | `write_bytes_rate` above 1 GB/s, 2 polls | First poll breaches without notifying, second notifies, then restores | +| Every OST's counters reset, then the write rate bursts again | `write_bytes_rate` | Two polls read unknown with no breach, no log entry, and Thold still enabled; the rate is a number again on the third, and the next burst breaches, notifies, and 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/0012-thold-rate-alerts-high-thresholds-only.md b/docs/decisions/0012-thold-rate-alerts-high-thresholds-only.md index a1d122d..2720db5 100644 --- a/docs/decisions/0012-thold-rate-alerts-high-thresholds-only.md +++ b/docs/decisions/0012-thold-rate-alerts-high-thresholds-only.md @@ -1,6 +1,6 @@ # 0012. Allow Thold rate alerts on counters for high thresholds only -Status: Accepted (2026-11-15). Decides #8. +Status: Accepted (2026-11-15), amended 2026-11-15 after the milestone 4 Thold run (see [Amendment](#amendment-2026-11-15)). Decides #8. ## Context @@ -23,3 +23,24 @@ Cumulative counters are stored as DERIVE with minimum 0 (ADR 0005). Offline RRDt - **Plugin-computed rate gauges now.** Reset-proof, but it adds per-value state and a second series beside every counter before any pilot has asked for low-threshold rate alerts. - **No rate alerts in phase 1.** It throws away high-threshold alerts, which the research shows work with a two-poll duration. + +## Amendment (2026-11-15) + +### Context + +The milestone 4 end-to-end run with Thold v1.8.2 ([thold-counters](../research/thold-counters.md#milestone-4-end-to-end-run)) showed that the decision above cannot hold with that release. Thold stores a DERIVE item's raw polled value as its previous value without checking that it is a number. After the `U` the reader publishes for a reset or a change of contributing targets, the next numeric value makes Thold's rate calculation throw a PHP `TypeError` in the poller output hook, and Cacti disables Thold for the whole install. The reader publishes that `U` by design, so a supported rate threshold would disable Thold at the first reset. + +### Decision + +- **Thold, rates.** Rate alerts use the summary's rate gauges, `read_bytes_rate`, `write_bytes_rate`, and `md_ops_rate`. The reader computes each from two consecutive sums of the same members read in one run each, at most two intervals apart, and publishes `U` for a reset, a member change, a stale or first read, or a sum that went down, the same cases the DERIVE value is unknown for. They are GAUGE data sources, so Thold reads them as levels and never computes a rate. +- **Thold, counters.** Thresholds on DERIVE counter data sources, per target or summary, are unsupported with Thold 1.8.2. +- **Low thresholds on rates.** Still unsupported in phase 1: in Thold 1.8.2's source an unknown value takes the not-breached path, so a low rate threshold would restore on every reset (read, not run). +- **Graphs.** Unchanged: per-target and summary counters stay DERIVE, and the overview graphs draw them. The Throughput and Metadata Operations graphs also print the rate gauges, because Cacti stores only the data source items a graph uses. +- The "no plugin-computed rate gauges in phase 1" item above is withdrawn. + +### Consequences + +- Rate alerts are per filesystem only; there are no per-target rate gauges. +- A reset makes the gauge unknown for two or three polls (all targets resetting together, or some), which a two-poll duration does not count as a breach. `tests/bin/alert-replay.sh` checks that a high rate threshold on `write_bytes_rate` fires, restores, stays quiet and enabled through a reset, and fires again after it. +- Overview graphs created before this change have RRD files without the rate gauges, since Cacti 1.2 does not add a data source item to an existing file. No release had them; a pre-release install must recreate its Throughput and Metadata Operations graphs. +- If a Thold release guards DERIVE values (its development branch at `dc76952` does), counter thresholds can be reconsidered in a later record. diff --git a/docs/decisions/README.md b/docs/decisions/README.md index c1c03a9..d583ad6 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -15,7 +15,7 @@ Each record captures one architecture decision: its context, the decision, its c | [0009](0009-read-nodes-through-a-forced-ssh-command.md) | Read nodes through a forced SSH command running a fixed script | Accepted | | [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 | +| [0012](0012-thold-rate-alerts-high-thresholds-only.md) | Allow Thold rate alerts on counters for high thresholds only | Accepted, amended: rate alerts use the summary rate gauges | | [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/operator-guide.md b/docs/operator-guide.md index 9b03f77..f2e360e 100644 --- a/docs/operator-guide.md +++ b/docs/operator-guide.md @@ -46,8 +46,8 @@ Each filesystem is one Cacti device. Its targets (OSTs and MDTs) are the indexes |---|---|---| | 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 | +| Throughput (overview) | Filesystem read and write bytes per second, and the read and write rate gauges for alerts (printed under the graph) | Any OST is missing, stale, unhealthy without its counter, or reset in the interval; the rate gauges also for one or two polls after a reset | +| Metadata (overview) | Filesystem metadata operations per second, all allowlisted operations together, and the operation rate gauge for alerts | Any MDT is missing, stale, or reset in the interval; the rate gauge also for one or two polls after a reset | | 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 | @@ -57,7 +57,7 @@ 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. +- **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 and the summary's rate gauges 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. @@ -67,7 +67,8 @@ Rules behind the table: 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. +4. If you are upgrading from a pre-release version that predates the rate gauges, preserve any Throughput and Metadata graph history you need, then delete and recreate those overview graphs. Their existing RRD files do not contain the new rate data sources. +5. 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. @@ -89,7 +90,8 @@ To restore, stop the pollers, restore the database and the RRD directory from th 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. +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. With **Keep Plugin Tables on Uninstall** checked (the default) the tables stay; clear it to drop them. + - **Devices.** By default every device stays, with its data sources and graphs. Check **Delete the Devices This Plugin Created on Uninstall** in Configuration, Settings, Parallel Filesystems (off by default) to have the uninstall delete the devices the plugin created from the admin page, through Cacti's own device delete: their graphs and data sources go with them, and the RRD files are removed only if Cacti's RRD cleanup setting removes them. The plugin records each device it creates, one row per device in `plugin_pfs_created_devices`; an existing device you mapped to a filesystem is never on that record and always stays, with the data queries and overview graphs the mapping added. A filesystem whose device was deleted keeps no mapping to it, so kept tables never point at a deleted device. An uninstall that drops the plugin tables keeps `plugin_pfs_created_devices` while it lists a device that is still in Cacti, so a later reinstall and uninstall can still delete it; drop that table by hand if you keep those devices for good. Devices, data sources, graphs, and RRD files you created yourself 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 diff --git a/docs/release.md b/docs/release.md index 7ed5911..c27af37 100644 --- a/docs/release.md +++ b/docs/release.md @@ -24,7 +24,7 @@ Tests, CI configuration, and analysis configuration are left out by `export-igno ## 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. +2. Merge after CI passes on every matrix entry. CI's `end-to-end` job runs the device flow, target churn, backup and restore, the Thold and Maint replay, and failure qualification on Cacti 1.2.31 and the 1.2.x branch with PHP 8.2. Two runs stay manual: the RRD permission scenario of the failure run, which needs root (CI skips it), and the scale harness (`tests/bin/scale-replay.sh`), which takes several minutes at 2,000 targets. Run both in a disposable container 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: diff --git a/docs/research/scale.md b/docs/research/scale.md index f3487f5..8843502 100644 --- a/docs/research/scale.md +++ b/docs/research/scale.md @@ -78,7 +78,7 @@ 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. +- **Open item.** 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. A third isolated run named it: data source 935, the capacity data source (`kbytes_total`) of `sc2000-OST01a3`, the 420th OST, with its three poller items in place but no RRD file after two polls. The cause is not known; nothing marks that OST as different from its neighbours. - 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 diff --git a/docs/research/thold-counters.md b/docs/research/thold-counters.md index ccfd1e1..424a83e 100644 --- a/docs/research/thold-counters.md +++ b/docs/research/thold-counters.md @@ -75,3 +75,5 @@ ERROR PHP ERROR in Plugin 'thold': Uncaught TypeError: Unsupported operand type 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. + +Follow-up: the summary now carries reader-computed rate gauges (`read_bytes_rate`, `write_bytes_rate`, `md_ops_rate`), and rate alerts use them ([ADR 0012 amendment](../decisions/0012-thold-rate-alerts-high-thresholds-only.md#amendment-2026-11-15)). The replay thresholds `write_bytes_rate` through a reset of every OST's counters; see [alerting.md](../alerting.md#what-was-tested). diff --git a/docs/security-review.md b/docs/security-review.md index 1010eff..4004417 100644 --- a/docs/security-review.md +++ b/docs/security-review.md @@ -54,6 +54,8 @@ No issue found. ### File writes into Cacti +- Uninstall deletes devices only when the full-admin setting **Delete the Devices This Plugin Created on Uninstall** is checked (off by default), and only the host ids `DeviceProvisioner::create()` recorded in the `plugin_pfs_created_devices` table that still exist (one row per device, so the record has no size limit; schema migration 3 moves the milestone 4 setting into it); a mapped existing device is never recorded. Deletion goes through Cacti's `api_device_remove_multi()`. Uninstall is a Plugins page action, which needs Cacti's plugin management permission rather than a device permission, so it is not limited by `is_device_allowed()`. + - 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. @@ -63,7 +65,7 @@ Residual: an account that can write `resource/script_server/` can still replace ### 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. +- SQL is in `Schema` and the `*Repository` classes, plus the 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. diff --git a/include/unbooted-uninstall.php b/include/unbooted-uninstall.php index e6dfae1..d0baf0b 100644 --- a/include/unbooted-uninstall.php +++ b/include/unbooted-uninstall.php @@ -26,14 +26,185 @@ * run both paths. No storage node is contacted. */ +/** + * The recorded host ids: the plugin_pfs_created_devices table, and the + * setting milestone 4 kept them in, for a schema not yet migrated. Mirrors + * CreatedDeviceRepository. + * + * @return list + */ +function pfs_unbooted_created_devices(): array { + $ids = array(); + + if (pfs_unbooted_record_exists()) { + $rows = db_fetch_assoc_prepared('SELECT host_id FROM plugin_pfs_created_devices', array()); + + if (!is_array($rows)) { + throw new RuntimeException('Uninstall stopped because device ownership could not be read.'); + } + + foreach ($rows as $row) { + $ids[] = (int) $row['host_id']; + } + } + + $row = db_fetch_row_prepared('SELECT value FROM settings WHERE name = ?', array('pfs_created_devices')); + $value = is_array($row) && isset($row['value']) && is_string($row['value']) ? $row['value'] : ''; + $legacy = $value === '' ? array() : json_decode($value, true); + if ($row === false || !is_array($legacy)) { + throw new RuntimeException('Uninstall stopped because legacy device ownership could not be read.'); + } + + foreach ($legacy as $id) { + if (is_int($id)) { + $ids[] = $id; + } + } + + return array_values(array_unique(array_filter($ids, function ($id) { + return $id > 0; + }))); +} + +function pfs_unbooted_record_exists(): bool { + $count = db_fetch_cell_prepared('SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?', array('plugin_pfs_created_devices')); + if ($count === false) { + throw new RuntimeException('Uninstall stopped because the ownership table could not be checked.'); + } + return (int) $count > 0; +} + +/** + * @param list $ids + * @return list + */ +function pfs_unbooted_removed_devices(array $ids): array { + return array_values(array_filter($ids, function ($id) { + $row = db_fetch_row_prepared('SELECT id, deleted FROM host WHERE id = ?', array($id)); + + if ($row === false) { + throw new RuntimeException('Uninstall stopped because device mappings could not be checked.'); + } + + return $row === array() || (is_array($row) && isset($row['deleted']) && $row['deleted'] === 'on'); + })); +} + +/** + * @return list + */ +function pfs_unbooted_mapped_host_ids(): array { + $columns = db_fetch_cell_prepared( + "SELECT COUNT(*) FROM information_schema.COLUMNS " + . "WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'plugin_pfs_filesystem' " + . "AND COLUMN_NAME = 'host_id'", + array() + ); + + if ($columns === false) { + throw new RuntimeException('Uninstall stopped because filesystem mappings could not be checked.'); + } + + if ((int) $columns === 0) { + return array(); + } + + $rows = db_fetch_assoc_prepared('SELECT host_id FROM plugin_pfs_filesystem WHERE host_id > 0', array()); + + if (!is_array($rows)) { + throw new RuntimeException('Uninstall stopped because filesystem mappings could not be read.'); + } + + $ids = array(); + + foreach ($rows as $row) { + $id = isset($row['host_id']) ? (int) $row['host_id'] : 0; + + if ($id > 0) { + $ids[] = $id; + } + } + + return array_values(array_unique($ids)); +} + +function pfs_unbooted_unmap_removed_devices(): void { + $removed = pfs_unbooted_removed_devices(pfs_unbooted_mapped_host_ids()); + + $sql = 'UPDATE plugin_pfs_filesystem SET host_id = 0 WHERE host_id IN ('; + $sql .= implode(', ', array_fill(0, count($removed), '?')) . ')'; + + if ($removed !== array() && !db_execute_prepared($sql, $removed)) { + throw new RuntimeException('Uninstall stopped because removed-device mappings could not be cleared.'); + } +} + function pfs_uninstall_unbooted(): void { + // The plugin can be uninstalled while disabled, when no device_remove + // hook cleared mappings for remotely soft-deleted hosts. + pfs_unbooted_unmap_removed_devices(); + + // A recorded device deleted while the plugin was disabled is no longer + // the plugin's to track. + if (pfs_unbooted_record_exists()) { + db_execute_prepared('DELETE FROM plugin_pfs_created_devices WHERE host_id NOT IN (SELECT id FROM host)', array()); + } + + // Deleting the devices the plugin created needs only core functions, so + // it is honoured here too (REQ-LIFE-005); setup.php is already loaded. + $delete = db_fetch_row_prepared('SELECT value FROM settings WHERE name = ?', array('pfs_uninstall_delete_devices')); + + if (is_array($delete) && isset($delete['value']) && $delete['value'] === 'on') { + $recorded = pfs_unbooted_created_devices(); + $existing = array(); + + foreach ($recorded as $id) { + if (is_int($id) && $id > 0 && (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM host WHERE id = ?', array($id)) > 0) { + $existing[] = $id; + } + } + + pfs_uninstall_devices($existing); + $existing = pfs_unbooted_removed_devices($recorded); + + // No plugin hook runs here, so the mapping and the record are + // cleared directly; kept tables must not point at a deleted device. + pfs_unbooted_unmap_removed_devices(); + + if ($existing !== array() && pfs_unbooted_record_exists()) { + $sql = 'DELETE FROM plugin_pfs_created_devices WHERE host_id IN ('; + $sql .= implode(', ', array_fill(0, count($existing), '?')) . ')'; + + if (!db_execute_prepared($sql, $existing)) { + throw new RuntimeException('Uninstall stopped because device ownership could not be cleared.'); + } + } + + if (count($existing) === count($recorded)) { + db_execute_prepared('DELETE FROM settings WHERE name = ?', array('pfs_created_devices')); + } + } + $row = db_fetch_row_prepared('SELECT value FROM settings WHERE name = ?', array('pfs_uninstall_keep_tables')); $keep = !is_array($row) || $row === array() || (isset($row['value']) && $row['value'] === 'on'); if ($keep) { - db_execute_prepared("DELETE FROM plugin_db_changes WHERE plugin = ? AND method = 'create'", array('pfs')); + if (!db_execute_prepared("DELETE FROM plugin_db_changes WHERE plugin = ? AND method = 'create'", array('pfs'))) { + throw new RuntimeException('Uninstall stopped because the plugin tables could not be preserved.'); + } cacti_log('NOTE: Uninstall kept the plugin tables as configured', false, 'PFS'); } else { + // As Schema::keepCreatedDevices(): a record that still lists a + // device outlives the other tables. + $count = pfs_unbooted_record_exists() ? db_fetch_cell_prepared('SELECT COUNT(*) FROM plugin_pfs_created_devices', array()) : 0; + + if ($count === false || (int) $count > 0) { + if (!db_execute_prepared("DELETE FROM plugin_db_changes WHERE plugin = ? AND `table` = ? AND method = 'create'", array('pfs', 'plugin_pfs_created_devices'))) { + throw new RuntimeException('Uninstall stopped because device ownership could not be preserved.'); + } + cacti_log('NOTE: Uninstall dropped the plugin tables but kept the record of the devices the plugin created, which are still in Cacti', false, 'PFS'); + } + db_execute_prepared('DELETE FROM settings WHERE name = ?', array('pfs_schema_version')); } } diff --git a/lib/CacheRepository.php b/lib/CacheRepository.php index 6ea83d7..8692a05 100644 --- a/lib/CacheRepository.php +++ b/lib/CacheRepository.php @@ -122,10 +122,16 @@ private function observation(int $targetId, Observation $o): bool { } private function summary(int $filesystemId, string $metric, ?float $value, Summary $summary): bool { + $counter = Summary::counterOf($metric); + + // A rate row keeps its counter's read time, which the next run's rate + // is measured from (SummaryRepository). + $observedAt = $counter === null ? $summary->observedAt : ($summary->counterAt[$counter] ?? 0); + return db_execute_prepared('INSERT INTO plugin_pfs_summary (filesystem_id, metric, value, members, observed_at, computed_at) VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE value = VALUES(value), members = VALUES(members), observed_at = VALUES(observed_at), computed_at = VALUES(computed_at)', [ - $filesystemId, $metric, $value, $summary->members[$metric] ?? '', $summary->observedAt, $summary->computedAt, + $filesystemId, $metric, $value, $summary->members[$metric] ?? '', $observedAt, $summary->computedAt, ], true, $this->connection); } diff --git a/lib/CactiObjectRepository.php b/lib/CactiObjectRepository.php index 2d471a9..5bc3d6d 100644 --- a/lib/CactiObjectRepository.php +++ b/lib/CactiObjectRepository.php @@ -51,6 +51,16 @@ public function deviceTemplateId(): int { return $this->idByHash('host_template', TemplateInstaller::hash('host_template', TemplateInstaller::DEVICE_TEMPLATE)); } + public function deviceRemoved(int $hostId): bool { + $row = db_fetch_row_prepared('SELECT id, deleted FROM host WHERE id = ?', [$hostId], true, $this->connection); + + if ($row === false) { + throw new \RuntimeException('Uninstall stopped because device status could not be checked.'); + } + + return $row === [] || (is_array($row) && Row::string($row, 'deleted') === 'on'); + } + public function defaultProfileId(): int { $id = (int) db_fetch_cell_prepared("SELECT id FROM data_source_profiles WHERE `default` = 'on' ORDER BY id LIMIT 1", [], '', true, $this->connection); diff --git a/lib/CreatedDeviceRepository.php b/lib/CreatedDeviceRepository.php new file mode 100644 index 0000000..fadc886 --- /dev/null +++ b/lib/CreatedDeviceRepository.php @@ -0,0 +1,95 @@ + + * 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. + */ + +namespace Somethingwithproof\Pfs; + +/** + * The Cacti devices the plugin itself created (DeviceProvisioner::create()), + * one row per device in plugin_pfs_created_devices, so the record has no + * size limit. Only these may be deleted on uninstall, and only when the + * administrator asked for it (REQ-LIFE-005): an existing device mapped onto + * a filesystem is never recorded. The record outlives the filesystem that + * asked for the device, and uninstall keeps the table while it lists a + * device even when the other plugin tables are dropped. + */ +final class CreatedDeviceRepository { + public const TABLE = 'plugin_pfs_created_devices'; + + /** Where milestone 4 kept the list, as JSON; migration 3 moves it. */ + public const LEGACY_SETTING = 'pfs_created_devices'; + + public function __construct(private readonly \PDO|false $connection) { + } + + /** + * @return list + */ + public function ids(): array { + return array_values(array_filter(array_map(static fn (array $row): int => Row::int($row, 'host_id', 0, 1), Row::rows(db_fetch_assoc_prepared('SELECT host_id FROM plugin_pfs_created_devices ORDER BY host_id', [], true, $this->connection))), static fn (int $id): bool => $id > 0)); + } + + public function add(int $hostId, int $now): bool { + return $hostId > 0 && db_execute_prepared('INSERT IGNORE INTO plugin_pfs_created_devices (host_id, created_at) VALUES (?, ?)', [$hostId, $now], true, $this->connection); + } + + /** A failed read must keep the ownership record through uninstall. */ + public function hasRecords(): bool { + $count = db_fetch_cell_prepared('SELECT COUNT(*) FROM plugin_pfs_created_devices', [], '', true, $this->connection); + + return $count === false || (int) $count > 0; + } + + /** + * Drop deleted devices from the record, so a later uninstall acts only on + * devices that still exist. + * + * @param list $hostIds + */ + public function forget(array $hostIds): bool { + $ids = array_values(array_unique(array_filter(array_map('intval', $hostIds), static fn (int $id): bool => $id > 0))); + + return $ids === [] || db_execute_prepared('DELETE FROM plugin_pfs_created_devices WHERE host_id IN (' . implode(', ', array_fill(0, count($ids), '?')) . ')', $ids, true, $this->connection); + } + + /** + * Move the milestone 4 record into the table and remove the setting. + * Safe to repeat: an id already in the table is kept, and the setting is + * removed only once every id it held is in the table. + */ + public function importLegacy(int $now): bool { + // Core documents the cell helper as returning bool, so the row is read. + $row = db_fetch_row_prepared('SELECT value FROM settings WHERE name = ?', [self::LEGACY_SETTING], true, $this->connection); + $value = is_array($row) ? Row::string($row, 'value') : ''; + $decoded = json_decode($value, true); + + if ($row === false || ($value !== '' && !is_array($decoded))) { + return false; + } + + $ok = true; + + foreach (is_array($decoded) ? $decoded : [] as $id) { + if (is_int($id) && $id > 0) { + $ok = $this->add($id, $now) && $ok; + } + } + + return $ok && db_execute_prepared('DELETE FROM settings WHERE name = ?', [self::LEGACY_SETTING], true, $this->connection); + } +} diff --git a/lib/DeviceProvisioner.php b/lib/DeviceProvisioner.php index e5b5e07..f5928cd 100644 --- a/lib/DeviceProvisioner.php +++ b/lib/DeviceProvisioner.php @@ -37,6 +37,8 @@ public function __construct( private readonly CactiObjectRepository $objects, private readonly BackendRegistry $backends, private readonly string $cactiPath, + private readonly CreatedDeviceRepository $created, + private readonly Clock $clock, ) { } @@ -122,6 +124,15 @@ public function create(Filesystem $filesystem): int { return 0; } + // Recorded before anything else can fail, so an uninstall that + // deletes the plugin's devices finds this one too. + if (!$this->created->add($hostId, $this->clock->now())) { + api_device_remove($hostId); + Log::error(sprintf('Could not record ownership of device %d for filesystem %d; rollback %s', $hostId, $filesystem->id, $this->objects->deviceRemoved($hostId) ? 'completed' : 'failed; remove the device in Cacti')); + + return 0; + } + if (!$this->filesystems->mapHost($filesystem->id, $hostId)) { Log::error(sprintf('Device %d was created for filesystem %d but could not be mapped', $hostId, $filesystem->id)); diff --git a/lib/FilesystemRepository.php b/lib/FilesystemRepository.php index 65cf368..b4458c6 100644 --- a/lib/FilesystemRepository.php +++ b/lib/FilesystemRepository.php @@ -56,6 +56,34 @@ public function findByHost(int $hostId): ?Filesystem { return is_array($row) ? Filesystem::fromRow($row) : null; } + /** + * @return list + */ + public function mappedHostIds(): array { + $rows = db_fetch_assoc_prepared( + 'SELECT host_id FROM plugin_pfs_filesystem WHERE host_id > 0 ORDER BY host_id', + [], + true, + $this->connection + ); + + if (!is_array($rows)) { + throw new \RuntimeException('Uninstall stopped because filesystem mappings could not be read.'); + } + + $ids = []; + + foreach ($rows as $row) { + $id = Row::int($row, 'host_id', 0, 1); + + if ($id > 0) { + $ids[] = $id; + } + } + + return array_values(array_unique($ids)); + } + /** * Map a filesystem to a Cacti device. A device carries at most one * filesystem, so a device already mapped elsewhere is refused. @@ -88,13 +116,17 @@ public function unmapHosts(array $hostIds): int { } $placeholders = implode(', ', array_fill(0, count($hostIds), '?')); - $count = (int) db_fetch_cell_prepared("SELECT COUNT(*) FROM plugin_pfs_filesystem WHERE host_id IN ($placeholders)", $hostIds, '', true, $this->connection); + $count = db_fetch_cell_prepared("SELECT COUNT(*) FROM plugin_pfs_filesystem WHERE host_id IN ($placeholders)", $hostIds, '', true, $this->connection); + + if ($count === false) { + throw new \RuntimeException('Uninstall stopped because filesystem mappings could not be checked.'); + } - if ($count > 0) { - db_execute_prepared("UPDATE plugin_pfs_filesystem SET host_id = 0, updated_at = ? WHERE host_id IN ($placeholders)", array_merge([$this->clock->now()], $hostIds), true, $this->connection); + if ((int) $count > 0 && !db_execute_prepared("UPDATE plugin_pfs_filesystem SET host_id = 0, updated_at = ? WHERE host_id IN ($placeholders)", array_merge([$this->clock->now()], $hostIds), true, $this->connection)) { + throw new \RuntimeException('Uninstall stopped because filesystem mappings could not be cleared.'); } - return $count; + return (int) $count; } public function nameTaken(string $backend, string $name, int $exceptId): bool { diff --git a/lib/Schema.php b/lib/Schema.php index 68de10f..3b90763 100644 --- a/lib/Schema.php +++ b/lib/Schema.php @@ -35,7 +35,7 @@ * (REQ-LIFE-006). */ final class Schema { - public const VERSION = 2; + public const VERSION = 3; public const HOOKS = [ 'config_arrays' => 'pfs_config_arrays', @@ -119,7 +119,27 @@ public function hooksRegistered(): bool { * schema version so a reinstall reuses them. */ public function untrackTables(): void { - db_execute_prepared("DELETE FROM plugin_db_changes WHERE plugin = ? AND method = 'create'", [self::PLUGIN], true, $this->connection); + if (!db_execute_prepared("DELETE FROM plugin_db_changes WHERE plugin = ? AND method = 'create'", [self::PLUGIN], true, $this->connection)) { + throw new \RuntimeException('Uninstall stopped because the plugin tables could not be preserved.'); + } + } + + /** + * Keep the created-device table through an uninstall that drops the + * other tables, while it still lists a device: the devices stay in + * Cacti, and a later uninstall may be asked to delete them. An empty + * table is dropped with the rest. Returns whether it was kept. + */ + public function keepCreatedDevices(): bool { + if (!(new CreatedDeviceRepository($this->connection))->hasRecords()) { + return false; + } + + if (!db_execute_prepared("DELETE FROM plugin_db_changes WHERE plugin = ? AND `table` = ? AND method = 'create'", [self::PLUGIN, CreatedDeviceRepository::TABLE], true, $this->connection)) { + throw new \RuntimeException('Uninstall stopped because device ownership could not be preserved.'); + } + + return true; } public function forgetVersion(): void { @@ -138,6 +158,11 @@ private function migrations(): array { 2 => fn (): bool => $this->addColumn('plugin_pfs_filesystem', 'host_id', 'int(10) unsigned NOT NULL DEFAULT 0', 'admin_state') && $this->addIndex('plugin_pfs_filesystem', 'host_id', 'host_id') && $this->createTables(['plugin_pfs_summary' => self::tables()['plugin_pfs_summary']]), + // The created-device record moves from one size-limited setting + // to its own table. A fresh install has the table from + // migration 1 and no setting to move. + 3 => fn (): bool => $this->createTables([CreatedDeviceRepository::TABLE => self::tables()[CreatedDeviceRepository::TABLE]]) + && (new CreatedDeviceRepository($this->connection))->importLegacy(time()), ]; } @@ -356,6 +381,16 @@ public static function tables(): array { ], 'primary' => 'poller_id', ], + // One row per device DeviceProvisioner::create() made, for the + // optional delete on uninstall (REQ-LIFE-005). + CreatedDeviceRepository::TABLE => $innodb + [ + 'comment' => 'Devices the parallel filesystem plugin created', + 'columns' => [ + $id('host_id'), + $time('created_at'), + ], + 'primary' => 'host_id', + ], ]; } } diff --git a/lib/Settings.php b/lib/Settings.php index 73d9f85..c6555ba 100644 --- a/lib/Settings.php +++ b/lib/Settings.php @@ -35,6 +35,7 @@ 'pfs_reader_budget', 'pfs_concurrency', 'pfs_uninstall_keep_tables', + 'pfs_uninstall_delete_devices', ]; public const DEFAULT_SSH = '/usr/bin/ssh'; @@ -56,6 +57,7 @@ public function __construct( public int $readerBudget, public int $concurrency, public bool $keepTablesOnUninstall, + public bool $deleteDevicesOnUninstall = false, ) { } @@ -63,7 +65,8 @@ public function __construct( * A setting that was never saved reads as its default, and an out of * range number as its default or its bound. Keeping tables is the * default, so an uninstall drops the registry only after an - * administrator cleared the box (REQ-LIFE-005). + * administrator cleared the box (REQ-LIFE-005). Deleting the devices the + * plugin created is off unless an administrator checked it. * * @param array $row setting name => stored value, absent when never saved */ @@ -78,6 +81,7 @@ public static function fromRow(array $row): self { readerBudget: min(Row::int($row, 'pfs_reader_budget', self::DEFAULT_BUDGET, 10), 3600), concurrency: min(Row::int($row, 'pfs_concurrency', self::DEFAULT_CONCURRENCY, 1), 64), keepTablesOnUninstall: array_key_exists('pfs_uninstall_keep_tables', $row) ? Row::bool($row, 'pfs_uninstall_keep_tables') : true, + deleteDevicesOnUninstall: array_key_exists('pfs_uninstall_delete_devices', $row) && Row::bool($row, 'pfs_uninstall_delete_devices'), ); } @@ -150,6 +154,12 @@ public static function form(): array { 'method' => 'checkbox', 'default' => 'on', ], + 'pfs_uninstall_delete_devices' => [ + 'friendly_name' => __('Delete the Devices This Plugin Created on Uninstall', 'pfs'), + 'description' => __('When checked, uninstalling the plugin deletes the devices it created for filesystems, with their graphs and data sources, as deleting them in Cacti would. Existing devices that were mapped to a filesystem are never deleted. RRD files are removed only if Cacti\'s own RRD cleanup setting removes them. Cleared, the devices stay.', 'pfs'), + 'method' => 'checkbox', + 'default' => '', + ], ]; } } diff --git a/lib/Summary.php b/lib/Summary.php index 07783f4..54e6696 100644 --- a/lib/Summary.php +++ b/lib/Summary.php @@ -22,8 +22,9 @@ /** * One filesystem's summary as the reader last computed it: the values the * "Parallel Filesystem Summary" data source serves, the member set behind - * each aggregate counter, and the time of the oldest observation that - * contributed. A null value is unknown. + * each aggregate counter, the read time each aggregate counter was summed + * at, and the time of the oldest observation that contributed. A null value + * is unknown. */ final readonly class Summary { /** Gauges: levels, percentages, and counts. */ @@ -37,18 +38,29 @@ /** Aggregate cumulative counters, stored as DERIVE. */ public const COUNTERS = ['read_bytes', 'write_bytes', 'md_ops']; + /** + * Per-second rates of the aggregate counters, computed by the reader and + * stored as GAUGE, so Thold can threshold a rate without seeing a counter + * (ADR 0012). Each is the counter's name plus RATE_SUFFIX. + */ + public const RATES = ['read_bytes_rate', 'write_bytes_rate', 'md_ops_rate']; + + public const RATE_SUFFIX = '_rate'; + /** Computed when the data source is polled, from observedAt. */ public const AGE = 'age'; /** - * @param array $values metric => value, for every name in GAUGES and COUNTERS - * @param array $members counter => hash of the targets (and operations) summed + * @param array $values metric => value, for every name in GAUGES, COUNTERS, and RATES + * @param array $members counter => hash of the targets (and operations) summed + * @param array $counterAt counter => the read time every summed value shares, 0 when the sum is unknown or its values were read at different times */ public function __construct( public array $values, public array $members, public int $observedAt, public int $computedAt, + public array $counterAt = [], ) { } @@ -56,10 +68,15 @@ public function __construct( * @return list every value name the data source returns, in order */ public static function names(): array { - return array_merge(self::GAUGES, self::COUNTERS, [self::AGE]); + return array_merge(self::GAUGES, self::COUNTERS, self::RATES, [self::AGE]); } public function value(string $metric): ?float { return $this->values[$metric] ?? null; } + + /** The counter a rate is computed from, or null when $metric is not a rate. */ + public static function counterOf(string $metric): ?string { + return in_array($metric, self::RATES, true) ? substr($metric, 0, -strlen(self::RATE_SUFFIX)) : null; + } } diff --git a/lib/SummaryCalculator.php b/lib/SummaryCalculator.php index 0903257..3c1de66 100644 --- a/lib/SummaryCalculator.php +++ b/lib/SummaryCalculator.php @@ -43,6 +43,18 @@ * change publishes unknown for that run. If Cacti misses the poll of that * unknown value the change is still drawn as one large interval; that is the * sampling alignment limit in the plan. + * + * Each aggregate counter also has a per-second rate, published as a gauge + * for Thold (ADR 0012): the change in the sum since the previous summary, + * over the time between the two reads. A rate is known only when both sums + * are known, have the same member set, were each read in one run (every + * summed value shares its read time), are at most two intervals apart, and + * the sum did not go down. So a reset, a missing or stale target, a member + * change, and the first read all give unknown, as the DERIVE value does. A + * reset of some targets gives three unknown runs: the reset leaves them out + * of the sum, the next run puts them back (a member change), and the run + * after that has no known previous sum. When every target resets at once + * the sum has no members to compare, so it is two. */ final class SummaryCalculator { private const OST_COUNTERS = ['read_bytes', 'write_bytes']; @@ -107,7 +119,7 @@ public static function calculate(array $targets, ?Summary $previous, int $interv } } - $values = array_fill_keys(array_merge(Summary::GAUGES, Summary::COUNTERS), null); + $values = array_fill_keys(array_merge(Summary::GAUGES, Summary::COUNTERS, Summary::RATES), null); if ($fill !== []) { $values['fill_max_pct'] = max($fill); @@ -135,6 +147,7 @@ public static function calculate(array $targets, ?Summary $previous, int $interv } $members = []; + $at = []; $summed = PHP_INT_MAX; // ost_contributors counts the OSTs behind every OST counter, so it @@ -144,6 +157,7 @@ public static function calculate(array $targets, ?Summary $previous, int $interv $summed = min($summed, $sum['contributors']); [$values[$counter], $members[$counter]] = self::guard($sum, $previous?->members[$counter] ?? null); + $at[$counter] = $values[$counter] === null ? 0 : (int) $sum['at']; } $values['ost_contributors'] = (float) $summed; @@ -161,8 +175,13 @@ public static function calculate(array $targets, ?Summary $previous, int $interv $sum = self::sum($mdts, array_keys($mdOps), $current); $values['mdt_contributors'] = (float) $sum['contributors']; [$values['md_ops'], $members['md_ops']] = self::guard($sum, $previous?->members['md_ops'] ?? null); + $at['md_ops'] = $values['md_ops'] === null ? 0 : (int) $sum['at']; + + foreach (Summary::COUNTERS as $counter) { + $values[$counter . Summary::RATE_SUFFIX] = self::rate($counter, $values[$counter], $members[$counter], $at[$counter], $previous, $interval); + } - return new Summary($values, $members, $oldest, $now); + return new Summary($values, $members, $oldest, $now, $at); } /** @@ -175,13 +194,14 @@ public static function calculate(array $targets, ?Summary $previous, int $interv * @param list $metrics * @param \Closure(?Observation): bool $current * - * @return array{value: ?float, members: list, contributors: int} + * @return array{value: ?float, members: list, contributors: int, at: int} at is the read time every summed value shares, or 0 */ private static function sum(array $targets, array $metrics, \Closure $current): array { $total = 0.0; $members = []; $contributors = 0; $complete = $targets !== []; + $times = []; foreach ($targets as $target) { $counted = false; @@ -196,6 +216,7 @@ private static function sum(array $targets, array $metrics, \Closure $current): $total += $value; $members[] = $target->id->name() . ':' . $metric; + $times[$observation->observedAt] = true; $counted = true; } @@ -218,7 +239,7 @@ private static function sum(array $targets, array $metrics, \Closure $current): sort($members); - return ['value' => $complete ? $total : null, 'members' => $members, 'contributors' => $contributors]; + return ['value' => $complete ? $total : null, 'members' => $members, 'contributors' => $contributors, 'at' => count($times) === 1 ? (int) array_key_first($times) : 0]; } /** @@ -247,7 +268,28 @@ private static function absentAsZero(SummaryTarget $target, ?Observation $observ } /** - * @param array{value: ?float, members: list, contributors: int} $sum + * The per-second rate of one aggregate counter since the previous summary, + * or null when it cannot be trusted (see the class comment). + */ + private static function rate(string $counter, ?float $value, string $members, int $at, ?Summary $previous, int $interval): ?float { + $before = $previous?->value($counter); + $beforeAt = $previous?->counterAt[$counter] ?? 0; + + if ($value === null || $before === null || $at <= 0 || $beforeAt <= 0 || $members === '' || ($previous?->members[$counter] ?? '') !== $members) { + return null; + } + + $elapsed = $at - $beforeAt; + + if ($elapsed <= 0 || $elapsed > 2 * $interval || $value < $before) { + return null; + } + + return ($value - $before) / $elapsed; + } + + /** + * @param array{value: ?float, members: list, contributors: int, at: int} $sum * * @return array{0: ?float, 1: string} the value to publish and the member hash to keep */ diff --git a/lib/SummaryRepository.php b/lib/SummaryRepository.php index b29ad74..a585883 100644 --- a/lib/SummaryRepository.php +++ b/lib/SummaryRepository.php @@ -22,7 +22,9 @@ /** * Reads the summary the reader stored per filesystem. The reader writes it * through CacheRepository, in the same transaction as the observations it - * was computed from. + * was computed from. A rate row's observed_at holds the read time its + * counter was summed at (Summary::$counterAt); every other row's holds the + * summary's oldest observation. */ final class SummaryRepository { public function __construct(private readonly \PDO|false $connection) { @@ -35,9 +37,10 @@ public function find(int $filesystemId): ?Summary { return null; } - $known = array_merge(Summary::GAUGES, Summary::COUNTERS); + $known = array_merge(Summary::GAUGES, Summary::COUNTERS, Summary::RATES); $values = array_fill_keys($known, null); $members = []; + $at = []; $observed = 0; $computed = 0; @@ -49,8 +52,16 @@ public function find(int $filesystemId): ?Summary { } $values[$metric] = Row::float($row, 'value'); - $observed = Row::int($row, 'observed_at', 0, 0); $computed = Row::int($row, 'computed_at', 0, 0); + $counter = Summary::counterOf($metric); + + if ($counter !== null) { + $at[$counter] = Row::int($row, 'observed_at', 0, 0); + + continue; + } + + $observed = Row::int($row, 'observed_at', 0, 0); $hash = Row::string($row, 'members'); @@ -59,6 +70,6 @@ public function find(int $filesystemId): ?Summary { } } - return new Summary($values, $members, $observed, $computed); + return new Summary($values, $members, $observed, $computed, $at); } } diff --git a/lib/SummaryScript.php b/lib/SummaryScript.php index e97be96..6eef21d 100644 --- a/lib/SummaryScript.php +++ b/lib/SummaryScript.php @@ -25,8 +25,11 @@ * the reader stored. Nothing here contacts a node. * * Gauges are served while the summary's oldest contributing observation is - * current or delayed, counters only while it is current (ADR 0012), and age - * whenever anything was ever observed. + * current or delayed, counters and their rates only while it is current + * (ADR 0012), and age whenever anything was ever observed. A rate is also + * served only while the counter it comes from was read recently enough to + * be current: that read can trail the capacity read the summary time is + * taken from. */ final class SummaryScript { public function __construct( @@ -56,6 +59,12 @@ public static function format(?Summary $summary, int $interval, Clock $clock): s $pairs[] = $name . ':' . ($freshness === Freshness::Current ? Number::format($summary?->value($name)) : 'U'); } + foreach (Summary::COUNTERS as $counter) { + $read = (new FreshnessEvaluator($clock))->evaluate($summary?->counterAt[$counter] ?? 0, $interval); + $served = $freshness === Freshness::Current && $read === Freshness::Current; + $pairs[] = $counter . Summary::RATE_SUFFIX . ':' . ($served ? Number::format($summary?->value($counter . Summary::RATE_SUFFIX)) : 'U'); + } + $age = $summary === null || $summary->observedAt <= 0 ? null : (float) max(0, $clock->now() - $summary->observedAt); $pairs[] = Summary::AGE . ':' . Number::format($age); diff --git a/locales/po/cacti.pot b/locales/po/cacti.pot index bb49d1a..02f4333 100644 --- a/locales/po/cacti.pot +++ b/locales/po/cacti.pot @@ -679,6 +679,14 @@ msgstr "" msgid "When checked, uninstalling the plugin keeps its filesystems, nodes, inventory, and cache. Clear it to have the uninstall drop them; export the registry first from the Parallel Filesystem Admin page. Storage nodes are never contacted either way." msgstr "" +#: lib/Settings.php +msgid "Delete the Devices This Plugin Created on Uninstall" +msgstr "" + +#: lib/Settings.php +msgid "When checked, uninstalling the plugin deletes the devices it created for filesystems, with their graphs and data sources, as deleting them in Cacti would. Existing devices that were mapped to a filesystem are never deleted. RRD files are removed only if Cacti's own RRD cleanup setting removes them. Cleared, the devices stay." +msgstr "" + #: lib/TargetsPage.php msgid "No filesystem is visible to you." msgstr "" diff --git a/setup.php b/setup.php index b7de4d7..75aaa9f 100644 --- a/setup.php +++ b/setup.php @@ -207,7 +207,9 @@ function pfs_provisioner(): \Somethingwithproof\Pfs\DeviceProvisioner { new \Somethingwithproof\Pfs\TargetRepository(false), new \Somethingwithproof\Pfs\CactiObjectRepository(false), \Somethingwithproof\Pfs\BackendRegistry::production(), - $config['base_path'] + $config['base_path'], + new \Somethingwithproof\Pfs\CreatedDeviceRepository(false), + $clock ); } @@ -273,10 +275,51 @@ function plugin_pfs_uninstall(): void { return; } - $schema = new \Somethingwithproof\Pfs\Schema(false); + $schema = new \Somethingwithproof\Pfs\Schema(false); + $objects = new \Somethingwithproof\Pfs\CactiObjectRepository(false); + $record = new \Somethingwithproof\Pfs\CreatedDeviceRepository(false); + + // Code replaced without the upgrade being run still has the record in + // its old place; finish the pending migrations first, which never + // contact a node. + if ($schema->storedVersion() > 0 && $schema->storedVersion() < \Somethingwithproof\Pfs\Schema::VERSION) { + if (!$schema->migrate()) { + throw new \RuntimeException('Uninstall stopped because the created-device record could not be migrated.'); + } + } + + // A remotely deleted Cacti device can remain as a soft-deleted host row. + // Clear its mapping even when uninstall was not asked to delete devices. + $filesystemRepository = new \Somethingwithproof\Pfs\FilesystemRepository( + false, + new \Somethingwithproof\Pfs\SystemClock() + ); + $removedHosts = array_values(array_filter( + $filesystemRepository->mappedHostIds(), + static fn (int $id): bool => $objects->deviceRemoved($id) + )); + $filesystemRepository->unmapHosts($removedHosts); + + // Forget ownership only after mappings for confirmed-removed devices clear. + $removedCreated = array_values(array_filter($record->ids(), static fn (int $id): bool => $objects->deviceRemoved($id))); + $record->forget($removedCreated); + + if (pfs_settings()->deleteDevicesOnUninstall) { + $created = $record->ids(); + + pfs_uninstall_devices($created); + $created = array_values(array_filter($created, static fn (int $id): bool => $objects->deviceRemoved($id))); + + // Core runs no hook of a disabled plugin, so device_remove did not + // clear the mapping or the record; kept tables must not point at a + // deleted device. + $filesystemRepository->unmapHosts($created); + $record->forget($created); + } // Removes only the query files the plugin wrote and nobody changed. The - // templates, devices, data sources, and graphs stay: they are the site's. + // templates stay, and so do devices unless deleted above: they are the + // site's. pfs_template_installer()->uninstall(); if (pfs_settings()->keepTablesOnUninstall) { @@ -284,10 +327,40 @@ function plugin_pfs_uninstall(): void { \Somethingwithproof\Pfs\Log::info('Uninstall kept the plugin tables as configured'); } else { + if ($schema->keepCreatedDevices()) { + \Somethingwithproof\Pfs\Log::info('Uninstall dropped the plugin tables but kept the record of the devices the plugin created, which are still in Cacti'); + } + $schema->forgetVersion(); } } +/** + * Delete the devices the plugin created, through Cacti's own device delete + * with their graphs and data sources (delete type 2, as the Devices page + * offers). Cacti's RRD cleanup setting decides what happens to the RRD + * files. The callers pass only recorded ids that still name a device, and + * unmap and forget them after. Shared with the unbooted uninstall, so PHP + * 8.0 syntax (REQ-LIFE-005). + * + * @param list $hostIds existing devices recorded as created by the plugin + */ +function pfs_uninstall_devices(array $hostIds): void { + global $config; + + if ($hostIds === array()) { + return; + } + + include_once($config['base_path'] . '/lib/api_device.php'); + include_once($config['base_path'] . '/lib/api_data_source.php'); + include_once($config['base_path'] . '/lib/api_graph.php'); + + api_device_remove_multi($hostIds, 2); + + cacti_log(sprintf('NOTE: Uninstall deleted the %d devices the plugin created, as configured', count($hostIds)), false, 'PFS'); +} + function pfs_config_arrays(): void { global $menu; @@ -349,6 +422,8 @@ function pfs_device_remove($hostIds) { } $count = (new \Somethingwithproof\Pfs\FilesystemRepository(false, new \Somethingwithproof\Pfs\SystemClock()))->unmapHosts($ids); + // Core invokes this hook before deleting the host. Keep ownership + // until uninstall can confirm deletion, including a remote soft delete. if ($count > 0) { \Somethingwithproof\Pfs\Log::info(sprintf('%d filesystems lost their device when it was deleted; they can be given a device again from the registry', $count)); diff --git a/templates/pfs-templates.xml b/templates/pfs-templates.xml index 54dfbc5..dd40e17 100644 --- a/templates/pfs-templates.xml +++ b/templates/pfs-templates.xml @@ -1025,6 +1025,44 @@ 9 + + 11 + hash_080103426ddd3cec3ded763ea9b37b9b285aa6 + 0 + FF + 1 + 0 + 0 + + + hash_0601030f36be6854f815e687c278a297bedeec + + Read rate for alerts: + on + 0.00 + + + 10 + + + 11 + hash_0801038a2e20b641a473fc4b92be12c03fc962 + 0 + FF + 1 + 0 + 0 + + + hash_0601030f36be6854f815e687c278a297bedeec + + Write rate for alerts: + on + 0.00 + + + 11 + @@ -1197,6 +1235,25 @@ 5 + + 11 + hash_080103b674258c1b25b19dbf6c8728e3aae8fd + 0 + FF + 1 + 0 + 0 + + + hash_0601030f36be6854f815e687c278a297bedeec + + Operation rate for alerts: + on + 0.00 + + + 6 + @@ -3133,6 +3190,30 @@ 600 hash_070103fe67b7068f994ce92887cb46a5f7f0b4 + + read_bytes_rate + 0 + 10000000000000 + 1 + 600 + hash_070103663255a79f78c239de7dd100839a5199 + + + write_bytes_rate + 0 + 10000000000000 + 1 + 600 + hash_07010370659696e06092b54686a97c11bc4543 + + + md_ops_rate + 0 + 1000000000 + 1 + 600 + hash_070103c042d8cf812b79b0fe0175d920996803 + age 0 @@ -3769,6 +3850,33 @@ out md_ops + + Read bytes rate + on + + + + out + read_bytes_rate + + + Write bytes rate + on + + + + out + write_bytes_rate + + + Md ops rate + on + + + + out + md_ops_rate + Age on diff --git a/tests/Integration/LifecycleTest.php b/tests/Integration/LifecycleTest.php index ce1e6a6..177a48a 100644 --- a/tests/Integration/LifecycleTest.php +++ b/tests/Integration/LifecycleTest.php @@ -21,6 +21,7 @@ define('PFS_VERSION', (string) (parse_ini_file(dirname(__DIR__, 2) . '/INFO', true)['info']['version'] ?? '')); const PFS_TABLES = [ + 'plugin_pfs_created_devices', 'plugin_pfs_filesystem', 'plugin_pfs_network', 'plugin_pfs_node', @@ -48,7 +49,7 @@ expect($state['plugin']['status'])->toEqual('4') ->and($state['plugin']['version'])->toEqual(PFS_VERSION) - ->and($state['schema'])->toEqual('2') + ->and($state['schema'])->toEqual('3') ->and(array_keys($state['tables']))->toBe(PFS_TABLES) ->and($state['tracked'])->toBe(PFS_TABLES) ->and(array_keys($state['hooks']))->toBe(PFS_HOOKS) @@ -117,7 +118,7 @@ expect($state['result'])->toBeTrue() ->and(array_keys($state['tables']))->toBe(PFS_TABLES) ->and($state['tables']['plugin_pfs_filesystem'])->toBe(1) - ->and($state['schema'])->toEqual('2') + ->and($state['schema'])->toEqual('3') ->and($state['plugin']['version'])->toEqual(PFS_VERSION); }); @@ -134,7 +135,7 @@ $state = lifecycle('upgrade'); expect($state['result'])->toBeTrue() - ->and($state['schema'])->toEqual('2') + ->and($state['schema'])->toEqual('3') ->and($state['host_column'])->toBeTrue() ->and(array_keys($state['tables']))->toBe(PFS_TABLES) ->and($state['tables']['plugin_pfs_filesystem'])->toBe(1); @@ -148,7 +149,7 @@ expect($stopped['result'])->toBeTrue() ->and($stopped['schema'])->toEqual('0'); - expect(lifecycle('upgrade')['schema'])->toEqual('2'); + expect(lifecycle('upgrade')['schema'])->toEqual('3'); }); it('refuses a schema newer than the code and leaves the recorded version alone', function () { @@ -204,6 +205,94 @@ ->and($dropped['schema'])->toBeEmpty(); }); +it('keeps every device on uninstall unless asked to delete the ones it created', function () { + lifecycle('install'); + + $made = lifecycle('devices'); + $created = (string) $made['result']['created']; + $mapped = (string) $made['result']['existing']; + + expect((int) $created)->toBeGreaterThan(0) + ->and($made['created_devices'])->toBe('[' . $created . ']') + ->and($made['devices'][$created]['graph_local'])->toBe(5) + ->and($made['devices'][$mapped]['graph_local'])->toBe(5); + + $kept = lifecycle('uninstall'); + + expect($kept['devices'])->toBe($made['devices']) + ->and($kept['created_devices'])->toBe('[' . $created . ']') + ->and($kept['filesystem_hosts'])->toBe(['made' => (int) $created, 'mapped' => (int) $mapped]); +}); + +it('deletes only the devices it created, with their graphs and data sources, when the box was checked', function () { + lifecycle('install'); + + $made = lifecycle('devices'); + $created = (string) $made['result']['created']; + $mapped = (string) $made['result']['existing']; + + lifecycle('set_setting', 'pfs_uninstall_delete_devices=on'); + + $after = lifecycle('uninstall'); + + expect(array_keys($after['devices']))->toBe([(int) $mapped]) + ->and($after['devices'][$mapped])->toBe($made['devices'][$mapped]) + ->and($after['created_devices'])->toBe('[]') + ->and($after['filesystem_hosts'])->toBe(['made' => 0, 'mapped' => (int) $mapped]) + ->and($after['tables']['plugin_pfs_filesystem'])->toBe(2); +}); + +it('deletes only the devices it created on uninstall when the runtime is refused', function () { + lifecycle('install'); + + $made = lifecycle('devices'); + $mapped = (string) $made['result']['existing']; + + lifecycle('set_setting', 'pfs_uninstall_delete_devices=on'); + + $after = lifecycle('uninstall_unbooted'); + + expect(array_keys($after['devices']))->toBe([(int) $mapped]) + ->and($after['created_devices'])->toBe('[]') + ->and($after['filesystem_hosts'])->toBe(['made' => 0, 'mapped' => (int) $mapped]); +}); + +it('keeps the record of devices it created through an uninstall that drops the other tables', function () { + lifecycle('install'); + + $made = lifecycle('devices'); + $created = (string) $made['result']['created']; + + lifecycle('set_setting', 'pfs_uninstall_keep_tables='); + + $dropped = lifecycle('uninstall'); + + // The devices stay in Cacti, so the record of which one the plugin made + // stays too, for a later uninstall asked to delete it. + expect(array_keys($dropped['tables']))->toBe(['plugin_pfs_created_devices']) + ->and($dropped['created_devices'])->toBe('[' . $created . ']') + ->and($dropped['devices'])->toBe($made['devices']); + + $reinstalled = lifecycle('install'); + expect($reinstalled['created_devices'])->toBe('[' . $created . ']') + ->and($reinstalled['tracked'])->toBe(PFS_TABLES); +}); + +it('moves a milestone 4 record of created devices from its setting into the table', function () { + lifecycle('install'); + lifecycle('to_schema_2', '[5, 1234567, "x", -1]'); + + $before = lifecycle('state'); + expect($before['tables'])->not->toHaveKey('plugin_pfs_created_devices') + ->and($before['legacy_created_devices'])->toBe('[5, 1234567, "x", -1]'); + + $state = lifecycle('upgrade'); + expect($state['schema'])->toEqual('3') + ->and($state['created_devices'])->toBe('[5,1234567]') + ->and($state['legacy_created_devices'])->toBe('') + ->and($state['tracked'])->toBe(PFS_TABLES); +}); + it('grants realms on install but never on a repair a viewer triggers', function () { expect(lifecycle('install')['admin'])->toBe(2); diff --git a/tests/Unit/LifecycleUnitTest.php b/tests/Unit/LifecycleUnitTest.php index 6701d7b..a2e6772 100644 --- a/tests/Unit/LifecycleUnitTest.php +++ b/tests/Unit/LifecycleUnitTest.php @@ -17,6 +17,7 @@ * more details. */ +use Somethingwithproof\Pfs\CreatedDeviceRepository; use Somethingwithproof\Pfs\Pages; use Somethingwithproof\Pfs\Schema; use Somethingwithproof\Pfs\Settings; @@ -28,7 +29,62 @@ ->and($settings->sshKeyFile)->toBe(Settings::DEFAULT_KEY_FILE) ->and($settings->readerBudget)->toBe(Settings::DEFAULT_BUDGET) ->and($settings->maxResponseBytes())->toBe(Settings::DEFAULT_MAX_KIB * 1024) - ->and($settings->keepTablesOnUninstall)->toBeTrue(); + ->and($settings->keepTablesOnUninstall)->toBeTrue() + ->and($settings->deleteDevicesOnUninstall)->toBeFalse(); +}); + +it('deletes the plugin\'s devices on uninstall only after the box was checked and saved', function () { + expect(Settings::fromRow(['pfs_uninstall_delete_devices' => ''])->deleteDevicesOnUninstall)->toBeFalse() + ->and(Settings::fromRow(['pfs_uninstall_delete_devices' => 'on'])->deleteDevicesOnUninstall)->toBeTrue() + ->and(Settings::form()['pfs_uninstall_delete_devices']['default'])->toBe(''); +}); + +it('records the devices the plugin created and forgets deleted ones, one row each', function () { + $GLOBALS['__pfs_db_exec'] = []; + $record = new CreatedDeviceRepository(false); + + expect($record->add(7, 100))->toBeTrue() + ->and($record->add(0, 100))->toBeFalse() + ->and($record->forget([7, 0, 7, 99]))->toBeTrue() + ->and($record->forget([]))->toBeTrue(); + + expect($GLOBALS['__pfs_db_exec'])->toBe([ + ['sql' => 'INSERT IGNORE INTO plugin_pfs_created_devices (host_id, created_at) VALUES (?, ?)', 'params' => [7, 100]], + ['sql' => 'DELETE FROM plugin_pfs_created_devices WHERE host_id IN (?, ?)', 'params' => [7, 99]], + ]); + + $GLOBALS['__pfs_db_rows'] = ['FROM plugin_pfs_created_devices' => [['host_id' => 3], ['host_id' => '7'], ['host_id' => 0]]]; + expect($record->ids())->toBe([3, 7]); + $GLOBALS['__pfs_db_rows'] = []; + $GLOBALS['__pfs_db_exec'] = []; +}); + +it('lists mapped Cacti devices for uninstall checks', function () { + $GLOBALS['__pfs_db_rows'] = ['FROM plugin_pfs_filesystem' => [['host_id' => 7], ['host_id' => '7'], ['host_id' => 0]]]; + + try { + $repository = new \Somethingwithproof\Pfs\FilesystemRepository(false, new \Somethingwithproof\Pfs\SystemClock()); + expect($repository->mappedHostIds())->toBe([7]); + } finally { + $GLOBALS['__pfs_db_rows'] = []; + } +}); + +it('keeps mappings intact when an unmap query or write fails', function () { + $GLOBALS['__pfs_db_rows'] = ['FROM plugin_pfs_filesystem' => [['COUNT(*)' => 1]]]; + $repository = new \Somethingwithproof\Pfs\FilesystemRepository(false, new \Somethingwithproof\Pfs\SystemClock()); + + try { + $GLOBALS['__pfs_db_rows']['FROM plugin_pfs_filesystem'] = false; + expect(fn () => $repository->unmapHosts([7]))->toThrow(RuntimeException::class); + + $GLOBALS['__pfs_db_rows']['FROM plugin_pfs_filesystem'] = [['COUNT(*)' => 1]]; + $GLOBALS['__pfs_db_fail'] = ['UPDATE plugin_pfs_filesystem SET host_id = 0']; + expect(fn () => $repository->unmapHosts([7]))->toThrow(RuntimeException::class); + } finally { + $GLOBALS['__pfs_db_rows'] = []; + $GLOBALS['__pfs_db_fail'] = []; + } }); it('drops tables on uninstall only after the box was cleared and saved', function () { @@ -37,6 +93,33 @@ ->and(Settings::fromRow(['pfs_uninstall_keep_tables' => 'on'])->keepTablesOnUninstall)->toBeTrue(); }); +it('keeps device ownership records when a database read fails or legacy JSON is damaged', function () { + $record = new CreatedDeviceRepository(false); + $GLOBALS['__pfs_db_rows'] = ['FROM plugin_pfs_created_devices' => false, 'FROM settings' => false]; + $GLOBALS['__pfs_db_exec'] = []; + + try { + expect($record->hasRecords())->toBeTrue() + ->and($record->importLegacy(100))->toBeFalse(); + $GLOBALS['__pfs_db_rows'] = ['FROM settings' => [['value' => '[123,']]]; + expect($record->importLegacy(100))->toBeFalse() + ->and($GLOBALS['__pfs_db_exec'])->toBe([]); + } finally { + $GLOBALS['__pfs_db_rows'] = []; + $GLOBALS['__pfs_db_exec'] = []; + } +}); + +it('accepts an empty legacy device setting during uninstall', function () { + $GLOBALS['__pfs_db_rows'] = ['FROM settings' => [['value' => '']]]; + try { + expect((new CreatedDeviceRepository(false))->importLegacy(100))->toBeTrue(); + } finally { + $GLOBALS['__pfs_db_rows'] = []; + $GLOBALS['__pfs_db_exec'] = []; + } +}); + it('bounds numeric settings', function (string $name, mixed $stored, string $property, int $expected) { expect(Settings::fromRow([$name => $stored])->{$property})->toBe($expected); })->with([ @@ -121,3 +204,150 @@ expect($metric[0]['type'])->toBe('varchar(19)'); }); + +it('forgets unbooted ownership only after a device is confirmed absent', function () { + require_once dirname(__DIR__, 2) . '/include/unbooted-uninstall.php'; + try { + $GLOBALS['__pfs_db_rows'] = ['FROM host' => [['id' => 7, 'deleted' => '']]]; + expect(pfs_unbooted_removed_devices([7]))->toBe([]); + $GLOBALS['__pfs_db_rows'] = ['FROM host' => [['id' => 7, 'deleted' => 'on']]]; + expect(pfs_unbooted_removed_devices([7]))->toBe([7]); + $GLOBALS['__pfs_db_rows'] = ['FROM host' => []]; + expect(pfs_unbooted_removed_devices([7]))->toBe([7]); + } finally { + $GLOBALS['__pfs_db_rows'] = []; + } +}); + +it('does not treat a failed unbooted host lookup as a removed device', function () { + $GLOBALS['__pfs_db_rows'] = ['FROM host' => false]; + + try { + expect(fn () => pfs_unbooted_removed_devices([7]))->toThrow(RuntimeException::class); + } finally { + $GLOBALS['__pfs_db_rows'] = []; + } +}); + +it('stops unbooted uninstall when ownership metadata or legacy data cannot be read', function () { + require_once dirname(__DIR__, 2) . '/include/unbooted-uninstall.php'; + try { + $GLOBALS['__pfs_db_rows'] = ['information_schema.TABLES' => false]; + expect(fn () => pfs_unbooted_created_devices())->toThrow(RuntimeException::class); + $GLOBALS['__pfs_db_rows'] = ['FROM settings' => [['value' => '[123,']]]; + expect(fn () => pfs_unbooted_created_devices())->toThrow(RuntimeException::class); + $GLOBALS['__pfs_db_rows'] = ['FROM settings' => false]; + expect(fn () => pfs_unbooted_created_devices())->toThrow(RuntimeException::class); + } finally { + $GLOBALS['__pfs_db_rows'] = []; + } +}); + +it('stops uninstall when core would still drop the ownership table', function () { + $GLOBALS['__pfs_db_rows'] = ['FROM plugin_pfs_created_devices' => [[1]]]; + $GLOBALS['__pfs_db_fail'] = ['DELETE FROM plugin_db_changes']; + try { + expect(fn () => (new Schema(false))->keepCreatedDevices())->toThrow(RuntimeException::class); + expect(fn () => (new Schema(false))->untrackTables())->toThrow(RuntimeException::class); + $GLOBALS['__pfs_db_rows']['information_schema.TABLES'] = [[1]]; + $GLOBALS['__pfs_db_rows']['FROM settings'] = [['value' => '']]; + expect(fn () => pfs_uninstall_unbooted())->toThrow(RuntimeException::class); + } finally { + $GLOBALS['__pfs_db_rows'] = []; + $GLOBALS['__pfs_db_fail'] = []; + } +}); + +it('cleans mappings for remote hosts whose deletion is queued by Cacti', function () { + $GLOBALS['__pfs_db_rows'] = ['FROM host' => [['id' => 7, 'deleted' => 'on']]]; + try { + expect((new \Somethingwithproof\Pfs\CactiObjectRepository(false))->deviceRemoved(7))->toBeTrue() + ->and(pfs_unbooted_removed_devices([7]))->toBe([7]); + } finally { + $GLOBALS['__pfs_db_rows'] = []; + } +}); + +it('does not treat a failed Cacti host lookup as a confirmed deletion', function () { + $GLOBALS['__pfs_db_rows'] = ['FROM host' => false]; + + try { + expect(fn () => (new \Somethingwithproof\Pfs\CactiObjectRepository(false))->deviceRemoved(7))->toThrow(RuntimeException::class); + } finally { + $GLOBALS['__pfs_db_rows'] = []; + } +}); + +it('clears mappings for remote hosts soft-deleted while the plugin was disabled', function () { + $GLOBALS['__pfs_db_rows'] = [ + 'information_schema.COLUMNS' => [['has_column' => 1]], + 'FROM plugin_pfs_filesystem' => [['host_id' => 7]], + 'FROM host' => [['id' => 7, 'deleted' => 'on']], + 'information_schema.TABLES' => [], + 'FROM settings' => [], + ]; + $GLOBALS['__pfs_db_exec'] = []; + + try { + pfs_uninstall_unbooted(); + + expect($GLOBALS['__pfs_db_exec'])->toContain([ + 'sql' => 'UPDATE plugin_pfs_filesystem SET host_id = 0 WHERE host_id IN (?)', + 'params' => [7], + ]); + } finally { + $GLOBALS['__pfs_db_rows'] = []; + $GLOBALS['__pfs_db_exec'] = []; + } +}); + +it('stops unbooted uninstall when a filesystem mapping cannot be read', function () { + $GLOBALS['__pfs_db_rows'] = [ + 'information_schema.COLUMNS' => [['has_column' => 1]], + 'FROM plugin_pfs_filesystem' => false, + ]; + $GLOBALS['__pfs_db_exec'] = []; + + try { + expect(fn () => pfs_uninstall_unbooted())->toThrow(RuntimeException::class); + expect($GLOBALS['__pfs_db_exec'])->toBe([]); + } finally { + $GLOBALS['__pfs_db_rows'] = []; + $GLOBALS['__pfs_db_exec'] = []; + } +}); + +it('keeps ownership records when clearing a removed-device mapping fails', function () { + $GLOBALS['__pfs_db_rows'] = [ + 'information_schema.COLUMNS' => [['has_column' => 1]], + 'FROM plugin_pfs_filesystem' => [['host_id' => 7]], + 'FROM host' => [['id' => 7, 'deleted' => 'on']], + 'information_schema.TABLES' => [], + 'FROM settings' => [], + ]; + $GLOBALS['__pfs_db_exec'] = []; + $GLOBALS['__pfs_db_fail'] = ['UPDATE plugin_pfs_filesystem SET host_id = 0']; + + try { + expect(fn () => pfs_uninstall_unbooted())->toThrow(RuntimeException::class); + expect(array_column($GLOBALS['__pfs_db_exec'], 'sql'))->not->toContain('DELETE FROM plugin_pfs_created_devices WHERE host_id NOT IN (SELECT id FROM host)'); + } finally { + $GLOBALS['__pfs_db_rows'] = []; + $GLOBALS['__pfs_db_exec'] = []; + $GLOBALS['__pfs_db_fail'] = []; + } +}); + +it('waits for a reader process that has not registered in Cacti yet', function () { + require_once dirname(__DIR__) . '/bin/reader-idle.php'; + $GLOBALS['__pfs_db_rows'] = []; + $process = proc_open([PHP_BINARY, '-r', 'usleep(5000000);', 'poller_pfs.php'], [['pipe', 'r'], ['file', '/dev/null', 'w'], ['file', '/dev/null', 'w']], $pipes); + expect(is_resource($process))->toBeTrue(); + try { + expect(pfs_reader_idle())->toBeFalse(); + } finally { + proc_terminate($process); + fclose($pipes[0]); + proc_close($process); + } +}); diff --git a/tests/Unit/SummaryTest.php b/tests/Unit/SummaryTest.php index 35cc34e..849cd33 100644 --- a/tests/Unit/SummaryTest.php +++ b/tests/Unit/SummaryTest.php @@ -255,6 +255,94 @@ function sum_ost(string $name, float $used, float $read = 1000.0, float $write = }); }); +describe('rates', function () { + /** + * Two OSTs and one MDT read at $at; $add is added to every counter. + * + * @return list + */ + $fs = fn (int $at, float $add = 0.0, array $reset = []): array => [ + sum_target('scratch-OST0000', sum_ost('scratch-OST0000', 200.0, 1000.0 + $add, 500.0 + $add), $at, Presence::Present, Condition::InService, $reset), + sum_target('scratch-OST0001', sum_ost('scratch-OST0001', 400.0, 1000.0 + $add, 500.0 + $add), $at), + sum_target('scratch-MDT0000', ['kbytes_total' => 100.0, 'kbytes_free' => 50.0, 'kbytes_avail' => 50.0, 'md_open' => 7.0 + $add, 'md_close' => 3.0], $at), + ]; + + it('are the change in each sum over the time between the two reads', function () use ($fs) { + $first = SummaryCalculator::calculate($fs(SUM_T), null, 300, SUM_T); + $second = SummaryCalculator::calculate($fs(SUM_T + 300, 3000.0), $first, 300, SUM_T + 300); + + expect($first->value('read_bytes_rate'))->toBeNull() + ->and($first->counterAt)->toBe(['read_bytes' => SUM_T, 'write_bytes' => SUM_T, 'md_ops' => SUM_T]) + ->and($second->value('read_bytes_rate'))->toBe(20.0) + ->and($second->value('write_bytes_rate'))->toBe(20.0) + ->and($second->value('md_ops_rate'))->toBe(10.0); + }); + + it('are unknown for the three runs a reset makes the sum unknown or unmatched, then resume', function () use ($fs) { + // The reset run leaves the target out of the sum, the next run puts + // it back (a member change), and the run after has no known previous + // sum; the fourth has a rate again. + $runs = [SummaryCalculator::calculate($fs(SUM_T), null, 300, SUM_T)]; + + foreach ([1, 2, 3, 4] as $i) { + $runs[] = SummaryCalculator::calculate($fs(SUM_T + 300 * $i, 3000.0 * $i, $i === 1 ? ['read_bytes'] : []), $runs[$i - 1], 300, SUM_T + 300 * $i); + } + + expect(array_map(static fn (Summary $s): ?float => $s->value('read_bytes'), $runs))->toBe([2000.0, null, null, 20000.0, 26000.0]) + ->and(array_map(static fn (Summary $s): ?float => $s->value('read_bytes_rate'), $runs))->toBe([null, null, null, null, 20.0]) + ->and($runs[1]->value('write_bytes_rate'))->toBe(20.0); + }); + + it('are unknown for two runs when every summed target resets at once', function () { + $osts = fn (int $i, bool $reset): array => [ + sum_target('scratch-OST0000', sum_ost('scratch-OST0000', 200.0, 1000.0 + 3000.0 * $i), SUM_T + 300 * $i, Presence::Present, Condition::InService, $reset ? ['read_bytes'] : []), + sum_target('scratch-OST0001', sum_ost('scratch-OST0001', 400.0, 1000.0 + 3000.0 * $i), SUM_T + 300 * $i, Presence::Present, Condition::InService, $reset ? ['read_bytes'] : []), + ]; + $runs = [SummaryCalculator::calculate($osts(0, false), null, 300, SUM_T)]; + + foreach ([1, 2, 3] as $i) { + $runs[] = SummaryCalculator::calculate($osts($i, $i === 1), $runs[$i - 1], 300, SUM_T + 300 * $i); + } + + expect(array_map(static fn (Summary $s): ?float => $s->value('read_bytes_rate'), $runs))->toBe([null, null, null, 20.0]); + }); + + it('are unknown when the member set changes, the previous read is too old, or the sum went down', function () use ($fs) { + $first = SummaryCalculator::calculate($fs(SUM_T), null, 300, SUM_T); + $joined = SummaryCalculator::calculate(array_merge($fs(SUM_T + 300, 3000.0), [sum_target('scratch-OST0002', sum_ost('scratch-OST0002', 100.0), SUM_T + 300)]), $first, 300, SUM_T + 300); + $late = SummaryCalculator::calculate($fs(SUM_T + 601, 3000.0), $first, 300, SUM_T + 601); + $dropped = SummaryCalculator::calculate($fs(SUM_T + 300, -100.0), $first, 300, SUM_T + 300); + + expect($joined->value('read_bytes_rate'))->toBeNull() + ->and($late->value('read_bytes_rate'))->toBeNull() + ->and($late->value('md_ops_rate'))->toBeNull() + ->and($dropped->value('read_bytes_rate'))->toBeNull(); + }); + + it('are unknown when the summed values were read at different times', function () { + $first = SummaryCalculator::calculate([ + sum_target('scratch-OST0000', sum_ost('scratch-OST0000', 200.0), SUM_T), + sum_target('scratch-OST0001', sum_ost('scratch-OST0001', 400.0), SUM_T), + ], null, 300, SUM_T); + $second = SummaryCalculator::calculate([ + sum_target('scratch-OST0000', sum_ost('scratch-OST0000', 200.0, 4000.0), SUM_T + 300), + sum_target('scratch-OST0001', sum_ost('scratch-OST0001', 400.0, 4000.0), SUM_T + 200), + ], $first, 300, SUM_T + 300); + + expect($second->value('read_bytes'))->toBe(8000.0) + ->and($second->counterAt['read_bytes'])->toBe(0) + ->and($second->value('read_bytes_rate'))->toBeNull(); + }); + + it('are served only while the summary is current', function () use ($fs) { + $first = SummaryCalculator::calculate($fs(SUM_T), null, 300, SUM_T); + $second = SummaryCalculator::calculate($fs(SUM_T + 300, 3000.0), $first, 300, SUM_T + 300); + + expect(SummaryScript::format($second, 300, new FixedClock(SUM_T + 310)))->toContain('read_bytes_rate:20')->toContain('md_ops_rate:10') + ->and(SummaryScript::format($second, 300, new FixedClock(SUM_T + 900)))->toContain('read_bytes_rate:U')->toContain('fill_max_pct:40'); + }); +}); + describe('summary input', function () { $summary = fn (int $at): Summary => SummaryCalculator::calculate([sum_target('scratch-OST0000', sum_ost('scratch-OST0000', 200.0), $at)], null, 300, $at); @@ -267,7 +355,7 @@ function sum_ost(string $name, float $used, float $read = 1000.0, float $write = $pairs[$name] = $value; } - expect(array_keys($pairs))->toBe(array_merge(Summary::GAUGES, Summary::COUNTERS, [Summary::AGE])) + expect(array_keys($pairs))->toBe(array_merge(Summary::GAUGES, Summary::COUNTERS, Summary::RATES, [Summary::AGE])) ->and($pairs['fill_max_pct'])->toBe('20') ->and($pairs['read_bytes'])->toBe('1000') ->and($pairs['age'])->toBe('10'); @@ -283,6 +371,19 @@ function sum_ost(string $name, float $used, float $read = 1000.0, float $write = ->and($never)->toContain('fill_max_pct:U')->toContain('age:U'); }); + it('serves a rate only while the counter it comes from is current, even when capacity is', function () { + $values = array_fill_keys(array_merge(Summary::GAUGES, Summary::COUNTERS, Summary::RATES), 1.0); + $at = ['read_bytes' => SUM_T, 'write_bytes' => SUM_T + 299, 'md_ops' => 0]; + $answer = SummaryScript::format(new Summary($values, [], SUM_T + 299, SUM_T + 299, $at), 300, new FixedClock(SUM_T + 460)); + + // read_bytes was read 460 s ago, past 1.5 intervals, while the + // capacity read the summary time comes from is 161 s old. + expect($answer)->toContain('fill_max_pct:1') + ->and($answer)->toContain('read_bytes_rate:U') + ->and($answer)->toContain('write_bytes_rate:1') + ->and($answer)->toContain('md_ops_rate:U'); + }); + it('keeps every summary name a valid RRD data source name', function () { foreach (Summary::names() as $name) { expect($name)->toMatch('/^[a-zA-Z0-9_]{1,19}$/'); diff --git a/tests/bin/alert-flow.php b/tests/bin/alert-flow.php index 5ade261..f50061e 100644 --- a/tests/bin/alert-flow.php +++ b/tests/bin/alert-flow.php @@ -56,7 +56,7 @@ 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'); +const ALERT_STEPS = array('setup', 'warmup', 'baseline', 'burst', 'burst2', 'rated', 'reset', 'rejoined', 'resumed', 'reburst', 'reburst2', '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. @@ -85,10 +85,10 @@ /** 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), + 'fill_spread_pct' => array('20', 1), + 'targets_missing' => array('0.5', 1), + 'age' => array('30', 1), + 'write_bytes_rate' => array('1000000000', 2), ); function alert_expect($ok, $message) { @@ -106,11 +106,16 @@ function alert_state($name, $value = null) { 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. */ +/** + * Two healthy OSTs at 40 and 45 percent; $write is the per-OST write total. + * Both report the stats start time kept in the state, which the reset step + * changes, as a stats clear or a server restart does. + */ 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), + $start = alert_state('start') === '' ? '1731000000.000000001' : alert_state('start'); + $osts = array( + 0 => array('used' => 40, 'read' => 1000000, 'write' => $write, 'start' => $start), + 1 => array('used' => 45, 'read' => 1000000, 'write' => $write, 'start' => $start), ); foreach ($change as $index => $fields) { @@ -243,6 +248,23 @@ function alert_create_thold($hostId, $name, $hi, $trigger) { return is_numeric($id) ? (int) $id : 0; } +/** 1 TB more per OST within one poll: far above 1 GB/s. */ +function alert_burst() { + return alert_osts(alert_write(1000000000000)); +} + +function alert_breached_once($step) { + $t = alert_thold('write_bytes_rate'); + alert_expect((int) $t['thold_alert'] !== 0 && (int) $t['thold_fail_count'] === 1 && alert_since('write_bytes_rate') === array(), "$step: one poll above the rate threshold breaches it without notifying (fail_count=" . $t['thold_fail_count'] . ', log ' . json_encode(alert_since('write_bytes_rate')) . ')'); +} + +/** After a reset the rate gauge is unknown, Thold logs nothing for it, and stays enabled. */ +function alert_unknown_rate($step) { + $t = alert_thold('write_bytes_rate'); + alert_expect(!is_numeric($t['lastread']) && (int) $t['thold_alert'] === 0 && alert_since('write_bytes_rate') === array(), "$step: the write rate gauge reads unknown after the reset, with no breach or log entry (lastread='" . $t['lastread'] . "', alert=" . $t['thold_alert'] . ', log ' . json_encode(alert_since('write_bytes_rate')) . ')'); + alert_expect(api_plugin_is_enabled('thold'), "$step: Thold is still enabled"); +} + function alert_rrd($localDataId, $name) { $path = get_data_source_path($localDataId, true); $out = (string) shell_exec('rrdtool lastupdate ' . escapeshellarg($path) . ' 2>&1'); @@ -311,38 +333,52 @@ function alert_rrd($localDataId, $name) { 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))); + alert_expect(is_numeric(alert_thold('write_bytes_rate')['lastread']), 'baseline: Thold reads the write rate gauge as a number'); + alert_read(alert_burst()); 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))); + case 'reburst': + alert_breached_once($step); + alert_read(alert_burst()); break; case 'burst2': - alert_check($step, 'write_bytes', true, array(ALERT_NOTIFY)); + case 'reburst2': + alert_check($step, 'write_bytes_rate', 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_check($step, 'write_bytes_rate', false, array(ALERT_RESTORE)); + + // Both OSTs report a new stats start time and counters near zero: + // a counter reset. A Thold threshold on the DERIVE write_bytes + // would see U here and fail on the next number (docs/alerting.md); + // the gauge is U for two polls and Thold carries on. (With every + // OST reset at once the run after the reset sums the same members + // again, so it is two unknown polls here, not the three of a + // single target's reset.) + alert_state('start', '1731700000.000000001'); + alert_state('write', 0); + alert_read(alert_osts(alert_write())); + + break; + case 'reset': + case 'rejoined': + alert_unknown_rate($step); alert_read(alert_osts(alert_write())); + break; + case 'resumed': + alert_check($step, 'write_bytes_rate', false, array()); + alert_expect(is_numeric(alert_thold('write_bytes_rate')['lastread']), 'resumed: the write rate gauge is a number again after the reset'); + alert_read(alert_burst()); + break; case 'calm': + alert_check($step, 'write_bytes_rate', false, array(ALERT_RESTORE)); 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)))); diff --git a/tests/bin/alert-replay.sh b/tests/bin/alert-replay.sh index 8ad40a2..17952cb 100644 --- a/tests/bin/alert-replay.sh +++ b/tests/bin/alert-replay.sh @@ -52,10 +52,21 @@ for step in $steps; do # 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. + # The background job may not have registered in processes yet when + # poller.php returns, and a foreground run that finds it registered + # exits without checking, so wait for the process itself to end too. + settled=0 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 + busy=0 + for f in /proc/[0-9]*/cmdline; do + case $(tr '\0' ' ' < "$f" 2>/dev/null) in + *poller_thold.php* | *thold_notify.php*) busy=1 ;; + esac + done + [ "$busy" -eq 0 ] && [ "$(php -r 'chdir("."); include("./include/cli_check.php"); print db_fetch_cell("SELECT COUNT(*) FROM processes WHERE tasktype = \"thold\"");')" = 0 ] && { settled=1; break; } sleep 1 done + [ "$settled" -eq 1 ] || { echo "the background Thold check did not finish"; fail=1; } php plugins/thold/poller_thold.php > /tmp/pfs-alert-thold.txt 2>&1 || { fail=1; cat /tmp/pfs-alert-thold.txt; } done diff --git a/tests/bin/build-templates.php b/tests/bin/build-templates.php index 49e3433..300cf85 100644 --- a/tests/bin/build-templates.php +++ b/tests/bin/build-templates.php @@ -31,8 +31,10 @@ * Data source types follow ADR 0005 and ADR 0012: capacity and counts are * GAUGE with minimum 0; cumulative counters are DERIVE with minimum 0 and a * generous maximum that is a plausibility bound, not a reset filter. The - * maximums are stated per second: 100 GB/s per OST, 10 million operations - * per second per target, and 100 times that for filesystem aggregates. + * summary's rates, which the reader computes, are GAUGE with the same bound. + * The maximums are stated per second: 100 GB/s per OST, 10 million + * operations per second per target, and 100 times that for filesystem + * aggregates. */ chdir(dirname(__DIR__, 4)); @@ -298,6 +300,9 @@ function pfs_graph_template($name, $title, $label, $base, array $items, $upper = if (in_array($name, Summary::COUNTERS, true)) { $summaryItems[$name] = array(PFS_DERIVE, $name === 'md_ops' ? PFS_MAX_FS_OPS : PFS_MAX_FS_BYTES, $fieldId); + } elseif (in_array($name, Summary::RATES, true)) { + // The reader's rates, for Thold: gauges with the counters' maximum. + $summaryItems[$name] = array(PFS_GAUGE, $name === 'md_ops_rate' ? PFS_MAX_FS_OPS : PFS_MAX_FS_BYTES, $fieldId); } else { $summaryItems[$name] = array(PFS_GAUGE, substr($name, -4) === '_pct' ? '100' : 'U', $fieldId); } @@ -331,10 +336,15 @@ function pfs_graph_template($name, $title, $label, $base, array $items, $upper = array('rrd' => $s['read_bytes'], 'type' => GRAPH_ITEM_TYPE_LINE2, 'color' => '1E8449', 'text' => 'Read', 'gprint' => $gNum, 'legends' => $last), array('rrd' => $s['write_bytes'], 'type' => GRAPH_ITEM_TYPE_LINE2, 'color' => '2471A3', 'text' => 'Written', 'gprint' => $gNum, 'legends' => $last), array('rrd' => $s['ost_contributors'], 'type' => GRAPH_ITEM_TYPE_GPRINT_LAST, 'text' => 'OSTs summed:', 'gprint' => $gCount), + // The rate gauges Thold thresholds (ADR 0012); printed so Cacti + // stores them. + array('rrd' => $s['read_bytes_rate'], 'type' => GRAPH_ITEM_TYPE_GPRINT_LAST, 'text' => 'Read rate for alerts:', 'gprint' => $gNum), + array('rrd' => $s['write_bytes_rate'], 'type' => GRAPH_ITEM_TYPE_GPRINT_LAST, 'text' => 'Write rate for alerts:', 'gprint' => $gNum), )), pfs_graph_template('Parallel Filesystem Metadata Operations', '|host_description| - Metadata Operations (operations per second)', 'operations per second', 1000, array( array('rrd' => $s['md_ops'], 'type' => GRAPH_ITEM_TYPE_LINE2, 'color' => '7D3C98', 'text' => 'All allowlisted operations', 'gprint' => $gNum, 'legends' => $last), array('rrd' => $s['mdt_contributors'], 'type' => GRAPH_ITEM_TYPE_GPRINT_LAST, 'text' => 'MDTs summed:', 'gprint' => $gCount), + array('rrd' => $s['md_ops_rate'], 'type' => GRAPH_ITEM_TYPE_GPRINT_LAST, 'text' => 'Operation rate for alerts:', 'gprint' => $gNum), )), ); diff --git a/tests/bin/device-flow.php b/tests/bin/device-flow.php index c067dcc..409a419 100644 --- a/tests/bin/device-flow.php +++ b/tests/bin/device-flow.php @@ -50,6 +50,7 @@ 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/reader-idle.php'); // Load the script server functions without running their CLI branch. $called_by_script_server = true; @@ -260,6 +261,14 @@ function flow_rrd($localDataId) { flow_expect(ss_pfs_targets($hostId, 'ost', 'get', 'read_bytes', '../../etc/passwd') === 'U' && ss_pfs_targets($hostId, 'ost', 'get', 'password', 'scratch-OST0000') === 'U' && ss_pfs_targets($hostId, 'mdt', 'get', 'read_bytes', 'scratch-OST0000') === 'U', 'hostile indexes and fields are served as U'); flow_expect(ss_pfs_targets($hostId + 999, 'ost', 'index') === '', 'a device without a filesystem lists no targets'); + // The poll before this phase started a reader in the background. While + // it holds the lease the reset read below would be skipped, so wait, + // bounded by the longest a run can hold the lease. + $bound = pfs_settings()->readerBudget + 60; + flow_expect(pfs_wait_until(function () { + return pfs_reader_idle(1); + }, $bound), "the background reader ended within $bound s before the reset read"); + // The counters go backwards: a reset. The reader marks it and the // script serves U for the counters until the next continuous read. $clock = new FixedClock(time() + 300); diff --git a/tests/bin/failure-flow.php b/tests/bin/failure-flow.php index 251cba5..728c6f8 100644 --- a/tests/bin/failure-flow.php +++ b/tests/bin/failure-flow.php @@ -24,9 +24,18 @@ * 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 + * arm wait for no reader to hold the lease, then choose what + * the stand-in does, make the node due, and record when + * the scenario started * (php plugins/pfs/poller_pfs.php --poller=1 --force, timed) - * check the state the reader recorded for that mode + * settle wait at most s seconds for a reader started elsewhere + * (by poller_bottom) to attempt the node, release the + * lease, and unregister its process + * running + * wait at most s seconds until the reader with that + * process id holds the lease, so it is mid-run + * check the state the reader recorded for that mode, from an + * attempt made after the scenario started * cleanup remove the filesystem and restore the settings * * Modes: ok, unreachable, hostkey, slow, oversized, unframed, dbloss. The @@ -40,6 +49,7 @@ 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'); +require_once($config['base_path'] . '/plugins/pfs/tests/bin/reader-idle.php'); $called_by_script_server = true; require_once($config['base_path'] . '/plugins/pfs/scripts/ss_pfs_targets.php'); @@ -54,8 +64,8 @@ $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"); +if (getenv('PFS_TEST_DATABASE') !== 'disposable' || $dir === '' || !is_dir($dir) || !in_array($step, array('setup', 'arm', 'settle', 'running', '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 , settle , running , check , or cleanup\n"); exit(2); } @@ -87,6 +97,34 @@ function fault_health() { return is_array($row) ? $row : array(); } +/** The poller 1 lease, or an empty array before any reader ran. */ +function fault_lease() { + $row = db_fetch_row('SELECT holder, expires_at FROM plugin_pfs_reader WHERE poller_id = 1'); + + return is_array($row) ? $row : array(); +} + +/** No reader holds the lease or is still registered as running. */ +function fault_lease_free() { + return pfs_reader_idle(1); +} + +/** Whether the node was attempted at or after the scenario started. */ +function fault_fresh() { + $health = fault_health(); + + return isset($health['last_attempt']) && (int) $health['last_attempt'] >= (int) fault_state('armed_at'); +} + +/** + * Poll $done every fifth of a second for at most $seconds. A wait on state + * another process writes, never a fixed sleep: the reader started by + * poller_bottom may not have registered yet when the poller returns. + */ +function fault_wait($done, $seconds) { + return pfs_wait_until($done, $seconds); +} + 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'))); } @@ -131,15 +169,42 @@ function fault_observed() { break; case 'arm': + // A reader still holding the lease makes the next forced run skip, + // and its check would then read an older attempt. + fault_expect(fault_wait('fault_lease_free', 60), "$mode: no reader holds the lease or is registered when the scenario starts (" . json_encode(fault_lease()) . ')'); 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()); + fault_state('armed_at', time()); + + break; + case 'settle': + $seconds = max(1, (int) $mode); + fault_expect(fault_wait(function () { + return fault_fresh() && fault_lease_free(); + }, $seconds), "the reader poller_bottom started attempted the node and ended within $seconds s (" . json_encode(array('health' => fault_health(), 'lease' => fault_lease())) . ')'); + + break; + case 'running': + $pid = (int) $mode; + $seconds = max(1, isset($argv[3]) ? (int) $argv[3] : 0); + fault_expect($pid > 0 && fault_wait(function () use ($pid) { + $lease = fault_lease(); + + return isset($lease['holder']) && strpos((string) $lease['holder'], 'poller1-' . $pid . '-') === 0 && (int) $lease['expires_at'] >= time(); + }, $seconds), "the reader with process id $pid holds the lease within $seconds s (" . json_encode(fault_lease()) . ')'); 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; + print 'EVIDENCE ' . $mode . ' health ' . json_encode($health) . ' armed_at ' . fault_state('armed_at') . PHP_EOL; + + // The dbloss run may have lost its connection before it recorded + // the attempt; every other mode must show an attempt of its own. + if ($mode !== 'dbloss') { + fault_expect(fault_fresh(), "$mode: the reader attempted the node after the scenario started, so the state below is this scenario's"); + } 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'); diff --git a/tests/bin/failure-replay.sh b/tests/bin/failure-replay.sh index 2a82c7f..59261d7 100644 --- a/tests/bin/failure-replay.sh +++ b/tests/bin/failure-replay.sh @@ -15,8 +15,9 @@ # 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: +# Failure qualification (tests/bin/failure-flow.php). Run from the root of a +# disposable Cacti install with the plugin enabled, as root for the RRD +# permission scenario: # # PFS_TEST_DATABASE=disposable PFS_TEST_MYSQL_DEFAULTS= \ # sh plugins/pfs/tests/bin/failure-replay.sh @@ -77,10 +78,9 @@ 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 +# The background reader may not have started when the poller returns, so +# wait for its attempt and its released lease rather than for a process. +flow settle 60 flow check slow # The database connection drops while the reader waits for a node. @@ -88,7 +88,10 @@ 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 +# Wait, bounded, until this reader holds the lease: it is then mid-run and +# its connection is open. The node answers after 5 s and the read timeout +# is 3 s, so the kill lands while the reader waits for the node. +flow running "$pid" 20 # 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 @@ -109,8 +112,9 @@ 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. +# Changing owners needs root; elsewhere (a CI runner) the scenario is skipped. echo "== RRD file the poller cannot write" -if id www-data > /dev/null 2>&1; then +if [ "$(id -u)" -eq 0 ] && 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} @@ -162,7 +166,7 @@ if id www-data > /dev/null 2>&1; then reader after-rrd flow check ok else - echo "SKIP no unprivileged www-data user to run the poller as" + echo "SKIP not root, or no unprivileged www-data user to run the poller as" fi flow cleanup diff --git a/tests/bin/lifecycle.php b/tests/bin/lifecycle.php index c4700c7..f96a178 100644 --- a/tests/bin/lifecycle.php +++ b/tests/bin/lifecycle.php @@ -45,7 +45,25 @@ switch ($action) { case 'reset': - api_plugin_uninstall('pfs'); + // A disposable database starts without the plugin tables, but the + // cleanup path still runs before every lifecycle scenario. Cacti's + // uninstall callback is meaningful only after the plugin schema has + // been created; otherwise the mapping lookup correctly fails closed. + $filesystemTableExists = (int) db_fetch_cell("SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'plugin_pfs_filesystem'") === 1; + + if ($filesystemTableExists) { + api_plugin_uninstall('pfs'); + } + + // Devices the device actions below made, with their graphs. + $hosts = array_map('intval', array_column(db_fetch_assoc("SELECT id FROM host WHERE hostname LIKE '%.pfs.invalid' OR hostname = 'lifecycle.example.invalid'"), 'id')); + + if ($hosts !== array()) { + include_once($config['base_path'] . '/lib/api_device.php'); + include_once($config['base_path'] . '/lib/api_data_source.php'); + include_once($config['base_path'] . '/lib/api_graph.php'); + api_device_remove_multi($hosts, 2); + } foreach (db_fetch_assoc("SELECT TABLE_NAME AS t FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE 'plugin\\_pfs\\_%'") as $row) { db_execute('DROP TABLE `' . $row['t'] . '`'); @@ -111,8 +129,19 @@ db_execute('ALTER TABLE plugin_pfs_filesystem DROP INDEX host_id, DROP COLUMN host_id'); db_execute('DROP TABLE IF EXISTS plugin_pfs_summary'); db_execute("DELETE FROM plugin_db_changes WHERE plugin = 'pfs' AND `table` = 'plugin_pfs_summary'"); + db_execute('DROP TABLE IF EXISTS plugin_pfs_created_devices'); + db_execute("DELETE FROM plugin_db_changes WHERE plugin = 'pfs' AND `table` = 'plugin_pfs_created_devices'"); db_execute("UPDATE settings SET value = '1' WHERE name = 'pfs_schema_version'"); + break; + case 'to_schema_2': + // What a milestone 4 install left: the created devices as one JSON + // setting, here the ids in the argument. + db_execute('DROP TABLE IF EXISTS plugin_pfs_created_devices'); + db_execute("DELETE FROM plugin_db_changes WHERE plugin = 'pfs' AND `table` = 'plugin_pfs_created_devices'"); + db_execute_prepared("REPLACE INTO settings (name, value) VALUES ('pfs_created_devices', ?)", array($argument)); + db_execute("UPDATE settings SET value = '2' WHERE name = 'pfs_schema_version'"); + break; case 'seed': // A filesystem row, so table drops and keeps are visible. @@ -122,10 +151,32 @@ case 'reader_flow': include($config['base_path'] . '/plugins/pfs/tests/bin/reader-flow.php'); + break; + case 'devices': + // One filesystem with a device the plugin creates, one mapped onto a + // device that already existed (REQ-LIFE-005). + include_once($config['base_path'] . '/plugins/pfs/setup.php'); + include_once($config['base_path'] . '/lib/api_device.php'); + pfs_boot(); + + $repo = new \Somethingwithproof\Pfs\FilesystemRepository(false, new \Somethingwithproof\Pfs\SystemClock()); + db_execute("INSERT INTO plugin_pfs_filesystem (name, backend, poller_id, expected_interval, admin_state) VALUES ('made', 'lustre', 1, 300, 'enabled')"); + $made = (int) db_fetch_insert_id(); + $created = pfs_provisioner()->create($repo->find($made)); + + $existing = (int) api_device_save(0, 0, 'lifecycle existing', 'lifecycle.example.invalid', '', 0, '', '', 161, 500, '', 0, 1, 23, 400, 1, '', '', '', '', '', '', 10, 1, 1, 0); + db_execute("INSERT INTO plugin_pfs_filesystem (name, backend, poller_id, expected_interval, admin_state) VALUES ('mapped', 'lustre', 1, 300, 'enabled')"); + $mapped = (int) db_fetch_insert_id(); + pfs_provisioner()->map($repo->find($mapped), $existing); + + $result = array('created' => $created, 'existing' => $existing); + break; case 'uninstall_unbooted': - // What core does on uninstall when pfs_boot() refuses: the PHP 8.0 - // fallback, then core drops whatever is still tracked. + // What core does on uninstall when pfs_boot() refuses: setup.php is + // loaded, the PHP 8.0 fallback runs, then core drops whatever is + // still tracked. + include_once($config['base_path'] . '/plugins/pfs/setup.php'); include_once($config['base_path'] . '/plugins/pfs/include/unbooted-uninstall.php'); pfs_uninstall_unbooted(); api_plugin_db_changes_remove('pfs'); @@ -180,5 +231,11 @@ 'admin' => (int) db_fetch_cell("SELECT COUNT(*) FROM user_auth_realm AS uar INNER JOIN plugin_realms AS pr ON pr.id + 100 = uar.realm_id WHERE pr.plugin = 'pfs' AND uar.user_id = 1"), 'tracked' => array_column(db_fetch_assoc("SELECT `table` FROM plugin_db_changes WHERE plugin = 'pfs' AND method = 'create' ORDER BY `table`"), 'table'), 'tables' => $tables, + 'devices' => array_map(static function ($row) { + return array('data_local' => (int) $row['ds'], 'graph_local' => (int) $row['graphs']); + }, array_column(db_fetch_assoc("SELECT h.id, (SELECT COUNT(*) FROM data_local d WHERE d.host_id = h.id) AS ds, (SELECT COUNT(*) FROM graph_local g WHERE g.host_id = h.id) AS graphs FROM host h WHERE h.hostname LIKE '%.pfs.invalid' OR h.hostname = 'lifecycle.example.invalid'"), null, 'id')), + 'created_devices' => db_fetch_cell("SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'plugin_pfs_created_devices'") ? json_encode(array_map('intval', array_column(db_fetch_assoc('SELECT host_id FROM plugin_pfs_created_devices ORDER BY host_id'), 'host_id'))) : '', + 'legacy_created_devices' => (string) db_fetch_cell("SELECT value FROM settings WHERE name = 'pfs_created_devices'"), + 'filesystem_hosts' => db_fetch_cell("SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'plugin_pfs_filesystem' AND COLUMN_NAME = 'host_id'") ? array_map('intval', array_column(db_fetch_assoc('SELECT name, host_id FROM plugin_pfs_filesystem ORDER BY name'), 'host_id', 'name')) : array(), 'host_column' => (int) db_fetch_cell("SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'plugin_pfs_filesystem' AND COLUMN_NAME = 'host_id'") === 1, ), JSON_PRETTY_PRINT) . PHP_EOL; diff --git a/tests/bin/php-guard-check.php b/tests/bin/php-guard-check.php index c9c6e45..a5d11a8 100644 --- a/tests/bin/php-guard-check.php +++ b/tests/bin/php-guard-check.php @@ -108,7 +108,7 @@ function guard_call_shims() { if ($supported) { guard_expect($state['status'] == 1, 'install and enable succeed (status ' . $state['status'] . ')'); - guard_expect($state['tables'] === 8, 'all eight plugin tables exist (' . $state['tables'] . ')'); + guard_expect($state['tables'] === 9, 'all nine plugin tables exist (' . $state['tables'] . ')'); guard_expect($state['hooks'] >= 3 && $state['realms'] === 2, 'hooks and realms are registered'); } else { guard_expect($state['status'] == 2, 'plugin is left as needing configuration, not enabled (status ' . $state['status'] . ')'); diff --git a/tests/bin/reader-idle.php b/tests/bin/reader-idle.php new file mode 100644 index 0000000..cac8675 --- /dev/null +++ b/tests/bin/reader-idle.php @@ -0,0 +1,61 @@ + + * 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. + */ + +/* + * Bounded waits on the production reader for the end-to-end flows. A forced + * Cacti poll starts poller_pfs.php in the background (poller_bottom), so a + * flow that reads or forces a run next has to wait for that reader to end. + * Reader::run() releases the lease before poller_pfs.php unregisters its + * process, so idle means both: no live lease and no registration. + * + * Must parse on PHP 8.0, like the other tests/bin scripts. + */ + +/** Whether no reader holds the poller's lease or is registered as running. */ +function pfs_reader_idle($poller = 1) { + $lease = db_fetch_row_prepared('SELECT expires_at FROM plugin_pfs_reader WHERE poller_id = ?', array($poller)); + $leaseFree = is_array($lease) && (!isset($lease['expires_at']) || (int) $lease['expires_at'] < time()); + $registered = db_fetch_cell_prepared("SELECT COUNT(*) FROM processes WHERE tasktype = 'pfs' AND taskname = 'reader' AND taskid = ?", array($poller)); + + // A background PHP process can pause before registering with Cacti. + // Include that startup window, and fail closed if process lookup fails. + $readers = array(); + $status = 0; + exec("pgrep -f '[p]oller_pfs[.]php'", $readers, $status); + + return $leaseFree && $registered !== false && (int) $registered === 0 && $status === 1; +} + +/** + * Poll $done every 0.2 seconds until it is true or $seconds have passed. + * Returns whether it became true. + */ +function pfs_wait_until($done, $seconds) { + $until = microtime(true) + $seconds; + + while (!$done()) { + if (microtime(true) >= $until) { + return false; + } + + usleep(200000); + } + + return true; +} diff --git a/tests/bin/scale-flow.php b/tests/bin/scale-flow.php index 6d405de..2d6eaff 100644 --- a/tests/bin/scale-flow.php +++ b/tests/bin/scale-flow.php @@ -204,8 +204,15 @@ function scale_read($name, array $nodes, $mds, $n, $at) { $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; + foreach (db_fetch_assoc_prepared('SELECT id, data_template_id, snmp_index FROM data_local WHERE host_id = ?', array($host)) as $row) { + $path = get_data_source_path((int) $row['id'], true); + + if (is_file($path)) { + $files++; + } else { + $items = (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM poller_item WHERE local_data_id = ?', array((int) $row['id'])); + print 'EVIDENCE no RRD file for data source ' . $row['id'] . " (template {$row['data_template_id']}, index '{$row['snmp_index']}', $items poller items): " . basename($path) . PHP_EOL; + } } scale_metric("$n rrd_files", $files); diff --git a/tests/bootstrap-unit.php b/tests/bootstrap-unit.php index 2c513a0..7983e2a 100644 --- a/tests/bootstrap-unit.php +++ b/tests/bootstrap-unit.php @@ -96,6 +96,11 @@ function pfs_test_rows(string $sql): mixed { function db_execute_prepared($sql, $params = [], $log = true, $db_conn = false, $log_function = null) { $GLOBALS['__pfs_db_exec'][] = ['sql' => $sql, 'params' => $params]; + foreach ($GLOBALS['__pfs_db_fail'] ?? [] as $needle) { + if (str_contains($sql, $needle)) { + return false; + } + } return true; } } @@ -110,7 +115,7 @@ function db_fetch_assoc_prepared($sql, $params = [], $log = true, $db_conn = fal function db_fetch_row_prepared($sql, $params = [], $log = true, $db_conn = false, $log_function = null) { $rows = pfs_test_rows($sql); - return is_array($rows) && isset($rows[0]) ? $rows[0] : []; + return $rows === false ? false : (is_array($rows) && isset($rows[0]) ? $rows[0] : []); } } @@ -147,7 +152,7 @@ function db_fetch_cell_prepared($sql, $params = [], $col_name = '', $log = true, $rows = pfs_test_rows($sql); - return is_array($rows) && isset($rows[0]) ? reset($rows[0]) : 0; + return $rows === false ? false : (is_array($rows) && isset($rows[0]) ? reset($rows[0]) : 0); } } @@ -181,3 +186,4 @@ function html_end_box($trailing_br = true, $div = false) { require_once dirname(__DIR__) . '/setup.php'; require_once dirname(__DIR__) . '/include/autoload.php'; +require_once dirname(__DIR__) . '/include/unbooted-uninstall.php';