diff --git a/.agents/skills/homebased/references/pools.md b/.agents/skills/homebased/references/pools.md index 28c9bc0..59c6a80 100644 --- a/.agents/skills/homebased/references/pools.md +++ b/.agents/skills/homebased/references/pools.md @@ -15,11 +15,11 @@ homebased --json pool show afv homebased --json pool release afv ``` -- The pool name is the CI class. Submit one `ci run --class ` per unit of work; the coordinator asks for a machine whenever ready jobs find no free slot, up to `--max`. Do not write a dispatcher loop. Once a pool is released, its class is the Fleet's again: a job submitted then waits for a Fleet machine that offers the class, and the old pool never fails it. +- The pool name is the CI class. Submit one `ci run --class ` per unit of work; the coordinator asks for a machine whenever ready jobs find no free slot, up to `--max`. Do not write a dispatcher loop. `pool create` refuses a name a Fleet machine already offers as a CI class (`class_offered`, exit 5); pick another name. Once a pool is released, its class is the Fleet's again: a job submitted then waits for a Fleet machine that offers the class, and the old pool never fails it. - `--deadline` is fixed at create (at most 24h). A job runs only on a machine that outlives its `--kill-after`, so a job that no machine of the pool could run to its kill limit, counting a new machine's boot, is refused with `pool_deadline_too_close`, and a waiting job that falls out of reach later (for example while its `--after` dependency runs) fails with `JOB_FAILED` carrying that code. The message names the longest `--kill-after` the pool takes now; size `--kill-after` to the job. - `--env-file` holds `NAME=value` secrets, such as an upload token, on the coordinator. Machines get them after they join; never put a secret in a job's command line or the repository. A `PATH` in it applies inside the run only, so name a program outside the machine's default `PATH` by its full path or start it from a `--git` script. - `--spend-cap` (US dollars, such as `25` or `12.50`) caps what the pool's cloudlease run may spend; cloudlease's own per-run cap applies without it, and a value above that cap ends the pool with `invalid_request`. Ask the user for the amount. -- `--slots` (default 1) is how many jobs one machine runs at once; `--idle-limit` (default 10m), `--stall-after` (default 30m), and `--boot-timeout` (by default a minute before cloudlease's boot grace ends, read from each lease, so 7m on DigitalOcean and 19m on phoenixNAP) tune the lifetime rules below. On a class whose boot grace is longer than 8 minutes, such as phoenixNAP, pass `--boot-timeout` (`19m`) so jobs submitted before the first machine exists are sized for that boot. `--boot-timeout` must be shorter than `--deadline`; `pool create` refuses an equal or longer value with `usage` (exit 2), so pick a later `--deadline` or a shorter boot timeout. +- `--slots` (default 1) is how many jobs one machine runs at once; `--idle-limit` (default 10m) and `--stall-after` (default 30m) tune the lifetime rules below. A machine that has not joined when cloudlease's boot grace ends (8 minutes by default, 20 on phoenixNAP) is deleted with reason `heartbeat_lapsed`, and the pool asks for another if jobs still wait. - `--min-free-disk` (GiB, default 1) is the free disk below which a pool machine admits no job. Set it to what one job needs on disk, within what the machine class has free after boot, so a machine filled by earlier jobs stops taking new ones and idles out. - Jobs run with `--git` (or `--repo` and `--commit`) from the pushed commit, or in a `cwd` that the boot leaves on the machine. A fresh machine has nothing else of yours on it. - Private repositories work: the machine never gets a git credential. At submit the coordinator fetches the commit with its own git credentials and makes a one-commit bundle; the machine downloads it from the coordinator over the link when the run starts and checks it out. So the checkout is shallow (one commit, no tags). The submit is refused, before any machine is asked for, with `commit_unavailable` when the coordinator cannot fetch the commit (push it, or fix the remote or the coordinator's credentials), `submodules_unsupported` when the commit has a `.gitmodules`, or `bundle_too_large` past 2 GiB. A download that breaks is tried 3 times, with each failure in the run's log, before the run fails. @@ -34,9 +34,9 @@ homebased --json pool release afv ## Interrupted machines -When the provider takes a machine back (reason `interrupted`, such as an AWS Spot interruption), the coordinator queues its jobs again for another machine and the pool asks for a replacement; do nothing. Each rerun shows as `JOB_PREEMPTED` with `machine_lost` (`pool`, `machine`, `reason`, `attempt` now queued, `max_attempts`, and `ends_at` when the machine gave notice), a progress event that does not wake a sleeping thread. On AWS the machine reads the two-minute Spot notice, so the job is queued again within seconds; the interrupted run keeps going until AWS shuts the machine down, and can watch the file named by `HOMEBASED_INTERRUPTION_FILE` to save a checkpoint off the machine. +When the provider takes a machine back (reason `interrupted`, such as an AWS Spot interruption), the coordinator queues its jobs again for another machine and the pool asks for a replacement; do nothing. Each rerun shows as `JOB_PREEMPTED` with `machine_lost` (`pool`, `machine`, `reason`, `attempt` now queued, `max_attempts`), a progress event that does not wake a sleeping thread. cloudlease notices an interrupted machine about a minute after the provider takes it, and the job is queued again then. -So a job on such a pool must be safe to run again and to overlap a dying copy of itself for up to two minutes: derive output names from the input, upload each output whole (write, then rename or put at once), and skip work whose output exists. +So a job on such a pool must be safe to run again: derive output names from the input, upload each output whole (write, then rename or put at once), and skip work whose output exists. A rerun ends with `JOB_FAILED` and `machine_released` with `not_rerun.cause`: `retries_exhausted` (it ran `max_attempts` times), `out_of_reach` (no machine could run it to its kill limit before the deadline), `pool_ended`, `pinned`, or `cancelled` (a cancel was asked for first). A replacement past the spend cap is refused, which stops the pool and fails the queued job with `spend_cap_reached` in `held_ending`. Report a job that kept getting interrupted to the user rather than resubmitting it in a loop. `heartbeat_lapsed` is never rerun, since a stalled job would stall again. diff --git a/docs/temporary-machines.md b/docs/temporary-machines.md index 1e118d3..e73642d 100644 --- a/docs/temporary-machines.md +++ b/docs/temporary-machines.md @@ -45,7 +45,6 @@ homebased pool release afv | `--slots` | CI slots of the class on each machine (default 1) | | `--idle-limit` | A machine with no work for this long releases itself (default 10m); on an hourly-billed provider it stays until shortly before its paid hour ends, if that is later | | `--stall-after` | Running work with no output for this long stops keeping its machine (default 30m) | -| `--boot-timeout` | A machine that has not joined this long after its create is released. By default a minute before cloudlease's boot grace ends, or a quarter of the grace for one under 4 minutes; the coordinator reads the grace from each lease's first `heartbeat_deadline_at`, so DigitalOcean's 8 minutes gives 7m and phoenixNAP's 20 gives 19m. A machine renews only once it joined, so cloudlease deletes it at the end of the grace anyway; a value past the grace only changes the reason to `heartbeat_lapsed`. Must be shorter than `--deadline`; `pool create` refuses an equal or longer value with `usage`, because no machine could then join before the pool ends | | `--min-free-disk` | Free disk, in GiB, below which a machine of the pool admits no CI run (default 1; a Fleet machine's `[ci] min_free_disk_gib` is 10). The boot data writes it as the machine's `[ci] min_free_disk_gib`. Set it to what one job needs, within what the class has free after boot; a machine below it takes no job, idles out, and a fresh one replaces it | | `--env-file` | `NAME=value` lines on the coordinator that every run on the pool's machines gets | | `--spend-cap` | Most the pool's cloudlease run may spend, in US dollars, such as `25` or `12.50`. cloudlease's own per-run cap applies without it, and refuses a larger value | @@ -53,13 +52,13 @@ homebased pool release afv The pool's name is the CI class its jobs name. A job of an open pool's class is accepted even before any machine exists. Submit pool jobs on the coordinator: only it reaches pool machines, and it counts only its own waiting jobs when it asks for machines. -A pool owns its class until it is released: when it ends, it fails the class's jobs that never got a machine, even if a Fleet machine also offers the class. Once it is released the class is the Fleet's again: a job submitted then is accepted only if a Fleet machine offers the class, waits for that machine's slot, and the released pool never ends it. +A pool owns its class until it is released: when it ends, it fails the class's jobs that never got a machine. So `pool create` refuses, with `class_offered` (exit 5), a name that a Fleet machine already offers as a CI class. Do not give a Fleet machine an open pool's class: the coordinator does not refuse that, and the pool still fails the class's waiting jobs when it ends. Once a pool is released the class is the Fleet's again: a job submitted then is accepted only if a Fleet machine offers the class, waits for that machine's slot, and the released pool never ends it. Placement never sends a job to a machine that cloudlease will delete before the job's kill limit, and every machine of the pool ends by its deadline, or sooner when the cloudlease class has a shorter lifetime. So the coordinator keeps each job within reach of some machine: -- At submit, a job is refused with `pool_deadline_too_close` unless a machine the pool has (booting or joined) outlives its `--kill-after` from now, or a machine asked for now would, once it joined: the boot timeout from now plus the kill limit must end by the pool's deadline, or by the end of the class's lifetime, which a lease that ends before the deadline shows. Before a lease of the pool has shown the grace, it uses `--boot-timeout` when set, and otherwise assumes cloudlease's default 8-minute grace; set `--boot-timeout` on a class with a longer grace, such as `19m` on phoenixNAP, so the first jobs are not admitted on the shorter estimate. The message names the longest `--kill-after` the pool takes. +- At submit, a job is refused with `pool_deadline_too_close` unless a machine the pool has (booting or joined) outlives its `--kill-after` from now, or a machine asked for now would, once it joined: cloudlease's boot grace from now plus the kill limit must end by the pool's deadline, or by the end of the class's lifetime, which a lease that ends before the deadline shows. Each lease shows the grace; before the pool has one, it assumes cloudlease's default 8 minutes, so on a class with a longer grace, such as phoenixNAP's 20 minutes, the first jobs are sized for the shorter boot. The message names the longest `--kill-after` the pool takes. - Each pass, a job that has not started and has fallen out of that reach, for example while its `--after` dependency ran, ends with `JOB_FAILED` whose `held_ending` has code `pool_deadline_too_close`. Time only takes reach away, so such a job could never run. -- The pool asks for machines only for ready jobs that a new machine could run; a job that only a machine it has could run waits for that machine's slot. A free or coming slot counts against a job only on a machine that outlives the job's kill limit, so a slot on a machine about to end does not stand in for a new one. Once a lease has shown the boot grace, a `--boot-timeout` past it counts as the grace, since cloudlease deletes an unjoined machine then. +- The pool asks for machines only for ready jobs that a new machine could run; a job that only a machine it has could run waits for that machine's slot. A free or coming slot counts against a job only on a machine that outlives the job's kill limit, so a slot on a machine about to end does not stand in for a new one. ## Lifecycle @@ -76,7 +75,7 @@ The coordinator moves each machine through these states, all from what cloudleas Each pass, about every 15 seconds, the coordinator: 1. creates the pool's cloudlease run on its first pass; -2. reads the run, moves each machine to its lease's state, and releases a machine that has not joined within the boot timeout; +2. reads the run and moves each machine to its lease's state. A machine renews only once it joined, so cloudlease deletes one that has not joined when its boot grace ends; it is `released` with reason `heartbeat_lapsed` once cloudlease confirms it gone, and its place under `--max` frees then; 3. ends waiting jobs out of reach (see above), then asks for machines while ready jobs of the class that a new machine could run outnumber the free slots on joined machines plus the slots of machines still booting, up to `--max`. A machine the provider could not create comes back from cloudlease already releasing with reason `create_failed`; the coordinator then waits 4 passes (a minute at the default interval) before it asks again, twice that after a second failure in a row, and stops the pool after a third; 4. for each machine cloudlease reports `released`, removes it from the Fleet. A job it still held whose machine was `interrupted` is queued again for another machine, within `--job-retries` (see [Interrupted machines](#interrupted-machines)); every other job it held ends with `JOB_FAILED`, and every job pinned to it with `--machine` that never reached it, such as one waiting on its `--after` entries, with `JOB_FAILED` whose `held_ending` has code `machine_released`; 5. at the deadline, or after `pool release`, releases the run, fails the class's jobs submitted before the release that have not started with `JOB_FAILED` whose `held_ending` has code `pool_deadline` or `pool_released`, and marks the pool released once every machine is gone. A pool whose run cloudlease no longer has ends the same way with `run_not_found`. The pool is marked released only once cloudlease took the run's release. @@ -113,9 +112,7 @@ The machine's boot data, written by the coordinator and passed through cloudleas A renewal that fails, such as with no answer or `401 unauthorized`, is tried again every 5 seconds within the round, then the next round; cloudlease's heartbeat window, 3 minutes by default, spans several rounds. Its hard deadline applies whatever the machine decides. -On a provider that bills every started hour, phoenixNAP and Latitude.sh, cloudlease names in each renew answer when the machine's paid hour ends, less 10 minutes for the release to finish, as `idle_hold_until`. An idle machine stays until then instead of releasing at `--idle-limit`, so a job that arrives in that window uses time already paid for. The hold applies at once in the first hour. After it, cloudlease names no hold within the boot grace after each hour from create turns, when the provider's next hour could start before then, since it does not know exactly when the provider's billing started; nor when the hold would pass the lease's hard deadline, and so the pool's deadline; or on a provider that bills by the second, DigitalOcean and AWS. A hold never starts a new hour, so it adds nothing to the run's spend or its spend cap. If `--idle-limit` ends after the hold, the machine releases at `--idle-limit` as before. A machine also waits for its first renew answer before an idle release, so even `--idle-limit 0s` keeps a hold cloudlease names. - -5. when `lease.json` has `"interruption_notice": "aws_imds"`, as cloudlease writes it for AWS Spot machines, it reads EC2's instance metadata service with IMDSv2 every 5 seconds for a Spot interruption notice (`spot/instance-action`). `[temporary] imds_endpoint` overrides the service's address, `http://169.254.169.254` by default. On a notice, about two minutes before AWS takes the instance back, it stops offering the CI class for good, writes the notice to the file every run finds in `HOMEBASED_INTERRUPTION_FILE`, and tells the coordinator; see [Interrupted machines](#interrupted-machines). Machines on other providers never poll. +On a provider that bills every started hour, phoenixNAP and Latitude.sh, an idle machine stays until about 10 minutes before its paid hour ends, as cloudlease names in each renew answer (`idle_hold_until`), instead of releasing at `--idle-limit`, and a job that arrives meanwhile uses time already paid for. A hold never starts a new paid hour or passes the pool's deadline, so it adds nothing to the run's spend. If `--idle-limit` ends later, the machine releases then. DigitalOcean and AWS bill by the second, so their machines release at `--idle-limit`. ## Code on the machine @@ -145,18 +142,18 @@ Anything the job wrote on the machine and had not uploaded is gone; the task log ## Interrupted machines -A machine is `interrupted` when its provider took it back while its lease was live, such as an AWS Spot interruption: cloudlease's presence check finds it gone, within about a minute of the provider ending it, or the machine reports the provider's notice first. The job did nothing wrong, so the coordinator queues it again for another machine of the pool, up to `--job-retries` times per job, and the pool asks for a replacement machine as it would for any waiting job. cloudlease's AWS launches leave out the Spot pools (instance type and zone) that interrupted the run within the last hour, so a replacement lands elsewhere when the class allows. +A machine is `interrupted` when its provider took it back while its lease was live, such as an AWS Spot interruption: cloudlease's presence check finds it gone, within about a minute of the provider ending it. The job did nothing wrong, so the coordinator queues it again for another machine of the pool, up to `--job-retries` times per job, and the pool asks for a replacement machine as it would for any waiting job. The replacement can land in the same Spot pool (instance type and zone), since cloudlease lets EC2 choose among all of the class's pools by spare capacity and price. The submitter sees each rerun as a `JOB_PREEMPTED` (a progress event: a sleeping thread does not wake for it) with `machine_lost`: ```json "machine_lost": { "pool": "afv", "machine": "afv-4fa9bd9a", "reason": "interrupted", - "ends_at": "2026-11-25T02:02:00Z", "attempt": 2, "max_attempts": 3 + "attempt": 2, "max_attempts": 3 } ``` -`attempt` is the run now queued, and `ends_at`, present when the machine gave notice, is when the provider ends it. The job's later events follow in the same sequence, and its final event comes from the run that ended it. +`attempt` is the run now queued. The job's later events follow in the same sequence, and its final event comes from the run that ended it. A job whose machine was interrupted ends with `JOB_FAILED` and `machine_released` instead, with `not_rerun` saying why: @@ -170,11 +167,7 @@ A job whose machine was interrupted ends with `JOB_FAILED` and `machine_released A rerun never outlives the pool: the deadline bounds every machine, and when the replacement's create would pass the spend cap, cloudlease refuses it with `spend_cap_reached`, the pool stops, and the queued job ends with that code in `held_ending`. Other reasons a machine goes away are never rerun: `heartbeat_lapsed` usually means every run on the machine stalled, which a rerun would repeat, and `hard_deadline` or `requested` mean the pool's time or its release ended the work. -On an AWS interruption notice the machine closes its class, so nothing more is placed on it, and the coordinator queues the machine's jobs at once, without waiting for cloudlease. Once every one of them is queued again, it counts the machine as `releasing`. A job it does not rerun, such as one on a pool with `--job-retries 0`, keeps its machine `joined`, so a run that ends before AWS takes the machine still reports its result. It keeps the lease: AWS ends the machine at the notice's time, and until then the interrupted run goes on. A run can read `HOMEBASED_INTERRUPTION_FILE`, which appears with `{"action": "terminate", "ends_at": "..."}` on a notice, to save a checkpoint somewhere off the machine. The rerun may start on another machine while the interrupted run still has up to two minutes, until AWS shuts the machine down. The interrupted machine keeps its place under `--max` until cloudlease confirms it gone, so with `--max 1` the rerun waits a few minutes for it; give Spot pools room for a replacement. - -So every job on a pool with `--job-retries` above 0 must be safe to run again, and to run beside a dying copy of itself for up to two minutes: write each output under a name derived from the job's input, upload it whole (write, then rename or put the object at once), and skip work whose output already exists. A job that cannot be rerun belongs on a pool with `--job-retries 0`. - -The machine does not act on EC2's rebalance recommendation. It is an early, often false, signal, and draining machines on it would churn the pool; the price-capacity-optimized launch already prefers the pools least likely to be interrupted. +So every job on a pool with `--job-retries` above 0 must be safe to run again: write each output under a name derived from the job's input, upload it whole (write, then rename or put the object at once), and skip work whose output already exists. A job that cannot be rerun belongs on a pool with `--job-retries 0`. ## Secrets @@ -191,7 +184,7 @@ Each side serves an endpoint id only what it granted that id: | Who | Grant | What the link lets it do | | --- | --- | --- | | Endpoint not bound to a lease | none (enrollment) | Only `POST /v1/cluster/pool/join`. The single-use join token binds its endpoint id to the machine's lease; a failed join closes the connection | -| Machine of a joined lease | pool member | Join again, report its provider's interruption notice (`/v1/cluster/pool/notice`, for its own lease only), the Fleet probe (`/v1/cluster/machine`), event delivery (`/v1/cluster/job-events`, `/v1/cluster/events`) for work it runs itself, and the bundles of jobs placed on it (`/v1/cluster/pool/jobs/{job}/bundle`). No route that starts work, sends messages, or reads other machines' tasks | +| Machine of a joined lease | pool member | Join again, the Fleet probe (`/v1/cluster/machine`), event delivery (`/v1/cluster/job-events`, `/v1/cluster/events`) for work it runs itself, and the bundles of jobs placed on it (`/v1/cluster/pool/jobs/{job}/bundle`). No route that starts work, sends messages, or reads other machines' tasks | | Coordinator, on the machine | peer | Every route of the machine's own API, over streams it opens on the machine's connection | The coordinator grants an id when its join succeeds, and revokes it and closes its connection when the lease leaves `joined`. The lease stays bound to that one id: a join from another id for the same lease is refused, and so is a join that names a machine id the coordinator already knows, its own or another Fleet or pool machine's. The machine grants only the coordinator's id, from its boot data. @@ -218,7 +211,7 @@ The full contract is the "Temporary machines contract" section of the cloudlease | `POST /v1/leases/{lease}/release` | Release one machine | | `POST /v1/runs/{run}/release` | Release the pool | -The machine calls, with its lease token, `POST /v1/leases/{lease}/renew` and `POST /v1/leases/{lease}/release` (`{"reason": "idle"}`). A renew answers `heartbeat_deadline_at`, `hard_deadline_at`, and `idle_hold_until` (a time or `null`); a `410 lease_ended` answer means the machine is going away. It reads `interruption_notice` from `lease.json` (`aws_imds` on AWS, absent elsewhere and from an older cloudlease) to decide whether to watch for a Spot interruption notice. A lease cloudlease ended because the provider took the machine back has release reason `interrupted`. +The machine calls, with its lease token, `POST /v1/leases/{lease}/renew` and `POST /v1/leases/{lease}/release` (`{"reason": "idle"}`). A renew answers `heartbeat_deadline_at`, `hard_deadline_at`, and `idle_hold_until` (a time or `null`); a `410 lease_ended` answer means the machine is going away. A lease cloudlease ended because the provider took the machine back has release reason `interrupted`. ## Not covered diff --git a/src/cli/pool.rs b/src/cli/pool.rs index 27cfd99..0b04229 100644 --- a/src/cli/pool.rs +++ b/src/cli/pool.rs @@ -41,11 +41,6 @@ pub enum PoolCommand { /// Running work with no output for this long stops keeping its machine #[arg(long = "stall-after", value_parser = humantime::parse_duration)] stall_after: Option, - /// A machine that has not joined this long after its create is - /// released; by default shortly before cloudlease's boot grace ends, - /// which each lease shows - #[arg(long = "boot-timeout", value_parser = humantime::parse_duration)] - boot_timeout: Option, /// Free disk, in GiB, below which a machine of the pool admits no CI /// run (default 1) #[arg(long = "min-free-disk", value_name = "GIB")] @@ -91,7 +86,6 @@ pub async fn run(ctx: &Ctx, command: PoolCommand) -> Result slots, idle_limit, stall_after, - boot_timeout, min_free_disk, env_file, spend_cap, @@ -110,7 +104,6 @@ pub async fn run(ctx: &Ctx, command: PoolCommand) -> Result "slots": slots, "idle_limit": format(idle_limit), "stall_after": format(stall_after), - "boot_timeout": format(boot_timeout), "env_file": env_file, "spend_cap_cents": spend_cap, "min_free_disk_gib": min_free_disk, diff --git a/src/config.rs b/src/config.rs index 113cea1..2a2446a 100644 --- a/src/config.rs +++ b/src/config.rs @@ -166,9 +166,6 @@ pub struct TemporaryConfig { /// Time between renewal decisions #[serde(with = "humantime_serde")] pub renew_interval: std::time::Duration, - /// Base URL of EC2's instance metadata service, read for a Spot - /// interruption notice when `lease.json` says the provider gives one - pub imds_endpoint: String, } /// Host memory admission settings @@ -523,8 +520,6 @@ struct RawTemporary { lease_file: Option, #[serde(default)] renew_interval: Option, - #[serde(default)] - imds_endpoint: Option, } impl RawTemporary { @@ -555,14 +550,6 @@ impl RawTemporary { // expects a renew every 30 seconds within it None => std::time::Duration::from_secs(30), }; - let imds_endpoint = self - .imds_endpoint - .unwrap_or_else(|| crate::pool::notice::DEFAULT_IMDS_ENDPOINT.to_owned()); - if !imds_endpoint.starts_with("http://") && !imds_endpoint.starts_with("https://") { - return Err(format!( - "temporary.imds_endpoint must be an http or https URL, got {imds_endpoint:?}" - )); - } Ok(TemporaryConfig { pool: self.pool, slot: self.slot, @@ -575,7 +562,6 @@ impl RawTemporary { join_token: crate::pool::JoinToken::new(self.join_token), lease_file, renew_interval, - imds_endpoint, }) } } diff --git a/src/curl.rs b/src/curl.rs index e2ee1eb..1c40b46 100644 --- a/src/curl.rs +++ b/src/curl.rs @@ -17,8 +17,6 @@ pub(crate) enum CurlMethod { Get, /// Send a POST request Post, - /// Send a PUT request - Put, } /// Input for one blocking curl request @@ -29,8 +27,6 @@ pub(crate) struct CurlRequest<'a> { pub(crate) url: &'a str, /// Optional bearer token pub(crate) bearer: Option<&'a str>, - /// Other headers, as names and values - pub(crate) headers: &'a [(&'a str, &'a str)], /// Optional JSON request body pub(crate) json_body: Option<&'a serde_json::Value>, /// Maximum request time @@ -115,12 +111,8 @@ fn render_config(request: &CurlRequest<'_>) -> Result { match request.method { CurlMethod::Get => "GET", CurlMethod::Post => "POST", - CurlMethod::Put => "PUT", }, ); - for (name, value) in request.headers { - push_config_value(&mut config, "header", &format!("{name}: {value}")); - } if let Some(bearer) = request.bearer { push_config_value( @@ -277,7 +269,6 @@ mod tests { method: CurlMethod::Post, url: "https://example.test/path?q=\"\\\n\r\t", bearer: Some(token), - headers: &[], json_body: Some(&body), timeout: Duration::from_secs(5), }; @@ -317,7 +308,6 @@ mod tests { method: CurlMethod::Post, url: &url, bearer: Some("unit-test-token"), - headers: &[], json_body: Some(&body), timeout: Duration::from_secs(5), }) diff --git a/src/daemon/actors/store.rs b/src/daemon/actors/store.rs index ddd942f..98e80db 100644 --- a/src/daemon/actors/store.rs +++ b/src/daemon/actors/store.rs @@ -700,11 +700,6 @@ pub(crate) enum StoreMsg { TemporaryActivity { reply: RpcReplyPort>, }, - /// Jobs this origin sent to a machine that have no final event - UnfinishedJobsOn { - machine: MachineId, - reply: RpcReplyPort, AppError>>, - }, /// Jobs this origin sent to a machine or holds pinned to it that have no /// final event JobsOfReleasedMachine { @@ -720,15 +715,6 @@ pub(crate) enum StoreMsg { policy: crate::pool::RerunPolicy, reply: RpcReplyPort, AppError>>, }, - /// Queue again a job this origin sent to a machine that gave notice its - /// provider ends it - RerunJobOfEndingMachine { - job: crate::queue::JobId, - machine: MachineId, - lost: Box, - policy: crate::pool::RerunPolicy, - reply: RpcReplyPort>, - }, /// Save a new service InsertService { service: Box, @@ -1577,9 +1563,6 @@ impl Actor for StoreActor { send_reply(reply, state.update_pool_machine(&machine)); } StoreMsg::TemporaryActivity { reply } => send_reply(reply, state.temporary_activity()), - StoreMsg::UnfinishedJobsOn { machine, reply } => { - send_reply(reply, state.unfinished_jobs_on(machine)); - } StoreMsg::JobsOfReleasedMachine { machine, reply } => { send_reply(reply, state.jobs_of_released_machine(machine)); } @@ -1593,16 +1576,6 @@ impl Actor for StoreActor { reply, state.end_job_of_released_machine(job, machine, &released, &policy), ), - StoreMsg::RerunJobOfEndingMachine { - job, - machine, - lost, - policy, - reply, - } => send_reply( - reply, - state.rerun_job_of_ending_machine(job, machine, &lost, &policy), - ), StoreMsg::InsertService { service, reply } => { send_reply(reply, state.insert_service(&service)); } diff --git a/src/daemon/ci_api.rs b/src/daemon/ci_api.rs index d31afae..252f9cb 100644 --- a/src/daemon/ci_api.rs +++ b/src/daemon/ci_api.rs @@ -116,18 +116,20 @@ pub(super) async fn fleet_status( } /// Refuse a CI job no reachable machine it may run on offers its class +/// +/// Returns whether an open pool admitted the job; the caller then saves its +/// route and passes it to [`super::pools::end_if_closed`] pub(super) async fn check_offered( state: &AppState, spec: &JobSpec, choice: MachineChoice, -) -> Result<(), AppError> { +) -> Result { let Some(ci) = &spec.ci else { - return Ok(()); + return Ok(false); }; // a pool's class is offered by machines it creates on demand. A pool - // that is not released owns its class: it fails the class's held jobs - // as it ends, so its refusal stands even if another machine offers it. - // Once released, the class is the Fleet's again + // that is not released owns its class, so its refusal stands even if a + // Fleet machine offers it. Once released, the class is the Fleet's again let pool = match choice { MachineChoice::Any => super::pools::admit_pool_job(state, ci).await?, MachineChoice::Pinned(machine) => { @@ -138,7 +140,7 @@ pub(super) async fn check_offered( } }; if pool { - return Ok(()); + return Ok(true); } let scope = match choice { MachineChoice::Any => Scope::All, @@ -152,7 +154,7 @@ pub(super) async fn check_offered( .is_some_and(|offer| offer.capacity.get() > 0) }; if statuses.iter().any(offered) { - return Ok(()); + return Ok(false); } let mut classes: Vec = statuses .iter() @@ -435,7 +437,7 @@ async fn move_job( }; let mut moved = route.spec.clone(); moved.machine.clone_from(&machine); - check_offered( + let pooled = check_offered( &state, &moved, if machine.is_some() { @@ -453,6 +455,11 @@ async fn move_job( reply, }) .await?; + let route = if pooled { + super::pools::end_if_closed(&state, route).await? + } else { + route + }; Ok(Json(serde_json::json!({ "api_version": API_VERSION, "job_id": route.job, diff --git a/src/daemon/pools.rs b/src/daemon/pools.rs index 0b36919..38ff775 100644 --- a/src/daemon/pools.rs +++ b/src/daemon/pools.rs @@ -25,6 +25,7 @@ use super::AppState; use super::actors::{StoreMsg, call}; use super::dependencies::held_ci_routes; use super::fleet_link::{FleetLink, Grant, LinkPeer}; +use super::fleet_view::Scope; use crate::config::PoolsConfig; use crate::domain::API_VERSION; use crate::error::AppError; @@ -35,11 +36,10 @@ use crate::pool::cloudlease::{ }; use crate::pool::{ ComingSlots, DEFAULT_IDLE_LIMIT, DEFAULT_JOB_RETRIES, DEFAULT_MIN_FREE_DISK_GIB, - DEFAULT_STALL_AFTER, InterruptionNotice, JoinAnswer, JoinRequest, JoinToken, JoinedMachine, - MAX_JOB_RETRIES, MAX_LIFETIME, MAX_MACHINES, MachineClass, MachineLease, MachineLost, - MachineReleased, MachineState, NoticeAnswer, Pool, PoolCode, PoolEnd, PoolError, PoolMachine, - PoolName, PoolReach, PoolSettings, PoolState, PoolView, ReleaseReason, Rerun, RerunPolicy, - RunEndCause, SlotId, parse_env_file, + DEFAULT_STALL_AFTER, JoinAnswer, JoinRequest, JoinToken, JoinedMachine, MAX_JOB_RETRIES, + MAX_LIFETIME, MAX_MACHINES, MachineClass, MachineLease, MachineReleased, MachineState, Pool, + PoolCode, PoolEnd, PoolError, PoolMachine, PoolName, PoolReach, PoolSettings, PoolState, + PoolView, ReleaseReason, Rerun, RerunPolicy, RunEndCause, SlotId, parse_env_file, }; use crate::queue::ci::{CiSpec, SlotCapacity}; use crate::queue::delivery::{HeldJobEnding, JobRoute}; @@ -62,10 +62,6 @@ pub fn read_routes() -> Router { /// Route a temporary machine joins through, over the Fleet link pub const JOIN_PATH: &str = "/v1/cluster/pool/join"; -/// Route a joined temporary machine reports its provider's interruption -/// notice through, over the Fleet link -pub const NOTICE_PATH: &str = "/v1/cluster/pool/notice"; - /// How long after its join a machine's slots count as coming even while it /// cannot yet say what it offers const JOIN_SETTLE: Duration = Duration::from_secs(120); @@ -85,7 +81,6 @@ pub(super) fn enrollment_routes() -> Router { /// other machines' tasks pub(super) fn member_routes(state: &AppState) -> Router { let routes = enrollment_routes() - .route(NOTICE_PATH, post(notice)) .route( "/v1/cluster/job-events", post(super::queue_api::member_job_event), @@ -140,8 +135,6 @@ struct CreateBody { idle_limit: Option, #[serde(default, with = "humantime_serde")] stall_after: Option, - #[serde(default, with = "humantime_serde")] - boot_timeout: Option, #[serde(default)] env_file: Option, #[serde(default)] @@ -173,25 +166,6 @@ impl CreateBody { if let Some(path) = &self.env_file { read_env(path).map_err(usage)?; } - if self - .boot_timeout - .is_some_and(|timeout| timeout.is_zero() || timeout > MAX_LIFETIME) - { - return Err(usage( - "--boot-timeout must be more than 0 and at most 24h".into(), - )); - } - // a machine could never join before the pool ends, so every job would be - // refused before the first lease shows the real boot grace - if let Some(timeout) = self.boot_timeout - && timeout >= self.deadline - { - return Err(usage(format!( - "--boot-timeout {} must be shorter than --deadline {}", - humantime::format_duration(timeout), - humantime::format_duration(self.deadline), - ))); - } let job_retries = self.job_retries.unwrap_or(DEFAULT_JOB_RETRIES); if job_retries > MAX_JOB_RETRIES { return Err(usage(format!( @@ -217,7 +191,6 @@ impl CreateBody { slots, idle_limit: self.idle_limit.unwrap_or(DEFAULT_IDLE_LIMIT), stall_after: self.stall_after.unwrap_or(DEFAULT_STALL_AFTER), - boot_timeout: self.boot_timeout, min_free_disk_gib, env_file: self.env_file, spend_cap_cents: self.spend_cap_cents, @@ -256,6 +229,7 @@ async fn create( }); } let pool = body.into_pool()?; + refuse_fleet_class(&state, &pool.name).await?; let inserted = call(&state.store, |reply| StoreMsg::InsertPool { pool: Box::new(pool), reply, @@ -282,6 +256,33 @@ async fn create( })?)) } +/// Refuse a pool whose class a Fleet machine already offers +/// +/// An open pool owns its class: it asks for machines for every waiting job +/// of the class and fails those still waiting when it ends, so it must not +/// share the class with a Fleet machine. A Fleet machine that starts +/// offering the class while the pool is open is not refused, since its +/// offer is its own config: the pool keeps the class until it is released +async fn refuse_fleet_class(state: &AppState, name: &PoolName) -> Result<(), AppError> { + let (_, statuses) = super::ci_api::fleet_status(state, Scope::All).await?; + let offered = statuses.iter().any(|status| { + status + .offer + .class(name.class()) + .is_some_and(|offer| offer.capacity.get() > 0) + }); + if !offered { + return Ok(()); + } + Err(PoolError::new( + PoolCode::ClassOffered, + format!( + "a Fleet machine already offers CI class {name} (see `ci slots`); name the pool after a class no Fleet machine offers" + ), + ) + .into()) +} + async fn list(State(state): State) -> Result, AppError> { let pools = call(&state.store, |reply| StoreMsg::Pools { reply }).await?; let mut views = Vec::with_capacity(pools.len()); @@ -400,6 +401,43 @@ pub(super) async fn admit_pool_job(state: &AppState, ci: &CiSpec) -> Result Result { + let Some(ci) = &route.spec.ci else { + return Ok(route); + }; + let name = PoolName::from_class(ci.class.clone()); + let pool = call(&state.store, |reply| StoreMsg::Pool { name, reply }).await?; + let Some(pool) = pool else { + return Ok(route); + }; + let end = match &pool.state { + PoolState::Open => return Ok(route), + PoolState::Stopped { end } + | PoolState::Releasing { end } + | PoolState::Released { end, .. } => end, + }; + let job = route.job; + let ending = HeldJobEnding::Refused { + code: end.job_code().to_owned(), + message: end.job_message(&pool.name), + }; + call(&state.store, |reply| StoreMsg::EndPoolJob { + job, + ending, + reply, + }) + .await?; + let saved = call(&state.store, |reply| StoreMsg::JobRoute { job, reply }).await?; + Ok(saved.unwrap_or(route)) +} + /// Make the bundle of a job pinned to `machine` when it is a machine of the /// pool its class names, so it reaches that machine with its commit; a /// regular Fleet machine fetches the commit itself @@ -545,103 +583,6 @@ pub(super) async fn join( })) } -/// `POST /v1/cluster/pool/notice` over the Fleet link: a joined machine says -/// its provider ends it soon, such as with an AWS Spot interruption notice -/// -/// Its unfinished jobs that may run again are queued for other machines at -/// once, rather than when cloudlease finds the machine gone a few minutes -/// later, and the machine counts as releasing. Its lease is kept: the -/// provider ends the machine at the notice's time, and until then a run may -/// save what it can. A retry gets the same answer, with the jobs already -/// queued left out -pub(super) async fn notice( - State(state): State, - Extension(peer): Extension, - Json(notice): Json, -) -> Result, AppError> { - configured(&state)?; - let refused = - |message: String| -> AppError { PoolError::new(PoolCode::NoticeRefused, message).into() }; - if notice.api_version != API_VERSION { - return Err(refused(format!("api_version must be {API_VERSION}"))); - } - let slot = notice.slot; - let _guard = state.locks.pool_joins.lock(slot).await; - let Some(mut machine) = - call(&state.store, |reply| StoreMsg::PoolMachine { slot, reply }).await? - else { - return Err(refused(format!("no pool machine {slot}"))); - }; - let (lease, joined) = match &machine.state { - MachineState::Joined { lease, joined } - | MachineState::Releasing { - lease, - joined: Some(joined), - .. - } if machine.pool == notice.pool - && lease.lease == notice.lease - && joined.endpoint == peer.endpoint => - { - (lease.clone(), joined.clone()) - } - _ => { - return Err(refused(format!( - "pool machine {slot} is not a joined machine of this notice's endpoint" - ))); - } - }; - - let pool = read_pool(&state, &machine.pool).await?; - let policy = rerun_policy(&state, &pool, slot).await?; - let lost = MachineLost { - pool: pool.name.clone(), - machine: machine.name.clone(), - reason: ReleaseReason::Interrupted, - ends_at: Some(notice.ends_at), - // each job's own next attempt replaces this - attempt: 0, - max_attempts: policy.max_attempts, - }; - let jobs = call(&state.store, |reply| StoreMsg::UnfinishedJobsOn { - machine: joined.machine, - reply, - }) - .await?; - let unfinished = jobs.len(); - let mut queued = Vec::new(); - for job in jobs { - let _job_guard = state.locks.job_submissions.lock(job).await; - let rerun = call(&state.store, |reply| StoreMsg::RerunJobOfEndingMachine { - job, - machine: joined.machine, - lost: Box::new(lost.clone()), - policy, - reply, - }) - .await?; - if rerun { - queued.push(job); - } - } - - warn!(pool = %pool.name, machine = %machine.name, action = %notice.action, ends_at = %notice.ends_at, queued = queued.len(), unfinished, "temporary machine gave an interruption notice"); - // a job left running there, such as one past its retry limit, may - // still finish before AWS takes the machine, so the machine keeps its - // link until cloudlease confirms it gone - if queued.len() == unfinished && matches!(machine.state, MachineState::Joined { .. }) { - machine.state = MachineState::Releasing { - lease, - joined: Some(joined), - reason: ReleaseReason::Interrupted, - }; - save_machine(&state, &machine).await?; - } - Ok(Json(NoticeAnswer { - api_version: API_VERSION, - queued, - })) -} - /// Whether a joining machine's id is one this coordinator has never seen /// /// The machine names its own id, and when its lease ends the coordinator @@ -741,13 +682,10 @@ pub(super) async fn run(state: AppState) { client: &client, config: &config, }; - // a job whose machine refused it after the pool's last pass is held - // again with no pool left to place it, so a released pool keeps - // ending its held jobs; it needs no cloudlease call for that - if let PoolState::Released { end, .. } = &pool.state { - if let Err(error) = pass.end_held_jobs(&pool, end).await { - warn!(pool = %name, "ending a released pool's held jobs: {error}"); - } + // a released pool ended its held jobs as it wound down; a job of + // its class submitted since waits for a Fleet machine that + // offers the class, so it is not the pool's to end + if let PoolState::Released { .. } = &pool.state { if let Err(error) = super::bundles::remove_if_released(&state, &name).await { warn!(pool = %name, "removing a released pool's bundles: {error}"); } @@ -978,13 +916,14 @@ impl Pass<'_> { lease: machine_lease(lease), }; } - (Some(_), MachineState::Booting { lease }) => { - if Utc::now() >= pool.settings.boot_released_at(lease) { - self.release_lease(&mut machine, ReleaseReason::BootTimeout) - .await; - } - } - (Some(_), MachineState::Joined { .. } | MachineState::Released { .. }) => {} + // cloudlease deletes a machine that has not joined by the end of + // its boot grace, which the arm above then reads as releasing + ( + Some(_), + MachineState::Booting { .. } + | MachineState::Joined { .. } + | MachineState::Released { .. }, + ) => {} (None, MachineState::Requested) => match run { // the create may not have reached cloudlease: send it again Some(_) if self.still_open(pool).await? => { @@ -1396,7 +1335,8 @@ impl Pass<'_> { /// End the pool's jobs that have not started and that no machine of the /// pool can run to their kill limit any more: time only takes reach away async fn end_out_of_reach(&self, pool: &Pool, reach: &PoolReach) -> Result<(), AppError> { - for route in self.owned_jobs(pool).await? { + let held = held_ci_routes(self.state, pool.name.class()).await?; + for route in held.ready.into_iter().chain(held.waiting) { let Some(kill) = route.spec.ci.as_ref().map(|ci| ci.kill_after.get()) else { continue; }; @@ -1423,21 +1363,10 @@ impl Pass<'_> { Ok(()) } - /// Held jobs of the pool's class that the pool owns, ready or not; - /// the class's other held jobs wait for a Fleet machine that offers it - async fn owned_jobs(&self, pool: &Pool) -> Result, AppError> { - let held = held_ci_routes(self.state, pool.name.class()).await?; - Ok(held - .ready - .into_iter() - .chain(held.waiting) - .filter(|route| pool.owns(route.submitted_at)) - .collect()) - } - /// End the pool's jobs that have not started, with why the pool ended async fn end_held_jobs(&self, pool: &Pool, end: &PoolEnd) -> Result<(), AppError> { - for route in self.owned_jobs(pool).await? { + let held = held_ci_routes(self.state, pool.name.class()).await?; + for route in held.ready.into_iter().chain(held.waiting) { let job = route.job; let ending = HeldJobEnding::Refused { code: end.job_code().to_owned(), @@ -1518,7 +1447,7 @@ fn machine_lease(lease: &Lease) -> MachineLease { lease: lease.lease_id.clone(), hard_deadline_at: lease.hard_deadline_at, created_at: lease.created_at, - boot_deadline_at: Some(lease.heartbeat_deadline_at), + boot_deadline_at: lease.heartbeat_deadline_at, } } @@ -1619,43 +1548,3 @@ fn local_reason(state: &MachineState) -> Option { _ => None, } } - -#[cfg(test)] -mod tests { - use serde_json::{Value, json}; - - use super::{AppError, CreateBody}; - - fn create(deadline: &str, boot_timeout: Option<&str>) -> Result<(), AppError> { - let mut body = json!({ - "api_version": crate::domain::API_VERSION, - "name": "ci", - "machine_class": "do-c16", - "max_machines": 1, - "deadline": deadline, - }); - if let Some(timeout) = boot_timeout { - body["boot_timeout"] = Value::from(timeout); - } - serde_json::from_value::(body) - .unwrap() - .into_pool() - .map(drop) - } - - #[test] - fn a_boot_timeout_must_be_shorter_than_the_deadline() { - for (deadline, timeout) in [("30m", "55m"), ("30m", "30m")] { - let Err(AppError::Usage { message }) = create(deadline, Some(timeout)) else { - panic!("{timeout} against {deadline} was accepted"); - }; - assert_eq!( - message, - format!("--boot-timeout {timeout} must be shorter than --deadline {deadline}") - ); - } - - create("30m", Some("29m")).unwrap(); - create("30m", None).unwrap(); - } -} diff --git a/src/daemon/queue_api.rs b/src/daemon/queue_api.rs index 7e0d71e..c6b189d 100644 --- a/src/daemon/queue_api.rs +++ b/src/daemon/queue_api.rs @@ -400,9 +400,6 @@ async fn submit( // a CI job waits on its origin until placement picks a machine, // and is refused now when no machine it may use offers its class let ci = body.spec.ci.is_some(); - // taken before admission reads any pool, so a job a pool admitted - // reads as taken before that pool's release - let taken_at = chrono::Utc::now(); if ci && body.placement.is_some() { return Err(AppError::Usage { message: "a CI job runs on CI slots, which have no queue order to place it in" @@ -410,12 +407,13 @@ async fn submit( }); } let held = waits || ci; + let mut pooled = false; if ci { let choice = match body.spec.machine { Some(_) => MachineChoice::Pinned(authority), None => MachineChoice::Any, }; - super::ci_api::check_offered(&state, &body.spec, choice).await?; + pooled = super::ci_api::check_offered(&state, &body.spec, choice).await?; } else if held { check_held_authority(&state, authority, &body.spec, body.placement).await?; } @@ -439,16 +437,21 @@ async fn submit( }, after: body.after, owes_final_event: held, - submitted_at: ci.then_some(taken_at), + submitted_at: ci.then(chrono::Utc::now), placement: body.placement, rerun: None, cancel_requested: false, }; - call(&state.store, |reply| StoreMsg::InsertJobRoute { + let route = call(&state.store, |reply| StoreMsg::InsertJobRoute { route: Box::new(route), reply, }) - .await? + .await?; + if pooled { + super::pools::end_if_closed(&state, route).await? + } else { + route + } } }; if let Some(view) = held_view(&state, &route).await? { diff --git a/src/daemon/temporary.rs b/src/daemon/temporary.rs index 56ac3c8..c190472 100644 --- a/src/daemon/temporary.rs +++ b/src/daemon/temporary.rs @@ -10,15 +10,8 @@ //! says the provider's paid time runs on. Before an idle release it stops //! offering the class and checks again, so a job placed in that instant //! keeps it alive and none can be queued after the check -//! -//! When `lease.json` says the provider gives notice before it ends the -//! machine, as AWS does for a Spot interruption, a watcher polls for it. On a -//! notice the machine stops offering the class for good, writes the notice -//! where its runs find it (`HOMEBASED_INTERRUPTION_FILE`), and tells the -//! coordinator, which queues its jobs again for other machines at once use std::sync::Arc; -use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; use chrono::{DateTime, Utc}; @@ -29,8 +22,7 @@ use tracing::{info, warn}; use super::AppState; use super::actors::{StoreMsg, call}; use super::fleet_link::Grant; -use super::keyed_locks::KeyedLocks; -use super::pools::{JOIN_PATH, NOTICE_PATH}; +use super::pools::JOIN_PATH; use super::queue_api::forward; use crate::config::TemporaryConfig; use crate::domain::API_VERSION; @@ -38,9 +30,8 @@ use crate::error::AppError; use crate::fleet::address::MachineAddress; use crate::fleet::http::{ClusterClient, DEFAULT_MAX_BODY}; use crate::pool::cloudlease::{CloudleaseError, LeaseCredential, Renewed, SelfRelease}; -use crate::pool::notice::{AwsImds, NoticeSource, POLL_INTERVAL, ProviderNotice}; use crate::pool::renewal::{Activity, IdleClock, IdleHold, Limits, Renewal}; -use crate::pool::{InterruptionNotice, JoinAnswer, JoinRequest, NoticeAnswer}; +use crate::pool::{JoinAnswer, JoinRequest}; use crate::queue::ci::SlotCapacity; use crate::store::queue::interface::QueueRequest; @@ -93,19 +84,7 @@ pub(super) async fn run(state: AppState, config: TemporaryConfig) { let coordinator = start_link(&state, &config).await; let answer = join_until_accepted(&state, &config, &coordinator, &lease).await; info!(pool = %answer.pool, "temporary machine joined its pool"); - let gate = OfferGate::default(); - let mut offered = setup(&state, &gate, &coordinator, &answer).await; - if let Some(source) = lease.interruption_notice { - let watcher = NoticeWatcher { - state: state.clone(), - config: config.clone(), - coordinator: coordinator.clone(), - lease: lease.clone(), - answer: answer.clone(), - gate: gate.clone(), - }; - tokio::spawn(watcher.run(source)); - } + let mut offered = setup(&state, &coordinator, &answer).await; let limits = Limits { idle_limit: answer.idle_limit, @@ -133,7 +112,7 @@ pub(super) async fn run(state: AppState, config: TemporaryConfig) { // a setup or a reopen that failed is tried again each round the // machine is not releasing; until then it takes no CI job if !offered && !matches!(decision, Renewal::Release { .. }) { - offered = setup(&state, &gate, &coordinator, &answer).await; + offered = setup(&state, &coordinator, &answer).await; } match decision { Renewal::Renew | Renewal::Hold { .. } => { @@ -150,7 +129,7 @@ pub(super) async fn run(state: AppState, config: TemporaryConfig) { } RenewOutcome::Failed => {} RenewOutcome::Ended => { - close_class(&state, &gate, &answer).await; + close_class(&state, &answer).await; break; } } @@ -162,8 +141,7 @@ pub(super) async fn run(state: AppState, config: TemporaryConfig) { withheld = true; } Renewal::Release { idle_since } => { - let end = - release_idle(&state, &gate, &lease, &answer, idle_since, &mut offered).await; + let end = release_idle(&state, &lease, &answer, idle_since, &mut offered).await; if end == LeaseEnd::Ended { break; } @@ -263,13 +241,8 @@ async fn join( } /// Apply the join answer; whether the machine now offers the pool's class -async fn setup( - state: &AppState, - gate: &OfferGate, - coordinator: &MachineAddress, - answer: &JoinAnswer, -) -> bool { - match apply(state, gate, coordinator, answer).await { +async fn setup(state: &AppState, coordinator: &MachineAddress, answer: &JoinAnswer) -> bool { + match apply(state, coordinator, answer).await { Ok(()) => true, Err(error) => { warn!("temporary machine setup: {error}"); @@ -282,7 +255,6 @@ async fn setup( /// offer the pool's class async fn apply( state: &AppState, - gate: &OfferGate, coordinator: &MachineAddress, answer: &JoinAnswer, ) -> Result<(), AppError> { @@ -301,42 +273,7 @@ async fn apply( .map(|(name, value)| format!("{name}={value}\n")) .collect(); write_private(&path, &text)?; - gate.offer(state, answer, answer.slots).await -} - -/// Changes to how many slots of the pool's class this machine offers, one -/// at a time, so none reopens the class after a notice closed it for good -#[derive(Clone, Default)] -struct OfferGate { - // one key: the machine offers one class, and the daemon allows no other mutex - changes: KeyedLocks<()>, - closed: Arc, -} - -impl OfferGate { - /// Offer `capacity` slots, unless a notice closed the class for good; - /// closing it always applies - async fn offer( - &self, - state: &AppState, - answer: &JoinAnswer, - capacity: SlotCapacity, - ) -> Result<(), AppError> { - let _change = self.changes.lock(()).await; - if self.closed.load(Ordering::Acquire) && capacity.get() > 0 { - return Err(AppError::Usage { - message: "the provider gave notice that it ends this machine".into(), - }); - } - offer(state, answer, capacity).await - } - - /// Stop offering the class, and never offer it again - async fn close_for_good(&self, state: &AppState, answer: &JoinAnswer) -> Result<(), AppError> { - let _change = self.changes.lock(()).await; - self.closed.store(true, Ordering::Release); - offer(state, answer, SlotCapacity::default()).await - } + offer(state, answer, answer.slots).await } /// Set how many slots of the pool's class this machine offers @@ -449,10 +386,10 @@ async fn renew(lease: &LeaseCredential, round: Duration) -> RenewOutcome { /// Stop offering the pool's class once cloudlease ended the lease, so no /// job is placed on a machine about to be deleted; running jobs go on /// until it is -async fn close_class(state: &AppState, gate: &OfferGate, answer: &JoinAnswer) { +async fn close_class(state: &AppState, answer: &JoinAnswer) { // the queue is this daemon's own, so a failure is brief; the machine is // deleted soon whatever happens - while let Err(error) = gate.offer(state, answer, SlotCapacity::default()).await { + while let Err(error) = offer(state, answer, SlotCapacity::default()).await { warn!("close the class after the lease ended: {error}"); tokio::time::sleep(RETRY).await; } @@ -461,7 +398,6 @@ async fn close_class(state: &AppState, gate: &OfferGate, answer: &JoinAnswer) { /// Stop offering the class, make sure nothing arrived, then release the lease async fn release_idle( state: &AppState, - gate: &OfferGate, lease: &LeaseCredential, answer: &JoinAnswer, idle_since: DateTime, @@ -469,7 +405,7 @@ async fn release_idle( ) -> LeaseEnd { // with no slots of its class the queue refuses a job of it in the same // store write that would queue it, so none can land after the check below - if let Err(error) = gate.offer(state, answer, SlotCapacity::default()).await { + if let Err(error) = offer(state, answer, SlotCapacity::default()).await { warn!("close the class before release: {error}"); return LeaseEnd::Live; } @@ -480,8 +416,7 @@ async fn release_idle( .map_or(true, |activity| activity != Activity::default()); if busy { // a failed reopen is tried again next round - *offered = gate - .offer(state, answer, answer.slots) + *offered = offer(state, answer, answer.slots) .await .inspect_err(|error| warn!("reopen after a late job: {error}")) .is_ok(); @@ -509,116 +444,3 @@ async fn release_idle( } } } - -/// Watches for the provider's notice that it ends this machine, and acts on -/// the first one -struct NoticeWatcher { - state: AppState, - config: TemporaryConfig, - coordinator: MachineAddress, - lease: LeaseCredential, - answer: JoinAnswer, - gate: OfferGate, -} - -impl NoticeWatcher { - async fn run(self, source: NoticeSource) { - let NoticeSource::AwsImds = source; - let notice = self.wait_for_notice().await; - warn!(action = %notice.action, ends_at = %notice.ends_at, "the provider gave notice that it ends this machine"); - - // first the file, so a run can start saving its work at once - if let Err(error) = write_notice(&self.state, ¬ice) { - warn!("write the interruption notice for runs: {error}"); - } - while let Err(error) = self.gate.close_for_good(&self.state, &self.answer).await { - warn!("close the class after the interruption notice: {error}"); - tokio::time::sleep(RETRY).await; - } - self.report(¬ice).await; - } - - /// Poll the metadata service until it shows a notice - async fn wait_for_notice(&self) -> ProviderNotice { - let mut imds = AwsImds::new(&self.config.imds_endpoint); - let mut failing = false; - let mut tick = tokio::time::interval(POLL_INTERVAL); - tick.set_missed_tick_behavior(MissedTickBehavior::Skip); - loop { - tick.tick().await; - let polled = tokio::task::spawn_blocking(move || { - let action = imds.instance_action(); - (imds, action) - }) - .await; - let action = match polled { - Ok((back, action)) => { - imds = back; - action - } - Err(error) => { - imds = AwsImds::new(&self.config.imds_endpoint); - Err(format!("metadata poll thread: {error}")) - } - }; - match action { - Ok(Some(notice)) => return notice, - Ok(None) => failing = false, - // warn once per outage, since the poll runs every few seconds - Err(error) if !failing => { - warn!("read the Spot interruption notice: {error}"); - failing = true; - } - Err(_) => {} - } - } - } - - /// Tell the coordinator until it answers, it refuses, or the machine - /// should be gone - async fn report(&self, notice: &ProviderNotice) { - let body = InterruptionNotice { - api_version: API_VERSION, - pool: self.answer.pool.clone(), - slot: self.config.slot, - lease: self.lease.lease_id.clone(), - action: notice.action.clone(), - ends_at: notice.ends_at, - }; - let give_up = notice.ends_at + chrono::Duration::minutes(1); - while Utc::now() < give_up { - let response = ClusterClient::new(JOIN_TIMEOUT, DEFAULT_MAX_BODY) - .post_json(&self.coordinator, NOTICE_PATH, &body) - .await; - let error = match response { - Ok(response) if response.status.is_success() => { - let queued = serde_json::from_slice::(&response.body) - .map_or(0, |answer| answer.queued.len()); - info!(queued, "the coordinator queued this machine's jobs again"); - return; - } - Ok(response) if response.status.is_client_error() => { - let error = crate::client::map_error(response.status, &response.body); - warn!("the coordinator refused the interruption notice: {error}"); - return; - } - Ok(response) => format!("status {}", response.status), - Err(error) => error.to_string(), - }; - warn!("report the interruption notice, retrying: {error}"); - tokio::time::sleep(RETRY).await; - } - } -} - -/// Write the notice where runs find it, whole or not at all -fn write_notice(state: &AppState, notice: &ProviderNotice) -> Result<(), AppError> { - let path = state.home.interruption_notice_path(); - let partial = path.with_extension("json.partial"); - if let Some(parent) = path.parent() { - std::fs::create_dir_all(parent)?; - } - std::fs::write(&partial, serde_json::to_vec(notice)?)?; - std::fs::rename(&partial, &path)?; - Ok(()) -} diff --git a/src/home.rs b/src/home.rs index e093e29..2a94d65 100644 --- a/src/home.rs +++ b/src/home.rs @@ -142,14 +142,6 @@ impl Home { self.root.join("temporary").join("env") } - /// Where a temporary machine writes its provider's notice that it ends - /// the machine soon; runs on the machine find this path in - /// `HOMEBASED_INTERRUPTION_FILE`, and the file appears only with a notice - #[must_use] - pub fn interruption_notice_path(&self) -> PathBuf { - self.root.join("temporary").join("interruption.json") - } - /// `iroh/secret.key`: this daemon's iroh key for the Fleet link, made on /// first use and kept so its endpoint id survives restarts #[must_use] diff --git a/src/notify.rs b/src/notify.rs index c1fe1b4..966105e 100644 --- a/src/notify.rs +++ b/src/notify.rs @@ -198,7 +198,6 @@ impl Notifier { method: CurlMethod::Post, url: &url, bearer: token.as_deref(), - headers: &[], json_body: Some(&body), timeout: Duration::from_secs(30), })?; diff --git a/src/pool.rs b/src/pool.rs index 25cdeec..a73b5c9 100644 --- a/src/pool.rs +++ b/src/pool.rs @@ -12,7 +12,6 @@ pub mod boot; pub mod bundle; pub mod cloudlease; pub mod error; -pub mod notice; pub mod renewal; use std::fmt; @@ -44,17 +43,11 @@ pub const DEFAULT_IDLE_LIMIT: Duration = Duration::from_secs(10 * 60); /// Time without output after which running work no longer keeps a machine, by default pub const DEFAULT_STALL_AFTER: Duration = Duration::from_secs(30 * 60); -/// How long before cloudlease's boot grace ends a machine that has not -/// joined is released, at most; a grace shorter than four of these keeps a -/// quarter of itself instead -/// -/// A machine renews only once it joined, so cloudlease deletes it at the end -/// of the grace anyway; releasing it first records `boot_timeout` as the -/// reason rather than `heartbeat_lapsed` -pub const BOOT_GRACE_MARGIN: Duration = Duration::from_secs(60); - /// cloudlease's boot grace when no lease of the pool has shown its own yet: /// cloudlease's default, 8 minutes +/// +/// A machine renews only once it joined, so cloudlease deletes one that has +/// not joined when the grace ends pub const ASSUMED_BOOT_GRACE: Duration = Duration::from_secs(8 * 60); /// Free disk, in GiB, below which a pool machine admits no CI run, by default @@ -64,13 +57,6 @@ pub const ASSUMED_BOOT_GRACE: Duration = Duration::from_secs(8 * 60); /// machine must still take work pub const DEFAULT_MIN_FREE_DISK_GIB: u64 = 1; -/// Time from a lease's create to the release of its machine if it has not -/// joined, for a boot grace of `grace` -#[must_use] -pub fn boot_timeout_within(grace: Duration) -> Duration { - grace.saturating_sub(BOOT_GRACE_MARGIN.min(grace / 4)) -} - /// Times a job whose machine was interrupted runs again on another machine /// of its pool, by default pub const DEFAULT_JOB_RETRIES: u32 = 2; @@ -334,18 +320,7 @@ pub struct PoolSettings { /// Running work with no output for this long no longer renews the lease #[serde(with = "humantime_serde")] pub stall_after: Duration, - /// A machine that has not joined this long after its create is - /// released; without it, shortly before cloudlease's boot grace ends, - /// which each lease shows in its first `heartbeat_deadline_at` - #[serde( - default, - with = "humantime_serde", - skip_serializing_if = "Option::is_none" - )] - pub boot_timeout: Option, - /// Free disk, in GiB, below which a machine of the pool admits no CI run; - /// a pool saved before the setting existed reads as the default - #[serde(default = "default_min_free_disk_gib")] + /// Free disk, in GiB, below which a machine of the pool admits no CI run pub min_free_disk_gib: u64, /// File on the coordinator of `NAME=value` lines each machine's runs /// get, read again at each join; never stored or sent to cloudlease @@ -356,31 +331,10 @@ pub struct PoolSettings { #[serde(default, skip_serializing_if = "Option::is_none")] pub spend_cap_cents: Option, /// Times a job whose machine was interrupted runs again on another - /// machine of the pool; a pool saved before the setting existed reads as - /// the default - #[serde(default = "default_job_retries")] + /// machine of the pool pub job_retries: u32, } -fn default_min_free_disk_gib() -> u64 { - DEFAULT_MIN_FREE_DISK_GIB -} - -fn default_job_retries() -> u32 { - DEFAULT_JOB_RETRIES -} - -impl PoolSettings { - /// When a machine of `lease` that has not joined is released - #[must_use] - pub fn boot_released_at(&self, lease: &MachineLease) -> DateTime { - let timeout = self - .boot_timeout - .unwrap_or_else(|| boot_timeout_within(lease.boot_grace())); - lease.created_at + chrono::Duration::from_std(timeout).unwrap_or_default() - } -} - /// Why cloudlease ended a pool's run that the coordinator did not release #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] @@ -557,21 +511,6 @@ impl Pool { } } - /// Whether a held CI job of the pool's class that its origin took at - /// `submitted_at` is the pool's to end if it never got a machine - /// - /// A pool owns its class until it is released. A job taken after its - /// release was admitted for a Fleet machine that offers the class, so it - /// is never the released pool's to end. A route with no submit time - /// predates pools - #[must_use] - pub fn owns(&self, submitted_at: Option>) -> bool { - match (&self.state, submitted_at) { - (PoolState::Released { at, .. }, Some(submitted_at)) => submitted_at <= *at, - _ => true, - } - } - /// The provider took a create, so earlier failures were not the class's fault pub fn create_succeeded(&mut self) { self.create_failures = None; @@ -622,8 +561,6 @@ pub enum ReleaseReason { SpendCap, /// The provider could not create it CreateFailed, - /// It did not join within the pool's boot timeout - BootTimeout, /// cloudlease refused to create it Refused, /// The provider took it back, such as an AWS Spot interruption, or it @@ -679,20 +616,17 @@ pub struct MachineLease { /// When cloudlease created the lease pub created_at: DateTime, /// When cloudlease's boot grace ends: the lease's first - /// `heartbeat_deadline_at`, before the machine ever renewed; `None` for a - /// lease saved before the coordinator kept it - #[serde(default, skip_serializing_if = "Option::is_none")] - pub boot_deadline_at: Option>, + /// `heartbeat_deadline_at`, before the machine ever renewed + pub boot_deadline_at: DateTime, } impl MachineLease { - /// cloudlease's boot grace for this lease; cloudlease's default when - /// the lease was saved without its boot deadline + /// cloudlease's boot grace for this lease #[must_use] pub fn boot_grace(&self) -> Duration { - self.boot_deadline_at.map_or(ASSUMED_BOOT_GRACE, |at| { - (at - self.created_at).to_std().unwrap_or_default() - }) + (self.boot_deadline_at - self.created_at) + .to_std() + .unwrap_or_default() } } @@ -886,21 +820,12 @@ impl PoolReach { .filter_map(|machine| machine.state.lease()) .collect(); // every lease of the pool has the same grace and class lifetime, - // so the newest one that kept its boot deadline tells - let shown_grace = leases + // so the newest one tells; cloudlease deletes a machine that has + // not joined by the end of its grace + let join_within = leases .iter() - .filter(|lease| lease.boot_deadline_at.is_some()) .max_by_key(|lease| lease.created_at) - .map(|lease| lease.boot_grace()); - // cloudlease deletes a machine that has not joined by the end of - // its grace, so a longer boot timeout never delays a join - // further; before a lease showed the grace, a set boot timeout - // is the only bound, and without one cloudlease's default - let join_within = match (pool.settings.boot_timeout, shown_grace) { - (Some(timeout), Some(grace)) => timeout.min(grace), - (Some(timeout), None) => timeout, - (None, grace) => boot_timeout_within(grace.unwrap_or(ASSUMED_BOOT_GRACE)), - }; + .map_or(ASSUMED_BOOT_GRACE, |lease| lease.boot_grace()); // a lease that ends before the pool's deadline shows the class's // own lifetime, which every later machine gets too let class_lifetime = leases @@ -1001,17 +926,12 @@ pub struct MachineReleased { pub output_lost: bool, /// Which run of the job ended with the machine: 1 for its first, more /// after its earlier machines were interrupted - #[serde(default = "first_attempt")] pub attempt: u32, /// Why a job whose machine was interrupted was not run again #[serde(default, skip_serializing_if = "Option::is_none")] pub not_rerun: Option, } -fn first_attempt() -> u32 { - 1 -} - /// Why a job whose machine was interrupted ended instead of running again #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "cause", rename_all = "snake_case")] @@ -1042,10 +962,6 @@ pub struct MachineLost { pub machine: MachineName, /// Why pub reason: ReleaseReason, - /// When the provider ends the machine, from its interruption notice; the - /// interrupted run may go on until then, beside the rerun - #[serde(default, skip_serializing_if = "Option::is_none")] - pub ends_at: Option>, /// The run now queued: 2 for the first rerun pub attempt: u32, /// Runs the pool allows each job: its retries and the first run @@ -1150,35 +1066,6 @@ pub struct JoinRequest { pub join_token: JoinToken, } -/// Body of `POST /v1/cluster/pool/notice`, sent by a temporary machine's -/// daemon when its provider gave notice that it ends the machine soon, such -/// as an AWS Spot interruption notice -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct InterruptionNotice { - /// Always 1 - pub api_version: u32, - /// Pool the machine serves - pub pool: PoolName, - /// Its slot - pub slot: SlotId, - /// Its lease - pub lease: LeaseId, - /// What the provider does then, such as `terminate` - pub action: String, - /// When the provider ends the machine - pub ends_at: DateTime, -} - -/// Answer to an interruption notice -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct NoticeAnswer { - /// Always 1 - pub api_version: u32, - /// Jobs the coordinator queued again for other machines - pub queued: Vec, -} - /// Answer to a join: everything the machine needs that boot data must not carry #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -1270,7 +1157,7 @@ mod tests { assert!(parse_env_file("novalue").is_err()); } - fn test_pool(deadline_at: DateTime, boot_timeout: Option) -> Pool { + fn test_pool(deadline_at: DateTime) -> Pool { Pool { name: "afv".parse().unwrap(), settings: PoolSettings { @@ -1280,7 +1167,6 @@ mod tests { slots: SlotCapacity::default(), idle_limit: DEFAULT_IDLE_LIMIT, stall_after: DEFAULT_STALL_AFTER, - boot_timeout, min_free_disk_gib: DEFAULT_MIN_FREE_DISK_GIB, env_file: None, spend_cap_cents: None, @@ -1308,7 +1194,7 @@ mod tests { lease: LeaseId::new("lease"), hard_deadline_at: created_at + chrono::Duration::minutes(life), created_at, - boot_deadline_at: Some(created_at + chrono::Duration::minutes(grace)), + boot_deadline_at: created_at + chrono::Duration::minutes(grace), }, }, } @@ -1319,15 +1205,15 @@ mod tests { #[test] fn reach_counts_a_new_machines_boot_and_learns_grace_and_class_lifetime() { let now = Utc::now(); - let pool = test_pool(now + chrono::Duration::hours(1), None); + let pool = test_pool(now + chrono::Duration::hours(1)); - // before any lease: cloudlease's default 8 minute grace, released at 7 + // before any lease: cloudlease's default 8 minute grace let reach = PoolReach::new(&pool, &[], now); - assert!(reach.can_run(53 * MINUTE)); - assert!(!reach.can_run(54 * MINUTE)); - assert_eq!(reach.longest_kill(), 53 * MINUTE); + assert!(reach.can_run(52 * MINUTE)); + assert!(!reach.can_run(53 * MINUTE)); + assert_eq!(reach.longest_kill(), 52 * MINUTE); - // a phoenixNAP lease shows a 20 minute grace; it is released at 19 + // a phoenixNAP lease shows a 20 minute grace let mut released = booting(&pool, now - chrono::Duration::hours(1), 20, 600); released.state = MachineState::Released { lease: released.state.lease().cloned(), @@ -1336,47 +1222,28 @@ mod tests { gone_at: now, }; let reach = PoolReach::new(&pool, std::slice::from_ref(&released), now); - assert!(reach.new_machine_can_run(41 * MINUTE)); - assert!(!reach.new_machine_can_run(42 * MINUTE)); + assert!(reach.new_machine_can_run(40 * MINUTE)); + assert!(!reach.new_machine_can_run(41 * MINUTE)); // a class whose machines live 30 minutes caps every new machine, but // a booting machine still offers what is left of its own life let short = booting(&pool, now - chrono::Duration::minutes(5), 8, 30); let reach = PoolReach::new(&pool, &[short], now); - assert!(!reach.new_machine_can_run(24 * MINUTE)); - assert!(reach.new_machine_can_run(23 * MINUTE)); + assert!(!reach.new_machine_can_run(23 * MINUTE)); + assert!(reach.new_machine_can_run(22 * MINUTE)); assert!(reach.can_run(25 * MINUTE)); assert!(!reach.can_run(26 * MINUTE)); // a stopped pool asks for no machine, so only live ones count - let mut stopped = test_pool(now + chrono::Duration::hours(1), Some(MINUTE)); + let mut stopped = test_pool(now + chrono::Duration::hours(1)); stopped.stop(PoolEnd::Requested); assert!(!PoolReach::new(&stopped, &[], now).can_run(MINUTE)); } - #[test] - fn a_boot_timeout_past_the_grace_does_not_shrink_reach() { - let now = Utc::now(); - // cloudlease deletes an unjoined machine at its 8 minute grace, so a - // 55 minute boot timeout still leaves a new machine 52 minutes - let pool = test_pool(now + chrono::Duration::hours(1), Some(55 * MINUTE)); - let lease = booting(&pool, now - chrono::Duration::minutes(1), 8, 120); - let reach = PoolReach::new(&pool, std::slice::from_ref(&lease), now); - assert!(reach.new_machine_can_run(52 * MINUTE)); - assert!(!reach.new_machine_can_run(53 * MINUTE)); - - // before any lease showed the grace, a set boot timeout is the bound, - // as for a phoenixNAP pool whose grace is 20 minutes - let pool = test_pool(now + chrono::Duration::minutes(30), Some(19 * MINUTE)); - let reach = PoolReach::new(&pool, &[], now); - assert!(reach.new_machine_can_run(11 * MINUTE)); - assert!(!reach.new_machine_can_run(12 * MINUTE)); - } - #[test] fn slots_on_machines_that_end_too_soon_leave_jobs_without_a_slot() { let now = Utc::now(); - let pool = test_pool(now + chrono::Duration::minutes(25), None); + let pool = test_pool(now + chrono::Duration::minutes(25)); let reach = PoolReach::new(&pool, &[], now); let soon = ComingSlots { ends_at: Some(now + chrono::Duration::minutes(2)), @@ -1403,50 +1270,10 @@ mod tests { ); } - #[test] - fn pools_and_leases_saved_before_these_settings_still_load() { - let pool = test_pool(Utc::now(), None); - let mut value = serde_json::to_value(&pool).unwrap(); - value["settings"] - .as_object_mut() - .unwrap() - .remove("min_free_disk_gib"); - let loaded: Pool = serde_json::from_value(value).unwrap(); - assert_eq!(loaded.settings.min_free_disk_gib, DEFAULT_MIN_FREE_DISK_GIB); - - let lease = serde_json::json!({ - "lease": "lease-1", - "hard_deadline_at": "2026-11-25T02:00:00Z", - "created_at": "2026-11-24T20:00:00Z", - }); - let lease: MachineLease = serde_json::from_value(lease).unwrap(); - assert_eq!(lease.boot_grace(), ASSUMED_BOOT_GRACE); - } - - #[test] - fn boot_timeouts_stop_short_of_the_grace_unless_set() { - assert_eq!(boot_timeout_within(8 * MINUTE), 7 * MINUTE); - assert_eq!(boot_timeout_within(20 * MINUTE), 19 * MINUTE); - assert_eq!(boot_timeout_within(MINUTE), Duration::from_secs(45)); - let now = Utc::now(); - let pool = test_pool(now + chrono::Duration::hours(1), None); - let machine = booting(&pool, now, 20, 60); - let lease = machine.state.lease().unwrap(); - assert_eq!( - pool.settings.boot_released_at(lease), - now + chrono::Duration::minutes(19) - ); - let set = test_pool(now + chrono::Duration::hours(1), Some(2 * MINUTE)); - assert_eq!( - set.settings.boot_released_at(lease), - now + chrono::Duration::minutes(2) - ); - } - #[test] fn only_an_interruption_reruns_and_only_within_the_limit_and_reach() { let now = Utc::now(); - let pool = test_pool(now + chrono::Duration::hours(1), None); + let pool = test_pool(now + chrono::Duration::hours(1)); let policy = RerunPolicy::new(&pool, &[], SlotId::new(), now); assert_eq!(policy.max_attempts, 3); let interrupted = ReleaseReason::Interrupted; @@ -1467,9 +1294,9 @@ mod tests { policy.decide(&interrupted, 1, 10 * MINUTE, true), Rerun::End(Some(NotRerun::Pinned)) ); - // a new machine joins within 7 minutes, so 54 minutes no longer fit + // a new machine joins within 8 minutes, so 53 minutes no longer fit assert_eq!( - policy.decide(&interrupted, 1, 54 * MINUTE, false), + policy.decide(&interrupted, 1, 53 * MINUTE, false), Rerun::End(Some(NotRerun::OutOfReach)) ); @@ -1490,9 +1317,9 @@ mod tests { ); // the lost machine's lease may be the only one showing a 4 minute - // grace: a replacement then joins within 3 minutes, so a 10 minute - // job fits in the 15 left, though the assumed 7 minutes would not - let closing = test_pool(now + chrono::Duration::minutes(15), None); + // grace: a replacement then joins within 4 minutes, so a 10 minute + // job fits in the 15 left, though the assumed 8 minutes would not + let closing = test_pool(now + chrono::Duration::minutes(15)); let lost = booting(&closing, now - chrono::Duration::minutes(5), 4, 60); let policy = RerunPolicy::new(&closing, std::slice::from_ref(&lost), lost.slot, now); assert_eq!( diff --git a/src/pool/cloudlease.rs b/src/pool/cloudlease.rs index 3417265..64cbd73 100644 --- a/src/pool/cloudlease.rs +++ b/src/pool/cloudlease.rs @@ -314,12 +314,7 @@ pub struct LeaseCredential { /// cloudlease deletes the machine at this time whatever happens pub hard_deadline_at: DateTime, /// cloudlease deletes the machine this long after its last renew - #[serde(default)] - heartbeat_ttl_secs: Option, - /// The notice the machine's provider gives before it ends the machine; - /// absent for a provider that gives none, and from an older cloudlease - #[serde(default)] - pub interruption_notice: Option, + heartbeat_ttl_secs: u64, } impl std::fmt::Debug for LeaseCredential { @@ -345,10 +340,11 @@ impl LeaseCredential { /// of the lease's heartbeat window, so a failed renew has rounds to spare #[must_use] pub fn renew_interval(&self, configured: Duration) -> Duration { - self.heartbeat_ttl_secs - .map(|ttl| Duration::from_secs(ttl) / 4) - .filter(|quarter| !quarter.is_zero()) - .map_or(configured, |quarter| configured.min(quarter)) + let quarter = Duration::from_secs(self.heartbeat_ttl_secs) / 4; + if quarter.is_zero() { + return configured; + } + configured.min(quarter) } /// Move the heartbeat deadline; `410 lease_ended` means the machine is going away @@ -413,7 +409,6 @@ fn request( method, url, bearer: Some(token), - headers: &[], json_body: body, timeout: REQUEST_TIMEOUT, }) @@ -456,7 +451,7 @@ mod tests { use super::LeaseCredential; - fn lease(ttl: Option) -> LeaseCredential { + fn lease(ttl: u64) -> LeaseCredential { serde_json::from_value(serde_json::json!({ "lease_id": "run_1-1", "token": "cll_secret", @@ -471,12 +466,11 @@ mod tests { fn renewals_come_at_least_four_times_per_heartbeat_window() { let configured = Duration::from_secs(30); // the default 3-minute window leaves the configured 30 s alone - assert_eq!(lease(Some(180)).renew_interval(configured), configured); + assert_eq!(lease(180).renew_interval(configured), configured); // the shortest window cloudlease allows forces 15 s assert_eq!( - lease(Some(60)).renew_interval(configured), + lease(60).renew_interval(configured), Duration::from_secs(15) ); - assert_eq!(lease(None).renew_interval(configured), configured); } } diff --git a/src/pool/error.rs b/src/pool/error.rs index 5f58c66..f2058d6 100644 --- a/src/pool/error.rs +++ b/src/pool/error.rs @@ -10,6 +10,8 @@ pub enum PoolCode { PoolsNotConfigured, /// A pool of that name is open or releasing PoolExists, + /// A Fleet machine already offers the CI class the pool would name + ClassOffered, /// No pool of that name PoolNotFound, /// The pool takes no more jobs or machines @@ -24,9 +26,6 @@ pub enum PoolCode { SubmodulesUnsupported, /// A pool job's commit makes a bundle larger than a machine takes BundleTooLarge, - /// A machine's interruption notice did not come from the joined machine - /// it names - NoticeRefused, } impl PoolCode { @@ -36,6 +35,7 @@ impl PoolCode { match self { Self::PoolsNotConfigured => "pools_not_configured", Self::PoolExists => "pool_exists", + Self::ClassOffered => "class_offered", Self::PoolNotFound => "pool_not_found", Self::PoolEnded => "pool_ended", Self::PoolDeadlineTooClose => "pool_deadline_too_close", @@ -43,7 +43,6 @@ impl PoolCode { Self::CommitUnavailable => "commit_unavailable", Self::SubmodulesUnsupported => "submodules_unsupported", Self::BundleTooLarge => "bundle_too_large", - Self::NoticeRefused => "notice_refused", } } @@ -57,7 +56,7 @@ impl PoolCode { | Self::SubmodulesUnsupported | Self::BundleTooLarge => 2, Self::PoolNotFound => 3, - Self::PoolExists | Self::PoolEnded | Self::JoinRefused | Self::NoticeRefused => 5, + Self::PoolExists | Self::ClassOffered | Self::PoolEnded | Self::JoinRefused => 5, } } } diff --git a/src/pool/notice.rs b/src/pool/notice.rs deleted file mode 100644 index a4049e0..0000000 --- a/src/pool/notice.rs +++ /dev/null @@ -1,155 +0,0 @@ -//! The provider's notice that it ends a temporary machine soon -//! -//! AWS gives a Spot instance about two minutes' notice before it takes the -//! instance back, through the instance metadata service: with IMDSv2 the -//! machine gets a session token with a `PUT`, then reads -//! `spot/instance-action`, which is `404` until a notice exists. cloudlease -//! says in `lease.json` which notice a machine's provider gives, so a -//! machine on any other provider never polls anything - -use std::time::{Duration, Instant}; - -use chrono::{DateTime, Utc}; -use serde::{Deserialize, Serialize}; - -use crate::curl::{CurlMethod, CurlRequest, send}; - -/// How often a machine reads its provider's notice; AWS suggests every 5 seconds -pub const POLL_INTERVAL: Duration = Duration::from_secs(5); - -/// The instance metadata service's address on EC2 -pub const DEFAULT_IMDS_ENDPOINT: &str = "http://169.254.169.254"; - -/// Time limit for one metadata call; the service is on the instance's own -/// link, so anything slower means it is not there -const REQUEST_TIMEOUT: Duration = Duration::from_secs(2); - -/// Lifetime the machine asks for its IMDSv2 session token, the most AWS allows -const TOKEN_TTL_SECS: u64 = 21_600; - -/// A token is renewed this long before it would expire -const TOKEN_MARGIN: Duration = Duration::from_secs(600); - -/// Which notice a machine's provider gives before it ends the machine, as -/// cloudlease writes it in `lease.json` -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum NoticeSource { - /// EC2's instance metadata service, version 2: the Spot instance action - AwsImds, -} - -/// The provider's notice that it ends the machine -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct ProviderNotice { - /// What the provider does then, such as `terminate` - pub action: String, - /// When - pub ends_at: DateTime, -} - -/// EC2's answer at `spot/instance-action` -#[derive(Debug, Deserialize)] -struct InstanceAction { - action: String, - time: DateTime, -} - -/// Reads the Spot instance action from EC2's metadata service with IMDSv2 -#[derive(Debug)] -pub struct AwsImds { - endpoint: String, - token: Option<(String, Instant)>, -} - -impl AwsImds { - /// A reader of the service at `endpoint`, such as [`DEFAULT_IMDS_ENDPOINT`] - #[must_use] - pub fn new(endpoint: &str) -> Self { - Self { - endpoint: endpoint.trim_end_matches('/').to_owned(), - token: None, - } - } - - /// The notice, or `None` while there is none - /// - /// Blocks for up to a few seconds; a failed call is an error the caller - /// retries at its next poll - pub fn instance_action(&mut self) -> Result, String> { - let token = self.token()?; - let url = format!("{}/latest/meta-data/spot/instance-action", self.endpoint); - let response = send(&CurlRequest { - method: CurlMethod::Get, - url: &url, - bearer: None, - headers: &[("X-aws-ec2-metadata-token", &token)], - json_body: None, - timeout: REQUEST_TIMEOUT, - })?; - match response.status { - 200 => parse_instance_action(&response.body).map(Some), - 404 => Ok(None), - // the token expired early, such as after the instance was stopped - 401 => { - self.token = None; - Err("the metadata service refused its session token".into()) - } - status => Err(format!("{url} answered {status}")), - } - } - - fn token(&mut self) -> Result { - if let Some((token, expires)) = &self.token - && Instant::now() + TOKEN_MARGIN < *expires - { - return Ok(token.clone()); - } - let url = format!("{}/latest/api/token", self.endpoint); - let ttl = TOKEN_TTL_SECS.to_string(); - let response = send(&CurlRequest { - method: CurlMethod::Put, - url: &url, - bearer: None, - headers: &[("X-aws-ec2-metadata-token-ttl-seconds", &ttl)], - json_body: None, - timeout: REQUEST_TIMEOUT, - })?; - if response.status != 200 || response.body.trim().is_empty() { - return Err(format!("{url} answered {}", response.status)); - } - let token = response.body.trim().to_owned(); - self.token = Some(( - token.clone(), - Instant::now() + Duration::from_secs(TOKEN_TTL_SECS), - )); - Ok(token) - } -} - -fn parse_instance_action(body: &str) -> Result { - let action: InstanceAction = serde_json::from_str(body) - .map_err(|error| format!("unreadable Spot instance action {body:?}: {error}"))?; - Ok(ProviderNotice { - action: action.action, - ends_at: action.time, - }) -} - -#[cfg(test)] -mod tests { - use super::{NoticeSource, parse_instance_action}; - - #[test] - fn reads_ec2s_instance_action_and_cloudleases_notice_source() { - let notice = - parse_instance_action(r#"{"action": "terminate", "time": "2026-11-25T03:12:00Z"}"#) - .unwrap(); - assert_eq!(notice.action, "terminate"); - assert_eq!(notice.ends_at.to_rfc3339(), "2026-11-25T03:12:00+00:00"); - assert!(parse_instance_action("").is_err()); - - let source: NoticeSource = serde_json::from_str("\"aws_imds\"").unwrap(); - assert_eq!(source, NoticeSource::AwsImds); - } -} diff --git a/src/runner.rs b/src/runner.rs index ede4e51..3073d20 100644 --- a/src/runner.rs +++ b/src/runner.rs @@ -1046,25 +1046,16 @@ impl ChildOomScore { } } -/// Variables a temporary machine's coordinator handed it at join, and where -/// a run finds its provider's interruption notice; none elsewhere +/// Variables a temporary machine's coordinator handed it at join; none elsewhere fn pool_variables(home: &Home) -> Result, AppError> { let text = match std::fs::read_to_string(home.pool_env_path()) { Ok(text) => text, Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()), Err(error) => return Err(error.into()), }; - let mut variables = - crate::pool::parse_env_file(&text).map_err(|message| AppError::Internal { - message: format!("pool variables: {message}"), - })?; - // a pool's own variables may not start with HOMEBASED_, so this never - // collides with one - variables.push(( - "HOMEBASED_INTERRUPTION_FILE".to_owned(), - home.interruption_notice_path().display().to_string(), - )); - Ok(variables) + crate::pool::parse_env_file(&text).map_err(|message| AppError::Internal { + message: format!("pool variables: {message}"), + }) } #[cfg(test)] diff --git a/src/store/queue/delivery.rs b/src/store/queue/delivery.rs index e839e42..58c9b83 100644 --- a/src/store/queue/delivery.rs +++ b/src/store/queue/delivery.rs @@ -434,7 +434,6 @@ impl Store { pool: released.pool.clone(), machine: released.machine.clone(), reason: released.reason.clone(), - ends_at: None, attempt, max_attempts: policy.max_attempts, }; @@ -453,35 +452,6 @@ impl Store { }) } - /// Queue one job this origin sent to `machine` again if `policy` lets - /// it run again, when the machine gave notice that its provider ends it - /// soon; whether it was queued - /// - /// The machine still runs, so a job that may not run again is left to - /// finish there or to end once cloudlease confirms the machine gone - pub fn rerun_job_of_ending_machine( - &self, - job: JobId, - machine: MachineId, - lost: &MachineLost, - policy: &RerunPolicy, - ) -> Result { - self.immediate(|| { - let Some(route) = self.unfinished_route_on(job, machine)? else { - return Ok(false); - }; - let Rerun::Queue { attempt } = decide_rerun(policy, &lost.reason, &route) else { - return Ok(false); - }; - let lost = MachineLost { - attempt, - ..lost.clone() - }; - self.queue_again(route, lost)?; - Ok(true) - }) - } - /// The job's route while it was sent to `machine` and has no final event fn unfinished_route_on( &self, @@ -489,7 +459,7 @@ impl Store { machine: MachineId, ) -> Result, AppError> { let route = self.job_route(job)?; - let open = self.unfinished_jobs_on(machine)?.contains(&job); + let open = self.jobs_on(machine, OnMachine::Sent)?.contains(&job); Ok(route.filter(|_| open)) } @@ -507,12 +477,6 @@ impl Store { self.save_route(&route) } - /// Jobs this origin sent to `machine` that have no final event, oldest - /// first - pub fn unfinished_jobs_on(&self, machine: MachineId) -> Result, AppError> { - self.jobs_on(machine, OnMachine::Sent) - } - /// Jobs this origin sent to `machine` or holds pinned to it that have no /// final event, oldest first: what a machine cloudlease confirmed gone /// leaves to end or rerun diff --git a/src/store/tests.rs b/src/store/tests.rs index 2578e9b..00997f1 100644 --- a/src/store/tests.rs +++ b/src/store/tests.rs @@ -1210,7 +1210,6 @@ fn a_pool_release_keeps_its_run_and_survives_a_stale_save() { slots: SlotCapacity::default(), idle_limit: Duration::from_secs(600), stall_after: Duration::from_secs(1800), - boot_timeout: Some(Duration::from_secs(900)), min_free_disk_gib: 1, env_file: None, spend_cap_cents: None, diff --git a/src/t3.rs b/src/t3.rs index c116581..1b2321a 100644 --- a/src/t3.rs +++ b/src/t3.rs @@ -1287,7 +1287,6 @@ fn require_protocol(origin: &str) -> Result<(), ApiFailure> { method: CurlMethod::Get, url: &format!("{origin}/.well-known/t3/environment"), bearer: None, - headers: &[], json_body: None, timeout: DESCRIPTOR_TIMEOUT, }) diff --git a/src/t3/launch.rs b/src/t3/launch.rs index e257d13..77e4887 100644 --- a/src/t3/launch.rs +++ b/src/t3/launch.rs @@ -676,7 +676,6 @@ fn set_icon(env: &T3Env, project_id: &str, change: &IconChange) -> Result<(), La method: CurlMethod::Post, url: &format!("{}{PROJECT_MUTATE_PATH}", server.origin), bearer: Some(&token.value), - headers: &[], json_body: Some(&update), timeout: PROJECT_UPDATE_TIMEOUT, }) diff --git a/src/t3/rpc.rs b/src/t3/rpc.rs index e439d07..7f9bc4d 100644 --- a/src/t3/rpc.rs +++ b/src/t3/rpc.rs @@ -142,7 +142,6 @@ fn issue_ticket(origin: &str, token: &str, timeout: Duration) -> Result Daemon { #[derive(Default)] struct Machines { daemons: BTreeMap, - /// Base of a fake metadata service each machine reads for a Spot - /// interruption notice, as on AWS; none on other providers - imds: Option, } impl Machines { @@ -72,7 +68,7 @@ impl Machines { if lease.state != "running" || self.daemons.contains_key(&lease.lease_id) { continue; } - let daemon = boot(fake, &lease, self.imds.as_deref()); + let daemon = boot(fake, &lease); self.daemons.insert(lease.lease_id.clone(), daemon); } } @@ -102,22 +98,19 @@ impl Machines { } } -fn boot(fake: &FakeCloudlease, lease: &FakeLease, imds: Option<&str>) -> Daemon { +fn boot(fake: &FakeCloudlease, lease: &FakeLease) -> Daemon { let mut daemon = Daemon::start(&lease.hostname, true); let lease_file = daemon.home.parent().unwrap().join("lease.json"); - let mut credential = json!({ + // the deployed cloudlease Worker still writes `interruption_notice`, + // which a machine must ignore + let credential = json!({ "lease_id": lease.lease_id, "token": lease.token, "api_base": fake.base(), "hard_deadline_at": lease.hard_deadline_at, "heartbeat_ttl_secs": 4, + "interruption_notice": "aws_imds", }); - // cloudlease names the notice an AWS machine's provider gives - let mut temporary = String::new(); - if let Some(base) = imds { - credential["interruption_notice"] = json!("aws_imds"); - temporary = format!("\nimds_endpoint = \"{base}/{}\"", lease.hostname); - } fs::write(&lease_file, credential.to_string()).unwrap(); let files = lease.boot["files"].as_array().unwrap(); let config = files @@ -129,7 +122,7 @@ fn boot(fake: &FakeCloudlease, lease: &FakeLease, imds: Option<&str>) -> Daemon .replace( "lease_file = \"/etc/cloudlease/lease.json\"", &format!( - "lease_file = \"{}\"\nrenew_interval = \"1s\"\nlink_listen = \"127.0.0.1:0\"{temporary}", + "lease_file = \"{}\"\nrenew_interval = \"1s\"\nlink_listen = \"127.0.0.1:0\"", lease_file.display() ), ); @@ -951,16 +944,15 @@ fn a_job_no_pool_machine_can_run_gets_no_machine_and_fails() { "--max", "2", "--deadline", - "3m", - "--boot-timeout", - "10s", + "10m", "--idle-limit", "3s", ], ); - // inside the deadline, but not once a new machine has booted: refused - let (_, late) = ci_run(&origin, thread, "tight", "2m55s", &[], "true"); + // inside the deadline, but not once a new machine has had cloudlease's + // default 8 minute boot grace: refused + let (_, late) = ci_run(&origin, thread, "tight", "2m5s", &[], "true"); assert!(!late.status.success()); let refusal = String::from_utf8_lossy(&late.stderr).into_owned() + &String::from_utf8_lossy(&late.stdout); @@ -968,12 +960,12 @@ fn a_job_no_pool_machine_can_run_gets_no_machine_and_fails() { // a new machine could still run this job now, but it waits for a task // that ends only after no machine could - let task = sleeper(&origin, thread, 25); + let task = sleeper(&origin, thread, 30); let job = accepted(ci_run( &origin, thread, "tight", - "2m40s", + "1m40s", &["--after", &task], "true", )); @@ -1116,52 +1108,41 @@ fn a_run_cloudlease_ends_outside_the_coordinator_ends_the_pool() { } #[test] -fn a_machine_that_never_joins_is_released_before_its_boot_grace_ends() { +fn a_machine_that_never_joins_frees_its_slot_when_its_boot_grace_ends() { let fake = FakeCloudlease::start(Duration::from_secs(4)); - // a lease's first heartbeat deadline gives the boot grace; no flag + // a lease's first heartbeat deadline gives the boot grace fake.set_boot_grace(Duration::from_secs(8)); let origin = coordinator(&fake); let thread = thread(&origin); - cli( - &origin, - thread, - &[ - "pool", - "create", - "slowboot", - "--machine-class", - "do-c16", - "--max", - "1", - "--deadline", - "1h", - ], - ); + create_pool(&origin, thread, "slowboot", &["--max", "1"]); run(&origin, thread, "slowboot", "true"); - // the machine never boots here: the coordinator releases it a quarter of - // the grace before cloudlease would let its heartbeat lapse + // no machine boots here, so cloudlease lets the first lease's heartbeat + // lapse at the end of its grace, and the job that still waits gets a + // second machine under --max 1 assert!( - wait_until(Duration::from_secs(30), || { - fake.leases() - .first() - .is_some_and(|lease| lease.release.is_some()) - }), - "the machine was never released: {}", - pool(&origin, thread, "slowboot") + wait_until(Duration::from_secs(40), || fake.leases().len() == 2), + "no second machine was asked for: {}\n{:?}", + pool(&origin, thread, "slowboot"), + fake.leases() ); - let lease = fake.leases().remove(0); + let first = fake.leases().remove(0); assert_eq!( - lease.release.as_ref().unwrap(), - &("requested".to_owned(), "client"), - "{lease:?}" + first.release.as_ref().unwrap(), + &("heartbeat_lapsed".to_owned(), "cloudlease"), + "{first:?}" ); - assert!( - wait_until(Duration::from_secs(10), || { - pool(&origin, thread, "slowboot")["machines"][0]["reason"] == "boot_timeout" - }), - "{}", - pool(&origin, thread, "slowboot") + let shown = pool(&origin, thread, "slowboot"); + let machine = shown["machines"] + .as_array() + .unwrap() + .iter() + .find(|machine| machine["name"] == first.hostname.as_str()) + .unwrap(); + assert_eq!( + (&machine["state"], &machine["reason"]), + (&json!("released"), &json!("heartbeat_lapsed")), + "{shown}" ); cli(&origin, thread, &["pool", "release", "slowboot"]); } @@ -1214,6 +1195,26 @@ fn a_released_pool_leaves_later_jobs_of_its_class_to_the_fleet() { // the coordinator now offers the class itself, as a permanent Fleet // machine would, so a new job waits for its slot and runs there cli(&origin, thread, &["ci", "capacity", "shared", "1"]); + // a pool may not share its class with a Fleet machine + let refused = cli_output( + &origin, + thread, + &[ + "pool", + "create", + "shared", + "--machine-class", + "do-c16", + "--max", + "1", + "--deadline", + "1h", + ], + ); + assert!(!refused.status.success()); + let refusal = String::from_utf8_lossy(&refused.stderr).into_owned() + + &String::from_utf8_lossy(&refused.stdout); + assert!(refusal.contains("class_offered"), "{refusal}"); let after = accepted(ci_run( &origin, thread, @@ -1494,7 +1495,6 @@ fn an_interrupted_job_runs_again_on_a_replacement_machine_and_succeeds() { assert_eq!(lost.reason.to_string(), "interrupted"); assert_eq!(lost.machine.to_string(), first.hostname); assert_eq!((lost.attempt, lost.max_attempts), (2, 3)); - assert_eq!(lost.ends_at, None); assert_eq!(fake.leases().len(), 2); } @@ -1551,11 +1551,11 @@ fn a_job_interrupted_on_every_machine_stops_at_its_retry_limit() { #[test] fn a_rerun_that_would_outlast_the_pool_deadline_fails_instead() { let fake = FakeCloudlease::start(Duration::from_secs(4)); - // a long grace, so the pool's boot timeout bounds a new machine's join - fake.set_boot_grace(Duration::from_secs(600)); + // a 9 minute grace, a minute past the 8 the pool assumes before its + // first lease shows the class's own + fake.set_boot_grace(Duration::from_secs(9 * 60)); let origin = coordinator(&fake); let thread = thread(&origin); - let created = std::time::Instant::now(); cli( &origin, thread, @@ -1569,14 +1569,12 @@ fn a_rerun_that_would_outlast_the_pool_deadline_fails_instead() { "1", "--deadline", "20m", - "--boot-timeout", - "150s", ], ); - // a new machine joins within 150 s, so a 17 minute job fits one for the - // first 30 s; the running machine still fits it for 3 minutes + // an 11m40s job fits a new machine on the assumed 8 minute grace, but + // not on the 9 minutes the first lease shows let starts = origin.user_home.join("starts"); - let job = run_with_kill(&origin, thread, "late", "17m", &always_works(&starts)); + let job = run_with_kill(&origin, thread, "late", "11m40s", &always_works(&starts)); let mut machines = Machines::default(); assert!( @@ -1584,9 +1582,6 @@ fn a_rerun_that_would_outlast_the_pool_deadline_fails_instead() { "the job never started: {}", pool(&origin, thread, "late") ); - while created.elapsed() < Duration::from_secs(40) { - std::thread::sleep(Duration::from_millis(200)); - } let lease = live_lease(&fake).unwrap(); fake.end_lease(&lease.lease_id, "interrupted"); @@ -1657,205 +1652,29 @@ fn a_rerun_the_spend_cap_refuses_a_machine_for_fails_with_the_pool() { } #[test] -fn a_spot_notice_queues_the_job_again_before_cloudlease_notices_the_machine_gone() { +fn a_job_cancelled_before_its_machine_is_interrupted_is_not_run_again() { let fake = FakeCloudlease::start(Duration::from_secs(4)); - let imds = FakeImds::start(); - let origin = coordinator(&fake); - let thread = thread(&origin); - create_pool(&origin, thread, "notice", &["--max", "2"]); - let starts = origin.user_home.join("starts"); - let seen = origin.user_home.join("notice-file"); - let script = format!( - "printf '%s\\n' \"$HOMEBASED_INTERRUPTION_FILE\" >> {}; {}", - seen.display(), - second_run_succeeds(&starts) - ); - let job = run(&origin, thread, "notice", &script); - - let mut machines = Machines { - imds: Some(imds.base().to_owned()), - ..Machines::default() - }; - assert!( - machines.drive(&fake, Duration::from_secs(60), || lines(&starts) == 1 - && imds.polls() > 0), - "the job never started or the machine never read its notice: {}", - pool(&origin, thread, "notice") - ); - let first = live_lease(&fake).unwrap(); - let ends_at = chrono::Utc::now() + chrono::Duration::minutes(2); - let noticed = std::time::Instant::now(); - imds.interrupt(&first.hostname, ends_at); - - // queued again on the notice, while cloudlease still holds the lease - let mut requeued = None; - assert!( - machines.drive(&fake, Duration::from_secs(30), || { - requeued = events(&origin, job) - .into_iter() - .find(|event| event.event == JobEventKind::JobPreempted); - requeued.is_some() - }), - "the notice never queued the job again: {}", - pool(&origin, thread, "notice") - ); - assert!(noticed.elapsed() < Duration::from_secs(30)); - let first_now = fake - .leases() - .into_iter() - .find(|lease| lease.lease_id == first.lease_id) - .unwrap(); - assert_eq!(first_now.state, "running"); - let lost = requeued.unwrap().machine_lost.unwrap(); - assert_eq!(lost.reason.to_string(), "interrupted"); - assert_eq!(lost.attempt, 2); - assert_eq!( - lost.ends_at.map(|at| at.timestamp()), - Some(ends_at.timestamp()) - ); - - // the run on the ending machine found the notice where its variable said - let first_daemon = &machines.daemons[&first.lease_id]; - let notice_path = first_daemon.home.join("temporary/interruption.json"); - let written = - fs::read_to_string(fs::read_to_string(&seen).unwrap().lines().next().unwrap()).unwrap(); - assert_eq!( - fs::read_to_string(¬ice_path).unwrap(), - written, - "HOMEBASED_INTERRUPTION_FILE names the notice file" - ); - let notice: Value = serde_json::from_str(&written).unwrap(); - assert_eq!(notice["action"], "terminate"); - - // a second machine runs the job to its end - assert!( - machines.drive(&fake, Duration::from_secs(90), || final_event(&origin, job) - .is_some()), - "the rerun never ended: {}\n{:?}", - pool(&origin, thread, "notice"), - fake.leases() - ); - assert_eq!( - final_event(&origin, job).unwrap().event, - JobEventKind::JobSucceeded - ); - assert_eq!(lines(&starts), 2); - - // when the provider ends the first machine, nothing more happens to the job - fake.end_lease(&first.lease_id, "interrupted"); - assert!( - machines.drive(&fake, Duration::from_secs(30), || { - pool(&origin, thread, "notice")["machines"] - .as_array() - .unwrap() - .iter() - .any(|machine| { - machine["name"] == first.hostname.as_str() && machine["state"] == "released" - }) - }), - "the interrupted machine never left the pool" - ); - let kinds: Vec = events(&origin, job) - .iter() - .map(|event| event.event) - .collect(); - assert_eq!( - kinds, - [JobEventKind::JobPreempted, JobEventKind::JobSucceeded] - ); -} - -#[test] -fn a_job_left_on_a_noticed_machine_still_reports_its_success() { - let fake = FakeCloudlease::start(Duration::from_secs(4)); - let imds = FakeImds::start(); - let origin = coordinator(&fake); - let thread = thread(&origin); - create_pool( - &origin, - thread, - "kept", - &["--max", "1", "--job-retries", "0"], - ); - let started = origin.user_home.join("started"); - let finish = origin.user_home.join("finish"); - let script = format!( - "touch {}; while [ ! -e {} ]; do sleep 1; done", - started.display(), - finish.display() - ); - let job = run(&origin, thread, "kept", &script); - - let mut machines = Machines { - imds: Some(imds.base().to_owned()), - ..Machines::default() - }; - assert!( - machines.drive(&fake, Duration::from_secs(60), || started.exists() - && imds.polls() > 0), - "the job never started: {}", - pool(&origin, thread, "kept") - ); - let first = live_lease(&fake).unwrap(); - imds.interrupt( - &first.hostname, - chrono::Utc::now() + chrono::Duration::minutes(2), - ); - - // the notice reaches the coordinator and a few reconcile passes go by - machines.drive(&fake, Duration::from_secs(20), || false); - assert!( - events(&origin, job).is_empty(), - "{:?}", - events(&origin, job) - ); - - // the run ends within AWS's two minutes and its success still arrives - fs::write(&finish, "").unwrap(); - assert!( - machines.drive(&fake, Duration::from_secs(30), || final_event(&origin, job) - .is_some()), - "the job's end never reached its origin: {}", - pool(&origin, thread, "kept") - ); - assert_eq!( - final_event(&origin, job).unwrap().event, - JobEventKind::JobSucceeded - ); -} - -#[test] -fn a_job_cancelled_before_its_machine_is_noticed_is_not_run_again() { - let fake = FakeCloudlease::start(Duration::from_secs(4)); - let imds = FakeImds::start(); let origin = coordinator(&fake); let thread = thread(&origin); create_pool(&origin, thread, "cancel", &["--max", "2"]); let starts = origin.user_home.join("starts"); - // the run takes its time to stop, so the notice lands mid-cancel + // the run takes its time to stop, so the interruption lands mid-cancel let script = format!( - "echo run >> {}; trap 'sleep 15; exit 0' TERM; while :; do sleep 1; done", + "echo run >> {}; trap 'sleep 30; exit 0' TERM; while :; do sleep 1; done", starts.display() ); let job = run(&origin, thread, "cancel", &script); - let mut machines = Machines { - imds: Some(imds.base().to_owned()), - ..Machines::default() - }; + let mut machines = Machines::default(); assert!( - machines.drive(&fake, Duration::from_secs(60), || lines(&starts) == 1 - && imds.polls() > 0), + machines.drive(&fake, Duration::from_secs(60), || lines(&starts) == 1), "the job never started: {}", pool(&origin, thread, "cancel") ); let job_text = job.to_string(); cli(&origin, thread, &["resource", "job", "cancel", &job_text]); let first = live_lease(&fake).unwrap(); - imds.interrupt( - &first.hostname, - chrono::Utc::now() + chrono::Duration::minutes(2), - ); + fake.end_lease(&first.lease_id, "interrupted"); assert!( machines.drive(&fake, Duration::from_secs(60), || final_event(&origin, job) @@ -1867,6 +1686,11 @@ fn a_job_cancelled_before_its_machine_is_noticed_is_not_run_again() { .iter() .map(|event| event.event) .collect(); - assert_eq!(kinds, [JobEventKind::JobCancelled]); + assert_eq!(kinds, [JobEventKind::JobFailed]); + let released = final_event(&origin, job).unwrap().machine_released.unwrap(); + assert_eq!( + serde_json::to_value(released.not_rerun).unwrap(), + json!({ "cause": "cancelled" }) + ); assert_eq!(lines(&starts), 1); } diff --git a/tests/support/fake_imds.rs b/tests/support/fake_imds.rs deleted file mode 100644 index f47fac3..0000000 --- a/tests/support/fake_imds.rs +++ /dev/null @@ -1,120 +0,0 @@ -//! A fake EC2 instance metadata service, version 2, for pool tests -//! -//! Each machine gets its own endpoint, `{base}/{name}`, so a test gives one -//! machine a Spot interruption notice while the others see none. A read -//! without the session token from `PUT /latest/api/token` is refused, as -//! IMDSv2 refuses it -use std::collections::BTreeSet; -use std::io::{BufRead, BufReader, Write}; -use std::net::{TcpListener, TcpStream}; -use std::sync::{Arc, Mutex}; -use std::thread; - -use chrono::{DateTime, Utc}; - -const TOKEN: &str = "imds-session-token"; - -#[derive(Default)] -struct State { - /// Machines with a notice, and when the notice says they end - noticed: BTreeSet, - ends_at: Option>, - /// Polls of the instance action, any machine - polls: u64, -} - -/// The running fake -pub struct FakeImds { - base: String, - state: Arc>, -} - -impl FakeImds { - /// Serve on a free loopback port - pub fn start() -> Self { - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let base = format!("http://{}", listener.local_addr().unwrap()); - let state = Arc::new(Mutex::new(State::default())); - let shared = state.clone(); - thread::spawn(move || { - for stream in listener.incoming() { - let Ok(stream) = stream else { continue }; - let state = shared.clone(); - thread::spawn(move || serve(stream, &state)); - } - }); - Self { base, state } - } - - /// Base of every machine's endpoint, which is `{base}/{name}` - pub fn base(&self) -> &str { - &self.base - } - - /// Give machine `name` a notice that it ends at `ends_at` - pub fn interrupt(&self, name: &str, ends_at: DateTime) { - let mut state = self.state.lock().unwrap(); - state.noticed.insert(name.to_owned()); - state.ends_at = Some(ends_at); - } - - /// How many times any machine read its instance action - pub fn polls(&self) -> u64 { - self.state.lock().unwrap().polls - } -} - -fn serve(stream: TcpStream, state: &Mutex) { - let mut reader = BufReader::new(stream.try_clone().unwrap()); - let mut line = String::new(); - if reader.read_line(&mut line).is_err() { - return; - } - let mut words = line.split_whitespace(); - let method = words.next().unwrap_or_default().to_owned(); - let path = words.next().unwrap_or_default().to_owned(); - let mut token = None; - let mut ttl = None; - loop { - let mut header = String::new(); - if reader.read_line(&mut header).is_err() || header.trim().is_empty() { - break; - } - let (name, value) = header.split_once(':').unwrap_or_default(); - match name.to_ascii_lowercase().as_str() { - "x-aws-ec2-metadata-token" => token = Some(value.trim().to_owned()), - "x-aws-ec2-metadata-token-ttl-seconds" => ttl = Some(value.trim().to_owned()), - _ => {} - } - } - let parts: Vec<&str> = path.trim_start_matches('/').splitn(2, '/').collect(); - let (machine, rest) = match parts.as_slice() { - [machine, rest] => (*machine, *rest), - _ => ("", ""), - }; - let (status, body) = match (method.as_str(), rest) { - ("PUT", "latest/api/token") if ttl.is_some() => (200, TOKEN.to_owned()), - ("GET", "latest/meta-data/spot/instance-action") if token.as_deref() == Some(TOKEN) => { - let mut state = state.lock().unwrap(); - state.polls += 1; - match state.ends_at.filter(|_| state.noticed.contains(machine)) { - Some(at) => ( - 200, - format!( - r#"{{"action":"terminate","time":"{}"}}"#, - at.format("%Y-%m-%dT%H:%M:%SZ") - ), - ), - None => (404, String::new()), - } - } - ("GET", _) => (401, String::new()), - _ => (405, String::new()), - }; - let mut writer = stream; - let _ = write!( - writer, - "HTTP/1.1 {status} X\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", - body.len() - ); -}