diff --git a/crates/fctl-agent/src/microvm/http.rs b/crates/fctl-agent/src/microvm/http.rs index 2f6f012a..34806688 100644 --- a/crates/fctl-agent/src/microvm/http.rs +++ b/crates/fctl-agent/src/microvm/http.rs @@ -115,7 +115,8 @@ async fn read_chunked(r: &mut (impl AsyncRead + Unpin)) -> Result> { while !read_line(r).await?.is_empty() {} return Ok(body); } - if body.len() + size > MAX_BODY { + // Not body.len() + size, which a size near usize::MAX overflows. + if size > MAX_BODY - body.len() { bail!("the request's body is too long"); } let start = body.len(); @@ -366,6 +367,9 @@ mod tests { let chunked = b"POST /x HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nhel\r\n2\r\nlo\r\n0\r\n\r\n"; assert_eq!(read_request(&mut &chunked[..]).await?.body, b"hello"); assert!(read_request(&mut &b"GET /"[..]).await.is_err()); + // A chunk too long to add to the body's length is refused. + let huge = b"POST /x HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nhel\r\nffffffffffffffff\r\n"; + assert!(read_request(&mut &huge[..]).await.is_err()); Ok(()) } diff --git a/crates/fctl-host/src/agentbin.rs b/crates/fctl-host/src/agentbin.rs index 1cd998c0..93ec63bb 100644 --- a/crates/fctl-host/src/agentbin.rs +++ b/crates/fctl-host/src/agentbin.rs @@ -114,13 +114,27 @@ async fn download(cfg: &HostConfig, arch: &str, cached: &std::path::Path) -> Res if expected != actual { bail!("checksum mismatch for {url}: expected {expected}, got {actual}"); } - let tmp = cached.with_extension("tmp"); - std::fs::write(&tmp, &bytes)?; - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o755))?; - } - std::fs::rename(&tmp, cached)?; + // Beside it, its whole name kept (with_extension would cut it at the + // version's last dot, the same for every architecture), and its own to + // this download: two at once write a file each. + let mut tmp = cached.as_os_str().to_owned(); + tmp.push(format!( + ".{}.tmp", + hex::encode(fctl_domain::random_bytes::<4>()) + )); + let tmp = PathBuf::from(tmp); + let put = || -> std::io::Result<()> { + std::fs::write(&tmp, &bytes)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o755))?; + } + std::fs::rename(&tmp, cached) + }; + // Named for this download alone, nothing else would remove it. + put().inspect_err(|_| { + let _ = std::fs::remove_file(&tmp); + })?; Ok(()) } diff --git a/crates/fctl-host/src/driver/lambda/mod.rs b/crates/fctl-host/src/driver/lambda/mod.rs index fd0b8490..7d701087 100644 --- a/crates/fctl-host/src/driver/lambda/mod.rs +++ b/crates/fctl-host/src/driver/lambda/mod.rs @@ -72,6 +72,16 @@ const GOING_AGAIN: Duration = Duration::from_secs(30); /// How long a run may go unanswered before the host takes it for one a /// stop cut short: well past a call's four tries of a minute each. const UNANSWERED_AFTER: Duration = Duration::from_secs(10 * 60); +/// How long a microVM whose session's run ended may go on unsuspended (it +/// was starting or resuming as the run ended, or its suspend failed) before +/// the upkeep suspends it, or lets it go. +const LOOSE_AFTER: Duration = Duration::from_secs(60); +/// How long the warm pool waits after a warm microVM failed to start before +/// it starts another. +const WARM_AGAIN: Duration = Duration::from_secs(60); +/// How long the upkeep leaves a microVM it has just changed before it takes +/// its absence from a list for gone: a list may not have it yet. +const LISTED_AFTER: Duration = Duration::from_secs(60); fn now_ms() -> Millis { crate::expiry::now_ms() @@ -162,6 +172,9 @@ struct ImageView { report: Option, looked_at: Option, failed_at: Option, + /// Why the last try failed, where it failed before Lambda built + /// anything (its archive's upload, say): what the wait after says. + failed_why: Option, } struct Inner { @@ -181,6 +194,9 @@ struct Inner { changed: AtomicU64, upkeep_started: AtomicBool, listed_at: Mutex>, + /// When a warm microVM last failed to start: the pool waits + /// [`WARM_AGAIN`] before the next. + warm_failed_at: Mutex>, region: Mutex>, /// Held across a save's snapshot of `saved` and its write, so that /// saves write one at a time, the newest last. @@ -239,6 +255,7 @@ impl LambdaDriver { upkeep_started: AtomicBool::new(false), save_lock: Mutex::new(()), listed_at: Mutex::new(None), + warm_failed_at: Mutex::new(None), region: Mutex::new(None), }), } @@ -269,6 +286,8 @@ impl LambdaDriver { *lock(&self.inner.region) = None; *lock(&self.inner.image) = ImageView::default(); *lock(&self.inner.problem) = None; + // New settings may start what the old couldn't. + *lock(&self.inner.warm_failed_at) = None; lock(&self.inner.saved).settings = settings; self.save(); self.note_changed(); @@ -441,6 +460,22 @@ impl LambdaDriver { } } + /// Notes, for the report, a problem that isn't one of AWS's answers. + fn note_other(&self, message: &str) { + { + let mut problem = lock(&self.inner.problem); + if problem.as_ref().is_some_and(|p| p.message == message) { + return; + } + *problem = Some(MicrovmProblem { + kind: "other".into(), + message: message.to_owned(), + since: now_ms(), + }); + } + self.note_changed(); + } + fn fail(&self, e: api::Error, doing: &str) -> anyhow::Error { self.note(Err(&e), doing); anyhow::anyhow!("{}", problem_words(&e, doing)) @@ -1217,7 +1252,9 @@ impl LambdaDriver { } /// Stops the sandbox, which keeps it: its microVM suspends, and goes - /// once it has been suspended for the settings' while. + /// once it has been suspended for the settings' while. One that isn't + /// running now (it starts or resumes), or doesn't suspend, the upkeep + /// suspends or lets go of (`let_go_of_stale`). pub async fn stop(&self, sb: &Sandbox) -> Result<()> { if self.vm(&sb.name).is_none() { return Ok(()); @@ -1436,6 +1473,7 @@ impl LambdaDriver { let mut view = ImageView { looked_at: Some(Instant::now()), failed_at: view.failed_at, + failed_why: view.failed_why, ..ImageView::default() }; match (&settings.image, found) { @@ -1581,6 +1619,7 @@ impl LambdaDriver { r.building = Some(fctl.to_owned()); view.report = Some(r); view.failed_at = Some(Instant::now()); + view.failed_why = None; lock(&self.inner.saved).building = None; self.save(); return Ok(()); @@ -1609,13 +1648,17 @@ impl LambdaDriver { .failed_at .is_some_and(|at| at.elapsed() < REBUILD_AFTER) { + let why = match &view.failed_why { + Some(why) => format!("{why}; it tries again in 30 minutes"), + None => format!( + "Lambda couldn't build the image for fctl {fctl}; it tries again in 30 minutes" + ), + }; let mut r = image::report( &arn, active.as_ref(), MicrovmImageStatus::Failed, - Some(format!( - "Lambda couldn't build the image for fctl {fctl}; it tries again in 30 minutes" - )), + Some(why), Some(now_ms()), ); r.building = Some(fctl.to_owned()); @@ -1631,9 +1674,33 @@ impl LambdaDriver { return Ok(()); }; let arch = settings.arch.unwrap_or_default(); - let uri = self + let uri = match self .upload_artifact(artifacts, ®ion, arch, api.keys()) - .await?; + .await + { + Ok(uri) => uri, + // Lambda builds nothing without it: said, and tried again once + // a failed build would be. + Err(e) => { + let why = format!( + "The host couldn't put what Lambda builds the image from in {artifacts}: {e:#}" + ); + tracing::warn!("{why}"); + self.note_other(&why); + view.failed_at = Some(Instant::now()); + view.failed_why = Some(why.clone()); + let mut r = image::report( + &arn, + active.as_ref(), + MicrovmImageStatus::Failed, + Some(why), + Some(now_ms()), + ); + r.building = Some(fctl.to_owned()); + view.report = Some(r); + return Ok(()); + } + }; let req = image::request(&image::Build { settings, fctl, @@ -1652,12 +1719,14 @@ impl LambdaDriver { Ok(a) => a, Err(e) => { self.note(Err(&e), "having Lambda build its image"); + let why = problem_words(&e, "having Lambda build its image"); view.failed_at = Some(Instant::now()); + view.failed_why = Some(why.clone()); let mut r = image::report( &arn, active.as_ref(), MicrovmImageStatus::Failed, - Some(problem_words(&e, "having Lambda build its image")), + Some(why), Some(now_ms()), ); r.building = Some(fctl.to_owned()); @@ -1730,7 +1799,7 @@ impl LambdaDriver { store .put(&key, &file, &sha) .await - .map_err(|e| anyhow::anyhow!("putting the image's archive in {artifacts}: {e}"))?; + .map_err(anyhow::Error::msg)?; let _ = std::fs::remove_file(&file); Ok(format!("s3://{}/{key}", bucket.name)) } @@ -1759,34 +1828,74 @@ impl LambdaDriver { .map(|i| (i.microvm_id, i.state)) .collect(); let busy: Vec = lock(&self.inner.busy).keys().cloned().collect(); - let gone: Vec = lock(&self.inner.saved) + let now = now_ms(); + // Those the list says are gone, and those it lacks: run from + // another image (the settings' before they changed), or gone. + let (gone, unlisted): (Vec<_>, Vec<_>) = lock(&self.inner.saved) .vms .iter() .filter(|v| !busy.contains(&v.name)) - .filter(|v| match &v.id { - Some(id) => matches!( - live.get(id).map(String::as_str), - None | Some("TERMINATED" | "TERMINATING") - ), - None => false, - }) // Just run: a list may not have it yet. - .filter(|v| now_ms() - v.since > 60_000) - .map(|v| v.name.clone()) - .collect(); - for name in gone { - tracing::info!("{name}'s microVM is gone"); - self.forget(&name); + .filter(|v| now - v.since > LISTED_AFTER.as_millis() as i64) + .filter_map(|v| { + let id = v.id.clone()?; + match live.get(&id).map(String::as_str) { + Some("TERMINATED" | "TERMINATING") => Some((v.name.clone(), id, true)), + None => Some((v.name.clone(), id, false)), + Some(_) => None, + } + }) + .partition(|(_, _, listed)| *listed); + for (name, id, _) in gone { + tracing::info!("{name}'s microVM {id} is gone"); + self.forget_if(&name, &id); + } + for (name, id, _) in unlisted { + let gone = match api.get(&id).await { + Ok(m) => m.gone(), + Err(e) => e.not_found(), + }; + if gone { + tracing::info!("{name}'s microVM {id} is gone"); + self.forget_if(&name, &id); + } + } + } + + /// Forgets `name`'s microVM if it is still `id`, and no session's host + /// works on it now: one that a session's next run replaced while the + /// upkeep asked about it stays. + fn forget_if(&self, name: &str, id: &str) { + if lock(&self.inner.busy).contains_key(name) { + return; + } + let forgot = { + let mut saved = lock(&self.inner.saved); + let had = saved.vms.len(); + saved + .vms + .retain(|v| !(v.name == name && v.id.as_deref() == Some(id))); + saved.vms.len() < had + }; + if forgot { + lock(&self.inner.tokens).remove(id); + self.save(); + self.note_changed(); } } /// Lets go of microVMs no session or pool needs: those whose session's /// run ended, once suspended for the settings' while or near their end. /// A session that runs lets its own go, saving its snapshot first. + /// + /// One whose session's run ended while it wasn't suspended (it was + /// starting or resuming as the run ended, or its suspend failed) would + /// run, and cost, until Lambda ends it: it suspends, to go once + /// suspended for the settings' while, or goes now if it can't. async fn let_go_of_stale(&self, settings: &MicrovmSettings) { let now = now_ms(); let busy: Vec = lock(&self.inner.busy).keys().cloned().collect(); - let stale: Vec = lock(&self.inner.saved) + let stale: Vec<(String, Option)> = lock(&self.inner.saved) .vms .iter() .filter(|v| v.ended && !v.warm() && !v.going() && !busy.contains(&v.name)) @@ -1795,14 +1904,69 @@ impl LambdaDriver { && rules::terminate_at(v.suspended_at.unwrap_or(v.since), settings) <= now; suspended || rules::ending(v.started_at, now) }) - .map(|v| v.name.clone()) + .map(|v| (v.name.clone(), v.id.clone())) .collect(); - for name in stale { + for (name, id) in &stale { + // Another's terminate took a while: a session's next run may + // have taken it, or run a new one, meanwhile. + if !self.still_ended(name, id.as_deref()) { + continue; + } tracing::info!("letting {name}'s microVM go"); - self.terminate_vm(&name).await; + self.terminate_vm(name).await; + } + let now = now_ms(); + let busy: Vec = lock(&self.inner.busy).keys().cloned().collect(); + let loose: Vec<(String, Option)> = lock(&self.inner.saved) + .vms + .iter() + .filter(|v| v.ended && !v.warm() && !v.going() && !busy.contains(&v.name)) + .filter(|v| !stale.iter().any(|(n, _)| *n == v.name)) + .filter(|v| !matches!(v.state, MicrovmState::Suspended | MicrovmState::Terminating)) + .filter(|v| now - v.since > LOOSE_AFTER.as_millis() as i64) + .map(|v| (v.name.clone(), v.id.clone())) + .collect(); + for (name, id) in loose { + if !self.still_ended(&name, id.as_deref()) { + continue; + } + let suspended = match &id { + Some(_) => { + tracing::info!("{name}'s run ended, but its microVM runs: suspending it"); + let sb = Sandbox { + name: name.clone(), + root: None, + }; + match self.suspend(&sb).await { + Ok(()) => true, + Err(e) => { + tracing::warn!("{name}: {e:#}"); + false + } + } + } + None => false, + }; + // As it tried to suspend, for up to a minute, a session's next + // run may have taken it back, or run a new one by its name. + if !suspended && self.still_ended(&name, id.as_deref()) { + tracing::info!("letting {name}'s microVM go"); + self.terminate_vm(&name).await; + } } } + /// Whether `name`'s microVM is still the one `id` names (or one still + /// with none), its session's run ended, and no session's host works on + /// it: what the upkeep checks again after an await, before it lets one + /// go by its name. + fn still_ended(&self, name: &str, id: Option<&str>) -> bool { + !lock(&self.inner.busy).contains_key(name) + && self + .vm(name) + .is_some_and(|v| v.ended && v.id.as_deref() == id) + } + /// Keeps the settings' `warm` microVMs started and suspended. async fn keep_warm(&self, settings: &MicrovmSettings) { let Ok((_, fingerprint, _)) = self.ready() else { @@ -1837,7 +2001,12 @@ impl LambdaDriver { let me = self.clone(); tokio::spawn(async move { me.terminate_vm(&name).await }); } - for _ in 0..plan.start { + // One that failed lately (a refusal the pause above doesn't cover: + // Lambda found the request wrong, say) would fail again at once. + let failed_lately = + lock(&self.inner.warm_failed_at).is_some_and(|at| at.elapsed() < WARM_AGAIN); + let start = if failed_lately { 0 } else { plan.start }; + for _ in 0..start { let name = format!("warm-{}", hex::encode(fctl_domain::random_bytes::<6>())); let vm = self.new_vm(&name, &fingerprint); // Held as it starts, so that the next plan counts it. @@ -1846,6 +2015,7 @@ impl LambdaDriver { tokio::spawn(async move { if let Err(e) = me.warm_up(&name, vm).await { tracing::warn!("a warm microVM: {e:#}"); + *lock(&me.inner.warm_failed_at) = Some(Instant::now()); me.terminate_vm(&name).await; } me.inner.wake.notify_one(); @@ -1962,7 +2132,9 @@ mod tests { /// A stand-in for Lambda's API: `TerminateMicrovm` answers a server /// error to its first `fail` requests, then as it should, and /// `RunMicrovm` runs `mvm-found`, as Lambda answers a request again - /// with its client token. Its URL, and the requests it had. + /// with its client token. `mvm-alive` suspends, and is suspended; + /// `mvm-taken` refuses to suspend, after 300 ms; no other microVM is + /// found, and a list has none. Its URL, and the requests it had. async fn lambda( fail: usize, throttled: usize, @@ -2010,21 +2182,27 @@ mod tests { parts.next().unwrap_or_default(), parts.next().unwrap_or_default() ); + let run = format!("POST /{}/microvms", api::VERSION); + let alive = format!("/{}/microvms/mvm-alive", api::VERSION); let (terminates, runs) = { let Ok(mut log) = log.lock() else { return }; log.push(request.clone()); ( log.iter().filter(|r| r.starts_with("DELETE ")).count(), - log.iter().filter(|r| r.starts_with("POST ")).count(), + log.iter().filter(|r| **r == run).count(), ) }; + let taken = format!("POST /{}/microvms/mvm-taken/suspend", api::VERSION); + if request == taken { + tokio::time::sleep(Duration::from_millis(300)).await; + } let (status, body) = if request.starts_with("DELETE ") { if terminates <= fail { ("500 Internal Server Error", r#"{"message":"try again"}"#) } else { ("200 OK", "{}") } - } else if request == format!("POST /{}/microvms", api::VERSION) { + } else if request == run { if runs <= throttled { ( "429 Too Many Requests", @@ -2033,6 +2211,17 @@ mod tests { } else { ("200 OK", r#"{"microvmId":"mvm-found","state":"PENDING"}"#) } + } else if request == taken { + ( + "400 Bad Request", + r#"{"__type":"ValidationException","message":"no"}"#, + ) + } else if request == format!("POST {alive}/suspend") { + ("200 OK", "{}") + } else if request == format!("GET {alive}") { + ("200 OK", r#"{"microvmId":"mvm-alive","state":"SUSPENDED"}"#) + } else if request.starts_with(&format!("GET /{}/microvms?", api::VERSION)) { + ("200 OK", r#"{"items":[]}"#) } else { ("404 Not Found", r#"{"message":"no such thing"}"#) }; @@ -2331,4 +2520,186 @@ mod tests { assert!(lock(&had).is_empty()); Ok(()) } + + fn own_image() -> MicrovmSettings { + rules::defaults(MicrovmImage::Own { + arn: "arn:aws:lambda:us-east-1:123456789012:microvm-image:agents".into(), + version: None, + }) + } + + #[tokio::test] + async fn microvms_whose_run_ended_unsuspended_suspend_or_go() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + let (url, had) = lambda(0, 0).await?; + let d = driver(dir.path(), &url)?; + let long_ago = now_ms() - LOOSE_AFTER.as_millis() as i64 - 1_000; + // Resuming as its run ended: it runs, and suspends. + let mut alive = d.new_vm("fctl-ses-alive", "f"); + alive.id = Some("mvm-alive".into()); + alive.state = MicrovmState::Running; + alive.ended = true; + alive.since = long_ago; + d.put(alive); + // Asked to run, never answered nor kept: nothing ran. + let mut never = d.new_vm("fctl-ses-never", "f"); + never.ended = true; + never.since = long_ago; + d.put(never); + // A session's run goes on in it. + let mut live = d.new_vm("fctl-ses-live", "f"); + live.id = Some("mvm-live".into()); + live.state = MicrovmState::Running; + live.since = long_ago; + d.put(live); + // Its run just ended: the session's host may suspend it yet. + let mut just = d.new_vm("fctl-ses-just", "f"); + just.id = Some("mvm-just".into()); + just.state = MicrovmState::Running; + just.ended = true; + d.put(just); + + d.let_go_of_stale(&own_image()).await; + assert_eq!( + names(&d), + ["fctl-ses-alive", "fctl-ses-live", "fctl-ses-just"] + ); + let state = |n: &str| d.vm(n).map(|v| v.state); + assert_eq!(state("fctl-ses-alive"), Some(MicrovmState::Suspended)); + assert_eq!(state("fctl-ses-live"), Some(MicrovmState::Running)); + assert_eq!(state("fctl-ses-just"), Some(MicrovmState::Running)); + let asked = lock(&had).clone(); + assert_eq!( + asked.first(), + Some(&format!( + "POST /{}/microvms/mvm-alive/suspend", + api::VERSION + )) + ); + assert!(asked.iter().all(|r| r.contains("mvm-alive")), "{asked:?}"); + Ok(()) + } + + #[tokio::test] + async fn one_a_session_took_back_as_it_failed_to_suspend_stays() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + let (url, had) = lambda(0, 0).await?; + let d = driver(dir.path(), &url)?; + let mut vm = d.new_vm("fctl-ses-taken", "f"); + vm.id = Some("mvm-taken".into()); + vm.state = MicrovmState::Running; + vm.ended = true; + vm.since -= LOOSE_AFTER.as_millis() as i64 + 1_000; + d.put(vm); + let sweep = { + let d = d.clone(); + tokio::spawn(async move { d.let_go_of_stale(&own_image()).await }) + }; + // The session's next run takes it as it suspends. + let suspend = format!("POST /{}/microvms/mvm-taken/suspend", api::VERSION); + let until = Instant::now() + Duration::from_secs(10); + while !lock(&had).contains(&suspend) { + anyhow::ensure!(Instant::now() < until, "it never suspended"); + tokio::time::sleep(Duration::from_millis(10)).await; + } + let _busy = d.busy("fctl-ses-taken"); + d.update("fctl-ses-taken", |v| v.ended = false); + sweep.await?; + assert_eq!(names(&d), ["fctl-ses-taken"]); + assert_eq!(lock(&had).clone(), [suspend]); + Ok(()) + } + + #[tokio::test] + async fn the_warm_pool_waits_after_a_start_that_failed() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + // It runs mvm-found, which is then nowhere to be found. + let (url, had) = lambda(0, 0).await?; + let d = driver(dir.path(), &url)?; + let mut settings = own_image(); + settings.warm = 1; + *lock(&d.inner.settings) = Some(settings.clone()); + { + let mut image = lock(&d.inner.image); + image.arn = Some("arn:aws:lambda:us-east-1:123456789012:microvm-image:agents".into()); + image.version = Some("1".into()); + } + d.keep_warm(&settings).await; + let until = Instant::now() + Duration::from_secs(10); + while lock(&d.inner.warm_failed_at).is_none() || !names(&d).is_empty() { + anyhow::ensure!(Instant::now() < until, "the warm microVM didn't fail"); + tokio::time::sleep(Duration::from_millis(20)).await; + } + // Not again at once. + d.keep_warm(&settings).await; + tokio::time::sleep(Duration::from_millis(100)).await; + assert!(names(&d).is_empty()); + let runs = lock(&had) + .iter() + .filter(|r| **r == format!("POST /{}/microvms", api::VERSION)) + .count(); + assert_eq!(runs, 1); + Ok(()) + } + + #[tokio::test] + async fn microvms_another_image_runs_are_kept_and_gone_ones_forgotten() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + // Its list of this image's microVMs has none. + let (url, _) = lambda(0, 0).await?; + let d = driver(dir.path(), &url)?; + lock(&d.inner.image).arn = + Some("arn:aws:lambda:us-east-1:123456789012:microvm-image:new".into()); + for (name, id) in [("fctl-ses-a", "mvm-alive"), ("fctl-ses-b", "mvm-gone")] { + let mut vm = d.new_vm(name, "f"); + vm.id = Some(id.into()); + vm.state = MicrovmState::Suspended; + vm.since -= LISTED_AFTER.as_millis() as i64 + 1_000; + d.put(vm); + } + d.follow_states().await; + assert_eq!(names(&d), ["fctl-ses-a"]); + Ok(()) + } + + #[tokio::test] + async fn an_image_archive_that_didnt_upload_is_said_and_waits() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + // The image isn't there yet: fctl builds it. + let (url, had) = lambda(0, 0).await?; + let d = driver(dir.path(), &url)?; + let settings = rules::defaults(MicrovmImage::Managed { + artifacts: "not-a-bucket".into(), + build_role_arn: "arn:aws:iam::123456789012:role/builds".into(), + name: None, + }); + d.keep_image(&settings).await?; + let report = lock(&d.inner.image).report.clone(); + let report = report.ok_or_else(|| anyhow::anyhow!("no report"))?; + assert_eq!(report.status, MicrovmImageStatus::Failed); + let why = report.error.unwrap_or_default(); + assert!( + why.starts_with( + "The host couldn't put what Lambda builds the image from in not-a-bucket: " + ), + "{why}" + ); + let problem = lock(&d.inner.problem).clone(); + assert_eq!( + problem.map(|p| (p.kind, p.message)), + Some(("other".into(), why.clone())) + ); + // Looked at again, it waits, and still says why. + lock(&d.inner.image).looked_at = None; + d.keep_image(&settings).await?; + let again = lock(&d.inner.image).report.clone(); + assert_eq!( + again.and_then(|r| r.error), + Some(format!("{why}; it tries again in 30 minutes")) + ); + // Lambda was never asked to build it. + let asked = lock(&had).clone(); + assert!(asked.iter().all(|r| r.starts_with("GET ")), "{asked:?}"); + Ok(()) + } } diff --git a/crates/fctl-host/src/session.rs b/crates/fctl-host/src/session.rs index 350462b9..c974b8b5 100644 --- a/crates/fctl-host/src/session.rs +++ b/crates/fctl-host/src/session.rs @@ -2380,9 +2380,19 @@ async fn run( && queued.is_empty() && in_flight == 0 && spool.is_none() - && upload.is_none() + && upload.as_ref().is_none_or(|u| u.is_finished()) && acked >= reported_seq() => { + // The upload of a checkpoint that ran out of + // time (or whose answer never came), done + // since: it holds off no more. + if let Some(up) = upload.take() { + match up.await { + Ok(Ok(())) => {} + Ok(Err(e)) => tracing::warn!("{session_id}: its snapshot's upload: {}", e.why), + Err(e) => tracing::warn!("{session_id}: its snapshot's upload: {e}"), + } + } let id = fctl_domain::ids::new_id("ckp", now); if let Some(l) = &link { l.send(HostToAgent::Checkpoint { id: id.clone() }); diff --git a/docs/architecture.md b/docs/architecture.md index 4649868e..04294952 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -6174,8 +6174,11 @@ starts there only once its runner has settings and its image is ready. version's description (`fctl 0.40.0, 2048 MiB, arm64`) says what it was built for. The host builds a new version as fctl updates, or the size or the architecture changes; sessions start from the version - before meanwhile, and a build that failed is tried again after 30 - minutes, saying why on the Runners tab. + before meanwhile, and a build that failed, or whose archive the host + couldn't put in the bucket, is tried again after 30 minutes, saying + why on the Runners tab. MicroVMs of an image the settings no longer + name stay until their sessions let them go: the host forgets one that + a list of the current image lacks only once Lambda says it is gone. - **A microVM.** `RunMicrovm` starts one from the image's active version (or the one the settings pin), with HTTP ingress through Lambda's connector, egress to the internet or through the settings' @@ -6228,11 +6231,14 @@ starts there only once its runner has settings and its image is ready. first. A microVM that won't resume goes too, and the session's next run, which the waiting message starts, carries on in a new one. Review agents' sessions, which save no snapshots and stop once their review - is posted, never suspend. + is posted, never suspend. A microVM whose session's run ended while it + wasn't suspended (it was starting or resuming, or its suspend failed) + suspends a minute later, or goes at once if it can't. - **Warm microVMs.** The host keeps `warm` microVMs of the current image started and suspended as soon as they answer (`fctl_domain::microvm::plan`), - starting at most three at once, and replaces those older than 2 hours - or of an older image or settings (`fingerprint`). A session of any + starting at most three at once, and none for a minute after one failed + to start, and replaces those older than 2 hours or of an older image + or settings (`fingerprint`). A session of any kind (people's, a review agent's, a schedule's, an autopilot's) takes one as it starts: the host renames it to the session's sandbox and resumes it, and the session's agent starts in milliseconds rather than diff --git a/web/src/components/workspace/microvms.test.tsx b/web/src/components/workspace/microvms.test.tsx index 0b7e9c32..c4325d3e 100644 --- a/web/src/components/workspace/microvms.test.tsx +++ b/web/src/components/workspace/microvms.test.tsx @@ -125,6 +125,8 @@ function show(node: ReactNode, microvms?: G.RunnerMicrovms) { return container; } +const noop = () => {}; + const button = (label: string) => { const b = [...document.querySelectorAll("button")].find((x) => x.textContent?.trim() === label); if (!b) throw new Error(`no button ${label}`); @@ -149,7 +151,7 @@ const input = (label: string) => { describe("the Runners tab's microVMs", () => { it("say what they do for sessions, and how to set up a runner of them while there is none", () => { - const text = show().textContent ?? ""; + const text = show().textContent ?? ""; expect(text).toContain("Sessions in AWS Lambda microVMs"); expect(text).toContain( "A session's microVM suspends once it has waited 90 seconds with nothing running, and costs no compute while it waits for CI or for you", @@ -163,7 +165,9 @@ describe("the Runners tab's microVMs", () => { }); it("say a session starts again from its task and branch where the workspace keeps no snapshots", () => { - const text = show().textContent; + const text = show( + , + ).textContent; expect(text).toContain( "the next message starts the session again in a new microVM, from its task and branch: Acme keeps no snapshots.", ); @@ -171,7 +175,7 @@ describe("the Runners tab's microVMs", () => { }); it("show each runner of them, with what its microVMs do and the room left", () => { - const view = show(); + const view = show(); const card = view.querySelector("li"); expect(card?.textContent).toContain("microvmsonline"); // Each fact whole, a dot between each, which wrap between them on a phone. @@ -189,7 +193,7 @@ describe("the Runners tab's microVMs", () => { it("say, in the section, when its sessions' microVMs suspend and go", () => { const r = runner(); - const text = show(, { + const text = show(, { runner: r.id, settings: settings({ suspend_after_secs: 120, terminate_after_minutes: 30 }), manage: true, @@ -205,6 +209,7 @@ describe("the Runners tab's microVMs", () => { w={acme} admin runners={[runner({ microvms_configured: false, microvms: report({ configured: false }) })]} + onTakeOut={noop} />, ); expect(view.querySelector(".text-amber")?.textContent).toBe( @@ -217,6 +222,7 @@ describe("the Runners tab's microVMs", () => { w={{ ...acme, role: "member" }} admin={false} runners={[runner({ id: "run_other", microvms_configured: false })]} + onTakeOut={noop} />, ); expect([...member.querySelectorAll("button")].map((b) => b.textContent)).toContain("Open"); @@ -238,10 +244,29 @@ describe("the Runners tab's microVMs", () => { }), }), ]} + onTakeOut={noop} />, ).textContent; expect(text).toContain("Its host may not run microVMs: lambda:RunMicrovm is denied."); }); + + it("let admins take out one added from elsewhere, and remove a member's that enrolled here", () => { + const asked: string[] = []; + const onTakeOut = (r: G.Runner) => asked.push(r.id); + const added = runner({ id: "run_added", workspace: undefined, yours: false }); + show(); + act(() => button("Take out").click()); + const grace = { id: "usr_grace", name: "Grace" } as G.UserRef; + const graces = runner({ id: "run_grace", created_by: grace, yours: false }); + show(); + act(() => button("Remove").click()); + expect(asked).toEqual(["run_added", "run_grace"]); + // Members do neither with others' runners. + const member = { ...acme, role: "member" } as G.Workspace; + const view = show(); + const labels = [...view.querySelectorAll("button")].map((b) => b.textContent?.trim()); + expect(labels).not.toContain("Take out"); + }); }); describe("a runner's microVMs sheet", () => { @@ -281,7 +306,7 @@ describe("a runner's microVMs sheet", () => { }); const open = (m: G.RunnerMicrovms, admin = true) => { - show(, m); + show(, m); act(() => button("Open").click()); // The sheet, not the runner's menu's dialogs. return [...document.querySelectorAll("dialog")].find((d) => d.textContent?.includes("'s microVMs")); @@ -318,6 +343,14 @@ describe("a runner's microVMs sheet", () => { expect(saves).toEqual([{ id: "run_lambda", settings: settings({ warm: 4 }) }]); }); + it("says under its version what's wrong with one Lambda wouldn't take", async () => { + const sheet = open(microvms()); + type(input("Version"), "1 0"); + await act(async () => button("Save").click()); + expect(saves).toEqual([]); + expect(sheet?.textContent).toContain("No spaces, and 64 characters at most"); + }); + it("asks for a bucket and a build role for an image fctl builds", async () => { const sheet = open(microvms({ settings: undefined, updated_at: undefined, updated_by: undefined })); expect(sheet?.textContent).toContain("Its host runs no session until it has these."); diff --git a/web/src/components/workspace/microvms.tsx b/web/src/components/workspace/microvms.tsx index d2391dc1..6eaf5144 100644 --- a/web/src/components/workspace/microvms.tsx +++ b/web/src/components/workspace/microvms.tsx @@ -62,10 +62,13 @@ export function MicrovmsSection({ w, admin, runners, + onTakeOut, }: { w: G.Workspace; admin: boolean; runners: G.Runner[]; + /** Asks before taking a runner out of the workspace, or removing one that enrolled here. */ + onTakeOut: (r: G.Runner) => void; }) { const mine = runners.filter(isMicrovmRunner); const [open, setOpen] = useState(); @@ -96,7 +99,14 @@ export function MicrovmsSection({ {mine.length > 0 && (
    {mine.map((r) => ( - setOpen(r.id)} /> + setOpen(r.id)} + onTakeOut={onTakeOut} + /> ))}
)} @@ -281,14 +291,21 @@ function MicrovmCard({ runner: r, admin, onOpen, + onTakeOut, }: { w: G.Workspace; runner: G.Runner; admin: boolean; onOpen: () => void; + onTakeOut: (r: G.Runner) => void; }) { const report = r.microvms; - const own = r.workspace?.id === w.id && !r.created_by; + // As a runner's row: one that enrolled here (the workspace's own, or a member's for their own + // sessions) is managed whole; one added from elsewhere is taken out, and a member's that + // enrolled here for someone else's sessions is removed. + const enrolled = r.workspace?.id === w.id; + const own = enrolled && !r.created_by; + const managedWhole = own || (enrolled && r.yours); const manage = (own && admin) || r.yours; const unset = r.microvms_configured === false; const image = report?.image && imageWords(report.image); @@ -376,7 +393,13 @@ function MicrovmCard({ - {manage && } + {managedWhole + ? manage && + : (admin || r.yours) && ( + + )} @@ -825,7 +848,7 @@ function SettingsForm({ w, runner, m }: { w: G.Workspace; runner: G.Runner; m: G /> )} - + {(id) => ( { it("say what's wrong, the field first", () => { expect(settingsProblem({ ...own(), image: { kind: "own", arn: "nope" } })?.field).toBe("image.arn"); + expect(settingsProblem({ ...own(), image: { kind: "own", arn: OWN, version: "1.0" } })).toBeUndefined(); + for (const version of ["1 0", "1".repeat(65)]) + expect(settingsProblem({ ...own(), image: { kind: "own", arn: OWN, version } })?.field).toBe( + "image.version", + ); expect( settingsProblem({ ...own(), diff --git a/web/src/lib/microvms.ts b/web/src/lib/microvms.ts index 2d8eae58..1ea76195 100644 --- a/web/src/lib/microvms.ts +++ b/web/src/lib/microvms.ts @@ -104,6 +104,16 @@ export function settingsProblem(s: G.MicrovmSettings): { field: string; message: field: "image.arn", message: "Enter a microVM image's ARN: arn:aws:lambda:::microvm-image:", }; + // As the server takes it: up to 64 bytes, with no spaces. + const version = s.image.kind === "own" ? s.image.version : undefined; + if ( + version !== undefined && + (!version || new TextEncoder().encode(version).length > 64 || /\s/.test(version)) + ) + return { + field: "image.version", + message: "No spaces, and 64 characters at most", + }; if (s.image.kind === "managed") { if (!/^s3:\/\/[a-z0-9][a-z0-9.-]{1,61}[a-z0-9](\/.*)?$/.test(s.image.artifacts.trim())) return { field: "image.artifacts", message: "Enter an S3 location: s3://bucket/prefix" }; diff --git a/web/src/routes/workspace.tsx b/web/src/routes/workspace.tsx index b23c3c97..1957266f 100644 --- a/web/src/routes/workspace.tsx +++ b/web/src/routes/workspace.tsx @@ -1186,7 +1186,7 @@ function Runners({ w }: { w: G.Workspace }) { )} /> - +