diff --git a/.github/workflows/plugin-ci-workflow.yml b/.github/workflows/plugin-ci-workflow.yml index 8c644ad..0cbc267 100644 --- a/.github/workflows/plugin-ci-workflow.yml +++ b/.github/workflows/plugin-ci-workflow.yml @@ -537,7 +537,8 @@ jobs: # The plugin's own transports, built from a cluster record as the reader # builds them: the client commands through docker exec into slurmctld, - # and slurmrestd on loopback with the token file. + # and slurmrestd on loopback with the token file. It also checks parser + # discovery and, on 26.05, a conditional nodes read that answers 304. - name: Collect a snapshot with the plugin's transports run: php plugin/tests/slurm-live/collect.php "$GITHUB_WORKSPACE/plugin" "$RUNNER_TEMP/slurm-out" "$RUNNER_TEMP/hpcsched-tokens/live.token" diff --git a/README.md b/README.md index 871b6ac..dbcfc6b 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ Out of scope: any scheduler write path (submit, cancel, hold, drain, resume), a |---|---| | Cacti | 1.2.31 or later, no core patches | | PHP | 8.2 or later; `setup.php` stays parseable on 8.0 so an unsupported runtime gets a refusal instead of a broken Cacti UI | -| Slurm | Provisionally 25.05, 25.11, and 26.05 (decision #8 is open). The data parser is a setting: v0.0.43 by default, which SchedMD removes in 27.05, or v0.0.44 or v0.0.45 on releases that ship them | +| Slurm | 25.05, 25.11, and 26.05, the three latest releases ([ADR 0013](docs/decisions/0013-three-latest-slurm-releases.md)); 25.11 and 26.05 are tested against a live cluster, 25.05 against fixtures only. Client commands are the default transport ([ADR 0012](docs/decisions/0012-client-commands-default-transport.md)) and use the data parser setting: v0.0.43 by default, which SchedMD removes in 27.05, or v0.0.44 or v0.0.45 on releases that ship them. slurmrestd clusters discover the newest parser the daemon serves | | Thold, Maint | No Thold change; Maint integration is a proposal that needs Maint maintainers' agreement | ## Design diff --git a/docs/PLAN.md b/docs/PLAN.md index 687c06c..ec89ea0 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -138,7 +138,7 @@ Each row is a milestone 1 test, because a change in any of them changes the desi | "The power to create JWTs is the power of root on a cluster." `slurmrestd` must not run as root or `SlurmUser`. It listens on TCP (`:6820` in the quick start) or UNIX sockets. | The plugin never creates tokens ([ADR 0009](decisions/0009-credentials-by-file-or-munge-never-minted.md)). | [JWT](https://slurm.schedmd.com/jwt.html), [slurmrestd](https://slurm.schedmd.com/slurmrestd.html) | | The API is not designed to be internet facing. The REST details page says only unencrypted HTTP is supported and recommends a TLS-wrapping proxy, while the slurmrestd man page describes native TLS through the `tls/s2n` plugin and `https://` listeners. | The two pages disagree. Source and the man page show native TLS from 25.05 (with the optional s2n library at build time); the REST details page is out of date. The plugin verifies TLS where used and documents network placement. | [REST API details](https://slurm.schedmd.com/rest.html), [slurmrestd](https://slurm.schedmd.com/slurmrestd.html) | | Each cluster needs its own `slurmrestd`. | One cluster per endpoint setting. | [REST quick start](https://slurm.schedmd.com/rest_quickstart.html) | -| `GET /slurm/{version}/nodes` takes `update_time` and returns 304 with an empty body when nothing changed; other endpoints that accept `update_time` return 200 with a warning. **Milestone 1:** the 304 exists in source only from 26.05; on 24.11, 25.05, and 25.11 the nodes handler has no such branch, and jobs returns 200 with a warning at all releases checked. | The transport must not treat a 304 as an empty result, and the first release does not use `update_time`. | [REST API details](https://slurm.schedmd.com/rest.html), [slurmrestd.md](research/slurmrestd.md) | +| `GET /slurm/{version}/nodes` takes `update_time` and returns 304 with an empty body when nothing changed; other endpoints that accept `update_time` return 200 with a warning. **Milestone 1:** the 304 exists in source only from 26.05 (**Milestone 3:** from 26.05.3, per its changelog and `nodes.c`); on 24.11, 25.05, and 25.11 the nodes handler has no such branch, and jobs returns 200 with a warning at all releases checked. | The transport must not treat a 304 as an empty result, and the first release does not use `update_time`. | [REST API details](https://slurm.schedmd.com/rest.html), [slurmrestd.md](research/slurmrestd.md) | | The v0.0.45 reference lists `GET` on `/slurm/v0.0.45/jobs/`, `jobs/state/`, `nodes/`, `partitions/`, `reservations/`, `shares`, `diag/`, `ping/`, and `GET /slurmdb/v0.0.45/jobs/`, and also lists POST and DELETE endpoints that change state. | **Milestone 1:** the reference also lists two GET routes that change state: `GET /slurm/v0.0.NN/reconfigure/` (calls `slurm_reconfigure()`, at all releases checked) and, on 26.05, `GET /slurm/v0.0.NN/job/{job_id}/requeue`. A method rule is not enough, so the plugin uses an exact path-and-method allowlist (the nine paths named in this row, GET only, parser fixed by configuration) and refuses everything else in code. A token for a user who can modify state is more power than the plugin needs. | [REST API reference](https://slurm.schedmd.com/rest_api.html), [slurmrestd.md](research/slurmrestd.md) | **Cacti core 1.2.31** @@ -236,9 +236,9 @@ The number of calls does not depend on job, node, or series counts. Through `slu **Transports.** The Slurm backend separates fetching from parsing. - *Client commands.* The reader runs `squeue`, `sinfo`, `scontrol`, and `sshare` with argument arrays (no shell), a fixed option set, a timeout, and an output size limit. It relies on the poller user's Slurm client setup and does not handle credentials. Output is parsed from JSON pinned to a data parser, or from delimiter-separated format output where measurement shows JSON is too costly. Format output is fragile if a field can contain the delimiter, which research checks. **Milestone 2:** nodes come from `scontrol --json show node` rather than `sinfo`, so all sections share one JSON parser; there is no delimiter-format fallback. Each binary path is an absolute setting, the environment is reduced to `PATH`, `LC_ALL`, and an optional per-cluster `SLURM_CONF`, and when `prlimit` is configured each child runs under an address-space limit. -- *slurmrestd.* The reader sends HTTP GET requests to an allowlist of paths, discovers the highest data parser version the daemon offers among those the plugin supports, and authenticates with a token read from a file. It handles 304 on conditional requests as "no change". **Milestone 2 diverges:** there is no discovery request. The data parser is one setting for both transports, chosen from `v0.0.43`, `v0.0.44`, and `v0.0.45` with `v0.0.43` as the default, and the path allowlist is exact for the chosen version; the health page warns when a cluster reports a release that does not ship it. A 404 is reported as a configuration error. `update_time` is never sent, so a 304 is not expected; one is still recorded as a failed section, never as an empty result. +- *slurmrestd.* The reader sends HTTP GET requests to an allowlist of paths, discovers the highest data parser version the daemon offers among those the plugin supports, and authenticates with a token read from a file. It handles 304 on conditional requests as "no change". **Milestone 2 diverges:** there is no discovery request. The data parser is one setting for both transports, chosen from `v0.0.43`, `v0.0.44`, and `v0.0.45` with `v0.0.43` as the default, and the path allowlist is exact for the chosen version; the health page warns when a cluster reports a release that does not ship it. A 404 is reported as a configuration error. `update_time` is never sent, so a 304 is not expected; one is still recorded as a failed section, never as an empty result. **Milestone 3 (#35):** slurmrestd clusters discover their parser. The reader asks `GET /slurm/{parser}/ping/` for each supported parser, newest first: 200 chooses it, 404 tries the next, any other answer fails the run with its class, and no supported parser is a configuration error. The choice is cached per cluster as the parser of its last completed slurmrestd run, and is kept while the release that run reported ships no newer supported parser; a run that did not complete (a 404 among the causes) or an upgraded release discovers again. The health page shows the parser with "discovered", and the data parser setting now applies to client commands only. Discovery uses `ping/`, not the OpenAPI document, because `ping/` is already a read-only path of each parser and needs no second document parser. `update_time` is sent to `/nodes/` only, only on 26.05.3 and later (taken from the release of the previous run; before 26.05.3 the handler fails an unchanged answer instead of a 304, and fails with HTTP 500 when nodes changed but partitions did not), only after a completed node read whose rows are at most 600 seconds old, and set to that read's observation time less the 120 second skew allowance. A 304 then keeps the stored node rows and counts the section as read now; any other answer is read whole. `/jobs/` answers an unchanged request with 200, a warning, and no jobs, which would read as an empty queue, so it is never conditional; partitions, reservations, and shares have no unchanged answer. A 304 to a request without `update_time` is still a failed section. -Which transport is the default is an open decision with evidence from milestone 1. Both implement the same interface and produce the same snapshot. The plugin never uses `scontrol update`, `scancel`, `sbatch`, `srun`, `salloc`, or `sacctmgr`, and never uses `sudo`. +Client commands are the default transport ([ADR 0012](decisions/0012-client-commands-default-transport.md), decides #7). Both implement the same interface and produce the same snapshot. The plugin never uses `scontrol update`, `scancel`, `sbatch`, `srun`, `salloc`, or `sacctmgr`, and never uses `sudo`. **Normalized snapshot.** One snapshot contains: @@ -466,7 +466,7 @@ Phase 2 needs a security review covering mapping input, writes to Maint's tables ## Testing - **Fixtures.** Captured command and REST output per Slurm release for: idle, busy, and drained clusters; held, array, and multi-partition jobs; every documented reason and an unknown one; every documented node state and an unknown one; reservations including `MAINT` and recurring; nodes in several partitions; shares with and without Fair Tree. -- **Matrix.** Containers for each supported Slurm release (`slurmctld`, and `slurmrestd` where provided) against Cacti 1.2.31 and current `1.2.x`, on every PHP minor in the CI matrix. `setup.php` and shims are also linted under PHP 8.0. **Milestone 3 diverges:** the CI job `slurm-live` runs a real cluster from slurm-docker-cluster 3.0.2 (pinned by commit, MariaDB pinned by digest) with six nodes, creates allocated, mixed, drained, down, down and drained, and maintenance nodes, a maintenance reservation, and held, array, and pending jobs, then checks the raw JSON and the plugin's parser for every data parser the release serves, through both client commands and `slurmrestd`. 26.05.5 uses the published image, pinned by digest, on every change; 25.11.8 has no published image and is built from source, which takes about eight minutes, so it runs on pushes to `main`, weekly, and on request. 25.05 has no matching cluster configuration and stays on the synthetic fixtures. It then collects a snapshot with the plugin's own transports, built from a cluster record as the reader builds them: the client commands through `docker exec` into the `slurmctld` container (so `prlimit` is off there, since it would limit `docker` rather than the client), and `slurmrestd` on loopback with a token file. Each snapshot must complete every section and match the captured parse. The reader's database write is not part of the job; the Cacti replays cover it with stand-ins. Captures from it are in `tests/fixtures/slurm/live` and run in the unit suite. +- **Matrix.** Containers for each supported Slurm release (`slurmctld`, and `slurmrestd` where provided) against Cacti 1.2.31 and current `1.2.x`, on every PHP minor in the CI matrix. `setup.php` and shims are also linted under PHP 8.0. **Milestone 3 diverges:** the CI job `slurm-live` runs a real cluster from slurm-docker-cluster 3.0.2 (pinned by commit, MariaDB pinned by digest) with six nodes, creates allocated, mixed, drained, down, down and drained, and maintenance nodes, a maintenance reservation, and held, array, and pending jobs, then checks the raw JSON and the plugin's parser for every data parser the release serves, through both client commands and `slurmrestd`. 26.05.5 uses the published image, pinned by digest, on every change; 25.11.8 has no published image and is built from source, which takes about eight minutes, so it runs on pushes to `main`, weekly, and on request. 25.05 has no matching cluster configuration and stays on the synthetic fixtures ([ADR 0013](decisions/0013-three-latest-slurm-releases.md)). It then collects a snapshot with the plugin's own transports, built from a cluster record as the reader builds them: the client commands through `docker exec` into the `slurmctld` container (so `prlimit` is off there, since it would limit `docker` rather than the client), and `slurmrestd` on loopback with a token file. Each snapshot must complete every section and match the captured parse. A slurmrestd collection with no previous run must discover the newest supported parser the daemon serves (v0.0.45 on 26.05, v0.0.44 on 25.11). A second nodes read after a whole one must answer 304 and keep the rows on 26.05, retried 30 seconds apart while the cluster's last node changes are inside the skew window, and must be read whole with no `update_time` on 25.11. The reader's database write is not part of the job; the Cacti replays cover it with stand-ins. Captures from it are in `tests/fixtures/slurm/live` and run in the unit suite. - **Transport safety.** Hung command, output flood, malformed JSON, 304, 401, 403, 500, slow response, oversized response, and node names with shell metacharacters. - **Counting.** Fixtures for each counting rule in the Graphs section, checked with `rrdtool xport` against expected values. - **Permissions.** Every page, graph, and data source as an administrator, a scoped user, a user whose access was just revoked, and a user with no access. @@ -490,7 +490,7 @@ Phase 2 needs a security review covering mapping input, writes to Maint's tables | Milestone | Production lines | Gates outside the code | |---|---|---| -| 2. Foundation | 5,500 to 7,500 | harness choice (#11); decisions #7 and #8 | +| 2. Foundation | 5,500 to 7,500 | harness choice (#11); decisions #7 and #8 (made in ADRs 0012 and 0013) | | 3. Cluster graphs and pending reasons | 2,500 to 3,500, plus template XML | decision #12; live series-count run (#25) | | 4. Phase 1 release | 500 to 1,000 | a Slurm test cluster and pilots | | 5. Nodes and maintenance | 2,000 to 3,000 | decision #13 with Maint's maintainers; security review | @@ -513,9 +513,9 @@ No calendar duration is claimed: the comparison plugins' commit spans measure as | Maintenance mechanism | Direct rows (proposed); Maint function; none | Milestone 5 | Maint maintainers | | Fair-share account selection | Chosen list plus top-N (proposed); all; top-level only | Milestone 6 | sshare research | -Evidence for the decisions milestone 1 feeds (the decisions themselves are the owner's): +Evidence that fed decisions #7 and #8, now made in [ADR 0012](decisions/0012-client-commands-default-transport.md) and [ADR 0013](decisions/0013-three-latest-slurm-releases.md), and #9: -- **Default transport (#7).** Both transports produce the snapshot. Source shows the REST path needs an exact-path allowlist and supports TLS only from 25.05; the client-command path needs no credential handling and works on packaged releases older than the REST parsers. The load comparison is *live*, so no transport is shown to be cheaper. +- **Default transport (#7).** Both transports produce the snapshot. Source shows the REST path needs an exact-path allowlist and supports TLS only from 25.05; the client-command path needs no credential handling and works on packaged releases older than the REST parsers. Milestone 3's live job read 26.05.5 and 25.11.8 through both with the same snapshot; the load comparison was not measured, so no transport is shown to be cheaper. - **Supported releases (#8).** SchedMD's own end-of-support dates leave 25.11 and 26.05 supported, 25.05 ending this month, and 24.11 unsupported. `v0.0.43` is the one parser common to 25.05, 25.11, 26.05, and the 26.11 candidate. - **Node matching (#9).** Hostname, address, description, then a low-confidence short-name tier with ambiguity left unmapped passed the 11 fixture cases; `external_id` alone is not supported (40 characters, not unique). @@ -554,7 +554,7 @@ Documentation and source work for milestone 1 was done on 2026-11-15. Nothing wa | [#26](https://github.com/somethingwithproof/plugin_hpcsched/issues/26) | [prior-art.md](research/prior-art.md) | organization plugins read; searches | maintainer and pilot questions | | [#27](https://github.com/somethingwithproof/plugin_hpcsched/issues/27) | [estimates.md](research/estimates.md) | ranges from measured lines | re-check after live work | -Decisions #7 (default transport), #8 (supported releases), and #9 (node matching) are not made here; the evidence is in the files above and summarized under Open decisions. +Decisions #7 (default transport) and #8 (supported releases) are made in [ADR 0012](decisions/0012-client-commands-default-transport.md) and [ADR 0013](decisions/0013-three-latest-slurm-releases.md). Decision #9 (node matching) is not made here; the evidence is in the files above and summarized under Open decisions. ## Research diff --git a/docs/decisions/0012-client-commands-default-transport.md b/docs/decisions/0012-client-commands-default-transport.md new file mode 100644 index 0000000..21e50be --- /dev/null +++ b/docs/decisions/0012-client-commands-default-transport.md @@ -0,0 +1,31 @@ +# 0012. Read Slurm through its client commands by default + +Status: Accepted (2026-11-15). Decides [#7](https://github.com/somethingwithproof/plugin_hpcsched/issues/7). + +## Context + +The plugin reads Slurm through one of two transports that produce the same snapshot ([ADR 0004](0004-scheduler-backend-interface.md)): the client commands (`squeue`, `scontrol`, `sshare`) run on the poller host, or HTTP GET requests to `slurmrestd`. A new cluster record needs one of them as its default. + +From milestone 1's source reading ([slurmrestd.md](../research/slurmrestd.md), [slurm-releases.md](../research/slurm-releases.md)): + +- The client commands authenticate with the poller host's own munge or auth/slurm setup, so the plugin handles no credential. They need the Slurm client package and configuration on every poller that reads a cluster. +- `slurmrestd` needs a token, which the plugin reads from a file and never stores ([ADR 0009](0009-credentials-by-file-or-munge-never-minted.md)), and an exact path allowlist, because some GET paths change state (`reconfigure/`, and `job/{id}/requeue` on 26.05). Native TLS exists only from 25.05 and only when the build includes s2n. Many sites do not run `slurmrestd` at all. + +Milestone 3's live job read 26.05.5 and 25.11.8 clusters through both transports with matching snapshots. It did not compare their load on the controller. + +## Decision + +Client commands are the default transport for a new cluster. `slurmrestd` stays a per-cluster choice for sites that run it, cannot install the client on the poller, or want to keep munge keys off it. + +The data parser setting applies to client commands. A `slurmrestd` cluster discovers the newest parser its daemon serves among those the plugin supports (PLAN, Transports). + +## Consequences + +- A default cluster needs no token, TLS material, or allowlist review. +- The poller host must have a working Slurm client and configuration for each cluster read through client commands, and the documentation says so. +- Controller load from the two transports is unmeasured. If a site shows `slurmrestd` is cheaper, that changes the recommendation for large clusters, not this default. + +## Alternatives rejected + +- **`slurmrestd` by default.** It needs a token on the poller and a daemon many sites do not run, and its GET surface includes state-changing paths. +- **No default (require a choice).** Every new cluster would need a decision before it is read, with no difference in the snapshot to justify one. diff --git a/docs/decisions/0013-three-latest-slurm-releases.md b/docs/decisions/0013-three-latest-slurm-releases.md new file mode 100644 index 0000000..3528643 --- /dev/null +++ b/docs/decisions/0013-three-latest-slurm-releases.md @@ -0,0 +1,34 @@ +# 0013. Support the three latest Slurm releases + +Status: Accepted (2026-11-15). Decides [#8](https://github.com/somethingwithproof/plugin_hpcsched/issues/8). + +## Context + +Slurm releases every six months and SchedMD supports each for about 18 months ([upgrade guide](https://slurm.schedmd.com/upgrades.html)). The data parsers change with each release ([slurm-releases.md](../research/slurm-releases.md)): + +| Release | Data parsers | End of support (SchedMD) | +|---|---|---| +| 25.05 | v0.0.40 to v0.0.43 | November 2026 | +| 25.11 | v0.0.41 to v0.0.44 | May 2027 | +| 26.05 | v0.0.42 to v0.0.45 | listed as November 2028, which contradicts the 18 month rule | + +Milestone 3's live job runs a real cluster for 26.05.5 (published image) and 25.11.8 (built from source). No matching cluster configuration exists for 25.05, so it is covered by synthetic fixtures only. + +## Decision + +The plugin supports the three latest Slurm releases: 25.05, 25.11, and 26.05. It reads data parsers v0.0.43, v0.0.44, and v0.0.45, so every supported release has at least one parser the plugin reads, and v0.0.43 is common to all three. + +- 26.05 and 25.11 are tested against a live cluster through both transports. +- 25.05 is tested against fixtures only, and the README says so. +- When a new release is published, support moves to the three latest: the oldest release leaves the set, and the parser list follows. + +## Consequences + +- A cluster on 24.11 or earlier is not read: its client commands do not accept the pinned parser, and discovery finds no supported parser on its `slurmrestd`. Each run fails with an error class, never with a shape the plugin does not know. +- 25.05 reaches SchedMD's end of support this month and leaves the set when 26.11 is released. Until then a 25.05 regression shows only as a fixture change. +- SchedMD removes v0.0.43 in 27.05, so the client command default (v0.0.43) must move before the plugin supports 27.05. + +## Alternatives rejected + +- **SchedMD's supported releases only.** It would drop 25.05 this month while sites still run it, and the date for 26.05 is not reliable. +- **Every release that ships a parser the plugin reads.** It ties support to parser lifetimes, which are longer than SchedMD's support and are not tested. diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 25a1909..8cd90ea 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -15,5 +15,7 @@ Each record captures one architecture decision: its context, the decision, its c | [0009](0009-credentials-by-file-or-munge-never-minted.md) | Read scheduler credentials from the host, never store or mint them | Accepted | | [0010](0010-bound-series-cardinality.md) | Bound the number of RRD series the plugin creates | Accepted | | [0011](0011-pending-reason-families-and-counting.md) | Group pending reasons into eleven fixed families and fix the counting rules | Accepted | +| [0012](0012-client-commands-default-transport.md) | Read Slurm through its client commands by default | Accepted | +| [0013](0013-three-latest-slurm-releases.md) | Support the three latest Slurm releases | Accepted | Open decisions are tracked as issues labelled `type: decision`. diff --git a/docs/research/slurmrestd.md b/docs/research/slurmrestd.md index 3525d70..b8ac934 100644 --- a/docs/research/slurmrestd.md +++ b/docs/research/slurmrestd.md @@ -2,7 +2,7 @@ Research for [#17](https://github.com/somethingwithproof/plugin_hpcsched/issues/17), run 2026-11-15. Question: do the endpoints, headers, version discovery, and conditional queries behave as documented, and what can a minimally privileged account see? -**Result.** Every endpoint, header, and default in the plan's REST table was found in source, with two corrections and one finding that changes the security design. Correction one: the 304 response to `update_time` on `/nodes` exists only from 26.05. On 24.11, 25.05, and 25.11 the same query goes through the generic error path, so the plugin must not rely on it unless it has checked the release. Correction two: native TLS is 25.05 and later, and needs the s2n library at build time. The finding: "GET-only" is not a safe allowlist. `GET /slurm/{parser}/reconfigure/` asks `slurmctld` to reconfigure, and on 26.05 `GET /slurm/{parser}/job/{job_id}/requeue` requeues a job. The plugin needs an exact list of path and method pairs, not a method rule. Least-privilege visibility, token behavior for a user with no association, and failure modes are *live*. +**Result.** Every endpoint, header, and default in the plan's REST table was found in source, with two corrections and one finding that changes the security design. Correction one: the 304 response to `update_time` on `/nodes` is safe to use only from 26.05.3. The initial 26.05 releases also fail when partitions are unchanged (see Conditional queries below). On 24.11, 25.05, and 25.11 the same query goes through the generic error path, so the plugin must not rely on it unless it has checked the release. Correction two: native TLS is 25.05 and later, and needs the s2n library at build time. The finding: "GET-only" is not a safe allowlist. `GET /slurm/{parser}/reconfigure/` asks `slurmctld` to reconfigure, and on 26.05 `GET /slurm/{parser}/job/{job_id}/requeue` requeues a job. The plugin needs an exact list of path and method pairs, not a method rule. Least-privilege visibility, token behavior for a user with no association, and failure modes are *live*. ## Method @@ -51,7 +51,7 @@ Final allowlist for the plugin (exact method and path, no pattern match): `GET / | Fact | Evidence | Status | |---|---|---| | `update_time` is an accepted query parameter on jobs, partitions, nodes, reservations, and config | `add_parse(TIMESTAMP, update_time, ...)` at [v0.0.45 parsers.c lines 11273 to 11318](https://github.com/SchedMD/slurm/blob/599e8ac50eaff5547946f3f0687d9fe3bf44347f/src/plugins/data_parser/v0.0.45/parsers.c#L11273-L11318) | confirmed | -| `/nodes` returns 304 with an empty body when nothing changed | 26.05 [nodes.c lines 116 to 133](https://github.com/SchedMD/slurm/blob/599e8ac50eaff5547946f3f0687d9fe3bf44347f/src/slurmrestd/plugins/openapi/slurmctld/nodes.c#L116-L133) and [operations.c lines 362 to 377](https://github.com/SchedMD/slurm/blob/599e8ac50eaff5547946f3f0687d9fe3bf44347f/src/slurmrestd/operations.c#L362-L377); the 26.11 candidate has the same code | confirmed for 26.05 and later | +| `/nodes` returns 304 with an empty body when nothing changed | 26.05 [nodes.c lines 116 to 133](https://github.com/SchedMD/slurm/blob/599e8ac50eaff5547946f3f0687d9fe3bf44347f/src/slurmrestd/plugins/openapi/slurmctld/nodes.c#L116-L133) and [operations.c lines 362 to 377](https://github.com/SchedMD/slurm/blob/599e8ac50eaff5547946f3f0687d9fe3bf44347f/src/slurmrestd/operations.c#L362-L377); the 26.11 candidate has the same code | confirmed from 26.05.3; 26.05.0 to 26.05.2 send an unchanged answer to `resp_error` and pass `update_time` to the partition read too, an HTTP 500 when only partitions are unchanged ([26.05.3 changelog](https://github.com/SchedMD/slurm/blob/slurm-26-05-3-1/CHANGELOG/slurm-26.05.md)) | | On 24.11, 25.05, and 25.11 the nodes handler has no such branch: a failed `slurm_load_node` goes to `resp_error` with `errno` | [25.11 nodes.c lines 116 to 122](https://github.com/SchedMD/slurm/blob/5f7be9109e151bc59099786d7e3faccbca105869/src/slurmrestd/plugins/openapi/slurmctld/nodes.c#L116-L122) | **differs** from the plan; what status code a client then sees is *live* | | `/jobs/` returns 200 with a warning ("No job changes since update_time") when nothing changed | [26.05 jobs.c lines 131 to 140](https://github.com/SchedMD/slurm/blob/599e8ac50eaff5547946f3f0687d9fe3bf44347f/src/slurmrestd/plugins/openapi/slurmctld/jobs.c#L131-L140); present at 24.11 to 26.05 | confirmed | | `/partitions/` and `/reservations/` have no `SLURM_NO_CHANGE_IN_DATA` branch at any release checked | `git grep` over the four tags | confirmed | diff --git a/lib/CommandTransport.php b/lib/CommandTransport.php index 72e3414..e69b416 100644 --- a/lib/CommandTransport.php +++ b/lib/CommandTransport.php @@ -20,8 +20,8 @@ namespace Somethingwithproof\Hpcsched; /** - * Reads Slurm through its client commands, the default transport (decision - * #7, provisional). Authentication is the poller host's own munge or + * Reads Slurm through its client commands, the default transport (ADR + * 0012). Authentication is the poller host's own munge or * auth/slurm setup; no credential passes through the plugin. * * Every argument vector is fixed here: the binary is an absolute path from @@ -125,7 +125,14 @@ public function environment(): array { return $env; } - public function fetch(Section $section, string $dataParser, float $deadline): string { + /** + * The client commands have no conditional read. + */ + public function since(Section $section, ?SectionRecord $previous, string $release, int $now): int { + return 0; + } + + public function fetch(Section $section, string $dataParser, float $deadline, int $since = 0): string { if ($this->slurmConf !== '' && !Settings::pathAcceptable($this->slurmConf)) { throw new TransportError(ErrorClass::Config, 'slurm.conf path'); } diff --git a/lib/DataParser.php b/lib/DataParser.php index 0e711ec..df50064 100644 --- a/lib/DataParser.php +++ b/lib/DataParser.php @@ -22,7 +22,7 @@ /** * The Slurm data parser the plugin pins, chosen in Settings from the * versions below. v0.0.43 is the default because every supported release - * (25.05, 25.11, 26.05; decision #8, provisional) ships it, so one setting + * (25.05, 25.11, 26.05; ADR 0013) ships it, so one setting * serves a mixed site and an upgraded client package cannot change the shape * under the plugin (docs/research/slurm-client-output.md). SchedMD removes * v0.0.43 in 27.05, so a site on 25.11 or later can move to a newer parser @@ -51,6 +51,43 @@ public static function supported(string $version): bool { return in_array($version, self::VERSIONS, true); } + /** + * The supported versions, newest first: the order slurmrestd discovery + * tries them in (REQ-REST-002). + * + * @return list + */ + public static function newestFirst(): array { + return array_reverse(self::VERSIONS); + } + + /** + * The newest supported version a supported release ships, or null for a + * release the plugin does not support. + */ + public static function newestShippedBy(string $release): ?string { + foreach (self::newestFirst() as $version) { + if (self::shippedBy($release, $version)) { + return $version; + } + } + + return null; + } + + /** + * Whether a release is the given release or a later one, for example + * "26.05.5" against "26.05.3". A release without a patch level counts + * as its .0, and an unparsable release answers false. + */ + public static function atLeast(string $release, string $version): bool { + if (preg_match('/^(\d{2})\.(\d{2})(?:\.(\d+))?(?:[^\d.]|$)/', $release, $m) !== 1) { + return false; + } + + return version_compare($m[1] . '.' . $m[2] . '.' . ($m[3] ?? '0'), $version, '>='); + } + /** * Whether a reported release (for example "25.11.2") is a supported * major release. diff --git a/lib/HealthPage.php b/lib/HealthPage.php index 5265fcc..2880707 100644 --- a/lib/HealthPage.php +++ b/lib/HealthPage.php @@ -77,7 +77,7 @@ public function render(): void { (string) ($run->calls ?? 0), ($run->release ?? '') === '' ? '-' : (string) $run?->release, $cluster->transport->label(), - ($run->dataParser ?? '') === '' ? '-' : (string) $run?->dataParser, + self::parser($cluster, $run), Format::age($run->lastSuccess ?? 0, $now), ]); @@ -152,4 +152,18 @@ private function templateProblems(): array { return $problems; } + + /** + * The data parser of the last run: the Settings choice for client + * commands, the one discovered from the daemon for slurmrestd. + */ + private static function parser(Cluster $cluster, ?ClusterRun $run): string { + $parser = $run->dataParser ?? ''; + + if ($parser === '') { + return '-'; + } + + return $cluster->transport === Transport::Rest ? __('%s, discovered', $parser, 'hpcsched') : $parser; + } } diff --git a/lib/HealthWarnings.php b/lib/HealthWarnings.php index 57ffb9e..0ddfc0d 100644 --- a/lib/HealthWarnings.php +++ b/lib/HealthWarnings.php @@ -88,7 +88,7 @@ public static function for(Cluster $cluster, ?ClusterRun $run, Freshness $freshn if ($run->release !== '' && !DataParser::releaseSupported($run->release)) { $out[] = __('The scheduler reports Slurm %s, which is not a supported release (%s).', $run->release, implode(', ', DataParser::SUPPORTED_RELEASES), 'hpcsched'); - } elseif ($run->release !== '' && !DataParser::shippedBy($run->release, $settings->dataParser)) { + } elseif ($cluster->transport === Transport::Commands && $run->release !== '' && !DataParser::shippedBy($run->release, $settings->dataParser)) { $out[] = __('The scheduler reports Slurm %s, which does not ship the data parser %s chosen in Settings.', $run->release, $settings->dataParser, 'hpcsched'); } diff --git a/lib/HttpRequest.php b/lib/HttpRequest.php index 4aa2207..93cfd41 100644 --- a/lib/HttpRequest.php +++ b/lib/HttpRequest.php @@ -26,11 +26,13 @@ final readonly class HttpRequest { /** * @param array $headers + * @param array $query name => non-negative integer, the only query values the plugin sends */ public function __construct( public Endpoint $endpoint, public string $path, public array $headers = [], + public array $query = [], ) { } } diff --git a/lib/Reader.php b/lib/Reader.php index 16b5088..8ae28cc 100644 --- a/lib/Reader.php +++ b/lib/Reader.php @@ -68,9 +68,9 @@ private function runLeased(Cluster $cluster, int $budget, int $interval): Cluste $state = TokenState::None; try { - $transport = $this->transports->for($cluster, $redactor, $token); + $transport = $this->transports->for($cluster, $redactor, $token, $previous); $state = $token->state ?? TokenState::None; - $snapshot = (new SlurmBackend($transport, $this->clock))->collect($cluster, $deadline); + $snapshot = (new SlurmBackend($transport, $this->clock, $this->snapshots->sections($cluster->id), $previous->release))->collect($cluster, $deadline); $limited = $transport->memoryLimited(); } catch (TransportError $e) { $snapshot = $this->failed($cluster, $e->errorClass); diff --git a/lib/RestTransport.php b/lib/RestTransport.php index b32919b..835e17b 100644 --- a/lib/RestTransport.php +++ b/lib/RestTransport.php @@ -29,10 +29,22 @@ * (docs/research/slurmrestd.md). The allowlist only limits the plugin's own * requests; it does not restrict slurmrestd. * - * update_time is never sent: slurmrestd answers 304 when nothing changed, - * and the plugin wants a whole snapshot every run. A 304 anyway is recorded - * as not_modified with the section failed, so the previous data stays and - * is never read as empty. + * The data parser is discovered from the daemon (REQ-REST-002): the newest + * supported version whose ping/ path it serves, tried newest first. A 404 + * costs no controller call, and a 200 one ping. The reader passes the + * parser of the cluster's last completed run as $cached, so discovery runs + * on the first run, after a run that did not complete (a 404 among them), + * and when the release the daemon reports ships a newer supported parser. + * The setting in Settings applies to client commands only. + * + * update_time is sent only where an unchanged answer is unambiguous + * (REQ-REST-005, since()): /nodes/ from 26.05.3, which answers 304 with + * an empty body. A 304 to that request leaves the stored rows as they are and + * counts as a fresh read. /jobs/ answers an unchanged request with 200, a + * warning, and no jobs, which would read as an empty queue; partitions and + * reservations have no unchanged answer; shares take no update_time. A 304 + * to a request without update_time is recorded as not_modified with the + * section failed, so the previous data stays and is never read as empty. */ final class RestTransport implements SlurmTransport { /** @@ -46,15 +58,36 @@ final class RestTransport implements SlurmTransport { 'shares' => '/slurm/{p}/shares', ]; + /** Discovery's path: one read-only ping of the controllers. */ + public const PING = '/slurm/{p}/ping/'; + + /** + * The first release whose /nodes/ answers an unchanged request with 304. + * Before 26.05.3 the handler treats an unchanged answer as a failure, + * and passes update_time to its partition read too, so a node change + * with unchanged partitions fails with HTTP 500 (fixed in 26.05.3). + */ + public const CONDITIONAL_NODES_FROM = '26.05.3'; + + /** + * A conditional read is used only while the stored node rows are younger + * than this. On 26.05 the 304 follows node changes only, so a node moved + * between partitions without other change would keep its old partitions; + * a full read at least this often bounds that. + */ + public const FULL_READ_SECONDS = 600; + private int $calls = 0; + private string $parser = ''; + public function __construct( private readonly HttpTransport $http, private readonly Endpoint $endpoint, private readonly string $user, private readonly Token $token, private readonly float $callTimeout, - private readonly string $dataParser = DataParser::DEFAULT_VERSION, + private readonly string $cached = '', ) { } @@ -63,7 +96,11 @@ public function transport(): Transport { } public function dataParser(float $deadline): string { - return $this->dataParser; + if ($this->parser === '') { + $this->parser = DataParser::supported($this->cached) ? $this->cached : $this->discover($deadline); + } + + return $this->parser; } public function calls(): int { @@ -83,7 +120,7 @@ public static function allowed(string $path, string $dataParser): bool { return false; } - foreach (self::PATHS as $template) { + foreach (array_merge(self::PATHS, [self::PING]) as $template) { if ($path === str_replace('{p}', $dataParser, $template)) { return true; } @@ -92,7 +129,30 @@ public static function allowed(string $path, string $dataParser): bool { return false; } - public function fetch(Section $section, string $dataParser, float $deadline): string { + /** + * The update_time to send for a section, or 0 for an unconditional read. + * Only /nodes/ from 26.05.3, after a completed read whose rows are younger + * than FULL_READ_SECONDS. The time is the previous observation less the + * clock skew the freshness rules allow, so a change the controller + * stamped just before the previous read is never taken as old. + */ + public function since(Section $section, ?SectionRecord $previous, string $release, int $now): int { + if ($section !== Section::Nodes || $previous === null || $previous->state !== SectionState::Completed) { + return 0; + } + + if (!DataParser::atLeast($release, self::CONDITIONAL_NODES_FROM)) { + return 0; + } + + if ($previous->observedAt <= 0 || $now - $previous->ingestedAt > self::FULL_READ_SECONDS) { + return 0; + } + + return max(0, $previous->observedAt - FreshnessEvaluator::SKEW_ALLOWANCE); + } + + public function fetch(Section $section, string $dataParser, float $deadline, int $since = 0): string { if (!DataParser::supported($dataParser)) { throw new TransportError(ErrorClass::Config, 'data parser'); } @@ -103,6 +163,38 @@ public function fetch(Section $section, string $dataParser, float $deadline): st throw new TransportError(ErrorClass::Refused, 'path not on the allowlist'); } + $response = $this->get($path, $deadline, $since > 0 ? ['update_time' => $since] : []); + + if ($response->status === 304 && $since > 0) { + throw new Unchanged(); + } + + return $response->status === 200 ? $response->body : throw self::error($response->status); + } + + /** + * The newest supported data parser the daemon serves. + */ + private function discover(float $deadline): string { + foreach (DataParser::newestFirst() as $version) { + $status = $this->get(str_replace('{p}', $version, self::PING), $deadline)->status; + + if ($status === 200) { + return $version; + } + + if ($status !== 404) { + throw self::error($status); + } + } + + throw new TransportError(ErrorClass::Config, 'slurmrestd serves none of the data parsers ' . implode(', ', DataParser::VERSIONS)); + } + + /** + * @param array $query + */ + private function get(string $path, float $deadline, array $query = []): HttpResponse { $headers = ['X-SLURM-USER-TOKEN' => $this->token->secret->reveal()]; if ($this->user !== '') { @@ -115,17 +207,18 @@ public function fetch(Section $section, string $dataParser, float $deadline): st $this->calls++; - $response = $this->http->get(new HttpRequest($this->endpoint, $this->endpoint->basePath . $path, $headers), min($deadline, microtime(true) + $this->callTimeout)); + return $this->http->get(new HttpRequest($this->endpoint, $this->endpoint->basePath . $path, $headers, $query), min($deadline, microtime(true) + $this->callTimeout)); + } + private static function error(int $status): TransportError { return match (true) { - $response->status === 200 => $response->body, - $response->status === 304 => throw new TransportError(ErrorClass::NotModified, '304'), - $response->status === 401 => throw new TransportError(ErrorClass::Credential, '401'), - $response->status === 403 => throw new TransportError(ErrorClass::Access, '403'), - $response->status === 404 => throw new TransportError(ErrorClass::Config, '404: the data parser or endpoint is not offered'), - $response->status === 429 => throw new TransportError(ErrorClass::RateLimited, '429'), - $response->status === 502, $response->status === 503, $response->status === 504 => throw new TransportError(ErrorClass::Unreachable, (string) $response->status), - default => throw new TransportError(ErrorClass::Failed, (string) $response->status), + $status === 304 => new TransportError(ErrorClass::NotModified, '304'), + $status === 401 => new TransportError(ErrorClass::Credential, '401'), + $status === 403 => new TransportError(ErrorClass::Access, '403'), + $status === 404 => new TransportError(ErrorClass::Config, '404: the data parser or endpoint is not offered'), + $status === 429 => new TransportError(ErrorClass::RateLimited, '429'), + $status === 502, $status === 503, $status === 504 => new TransportError(ErrorClass::Unreachable, (string) $status), + default => new TransportError(ErrorClass::Failed, (string) $status), }; } } diff --git a/lib/SectionOutcome.php b/lib/SectionOutcome.php index b30749c..4b3e4a9 100644 --- a/lib/SectionOutcome.php +++ b/lib/SectionOutcome.php @@ -20,10 +20,15 @@ namespace Somethingwithproof\Hpcsched; final readonly class SectionOutcome { + /** + * @param bool $unchanged a completed conditional read that found nothing + * changed: the stored rows stay and count as read now + */ public function __construct( public SectionState $state, public ?ErrorClass $error = null, public int $records = 0, + public bool $unchanged = false, ) { } @@ -31,6 +36,10 @@ public static function completed(int $records): self { return new self(SectionState::Completed, null, $records); } + public static function unchanged(int $records): self { + return new self(SectionState::Completed, null, $records, true); + } + public static function failed(ErrorClass $error): self { return new self(SectionState::Failed, $error); } diff --git a/lib/Settings.php b/lib/Settings.php index 557b682..77ac06c 100644 --- a/lib/Settings.php +++ b/lib/Settings.php @@ -246,7 +246,7 @@ public static function form(): array { ], 'hpcsched_data_parser' => [ 'friendly_name' => __('Data Parser', 'hpcsched'), - 'description' => __('Slurm data parser for every call, through client commands and slurmrestd alike. Choose one that every cluster\'s release ships: v0.0.43 is in 25.05, 25.11, and 26.05 and is removed in 27.05; v0.0.44 needs 25.11 or later; v0.0.45 needs 26.05 or later. The health page warns when a cluster reports a release without it.', 'hpcsched'), + 'description' => __('Slurm data parser for the client commands. Choose one that the release of every cluster read through client commands ships: v0.0.43 is in 25.05, 25.11, and 26.05 and is removed in 27.05; v0.0.44 needs 25.11 or later; v0.0.45 needs 26.05 or later. The health page warns when a cluster reports a release without it. Clusters read through slurmrestd ignore this setting: they use the newest of these the daemon serves, and the health page shows which.', 'hpcsched'), 'method' => 'drop_array', 'array' => array_combine(DataParser::VERSIONS, DataParser::VERSIONS), 'default' => DataParser::DEFAULT_VERSION, diff --git a/lib/SlurmBackend.php b/lib/SlurmBackend.php index f3da71f..8d9e9e8 100644 --- a/lib/SlurmBackend.php +++ b/lib/SlurmBackend.php @@ -26,12 +26,20 @@ * class and keeps no data, so a failure is never read as an empty section * (REQ-BACKEND-003). After a rate limit or a refused credential the rest of * the run is not attempted, since every later call would meet the same - * answer and add load. + * answer and add load. A conditional read that finds nothing changed + * completes its section with no data and is marked unchanged; the snapshot + * write keeps that section's stored rows. */ final class SlurmBackend implements Backend { + /** + * @param array $previous the cluster's stored section records, for conditional reads + * @param string $release the release the scheduler reported on the last run + */ public function __construct( private readonly SlurmTransport $transport, private readonly Clock $clock, + private readonly array $previous = [], + private readonly string $release = '', ) { } @@ -64,8 +72,19 @@ public function collect(Cluster $cluster, float $deadline): Snapshot { continue; } + $stored = $this->previous[$section->value] ?? null; + + // An edit can point this cluster at another controller. A read + // observed before that edit cannot validate the new endpoint's + // rows, even if that endpoint answers a conditional read with 304. + if ($stored !== null && $stored->observedAt <= $cluster->updatedAt) { + $stored = null; + } + + $since = $this->transport->since($section, $stored, $this->release, $this->clock->now()); + try { - $doc = SlurmJson::decode($this->transport->fetch($section, $parser, $deadline)); + $doc = SlurmJson::decode($this->transport->fetch($section, $parser, $deadline, $since)); $release = $release !== '' ? $release : SlurmJson::release($doc); $parsed = match ($section) { @@ -80,6 +99,10 @@ public function collect(Cluster $cluster, float $deadline): Snapshot { $data[$section->value] = $parsed; $outcomes[$section->value] = SectionOutcome::completed($parsed instanceof JobTally ? $parsed->total() : count($parsed)); + } catch (Unchanged) { + // Only a conditional read answers Unchanged, and only after a + // completed one, so the stored rows are the scheduler's. + $outcomes[$section->value] = SectionOutcome::unchanged($stored->records ?? 0); } catch (TransportError $e) { $outcomes[$section->value] = SectionOutcome::failed($e->errorClass); $stop = $e->errorClass->backsOff() || $e->errorClass === ErrorClass::Credential; diff --git a/lib/SlurmTransport.php b/lib/SlurmTransport.php index e4b2571..fca9dfa 100644 --- a/lib/SlurmTransport.php +++ b/lib/SlurmTransport.php @@ -38,11 +38,20 @@ public function transport(): Transport; public function dataParser(float $deadline): string; /** - * The raw JSON document for one section. + * The update_time for a conditional read of a section, given its stored + * record and the release the scheduler last reported, or 0 to read it + * whole. + */ + public function since(Section $section, ?SectionRecord $previous, string $release, int $now): int; + + /** + * The raw JSON document for one section. With $since above 0 the read + * is conditional. * * @throws TransportError + * @throws Unchanged when a conditional read found nothing changed */ - public function fetch(Section $section, string $dataParser, float $deadline): string; + public function fetch(Section $section, string $dataParser, float $deadline, int $since = 0): string; /** * Scheduler calls made so far, for the run record. diff --git a/lib/SnapshotRepository.php b/lib/SnapshotRepository.php index 98a29fc..dcb6785 100644 --- a/lib/SnapshotRepository.php +++ b/lib/SnapshotRepository.php @@ -53,7 +53,7 @@ public function apply(int $clusterId, string $holder, int $now, int $interval, S $section = Section::from($name); - if ($outcome->state === SectionState::Completed) { + if ($outcome->state === SectionState::Completed && !$outcome->unchanged) { $ok = $this->replace($clusterId, $section, $snapshot, $stamps) && $this->inTransaction(); // The node counts are the nodes section's, so they are @@ -80,10 +80,27 @@ public function apply(int $clusterId, string $holder, int $now, int $interval, S return false; } + /** + * The cluster's stored section records, which the reader passes to the + * backend for conditional reads. + * + * @return array section value => record + */ + public function sections(int $clusterId): array { + return (new SeriesRepository($this->connection))->sections($clusterId); + } + /** * @param array{int, int, int} $stamps observed, ingested, interval */ private function section(int $clusterId, Section $section, SectionOutcome $outcome, int $now, array $stamps): bool { + // Nothing changed since the last read: the rows stay, and so do their + // ingestion time and count, but the data is current as of this run. + if ($outcome->unchanged) { + return db_execute_prepared('UPDATE plugin_hpcsched_section SET state = ?, error_class = \'\', attempted_at = ?, observed_at = ?, collect_interval = ? WHERE cluster_id = ? AND section = ?', + [$outcome->state->value, $now, $stamps[0], $stamps[2], $clusterId, $section->value], true, $this->connection) !== false; + } + if ($outcome->state === SectionState::Completed) { return db_execute_prepared('INSERT INTO plugin_hpcsched_section (cluster_id, section, state, error_class, attempted_at, records, observed_at, ingested_at, collect_interval) VALUES (?, ?, ?, \'\', ?, ?, ?, ?, ?) diff --git a/lib/SocketTransport.php b/lib/SocketTransport.php index be60ce6..dd90d3a 100644 --- a/lib/SocketTransport.php +++ b/lib/SocketTransport.php @@ -49,9 +49,21 @@ public function get(HttpRequest $request, float $deadline): HttpResponse { throw new TransportError(ErrorClass::Refused, 'path'); } + $query = []; + + foreach ($request->query as $name => $value) { + if (preg_match('/^[a-z_]+$/', $name) !== 1 || $value < 0) { + throw new TransportError(ErrorClass::Refused, 'query'); + } + + $query[] = $name . '=' . $value; + } + + $target = $request->path . ($query === [] ? '' : '?' . implode('&', $query)); + // A CR or LF in a name or value would let a caller inject headers or // a second request. - $raw = 'GET ' . $request->path . " HTTP/1.1\r\nHost: " . $endpoint->hostHeader() . "\r\nConnection: close\r\nAccept: application/json\r\n"; + $raw = 'GET ' . $target . " HTTP/1.1\r\nHost: " . $endpoint->hostHeader() . "\r\nConnection: close\r\nAccept: application/json\r\n"; foreach ($request->headers as $name => $value) { if (preg_match('/^[!#$%&\'*+.^_`|~0-9A-Za-z-]+$/', $name) !== 1 || preg_match('/[\r\n\x00]/', $value) === 1) { diff --git a/lib/Transport.php b/lib/Transport.php index 3a46b7e..5d1f9b9 100644 --- a/lib/Transport.php +++ b/lib/Transport.php @@ -21,7 +21,7 @@ /** * How a cluster's scheduler is read. Client commands are the default - * (decision #7, provisional); slurmrestd is the configurable alternative. + * (ADR 0012); slurmrestd is the configurable alternative. */ enum Transport: string { case Commands = 'commands'; diff --git a/lib/Transports.php b/lib/Transports.php index 0fadc86..2ad82cb 100644 --- a/lib/Transports.php +++ b/lib/Transports.php @@ -35,7 +35,7 @@ public function __construct( * @throws TransportError for a REST cluster whose URL is not allowed * @throws CredentialError for a REST cluster whose token file is refused */ - public function for(Cluster $cluster, Redactor $redactor, ?Token &$token = null): SlurmTransport { + public function for(Cluster $cluster, Redactor $redactor, ?Token &$token = null, ?ClusterRun $previous = null): SlurmTransport { if ($cluster->transport === Transport::Commands) { return new CommandTransport($this->runner, $this->settings, $cluster->slurmConf); } @@ -50,6 +50,23 @@ public function for(Cluster $cluster, Redactor $redactor, ?Token &$token = null) $redactor->add($token->secret); - return new RestTransport($this->http, $endpoint, $cluster->restUser, $token, (float) $this->settings->callTimeout, $this->settings->dataParser); + return new RestTransport($this->http, $endpoint, $cluster->restUser, $token, (float) $this->settings->callTimeout, self::cachedParser($previous)); + } + + /** + * The data parser discovered on the cluster's last run, while it can + * still be trusted: that run read slurmrestd and completed, and the + * release it reported ships no newer supported parser. Otherwise '' + * (discover again), so a 404 or an upgraded daemon leads to a fresh + * discovery on the next run (REQ-REST-002). + */ + public static function cachedParser(?ClusterRun $previous): string { + if ($previous === null || $previous->transport !== Transport::Rest->value || $previous->outcome !== RunOutcome::Completed || !DataParser::supported($previous->dataParser)) { + return ''; + } + + $newest = DataParser::newestShippedBy($previous->release); + + return $newest === null || $newest === $previous->dataParser ? $previous->dataParser : ''; } } diff --git a/lib/Unchanged.php b/lib/Unchanged.php new file mode 100644 index 0000000..54ca3fc --- /dev/null +++ b/lib/Unchanged.php @@ -0,0 +1,28 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_hpcsched, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_hpcsched + * + * 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\Hpcsched; + +/** + * A conditional read the scheduler answered with "nothing changed since + * update_time" (REQ-REST-005). Not an error: the stored rows are still the + * scheduler's data, and the section counts as freshly read. + */ +final class Unchanged extends \RuntimeException { +} diff --git a/locales/po/cacti.pot b/locales/po/cacti.pot index a8ce813..34b9418 100644 --- a/locales/po/cacti.pot +++ b/locales/po/cacti.pot @@ -532,6 +532,11 @@ msgstr "" msgid "Some HPC Scheduler templates are missing from Cacti. Install them below." msgstr "" +#: lib/HealthPage.php +#, php-format +msgid "%s, discovered" +msgstr "" + #: lib/HealthWarnings.php #, php-format msgid "Maximum Answer Size is %d MiB, but a decoded answer of that size does not fit in the Collection Memory of %d MiB; the reader allows %d MiB. Raise Collection Memory or lower Maximum Answer Size in Settings." @@ -839,7 +844,7 @@ msgid "Data Parser" msgstr "" #: lib/Settings.php -msgid "Slurm data parser for every call, through client commands and slurmrestd alike. Choose one that every cluster's release ships: v0.0.43 is in 25.05, 25.11, and 26.05 and is removed in 27.05; v0.0.44 needs 25.11 or later; v0.0.45 needs 26.05 or later. The health page warns when a cluster reports a release without it." +msgid "Slurm data parser for the client commands. Choose one that the release of every cluster read through client commands ships: v0.0.43 is in 25.05, 25.11, and 26.05 and is removed in 27.05; v0.0.44 needs 25.11 or later; v0.0.45 needs 26.05 or later. The health page warns when a cluster reports a release without it. Clusters read through slurmrestd ignore this setting: they use the newest of these the daemon serves, and the health page shows which." msgstr "" #: lib/Settings.php diff --git a/tests/Integration/LifecycleTest.php b/tests/Integration/LifecycleTest.php index 9accc48..d4c2779 100644 --- a/tests/Integration/LifecycleTest.php +++ b/tests/Integration/LifecycleTest.php @@ -279,8 +279,10 @@ $r = lifecycle('reader_flow')['result']; - expect($r['rest1'])->toBe(['outcome' => 'completed', 'error' => null, 'calls' => 5, 'release' => '25.11.2', 'limited' => true, 'token' => 'group_readable']) - ->and($r['requests1'])->toBe(['/slurm/v0.0.43/jobs/', '/slurm/v0.0.43/nodes/', '/slurm/v0.0.43/partitions/', '/slurm/v0.0.43/reservations/', '/slurm/v0.0.43/shares']) + // One discovery ping finds the newest parser the fake serves; the fake + // reports 25.11, so no read is conditional. + expect($r['rest1'])->toBe(['outcome' => 'completed', 'error' => null, 'calls' => 6, 'release' => '25.11.2', 'limited' => true, 'token' => 'group_readable']) + ->and($r['requests1'])->toBe(['/slurm/v0.0.45/ping/', '/slurm/v0.0.45/jobs/', '/slurm/v0.0.45/nodes/', '/slurm/v0.0.45/partitions/', '/slurm/v0.0.45/reservations/', '/slurm/v0.0.45/shares']) ->and($r['rest2'])->toMatchArray(['outcome' => 'failed', 'error' => 'credential', 'calls' => 1]) ->and($r['nodes2'])->toBe(8) ->and($r['token_found'])->toBeFalse(); diff --git a/tests/Support/StubTransport.php b/tests/Support/StubTransport.php index 3f2f4e8..402baca 100644 --- a/tests/Support/StubTransport.php +++ b/tests/Support/StubTransport.php @@ -21,9 +21,11 @@ use Somethingwithproof\Hpcsched\ErrorClass; use Somethingwithproof\Hpcsched\Section; +use Somethingwithproof\Hpcsched\SectionRecord; use Somethingwithproof\Hpcsched\SlurmTransport; use Somethingwithproof\Hpcsched\Transport; use Somethingwithproof\Hpcsched\TransportError; +use Somethingwithproof\Hpcsched\Unchanged; // Test code: refuse to run from a web request. PHP_SAPI === 'cli' || exit(1); @@ -36,10 +38,18 @@ final class StubTransport implements SlurmTransport { /** @var list */ public array $fetched = []; + /** @var array section value => update_time sent */ + public array $since = []; + /** - * @param array $answers section value => JSON or error + * @param array $answers section value => JSON or error + * @param array $conditional section value => update_time to ask for; such a read answers Unchanged */ - public function __construct(private readonly array $answers, private readonly float $delay = 0.0) { + public function __construct(private readonly array $answers, private readonly float $delay = 0.0, private readonly array $conditional = []) { + } + + public function since(Section $section, ?SectionRecord $previous, string $release, int $now): int { + return $this->conditional[$section->value] ?? 0; } public function transport(): Transport { @@ -50,9 +60,15 @@ public function dataParser(float $deadline): string { return 'v0.0.43'; } - public function fetch(Section $section, string $dataParser, float $deadline): string { + public function fetch(Section $section, string $dataParser, float $deadline, int $since = 0): string { $this->fetched[] = $section->value; + if ($since > 0) { + $this->since[$section->value] = $since; + + throw new Unchanged(); + } + if ($this->delay > 0) { usleep((int) ($this->delay * 1e6)); } diff --git a/tests/Support/fake-slurmrestd.php b/tests/Support/fake-slurmrestd.php index e055df7..1d4780f 100644 --- a/tests/Support/fake-slurmrestd.php +++ b/tests/Support/fake-slurmrestd.php @@ -55,6 +55,7 @@ "/slurm/$parser/partitions/" => 'partitions', "/slurm/$parser/reservations/" => 'reservations', "/slurm/$parser/shares" => 'shares', + "/slurm/$parser/ping/" => 'ping', ]; } @@ -99,12 +100,26 @@ function respond($conn, int $status, string $body, string $extra = ''): void { $scenario = $headers['x-slurm-user-name'] ?? 'ok'; $token = $headers['x-slurm-user-token'] ?? ''; - $section = $routes[$target] ?? null; + [$path] = explode('?', $target, 2); + $section = $routes[$path] ?? null; + $parser = explode('/', $path)[2] ?? ''; + + // Served data parsers: every one by default, only v0.0.43 (a 25.05 + // daemon), or none the plugin supports. + if (($scenario === 'only43' && $parser !== 'v0.0.43') || $scenario === 'noparsers') { + $section = null; + } file_put_contents($logFile, json_encode(['method' => $method, 'target' => $target, 'token' => $token !== '', 'token_sha' => hash('sha256', $token)]) . "\n", FILE_APPEND); if ($method !== 'GET' || $section === null) { respond($conn, 404, '{"errors":[{"error":"Unable to find requested URL"}]}'); + } elseif ($section === 'ping' && in_array($scenario, ['ok', 'only43', 'nodes304'], true)) { + respond($conn, 200, '{"pings":[{"hostname":"ctl","pinged":"UP"}]}'); + } elseif ($scenario === 'nodes304' && $section === 'nodes' && str_contains($target, '?update_time=')) { + // 26.05: /nodes/ with update_time answers 304 and no body when + // nothing changed. + @fwrite($conn, "HTTP/1.1 304 Not Modified\r\nConnection: close\r\nContent-Length: 0\r\n\r\n"); } else { match ($scenario) { 'notmodified' => @fwrite($conn, "HTTP/1.1 304 Not Modified\r\nConnection: close\r\nContent-Length: 40\r\n\r\n"), diff --git a/tests/Unit/HealthWarningsTest.php b/tests/Unit/HealthWarningsTest.php index 0455cb1..479c76e 100644 --- a/tests/Unit/HealthWarningsTest.php +++ b/tests/Unit/HealthWarningsTest.php @@ -69,9 +69,13 @@ function hpcsched_rest_config(string $url = 'https://slurm.example.org'): Cluste ->and($text)->toContain('stale'); }); -it('warns when a cluster reports a release that does not ship the chosen data parser', function () { - $run = static fn (string $release): ClusterRun => new ClusterRun(1, outcome: RunOutcome::Completed, release: $release, memoryLimited: true, tokenState: TokenState::Ok); - $for = static fn (string $parser, string $release): string => implode("\n", HealthWarnings::for(hpcsched_rest_config(), $run($release), Freshness::Current, Settings::fromRow(['hpcsched_data_parser' => $parser]), 60, 100000)); +it('warns when a cluster on client commands reports a release that does not ship the chosen data parser', function () { + $run = static fn (string $release): ClusterRun => new ClusterRun(1, outcome: RunOutcome::Completed, release: $release, memoryLimited: true, tokenState: TokenState::Ok); + $commands = new Cluster(1, 'demo', 1, AdminState::Enabled, Transport::Commands, 60); + $for = static fn (string $parser, string $release, ?Cluster $cluster = null): string => implode("\n", HealthWarnings::for($cluster ?? $commands, $run($release), Freshness::Current, Settings::fromRow(['hpcsched_data_parser' => $parser]), 60, 100000)); + + // slurmrestd clusters discover their parser, so the setting is not theirs. + expect($for('v0.0.45', '25.11.2', hpcsched_rest_config()))->not->toContain('does not ship'); expect($for('v0.0.45', '25.11.2'))->toContain('Slurm 25.11.2, which does not ship the data parser v0.0.45') ->and($for('v0.0.44', '25.05.4'))->toContain('does not ship the data parser v0.0.44') diff --git a/tests/Unit/ReaderTest.php b/tests/Unit/ReaderTest.php index de01d87..cf757f9 100644 --- a/tests/Unit/ReaderTest.php +++ b/tests/Unit/ReaderTest.php @@ -22,6 +22,7 @@ use Somethingwithproof\Hpcsched\AdminState; use Somethingwithproof\Hpcsched\Cluster; +use Somethingwithproof\Hpcsched\ClusterRun; use Somethingwithproof\Hpcsched\ClusterRepository; use Somethingwithproof\Hpcsched\CommandRunner; use Somethingwithproof\Hpcsched\ErrorClass; @@ -67,6 +68,10 @@ function hpcsched_rest_cluster(Scratch $scratch): Cluster { * @param array $responses */ function hpcsched_reader_for(array $responses, FixedClock $clock): Reader { + // Discovery's first ping, for the newest parser, answers unless a test + // says otherwise. + $responses += ['/ping/' => new HttpResponse(200, [], '{}')]; + return new Reader(new RunRepository(false, $clock), new SnapshotRepository(false), new Transports(Settings::fromRow(['hpcsched_token_dirs' => sys_get_temp_dir()]), new CommandRunner(), new StubHttp($responses)), $clock, 'test'); } @@ -98,7 +103,8 @@ function hpcsched_sql(): array { expect($run->outcome)->toBe(RunOutcome::Completed) ->and($run->release)->toBe('26.05.0') - ->and($run->calls)->toBe(5) + // One discovery ping and five sections. + ->and($run->calls)->toBe(6) ->and($run->lastSuccess)->toBe(100000) ->and(array_count_values($sql)['BEGIN'])->toBe(1) ->and(array_count_values($sql)['COMMIT'])->toBe(1) @@ -268,8 +274,75 @@ function hpcsched_sql(): array { } expect($run->outcome)->toBe(RunOutcome::Completed) - ->and($run->calls)->toBe(3) + ->and($run->calls)->toBe(4) ->and($run->overran)->toBeFalse() ->and($run->duration)->toBeLessThan((float) $cluster->budget(60)) ->and($nodeRows)->toBe(10000); }); + +describe('discovered parser and conditional reads (REQ-REST-002, REQ-REST-005)', function () { + it('reads nodes unconditionally after the REST endpoint changes', function (int $editedAt) { + $clock = new FixedClock(100000); + $GLOBALS['__hpcsched_db_rows']['SELECT * FROM plugin_hpcsched_run WHERE cluster_id'] = [['cluster_id' => 1, 'outcome' => 'completed', 'transport' => 'rest', 'data_parser' => 'v0.0.45', 'slurm_release' => '26.05.3']]; + $GLOBALS['__hpcsched_db_rows']['FROM plugin_hpcsched_section WHERE cluster_id'] = [ + ['cluster_id' => 1, 'section' => 'nodes', 'state' => 'completed', 'observed_at' => 99940, 'ingested_at' => 99970, 'records' => 8, 'collect_interval' => 60], + ]; + $cluster = new Cluster(1, 'edited', 1, AdminState::Enabled, Transport::Rest, 60, restUrl: 'https://new-slurm.example.org', tokenFile: $this->scratch->file('token', 'opaque', 0600), updatedAt: $editedAt); + $http = new StubHttp(hpcsched_fixture_responses()); + $reader = new Reader(new RunRepository(false, $clock), new SnapshotRepository(false), new Transports(Settings::fromRow(['hpcsched_token_dirs' => sys_get_temp_dir()]), new CommandRunner(), $http), $clock, 'test'); + $run = $reader->run($cluster, 60); + $nodes = array_values(array_filter($http->requests, static fn ($r): bool => str_ends_with($r->path, '/nodes/'))); + + expect($run->outcome)->toBe(RunOutcome::Completed) + ->and($nodes[0]->query)->toBe([]) + ->and($nodes[0]->endpoint->host)->toBe('new-slurm.example.org') + ->and(hpcsched_sql())->toContain('DELETE FROM plugin_hpcsched_node WHERE cluster_id = ?'); + })->with([99940, 99950, 99980]); + + it('trusts the parser of the last completed slurmrestd run only while its release ships no newer one', function () { + $run = static fn (string $parser, string $release, RunOutcome $outcome = RunOutcome::Completed, string $transport = 'rest'): ClusterRun => new ClusterRun(1, outcome: $outcome, release: $release, transport: $transport, dataParser: $parser); + + expect(Transports::cachedParser(null))->toBe('') + ->and(Transports::cachedParser($run('v0.0.45', '26.05.5')))->toBe('v0.0.45') + ->and(Transports::cachedParser($run('v0.0.44', '25.11.8')))->toBe('v0.0.44') + ->and(Transports::cachedParser($run('v0.0.43', '25.05.4')))->toBe('v0.0.43') + // Upgraded to a release that ships a newer parser: discover again. + ->and(Transports::cachedParser($run('v0.0.44', '26.05.5')))->toBe('') + // A run that did not complete, a 404 among the causes: discover again. + ->and(Transports::cachedParser($run('v0.0.45', '26.05.5', RunOutcome::Partial)))->toBe('') + ->and(Transports::cachedParser($run('v0.0.45', '26.05.5', RunOutcome::Failed)))->toBe('') + ->and(Transports::cachedParser($run('v0.0.43', '26.05.5', transport: 'commands')))->toBe('') + ->and(Transports::cachedParser($run('v0.0.42', '25.11.8')))->toBe('') + // A release the plugin does not know keeps the parser that worked. + ->and(Transports::cachedParser($run('v0.0.45', '27.05.0')))->toBe('v0.0.45'); + }); + + it('keeps the node rows on a 304 to a conditional read and counts the section as read now', function () { + $clock = new FixedClock(100000); + $GLOBALS['__hpcsched_db_rows']['SELECT * FROM plugin_hpcsched_run WHERE cluster_id'] = [['cluster_id' => 1, 'outcome' => 'completed', 'transport' => 'rest', 'data_parser' => 'v0.0.45', 'slurm_release' => '26.05.3']]; + $GLOBALS['__hpcsched_db_rows']['FROM plugin_hpcsched_section WHERE cluster_id'] = [ + ['cluster_id' => 1, 'section' => 'nodes', 'state' => 'completed', 'attempted_at' => 99940, 'records' => 8, 'observed_at' => 99940, 'ingested_at' => 99940, 'collect_interval' => 60], + ]; + $responses = hpcsched_fixture_responses(); + $responses['/nodes/'] = new HttpResponse(304, [], ''); + $http = new StubHttp($responses); + $reader = new Reader(new RunRepository(false, $clock), new SnapshotRepository(false), new Transports(Settings::fromRow(['hpcsched_token_dirs' => sys_get_temp_dir()]), new CommandRunner(), $http), $clock, 'test'); + $run = $reader->run(hpcsched_rest_cluster($this->scratch), 60); + $sql = hpcsched_sql(); + $nodes = array_values(array_filter($http->requests, static fn ($r): bool => str_ends_with($r->path, '/nodes/'))); + $update = array_values(array_filter($GLOBALS['__hpcsched_db_exec'], static fn (array $st): bool => str_starts_with($st['sql'], 'UPDATE plugin_hpcsched_section SET state'))); + + expect($run->outcome)->toBe(RunOutcome::Completed) + ->and($run->dataParser)->toBe('v0.0.45') + // The cached parser: no ping. + ->and(array_filter($http->requests, static fn ($r): bool => str_ends_with($r->path, '/ping/')))->toBe([]) + ->and($nodes[0]->path)->toBe('/slurm/v0.0.45/nodes/') + ->and($nodes[0]->query)->toBe(['update_time' => 99940 - 120]) + ->and($run->calls)->toBe(5) + // The node rows and their counts are not touched; the other sections are replaced. + ->and(array_filter($sql, static fn (string $q): bool => str_contains($q, 'plugin_hpcsched_node ') || str_contains($q, 'plugin_hpcsched_node_count')))->toBe([]) + ->and(in_array('DELETE FROM plugin_hpcsched_job_count WHERE cluster_id = ?', $sql, true))->toBeTrue() + ->and($update)->toHaveCount(1) + ->and($update[0]['params'])->toBe(['completed', 100000, 100000, 60, 1, 'nodes']); + }); +}); diff --git a/tests/Unit/RestTransportTest.php b/tests/Unit/RestTransportTest.php index dbbaeb7..27abda0 100644 --- a/tests/Unit/RestTransportTest.php +++ b/tests/Unit/RestTransportTest.php @@ -21,16 +21,20 @@ use Somethingwithproof\Hpcsched\DataParser; use Somethingwithproof\Hpcsched\Endpoint; +use Somethingwithproof\Hpcsched\HttpRequest; use Somethingwithproof\Hpcsched\ErrorClass; use Somethingwithproof\Hpcsched\RestTransport; use Somethingwithproof\Hpcsched\Secret; use Somethingwithproof\Hpcsched\Section; +use Somethingwithproof\Hpcsched\SectionRecord; +use Somethingwithproof\Hpcsched\SectionState; use Somethingwithproof\Hpcsched\SlurmJson; use Somethingwithproof\Hpcsched\SocketTransport; use Somethingwithproof\Hpcsched\Tests\FakeRestd; use Somethingwithproof\Hpcsched\Token; use Somethingwithproof\Hpcsched\TokenState; use Somethingwithproof\Hpcsched\TransportError; +use Somethingwithproof\Hpcsched\Unchanged; /* * The slurmrestd transport against tests/Support/fake-slurmrestd.php on a @@ -39,8 +43,15 @@ const HPCSCHED_TEST_TOKEN = 'eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjQxMDI0NDQ4MDAsInN1biI6ImNhY3RpIn0.c2lnbmF0dXJl'; -function hpcsched_rest(FakeRestd $server, string $scenario = 'ok', int $maxBytes = 8388608, ?string $ca = null, string $parser = DataParser::DEFAULT_VERSION): RestTransport { - return new RestTransport(new SocketTransport($maxBytes, 2.0, $ca ?? ($server->mode === 'tls' ? $server->ca() : null)), Endpoint::parse($server->url()), $scenario, new Token(new Secret(HPCSCHED_TEST_TOKEN), TokenState::Ok, 0), 5.0, $parser); +/** + * $cached is the parser of the cluster's last completed run; '' discovers. + */ +function hpcsched_rest(FakeRestd $server, string $scenario = 'ok', int $maxBytes = 8388608, ?string $ca = null, string $cached = DataParser::DEFAULT_VERSION): RestTransport { + return new RestTransport(new SocketTransport($maxBytes, 2.0, $ca ?? ($server->mode === 'tls' ? $server->ca() : null)), Endpoint::parse($server->url()), $scenario, new Token(new Secret(HPCSCHED_TEST_TOKEN), TokenState::Ok, 0), 5.0, $cached); +} + +function hpcsched_nodes_record(string $state = 'completed', int $observed = 99940, int $ingested = 99940): SectionRecord { + return new SectionRecord(1, Section::Nodes, SectionState::from($state), null, $observed, 8, $observed, $ingested, 60); } function hpcsched_rest_error(callable $call): ?ErrorClass { @@ -130,6 +141,8 @@ function hpcsched_rest_error(callable $call): ?ErrorClass { })->with([ ['/slurm/v0.0.43/jobs/', true], ['/slurm/v0.0.43/shares', true], + ['/slurm/v0.0.43/ping/', true], + ['/slurm/v0.0.43/diag/', false], ['/slurm/v0.0.43/reconfigure/', false], ['/slurm/v0.0.43/job/1/requeue', false], ['/slurm/v0.0.43/jobs/?update_time=1', false], @@ -152,9 +165,9 @@ function hpcsched_rest_error(callable $call): ?ErrorClass { ['v0.0.43/../v0.0.45', '/slurm/v0.0.43/../v0.0.45/jobs/', false], ]); -it('requests the paths of the data parser it was given and refuses one outside the supported set', function () { +it('requests the paths of the cached data parser and refuses one outside the supported set', function () { $before = count($GLOBALS['__hpcsched_plain']->requests()); - $transport = hpcsched_rest($GLOBALS['__hpcsched_plain'], parser: 'v0.0.45'); + $transport = hpcsched_rest($GLOBALS['__hpcsched_plain'], cached: 'v0.0.45'); expect($transport->dataParser(microtime(true) + 10))->toBe('v0.0.45'); @@ -191,3 +204,103 @@ function hpcsched_rest_error(callable $call): ?ErrorClass { ['https://slurm example.org', false], ['', false], ]); + +describe('data parser discovery (REQ-REST-002)', function () { + it('picks the newest supported parser the daemon serves, with one ping when that is the newest', function () { + $server = $GLOBALS['__hpcsched_plain']; + $before = count($server->requests()); + $transport = hpcsched_rest($server, 'ok', cached: ''); + + expect($transport->dataParser(microtime(true) + 10))->toBe('v0.0.45') + ->and($transport->dataParser(microtime(true) + 10))->toBe('v0.0.45') + ->and(array_column(array_slice($server->requests(), $before), 'target'))->toBe(['/slurm/v0.0.45/ping/']) + ->and($transport->calls())->toBe(1); + }); + + it('falls back newest first through the supported list', function () { + $server = $GLOBALS['__hpcsched_plain']; + $before = count($server->requests()); + $transport = hpcsched_rest($server, 'only43', cached: ''); + + expect($transport->dataParser(microtime(true) + 10))->toBe('v0.0.43') + ->and(array_column(array_slice($server->requests(), $before), 'target'))->toBe(['/slurm/v0.0.45/ping/', '/slurm/v0.0.44/ping/', '/slurm/v0.0.43/ping/']); + }); + + it('fails as configuration when the daemon serves no supported parser, and stops at a refused credential', function () { + $server = $GLOBALS['__hpcsched_plain']; + $before = count($server->requests()); + + expect(hpcsched_rest_error(fn () => hpcsched_rest($server, 'noparsers', cached: '')->dataParser(microtime(true) + 10)))->toBe(ErrorClass::Config); + + $middle = count($server->requests()); + + expect($middle - $before)->toBe(3) + ->and(hpcsched_rest_error(fn () => hpcsched_rest($server, 'unauth', cached: '')->dataParser(microtime(true) + 10)))->toBe(ErrorClass::Credential) + ->and(count($server->requests()) - $middle)->toBe(1); + }); + + it('uses a cached parser without asking the daemon', function () { + $server = $GLOBALS['__hpcsched_plain']; + $before = count($server->requests()); + $transport = hpcsched_rest($server, 'ok', cached: 'v0.0.44'); + + expect($transport->dataParser(microtime(true) + 10))->toBe('v0.0.44') + ->and(count($server->requests()))->toBe($before) + ->and($transport->calls())->toBe(0); + }); +}); + +describe('conditional reads (REQ-REST-005)', function () { + it('asks /nodes/ for changes only on 26.05.3 and later, after a recent completed read', function () { + $t = hpcsched_rest($GLOBALS['__hpcsched_plain']); + + expect($t->since(Section::Nodes, hpcsched_nodes_record(), '26.05.5', 100000))->toBe(99940 - 120) + ->and($t->since(Section::Nodes, hpcsched_nodes_record(), '26.05.3', 100000))->toBe(99820) + ->and($t->since(Section::Nodes, hpcsched_nodes_record(), '26.11.0', 100000))->toBe(99820) + ->and($t->since(Section::Nodes, hpcsched_nodes_record(), '26.11.0rc1', 100000))->toBe(99820) + // Before 26.05.3 an unchanged /nodes/ answer is an error, not a 304, + // and a node change with unchanged partitions is an HTTP 500. + ->and($t->since(Section::Nodes, hpcsched_nodes_record(), '26.05.2', 100000))->toBe(0) + ->and($t->since(Section::Nodes, hpcsched_nodes_record(), '26.05.0', 100000))->toBe(0) + ->and($t->since(Section::Nodes, hpcsched_nodes_record(), '26.05', 100000))->toBe(0) + ->and($t->since(Section::Nodes, hpcsched_nodes_record(), '25.11.8', 100000))->toBe(0) + ->and($t->since(Section::Nodes, hpcsched_nodes_record(), '', 100000))->toBe(0) + // Jobs answer 200 with no jobs when unchanged; the others have no unchanged answer. + ->and($t->since(Section::Jobs, hpcsched_nodes_record(), '26.05.5', 100000))->toBe(0) + ->and($t->since(Section::Partitions, hpcsched_nodes_record(), '26.05.5', 100000))->toBe(0) + ->and($t->since(Section::Nodes, null, '26.05.5', 100000))->toBe(0) + ->and($t->since(Section::Nodes, hpcsched_nodes_record('failed'), '26.05.5', 100000))->toBe(0) + // Rows older than the full-read bound are read whole. + ->and($t->since(Section::Nodes, hpcsched_nodes_record(ingested: 100000 - RestTransport::FULL_READ_SECONDS - 1), '26.05.5', 100000))->toBe(0) + ->and($t->since(Section::Nodes, hpcsched_nodes_record(ingested: 100000 - RestTransport::FULL_READ_SECONDS), '26.05.5', 100000))->toBe(99820); + }); + + it('sends update_time as a query and takes a 304 as unchanged, not as empty', function () { + $server = $GLOBALS['__hpcsched_plain']; + $before = count($server->requests()); + $t = hpcsched_rest($server, 'nodes304', cached: 'v0.0.45'); + $caught = null; + + try { + $t->fetch(Section::Nodes, 'v0.0.45', microtime(true) + 10, 99820); + } catch (Unchanged $e) { + $caught = $e; + } + + $whole = $t->fetch(Section::Nodes, 'v0.0.45', microtime(true) + 10); + + expect($caught)->toBeInstanceOf(Unchanged::class) + ->and(count(SlurmJson::decode($whole)['nodes']))->toBe(8) + ->and(array_column(array_slice($server->requests(), $before), 'target'))->toBe(['/slurm/v0.0.45/nodes/?update_time=99820', '/slurm/v0.0.45/nodes/']); + }); +}); + +it('builds a query only from a lowercase name and a non-negative integer', function (string $name, int $value) { + $request = new HttpRequest(Endpoint::parse($GLOBALS['__hpcsched_plain']->url()), '/slurm/v0.0.45/nodes/', [], [$name => $value]); + + expect(hpcsched_rest_error(fn () => (new SocketTransport(1048576, 2.0))->get($request, microtime(true) + 5)))->toBe(ErrorClass::Refused); +})->with([ + 'separator in the name' => ['update_time&x', 1], + 'space in the name' => ['update time', 1], + 'negative value' => ['update_time', -1], +]); diff --git a/tests/slurm-live/collect.php b/tests/slurm-live/collect.php index 8f585b5..311093f 100644 --- a/tests/slurm-live/collect.php +++ b/tests/slurm-live/collect.php @@ -62,19 +62,27 @@ function cacti_log(string $message, bool $stdout = false, string $tag = '', int } use Somethingwithproof\Hpcsched\Cluster; +use Somethingwithproof\Hpcsched\ClusterRun; use Somethingwithproof\Hpcsched\CommandRunner; use Somethingwithproof\Hpcsched\DataParser; +use Somethingwithproof\Hpcsched\FreshnessEvaluator; use Somethingwithproof\Hpcsched\NodeRecord; use Somethingwithproof\Hpcsched\Redactor; +use Somethingwithproof\Hpcsched\RestTransport; +use Somethingwithproof\Hpcsched\RunOutcome; use Somethingwithproof\Hpcsched\Section; +use Somethingwithproof\Hpcsched\SectionRecord; use Somethingwithproof\Hpcsched\SectionState; use Somethingwithproof\Hpcsched\Settings; use Somethingwithproof\Hpcsched\SlurmBackend; use Somethingwithproof\Hpcsched\SlurmJson; use Somethingwithproof\Hpcsched\SlurmParser; +use Somethingwithproof\Hpcsched\SlurmTransport; +use Somethingwithproof\Hpcsched\Snapshot; use Somethingwithproof\Hpcsched\SocketTransport; use Somethingwithproof\Hpcsched\SystemClock; use Somethingwithproof\Hpcsched\Transports; +use Somethingwithproof\Hpcsched\Unchanged; $failed = 0; $check = function (string $label, bool $pass, mixed $got = null) use (&$failed): void { @@ -137,49 +145,116 @@ function cacti_log(string $message, bool $stdout = false, string $tag = '', int $check('the release serves a data parser the plugin supports', $parsers !== [], $parsers); +$cluster = static fn (string $transport): ?Cluster => Cluster::fromRow([ + 'id' => 1, 'name' => 'live', 'poller_id' => 1, 'admin_state' => 'enabled', 'transport' => $transport, 'collect_interval' => 60, + 'rest_url' => 'http://127.0.0.1:6820', 'rest_user' => 'root', 'token_file' => $tokenFile, 'collect_reservations' => 1, 'collect_shares' => 1, +]); + +// Build the real transport with the same settings and parser cache as the reader. +$transportFor = static function (string $transport, string $parser, ?ClusterRun $previous = null) use ($bin, $tokenFile, $cluster): SlurmTransport { + $settings = Settings::fromRow([ + 'hpcsched_squeue' => "$bin/squeue", + 'hpcsched_scontrol' => "$bin/scontrol", + 'hpcsched_sshare' => "$bin/sshare", + // prlimit would limit docker, not the client in the container. + 'hpcsched_prlimit' => '', + 'hpcsched_data_parser' => $parser, + 'hpcsched_token_dirs' => dirname($tokenFile), + ]); + $record = $cluster($transport); + $token = null; + + if ($record === null) { + throw new RuntimeException('cluster record'); + } + + return (new Transports($settings, new CommandRunner(), new SocketTransport($settings->maxOutputBytes())))->for($record, new Redactor(), $token, $previous); +}; + +/** @param array $sections */ +$collect = static function (string $transport, string $parser, ?ClusterRun $previous = null, array $sections = [], string $release = '') use ($transportFor, $cluster): Snapshot { + $for = $transportFor($transport, $parser, $previous); + + return (new SlurmBackend($for, new SystemClock(), $sections, $release))->collect($cluster($transport), microtime(true) + 120); +}; + +$compare = static function (string $label, Snapshot $snapshot, string $parser) use ($check, $load, $nodes, $names, $sameNodes): void { + foreach (Section::cases() as $section) { + $outcome = $snapshot->outcome($section); + $check("$label $section->value completed", $outcome->state === SectionState::Completed, $outcome->error?->value); + } + + $check("$label data parser", $snapshot->dataParser === $parser, $snapshot->dataParser); + $check("$label jobs match the capture", $snapshot->jobs?->rows() === SlurmParser::jobs($load("squeue.$parser.json"))->rows(), $snapshot->jobs?->rows()); + $check("$label nodes match the capture", $sameNodes($nodes($snapshot->nodes), $nodes(SlurmParser::nodes($load("scontrol-node.$parser.json")))), $nodes($snapshot->nodes)); + $check("$label partitions match the capture", $names($snapshot->partitions) === $names(SlurmParser::partitions($load("scontrol-partition.$parser.json"))), $names($snapshot->partitions)); + $check("$label reservations match the capture", $names($snapshot->reservations) === $names(SlurmParser::reservations($load("scontrol-reservation.$parser.json"))), $names($snapshot->reservations)); + $check("$label fair-share rows", count($snapshot->shares ?? []) >= 3, count($snapshot->shares ?? [])); +}; + +// Every served parser through each transport. A slurmrestd run is given +// the parser as the one its last completed run used (with no release, so +// the cache is kept), so every served parser is read, not just the newest. foreach ($parsers as $parser) { - $transports = ['commands']; + $compare("$parser commands", $collect('commands', $parser), $parser); if (in_array($parser, $rest, true)) { - $transports[] = 'rest'; + $compare("$parser rest", $collect('rest', $parser, new ClusterRun(1, outcome: RunOutcome::Completed, transport: 'rest', dataParser: $parser)), $parser); } +} - foreach ($transports as $transport) { - $settings = Settings::fromRow([ - 'hpcsched_squeue' => "$bin/squeue", - 'hpcsched_scontrol' => "$bin/scontrol", - 'hpcsched_sshare' => "$bin/sshare", - // prlimit would limit docker, not the client in the container. - 'hpcsched_prlimit' => '', - 'hpcsched_data_parser' => $parser, - 'hpcsched_token_dirs' => dirname($tokenFile), - ]); - $cluster = Cluster::fromRow([ - 'id' => 1, 'name' => 'live', 'poller_id' => 1, 'admin_state' => 'enabled', 'transport' => $transport, 'collect_interval' => 60, - 'rest_url' => 'http://127.0.0.1:6820', 'rest_user' => 'root', 'token_file' => $tokenFile, 'collect_reservations' => 1, 'collect_shares' => 1, - ]); - $label = "$parser $transport"; - - if ($cluster === null) { - $check("$label cluster record", false); - - continue; - } +// Discovery (REQ-REST-002): with no previous run, the newest supported +// parser the daemon serves. +$newest = null; + +foreach (DataParser::newestFirst() as $version) { + if (in_array($version, $rest, true)) { + $newest = $version; - $backend = new SlurmBackend((new Transports($settings, new CommandRunner(), new SocketTransport($settings->maxOutputBytes())))->for($cluster, new Redactor()), new SystemClock()); - $snapshot = $backend->collect($cluster, microtime(true) + 120); + break; + } +} - foreach (Section::cases() as $section) { - $outcome = $snapshot->outcome($section); - $check("$label $section->value completed", $outcome->state === SectionState::Completed, $outcome->error?->value); +$check('slurmrestd serves a data parser the plugin supports', $newest !== null, $rest); + +if ($newest !== null) { + $found = $collect('rest', DataParser::DEFAULT_VERSION); + + $compare("discovered $newest rest", $found, $newest); + $check('the discovered parser is the newest one the release ships', $found->dataParser === DataParser::newestShippedBy($found->release), [$found->release, $found->dataParser]); + + // The normal conditional read keeps the production skew allowance. + // Controller updates inside that window legitimately return 200, even + // when the node states visible here have not changed. + $conditional = DataParser::atLeast($found->release, RestTransport::CONDITIONAL_NODES_FROM); + $previous = new ClusterRun(1, outcome: RunOutcome::Completed, release: $found->release, transport: 'rest', dataParser: $found->dataParser); + $whole = $collect('rest', DataParser::DEFAULT_VERSION, $previous); + $sections = ['nodes' => new SectionRecord(1, Section::Nodes, SectionState::Completed, null, $whole->startedAt, count($whole->nodes ?? []), $whole->startedAt, time(), 60)]; + $again = $collect('rest', DataParser::DEFAULT_VERSION, $previous, $sections, $found->release); + $outcome = $again->outcome(Section::Nodes); + $unchanged = $outcome->unchanged; + $kept = $again->nodes === null && $outcome->records === count($whole->nodes ?? []); + $refreshed = $sameNodes($nodes($again->nodes), $nodes($whole->nodes)); + + if ($conditional) { + $check("$found->release conditional nodes read retains or refreshes the rows", $outcome->state === SectionState::Completed && ($unchanged ? $kept : $refreshed), [$outcome->state->value, $unchanged, $outcome->error?->value]); + + // Exercise the real 304 response separately with a cutoff ahead of + // the controller clock. This protocol probe is never persisted as a + // snapshot. ReaderTest covers preserving stored rows on that response; + // the normal collection above never advances its cutoff this way. + $transport = $transportFor('rest', DataParser::DEFAULT_VERSION, $previous); + $notModified = false; + + try { + $transport->fetch(Section::Nodes, $found->dataParser, microtime(true) + 30, time() + FreshnessEvaluator::SKEW_ALLOWANCE); + } catch (Unchanged) { + $notModified = true; } - $check("$label data parser", $snapshot->dataParser === $parser, $snapshot->dataParser); - $check("$label jobs match the capture", $snapshot->jobs?->rows() === SlurmParser::jobs($load("squeue.$parser.json"))->rows(), $snapshot->jobs?->rows()); - $check("$label nodes match the capture", $sameNodes($nodes($snapshot->nodes), $nodes(SlurmParser::nodes($load("scontrol-node.$parser.json")))), $nodes($snapshot->nodes)); - $check("$label partitions match the capture", $names($snapshot->partitions) === $names(SlurmParser::partitions($load("scontrol-partition.$parser.json"))), $names($snapshot->partitions)); - $check("$label reservations match the capture", $names($snapshot->reservations) === $names(SlurmParser::reservations($load("scontrol-reservation.$parser.json"))), $names($snapshot->reservations)); - $check("$label fair-share rows", count($snapshot->shares ?? []) >= 3, count($snapshot->shares ?? [])); + $check("$found->release maps a live HTTP 304 to Unchanged", $notModified); + } else { + $check("$found->release reads nodes whole, with no update_time", !$unchanged && $outcome->state === SectionState::Completed && $sameNodes($nodes($again->nodes), $nodes($whole->nodes)), [$outcome->state->value, $outcome->unchanged]); } }