diff --git a/Cargo.lock b/Cargo.lock index 1e0e8c86a..3973dafa7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -614,6 +614,7 @@ dependencies = [ "nix", "serde", "serde_json", + "sha1", "sha2", "tar", "tempfile", diff --git a/crates/fctl-agent/Cargo.toml b/crates/fctl-agent/Cargo.toml index e39a98b2e..a2ad5486b 100644 --- a/crates/fctl-agent/Cargo.toml +++ b/crates/fctl-agent/Cargo.toml @@ -34,6 +34,7 @@ flate2.workspace = true hex.workspace = true libc.workspace = true nix = { workspace = true, features = ["hostname", "mount", "net", "reboot", "resource", "socket", "time"] } +sha1.workspace = true sha2.workspace = true tar.workspace = true tokio-tun = "0.15.2" diff --git a/crates/fctl-agent/src/main.rs b/crates/fctl-agent/src/main.rs index 796a895d1..8a8786f01 100644 --- a/crates/fctl-agent/src/main.rs +++ b/crates/fctl-agent/src/main.rs @@ -5,6 +5,9 @@ //! - `fctl-agent attach` connects stdin/stdout to it (the host's channel). //! - As PID 1 it is a Firecracker microVM's init, and `vm-serve` runs what //! the host asks there (src/vm). +//! - `fctl-agent microvm-serve` is an AWS Lambda microVM's program, from its +//! image: it answers Lambda's lifecycle hooks and runs what the host asks +//! over WebSockets through the microVM's endpoint (src/microvm). //! - `fctl-agent run-as` runs a program as another user, for `vm-serve` and //! for a supervisor that runs as root. //! - `fctl-agent share`, on a Firecracker host, serves a project's package @@ -32,6 +35,8 @@ mod local; #[cfg(target_os = "linux")] mod metadata; #[cfg(target_os = "linux")] +mod microvm; +#[cfg(target_os = "linux")] mod net_filter; #[cfg(target_os = "linux")] mod netlink; @@ -106,6 +111,20 @@ enum Command { #[cfg(target_os = "linux")] #[command(hide = true)] VmServe, + /// Answer an AWS Lambda microVM's lifecycle hooks and run what the host + /// asks there, from the image's CMD. + #[cfg(target_os = "linux")] + MicrovmServe { + /// Where the host's WebSockets come, through the microVM's endpoint. + #[arg(long, default_value = "0.0.0.0:8080")] + listen: std::net::SocketAddr, + /// Where Lambda calls the lifecycle hooks. + #[arg(long, default_value = "0.0.0.0:9000")] + hooks: std::net::SocketAddr, + /// The user the image's sessions run as. + #[arg(long, env = "FCTL_SANDBOX_USER", default_value = "agent")] + user: String, + }, /// Serve a directory to a Firecracker VM over 9P, on the unix socket /// where Firecracker connects the VM's vsock port (on the host). #[cfg(target_os = "linux")] @@ -229,6 +248,27 @@ fn main() -> anyhow::Result<()> { runtime()?.block_on(vm::serve()) } #[cfg(target_os = "linux")] + Command::MicrovmServe { + listen, + hooks, + user, + } => { + // To the microVM's output, which Lambda keeps in CloudWatch Logs. + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_env("FCTL_LOG") + .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")), + ) + .with_ansi(false) + .with_writer(std::io::stderr) + .init(); + runtime()?.block_on(microvm::serve(microvm::Options { + listen, + hooks, + user, + })) + } + #[cfg(target_os = "linux")] Command::Share { dir, socket } => { init_logging(None)?; share::serve(&dir, &socket) diff --git a/crates/fctl-agent/src/microvm/http.rs b/crates/fctl-agent/src/microvm/http.rs new file mode 100644 index 000000000..2f6f012a7 --- /dev/null +++ b/crates/fctl-agent/src/microvm/http.rs @@ -0,0 +1,420 @@ +//! Just enough HTTP/1.1 and WebSockets (RFC 6455) for `microvm-serve`: +//! Lambda's lifecycle hooks are small POSTs, and the host's requests come +//! as WebSockets, which Lambda's endpoint carries to the microVM as plain +//! HTTP/1.1 upgrades. Each WebSocket becomes a byte stream +//! ([`tokio::io::DuplexStream`]): its binary messages, one after the other. + +use anyhow::{Context, Result, bail}; +use base64::Engine; +use base64::engine::general_purpose::STANDARD; +use sha1::{Digest, Sha1}; +use std::collections::HashMap; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, DuplexStream}; +use tokio::sync::mpsc; + +/// The most a request's head may take. +const MAX_HEAD: usize = 16 * 1024; +/// The most a hook's body may take: Lambda's run payload is 16 KiB at most. +const MAX_BODY: usize = 64 * 1024; +/// The most one WebSocket frame may carry. +const MAX_FRAME: u64 = 16 * 1024 * 1024; +/// What each WebSocket's stream buffers. +const BUFFER: usize = 1024 * 1024; + +/// A request's head and body. +#[derive(Debug, Default)] +pub struct Request { + pub method: String, + pub path: String, + /// Names in lowercase. + pub headers: HashMap, + pub body: Vec, +} + +impl Request { + pub fn header(&self, name: &str) -> Option<&str> { + self.headers.get(name).map(String::as_str) + } +} + +/// Reads a request's head, and its body unless it upgrades to a WebSocket. +pub async fn read_request(r: &mut (impl AsyncRead + Unpin)) -> Result { + let mut head = Vec::with_capacity(1024); + let mut byte = [0u8; 1]; + while !head.ends_with(b"\r\n\r\n") { + if head.len() >= MAX_HEAD { + bail!("the request's head is too long"); + } + if r.read(&mut byte).await? == 0 { + bail!("the connection closed before the request's head ended"); + } + head.push(byte[0]); + } + let text = String::from_utf8_lossy(&head); + let mut lines = text.split("\r\n"); + let first = lines.next().unwrap_or_default(); + let mut parts = first.split(' '); + let (Some(method), Some(path)) = (parts.next(), parts.next()) else { + bail!("not an HTTP request: {first:?}"); + }; + let mut req = Request { + method: method.to_owned(), + path: path.to_owned(), + ..Request::default() + }; + for line in lines.filter(|l| !l.is_empty()) { + if let Some((name, value)) = line.split_once(':') { + req.headers + .insert(name.trim().to_ascii_lowercase(), value.trim().to_owned()); + } + } + if req + .header("upgrade") + .is_some_and(|u| u.eq_ignore_ascii_case("websocket")) + { + return Ok(req); + } + if req + .header("transfer-encoding") + .is_some_and(|t| t.to_ascii_lowercase().contains("chunked")) + { + req.body = read_chunked(r).await?; + } else if let Some(len) = req.header("content-length") { + let len: usize = len.parse().context("reading Content-Length")?; + if len > MAX_BODY { + bail!("the request's body is too long"); + } + let mut body = vec![0u8; len]; + r.read_exact(&mut body).await?; + req.body = body; + } + Ok(req) +} + +async fn read_line(r: &mut (impl AsyncRead + Unpin)) -> Result { + let mut line = Vec::new(); + let mut byte = [0u8; 1]; + while !line.ends_with(b"\r\n") { + if line.len() > 1024 || r.read(&mut byte).await? == 0 { + bail!("a chunk's size line didn't end"); + } + line.push(byte[0]); + } + line.truncate(line.len() - 2); + Ok(String::from_utf8_lossy(&line).into_owned()) +} + +async fn read_chunked(r: &mut (impl AsyncRead + Unpin)) -> Result> { + let mut body = Vec::new(); + loop { + let size = read_line(r).await?; + let size = usize::from_str_radix(size.split(';').next().unwrap_or("").trim(), 16) + .context("reading a chunk's size")?; + if size == 0 { + // Trailers, up to the empty line. + while !read_line(r).await?.is_empty() {} + return Ok(body); + } + if body.len() + size > MAX_BODY { + bail!("the request's body is too long"); + } + let start = body.len(); + body.resize(start + size, 0); + r.read_exact(&mut body[start..]).await?; + read_line(r).await?; + } +} + +/// Writes a response and its body, and ends the connection's use. +pub async fn respond( + w: &mut (impl AsyncWrite + Unpin), + status: u16, + content_type: &str, + body: &[u8], +) -> Result<()> { + let reason = match status { + 200 => "OK", + 400 => "Bad Request", + 403 => "Forbidden", + 404 => "Not Found", + 405 => "Method Not Allowed", + 500 => "Internal Server Error", + 503 => "Service Unavailable", + _ => "", + }; + let head = format!( + "HTTP/1.1 {status} {reason}\r\ncontent-type: {content_type}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n", + body.len() + ); + w.write_all(head.as_bytes()).await?; + w.write_all(body).await?; + w.flush().await?; + Ok(()) +} + +/// The `Sec-WebSocket-Accept` that answers a client's key. +pub fn accept_key(key: &str) -> String { + let mut sha = Sha1::new(); + sha.update(key.trim().as_bytes()); + sha.update(b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"); + STANDARD.encode(sha.finalize()) +} + +/// Answers a WebSocket's upgrade, and carries its binary messages to and +/// from the stream it returns, until either side closes. +pub async fn upgrade(mut conn: S, req: &Request) -> Result +where + S: AsyncRead + AsyncWrite + Unpin + Send + 'static, +{ + let Some(key) = req.header("sec-websocket-key") else { + respond(&mut conn, 400, "text/plain", b"not a WebSocket").await?; + bail!("a WebSocket upgrade without a key"); + }; + let head = format!( + "HTTP/1.1 101 Switching Protocols\r\nupgrade: websocket\r\nconnection: Upgrade\r\nsec-websocket-accept: {}\r\n\r\n", + accept_key(key) + ); + conn.write_all(head.as_bytes()).await?; + conn.flush().await?; + let (ours, theirs) = tokio::io::duplex(BUFFER); + tokio::spawn(pump(conn, ours)); + Ok(theirs) +} + +/// What goes out on a WebSocket: data, or a control frame. +enum Out { + Binary(Vec), + Pong(Vec), + Close, +} + +/// Carries a WebSocket's messages to `stream`, and what `stream` gives +/// back as binary messages. +async fn pump(conn: S, stream: DuplexStream) +where + S: AsyncRead + AsyncWrite + Unpin + Send + 'static, +{ + let (mut conn_r, mut conn_w) = tokio::io::split(conn); + let (mut stream_r, mut stream_w) = tokio::io::split(stream); + let (out_tx, mut out_rx) = mpsc::channel::(16); + let writer = tokio::spawn(async move { + while let Some(out) = out_rx.recv().await { + let (opcode, payload) = match out { + Out::Binary(p) => (0x2, p), + Out::Pong(p) => (0xA, p), + Out::Close => (0x8, Vec::new()), + }; + let closing = opcode == 0x8; + if conn_w.write_all(&frame(opcode, &payload)).await.is_err() { + return; + } + if closing { + let _ = conn_w.shutdown().await; + return; + } + } + }); + // The stream's bytes, as messages. + let outgoing = out_tx.clone(); + let from_stream = tokio::spawn(async move { + let mut buf = vec![0u8; 64 * 1024]; + loop { + match stream_r.read(&mut buf).await { + Ok(0) | Err(_) => { + let _ = outgoing.send(Out::Close).await; + return; + } + Ok(n) => { + if outgoing.send(Out::Binary(buf[..n].to_vec())).await.is_err() { + return; + } + } + } + } + }); + // The messages, as the stream's bytes. + loop { + match read_frame(&mut conn_r).await { + Ok(Some((0x0..=0x2, payload))) => { + if stream_w.write_all(&payload).await.is_err() { + break; + } + } + Ok(Some((0x9, payload))) => { + if out_tx.send(Out::Pong(payload)).await.is_err() { + break; + } + } + Ok(Some((0xA, _))) => {} + Ok(Some((0x8, _))) | Ok(None) => { + let _ = out_tx.send(Out::Close).await; + break; + } + Ok(Some((op, _))) => { + tracing::debug!("a WebSocket frame of opcode {op} ended the connection"); + let _ = out_tx.send(Out::Close).await; + break; + } + Err(e) => { + tracing::debug!("reading a WebSocket frame: {e:#}"); + break; + } + } + } + let _ = stream_w.shutdown().await; + drop(out_tx); + from_stream.abort(); + let _ = writer.await; +} + +/// A frame from the server: unmasked. +pub fn frame(opcode: u8, payload: &[u8]) -> Vec { + let mut f = Vec::with_capacity(payload.len() + 10); + f.push(0x80 | opcode); + match payload.len() { + n if n < 126 => f.push(n as u8), + n if n <= 0xFFFF => { + f.push(126); + f.extend_from_slice(&(n as u16).to_be_bytes()); + } + n => { + f.push(127); + f.extend_from_slice(&(n as u64).to_be_bytes()); + } + } + f.extend_from_slice(payload); + f +} + +/// The next frame's opcode and payload, unmasked; `None` once the +/// connection ends between frames. +pub async fn read_frame(r: &mut (impl AsyncRead + Unpin)) -> Result)>> { + let mut head = [0u8; 2]; + match r.read_exact(&mut head).await { + Ok(_) => {} + Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => return Ok(None), + Err(e) => return Err(e.into()), + } + let opcode = head[0] & 0x0F; + let masked = head[1] & 0x80 != 0; + let len = match head[1] & 0x7F { + 126 => { + let mut b = [0u8; 2]; + r.read_exact(&mut b).await?; + u64::from(u16::from_be_bytes(b)) + } + 127 => { + let mut b = [0u8; 8]; + r.read_exact(&mut b).await?; + u64::from_be_bytes(b) + } + n => u64::from(n), + }; + if len > MAX_FRAME { + bail!("a WebSocket frame of {len} bytes is too long"); + } + let mut mask = [0u8; 4]; + if masked { + r.read_exact(&mut mask).await?; + } + let mut payload = vec![0u8; usize::try_from(len)?]; + r.read_exact(&mut payload).await?; + if masked { + for (i, b) in payload.iter_mut().enumerate() { + *b ^= mask[i % 4]; + } + } + Ok(Some((opcode, payload))) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A client's frame: masked. + fn client_frame(opcode: u8, payload: &[u8]) -> Vec { + let mask = [1u8, 2, 3, 4]; + let mut f = vec![0x80 | opcode]; + match payload.len() { + n if n < 126 => f.push(0x80 | n as u8), + n => { + f.push(0x80 | 126); + f.extend_from_slice(&(n as u16).to_be_bytes()); + } + } + f.extend_from_slice(&mask); + f.extend(payload.iter().enumerate().map(|(i, b)| b ^ mask[i % 4])); + f + } + + #[test] + fn the_accept_key_is_the_rfcs() { + // RFC 6455's own example. + assert_eq!( + accept_key("dGhlIHNhbXBsZSBub25jZQ=="), + "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=" + ); + } + + #[tokio::test] + async fn requests_read_with_their_bodies_plain_or_chunked() -> Result<()> { + let plain = b"POST /aws/lambda-microvms/runtime/v1/run HTTP/1.1\r\nHost: x\r\nContent-Length: 5\r\n\r\nhello"; + let req = read_request(&mut &plain[..]).await?; + assert_eq!(req.method, "POST"); + assert_eq!(req.path, "/aws/lambda-microvms/runtime/v1/run"); + assert_eq!(req.body, b"hello"); + 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()); + Ok(()) + } + + #[tokio::test] + async fn a_websocket_carries_bytes_both_ways_and_answers_pings() -> Result<()> { + let (client, server) = tokio::io::duplex(64 * 1024); + let (mut cr, mut cw) = tokio::io::split(client); + let mut req = Request::default(); + req.headers.insert( + "sec-websocket-key".into(), + "dGhlIHNhbXBsZSBub25jZQ==".into(), + ); + let serving = tokio::spawn(async move { upgrade(server, &req).await }); + // The 101. + let mut head = Vec::new(); + let mut byte = [0u8; 1]; + while !head.ends_with(b"\r\n\r\n") { + cr.read_exact(&mut byte).await?; + head.push(byte[0]); + } + assert!(String::from_utf8_lossy(&head).contains("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=")); + let mut stream = serving.await??; + // In: two messages, one stream. + cw.write_all(&client_frame(0x2, b"{\"type\":")).await?; + cw.write_all(&client_frame(0x2, b"\"hello\"}\n")).await?; + let mut got = vec![0u8; 17]; + stream.read_exact(&mut got).await?; + assert_eq!(got, b"{\"type\":\"hello\"}\n"); + // A ping gets its pong. + cw.write_all(&client_frame(0x9, b"hi")).await?; + assert_eq!(read_frame(&mut cr).await?, Some((0xA, b"hi".to_vec()))); + // Out: as binary messages, long ones too. + let long = vec![7u8; 70_000]; + stream.write_all(&long).await?; + let mut back = Vec::new(); + while back.len() < long.len() { + let Some((op, payload)) = read_frame(&mut cr).await? else { + bail!("closed early"); + }; + assert_eq!(op, 0x2); + back.extend(payload); + } + assert_eq!(back, long); + // The client closes: the stream ends, and the close is answered. + cw.write_all(&client_frame(0x8, b"")).await?; + let mut rest = Vec::new(); + stream.read_to_end(&mut rest).await?; + assert!(rest.is_empty()); + assert_eq!(read_frame(&mut cr).await?, Some((0x8, Vec::new()))); + Ok(()) + } +} diff --git a/crates/fctl-agent/src/microvm/mod.rs b/crates/fctl-agent/src/microvm/mod.rs new file mode 100644 index 000000000..397ddf36d --- /dev/null +++ b/crates/fctl-agent/src/microvm/mod.rs @@ -0,0 +1,277 @@ +//! `fctl-agent microvm-serve`: what runs in an AWS Lambda microVM, from the +//! image's `CMD` (docs/architecture.md#aws-lambda-microvms). +//! +//! Lambda builds the image by starting it and snapshotting it once +//! `microvm-serve` answers its `/ready` hook, so every microVM run from it +//! starts with `microvm-serve` already up. It serves two ports: +//! +//! - [`HOOKS_PORT`]: Lambda's lifecycle hooks. `/run` brings what the host +//! ran the microVM with ([`RunPayload`]): the runner, and the key that +//! the host's requests carry. `/suspend` writes out what the disk holds; +//! the rest only answer. +//! - [`SERVE_PORT`]: the host's requests, as WebSockets through the +//! microVM's endpoint, each carrying one of [`fctl_proto::vm`]'s +//! requests and what follows it, as a vsock connection carries one to a +//! Firecracker VM's init ([`crate::vm`]): `hello`, and `exec`, with which +//! the host puts its fctl-agent in, starts the supervisor and attaches +//! to it. A WebSocket without the run payload's key ([`KEY_HEADER`]) is +//! refused, so that a program in the microVM can't have it run what it +//! likes as root; the key comes only with the first `/run`, which Lambda +//! sends before anything of the session's runs. +//! +//! Not as root (the dev stack's stand-in for Lambda runs it as the +//! developer), it runs programs as itself, whatever user they ask for. + +mod http; + +use crate::vm::{Serving, handle_stream}; +use anyhow::{Context, Result}; +use fctl_proto::microvm::{HOOKS_PATH, HOOKS_PORT, KEY_HEADER, RunPayload, SERVE_PATH, SERVE_PORT}; +use fctl_proto::vm::Reply; +use std::net::SocketAddr; +use std::sync::{Arc, Mutex}; +use tokio::net::{TcpListener, TcpStream}; + +/// What `microvm-serve` listens on, and whom sessions run as. +#[derive(Clone, Debug)] +pub struct Options { + pub listen: SocketAddr, + pub hooks: SocketAddr, + /// The user the image's sessions run as: its `USER`, before the + /// `USER root` that runs `microvm-serve`. + pub user: String, +} + +impl Default for Options { + fn default() -> Self { + Self { + listen: SocketAddr::from(([0, 0, 0, 0], SERVE_PORT)), + hooks: SocketAddr::from(([0, 0, 0, 0], HOOKS_PORT)), + user: "agent".into(), + } + } +} + +/// What Lambda's `/run` brought. +#[derive(Clone, Debug, Default)] +struct Ran { + microvm: Option, + payload: Option, +} + +#[derive(Clone)] +struct Shared { + opts: Options, + ran: Arc>>, + /// Its own environment, which programs get: the image's, as Lambda + /// started it. + env: Arc>, + as_itself: bool, +} + +pub async fn serve(opts: Options) -> Result<()> { + let hooks = TcpListener::bind(opts.hooks) + .await + .with_context(|| format!("listening for Lambda's hooks on {}", opts.hooks))?; + let listener = TcpListener::bind(opts.listen) + .await + .with_context(|| format!("listening for the host on {}", opts.listen))?; + let as_itself = !nix::unistd::geteuid().is_root(); + if as_itself { + tracing::warn!("not running as root: programs run as this user, whatever they ask for"); + } + let shared = Shared { + opts, + ran: Arc::new(Mutex::new(None)), + env: Arc::new( + std::env::vars() + .filter(|(k, _)| !k.starts_with("FCTL_LOG")) + .map(|(k, v)| format!("{k}={v}")) + .collect(), + ), + as_itself, + }; + tracing::info!( + "microvm-serve {} ready: hooks on {}, the host's requests on {}", + env!("CARGO_PKG_VERSION"), + shared.opts.hooks, + shared.opts.listen + ); + let for_hooks = shared.clone(); + tokio::spawn(async move { + loop { + match hooks.accept().await { + Ok((conn, _)) => { + let shared = for_hooks.clone(); + tokio::spawn(async move { + if let Err(e) = hook(conn, &shared).await { + tracing::warn!("a hook: {e:#}"); + } + }); + } + Err(e) => tracing::warn!("taking a hook's connection: {e}"), + } + } + }); + loop { + let (conn, peer) = listener.accept().await.context("taking a connection")?; + let shared = shared.clone(); + tokio::spawn(async move { + if let Err(e) = request(conn, &shared).await { + tracing::debug!("a request from {peer}: {e:#}"); + } + }); + } +} + +/// One of Lambda's lifecycle hooks. +async fn hook(mut conn: TcpStream, shared: &Shared) -> Result<()> { + let req = http::read_request(&mut conn).await?; + let Some(name) = req + .path + .strip_prefix(HOOKS_PATH) + .and_then(|p| p.strip_prefix('/')) + else { + return http::respond(&mut conn, 404, "text/plain", b"not a hook").await; + }; + if req.method != "POST" { + return http::respond(&mut conn, 405, "text/plain", b"hooks are POSTs").await; + } + match name { + // Up and answering: Lambda snapshots it now, as the image builds. + "ready" | "validate" | "resume" | "terminate" => { + tracing::info!("hook: {name}"); + } + "run" => { + let ran = run_hook(&req.body); + let mut kept = shared + .ran + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + match kept.as_ref() { + // Only the first, Lambda's, as the microVM starts: anything + // later is from the microVM itself. + Some(_) => tracing::warn!("hook: run again, which changes nothing"), + None => { + tracing::info!( + "hook: run, as {} for runner {}", + ran.microvm.as_deref().unwrap_or("a microVM"), + ran.payload.as_ref().map_or("(none)", |p| p.runner.as_str()) + ); + *kept = Some(ran); + } + } + } + // What the disk holds is written out before Lambda checkpoints it. + "suspend" => { + tracing::info!("hook: suspend"); + let _ = tokio::task::spawn_blocking(nix::unistd::sync).await; + } + _ => return http::respond(&mut conn, 404, "text/plain", b"no such hook").await, + } + http::respond(&mut conn, 200, "application/json", b"{}").await +} + +/// What `/run`'s body says: `{"microvmId": …, "runHookPayload": "…"}`, +/// the payload being the host's [`RunPayload`], as JSON. +fn run_hook(body: &[u8]) -> Ran { + let v: serde_json::Value = serde_json::from_slice(body).unwrap_or_default(); + let microvm = v + .get("microvmId") + .and_then(|m| m.as_str()) + .map(str::to_owned); + let payload = v + .get("runHookPayload") + .and_then(|p| p.as_str()) + .and_then(|p| serde_json::from_str::(p).ok()); + Ran { microvm, payload } +} + +/// A connection on the serving port: the host's WebSocket, or a look at +/// whether it is up (`GET /health`). +async fn request(mut conn: TcpStream, shared: &Shared) -> Result<()> { + let req = http::read_request(&mut conn).await?; + let upgrade = req + .header("upgrade") + .is_some_and(|u| u.eq_ignore_ascii_case("websocket")); + if !upgrade { + return match req.path.as_str() { + "/health" => http::respond(&mut conn, 200, "text/plain", b"ok").await, + _ => http::respond(&mut conn, 404, "text/plain", b"not here").await, + }; + } + let ran = shared + .ran + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone(); + let key = ran + .as_ref() + .and_then(|r| r.payload.as_ref()) + .map(|p| p.key.clone()); + let presented = req.header(KEY_HEADER); + let allowed = match (&key, presented) { + (Some(key), Some(given)) => constant_eq(key.as_bytes(), given.as_bytes()), + _ => false, + }; + if req.path != SERVE_PATH || !allowed { + tracing::warn!("refused a WebSocket to {} without the run's key", req.path); + return http::respond(&mut conn, 403, "text/plain", b"not the host").await; + } + let stream = http::upgrade(conn, &req).await?; + let (r, w) = tokio::io::split(stream); + let payload = ran.as_ref().and_then(|r| r.payload.clone()); + let serving = Serving { + hello: Reply { + user: Some(shared.opts.user.clone()), + arch: Some(std::env::consts::ARCH.to_owned()), + microvm: ran.and_then(|r| r.microvm), + runner: payload.as_ref().map(|p| p.runner.clone()), + name: payload.map(|p| p.name), + ..Reply::default() + }, + env: shared.env.as_ref().clone(), + as_itself: shared.as_itself, + shutdown: false, + }; + handle_stream(r, w, &serving).await +} + +/// Whether two keys are the same, in a time that doesn't say how much of +/// them is. +fn constant_eq(a: &[u8], b: &[u8]) -> bool { + a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_run_hook_brings_the_microvm_and_the_hosts_payload() { + let payload = RunPayload { + fctl: 1, + runner: "rnr_1".into(), + name: "warm-1".into(), + key: "k".repeat(64), + }; + let body = serde_json::json!({ + "microvmId": "mvm-01234567", + "runHookPayload": serde_json::to_string(&payload).unwrap_or_default(), + }); + let ran = run_hook(body.to_string().as_bytes()); + assert_eq!(ran.microvm.as_deref(), Some("mvm-01234567")); + assert_eq!(ran.payload, Some(payload)); + // Lambda's own build runs, with no payload. + let ran = run_hook(br#"{"microvmId":"mvm-1"}"#); + assert_eq!(ran.payload, None); + assert!(run_hook(b"not json").microvm.is_none()); + } + + #[test] + fn keys_compare_whole() { + assert!(constant_eq(b"abc", b"abc")); + assert!(!constant_eq(b"abc", b"abd")); + assert!(!constant_eq(b"abc", b"ab")); + } +} diff --git a/crates/fctl-agent/src/supervisor.rs b/crates/fctl-agent/src/supervisor.rs index 29b6fed3f..7004d47e3 100644 --- a/crates/fctl-agent/src/supervisor.rs +++ b/crates/fctl-agent/src/supervisor.rs @@ -29,7 +29,8 @@ use fctl_domain::models::ModelName; use fctl_domain::{files, published, validate}; use fctl_proto::agent::{ AUTOPILOT_ENV, AgentConfig, AgentHello, AgentToHost, FEATURE_AGENT_SNAPSHOTS, - FEATURE_CLAUDE_RELAY, HostToAgent, SESSION_SOCKET_ENV, SessionReply, SessionRequest, + FEATURE_CHECKPOINTS, FEATURE_CLAUDE_RELAY, HostToAgent, SESSION_SOCKET_ENV, SessionReply, + SessionRequest, }; use fctl_proto::api::{AgentAnswer, AgentCall}; use fctl_proto::event::{ @@ -266,6 +267,9 @@ pub struct Supervisor { stderr_budget: (Instant, u32), claude_credential: Option, exit_after: Option, + /// Whether the host last heard that the session waits with nothing + /// running ([`AgentToHost::State`]'s `quiet`). + told_quiet: std::cell::Cell>, /// The repositories' state reported last. last_git: Option, /// The changed files' diffs sent last, which a host that attaches gets @@ -399,6 +403,7 @@ impl Supervisor { stderr_budget: (Instant::now(), 0), claude_credential: None, exit_after: None, + told_quiet: std::cell::Cell::new(None), last_git: None, last_diffs: None, refresh: Refresh::default(), @@ -454,6 +459,33 @@ impl Supervisor { } } } + self.tell_quiet(); + } + } + + /// The session's state, for the host: with whether it waits with + /// nothing running, which the host suspends a microVM after. + fn state_frame(&self) -> AgentToHost { + let quiet = self.quiet(); + self.told_quiet.set(Some(quiet)); + AgentToHost::State { + state: self.state.clone(), + quiet: Some(quiet), + } + } + + /// Whether the session waits for a message with nothing running, and + /// isn't stopping: what its idle timeout counts from. + fn quiet(&self) -> bool { + self.config.is_some() && self.stopping.is_none() && self.nothing_runs() + } + + /// Tells the host when the session starts or stops waiting with + /// nothing running, which a background task's end or Claude saying it + /// is done changes without a new status. + fn tell_quiet(&mut self) { + if self.host.is_some() && self.told_quiet.get() != Some(self.quiet()) { + self.send(&self.state_frame()); } } @@ -508,6 +540,7 @@ impl Supervisor { FEATURE_ATTACHMENTS, FEATURE_SETTINGS, FEATURE_AGENT_SNAPSHOTS, + FEATURE_CHECKPOINTS, ] .into_iter() // Where the host's channels can come in. @@ -554,6 +587,7 @@ impl Supervisor { async fn on_frame(&mut self, frame: HostToAgent) { match frame { HostToAgent::Ping => self.send(&AgentToHost::Pong), + HostToAgent::Checkpoint { id } => self.checkpoint(id).await, HostToAgent::SnapshotPart { id, n, data, last } => { self.on_snapshot_part(&id, n, &data, last) } @@ -593,9 +627,7 @@ impl Supervisor { } Err(e) => tracing::error!("journal replay failed: {e:#}"), } - self.send(&AgentToHost::State { - state: self.state.clone(), - }); + self.send(&self.state_frame()); // The host passes on to the control plane those it // hasn't sent over its uplink. if let Some(files) = &self.last_diffs { @@ -746,9 +778,7 @@ impl Supervisor { (false, _) => None, }; self.flush(); - self.send(&AgentToHost::State { - state: self.state.clone(), - }); + self.send(&self.state_frame()); } // ───────────────────────────── attachments ───────────────────────────── @@ -1181,9 +1211,7 @@ impl Supervisor { self.persisted.description = self.state.description.clone(); self.persist(); self.flush(); - self.send(&AgentToHost::State { - state: self.state.clone(), - }); + self.send(&self.state_frame()); Ok(SessionReply::Edited { id: spec.session_id.clone(), project_slug: spec.project.slug.clone(), @@ -1531,18 +1559,14 @@ impl Supervisor { if self.state.effort.as_ref() != Some(&effort) { self.state.effort = Some(effort); self.flush(); - self.send(&AgentToHost::State { - state: self.state.clone(), - }); + self.send(&self.state_frame()); } } Work::Context(window) => { if self.state.context != Some(window) { self.state.context = Some(window); self.flush(); - self.send(&AgentToHost::State { - state: self.state.clone(), - }); + self.send(&self.state_frame()); } } Work::Settings { @@ -1636,9 +1660,7 @@ impl Supervisor { ok: error.is_none(), error, }); - self.send(&AgentToHost::State { - state: self.state.clone(), - }); + self.send(&self.state_frame()); } // ───────────────────────────── Claude ───────────────────────────── @@ -2369,9 +2391,7 @@ impl Supervisor { let shown = self.model_name.init(m); if self.state.model.as_ref() != Some(&shown) { self.state.model = Some(shown); - self.send(&AgentToHost::State { - state: self.state.clone(), - }); + self.send(&self.state_frame()); } } let is_result = kind == ClaudeKind::Result; @@ -3254,19 +3274,19 @@ impl Supervisor { /// Saves the session's snapshot, as the sandbox stops, and hands it to /// the host in parts: its conversation and the work not on GitHub. /// Saving what is too large, or failing, says so in the transcript. - async fn save_snapshot(&mut self) { + async fn save_snapshot(&mut self) -> SnapshotSent { let (Some(config), Some(paths)) = (self.config.clone(), self.paths.clone()) else { - return; + return SnapshotSent::None; }; let Some(snap) = config.spec.snapshot.as_ref().filter(|s| s.save) else { - return; + return SnapshotSent::None; }; // Claude never ran here: nothing of this run's to keep. if !self.persisted.claude_started { - return; + return SnapshotSent::None; } let Ok(key) = STANDARD.decode(snap.key.as_bytes()) else { - return; + return SnapshotSent::Failed("the session's snapshot key isn't base64".into()); }; // Where the session's user writes, as for a restore. let dir = self.user_state.join("snapshot"); @@ -3283,7 +3303,7 @@ impl Supervisor { ) .await { - Ok(Some(saved)) => { + Ok(Some(mut saved)) => { if !saved.failed.is_empty() { let msg = format!( "The session's snapshot left out the work in {}: a resume on another runner starts there from the branch.", @@ -3291,20 +3311,43 @@ impl Supervisor { ); self.notice(NoticeLevel::Warn, "snapshot_work_left_out", &msg, None); self.flush(); + // The notice is the session's last event now: one the + // snapshot is behind wouldn't be restored. + saved.saved.agent_seq = self.journal.last_seq(); } self.send_snapshot(saved); + SnapshotSent::Sent } - Ok(None) => {} + Ok(None) => SnapshotSent::None, Err(e) => { let msg = format!( "The session's snapshot wasn't saved: {e:#}. A resume on another runner starts from the task and the branch." ); self.notice(NoticeLevel::Warn, "snapshot_not_saved", &msg, None); self.flush(); + SnapshotSent::Failed(format!("{e:#}")) } } } + /// Saves the session's snapshot as it waits, for a host about to + /// suspend its sandbox ([`HostToAgent::Checkpoint`]), and says what + /// came of it. A session at work again by now saves none: the host + /// suspends nothing then. + async fn checkpoint(&mut self, id: String) { + let (saved, error) = if !self.quiet() { + (false, Some("the session is at work".to_owned())) + } else { + self.flush(); + match self.save_snapshot().await { + SnapshotSent::Sent => (true, None), + SnapshotSent::None => (false, None), + SnapshotSent::Failed(why) => (false, Some(why)), + } + }; + self.send(&AgentToHost::Checkpointed { id, saved, error }); + } + /// Hands a saved snapshot to the host, part by part, the last with what /// it holds. fn send_snapshot(&mut self, saved: crate::snapshot::Saved) { @@ -3425,13 +3468,23 @@ impl Supervisor { self.flush(); // The session's snapshot, after its last event, for a resume on // another runner. - self.save_snapshot().await; + let _ = self.save_snapshot().await; self.send(&AgentToHost::Exited { status, reason }); // Give the host a moment to read everything. self.exit_after = Some(Instant::now() + Duration::from_secs(3)); } } +/// What came of saving the session's snapshot. +enum SnapshotSent { + /// Its parts went to the host. + Sent, + /// There was none to save: the session keeps none, or Claude never ran. + None, + /// Saving it failed, as the transcript says. + Failed(String), +} + /// Repositories and why their work didn't come along, for the transcript: /// `acme/api (its bundle's history is missing)`. fn failures(failed: &[(String, String)]) -> String { @@ -5032,7 +5085,7 @@ mod tests { fn states_sent(host: &mut mpsc::UnboundedReceiver) -> Vec { let mut out = vec![]; while let Ok(text) = host.try_recv() { - if let Ok(AgentToHost::State { state }) = serde_json::from_str(&text) { + if let Ok(AgentToHost::State { state, .. }) = serde_json::from_str(&text) { out.push(state); } } @@ -5388,7 +5441,7 @@ done let state = frames .iter() .find_map(|t| match serde_json::from_str(t) { - Ok(AgentToHost::State { state }) => Some(state), + Ok(AgentToHost::State { state, .. }) => Some(state), _ => None, }) .ok_or_else(|| anyhow::anyhow!("no state sent"))?; @@ -5449,7 +5502,7 @@ done } assert!(frames.iter().any(|t| matches!( serde_json::from_str(t), - Ok(AgentToHost::State { state }) if state.model.as_deref() == Some("sonnet") + Ok(AgentToHost::State { state, .. }) if state.model.as_deref() == Some("sonnet") ))); let refused = frames.iter().find_map(|t| match serde_json::from_str(t) { Ok(AgentToHost::Delivered { @@ -6621,7 +6674,7 @@ done let statuses: Vec = frames .iter() .filter_map(|f| match f { - AgentToHost::State { state } => Some(state.status), + AgentToHost::State { state, .. } => Some(state.status), _ => None, }) .collect(); @@ -6686,6 +6739,78 @@ done Ok(()) } + /// Whether the session waits with nothing running, as the frames sent + /// the host say it, newest last. + fn quiet_sent(host: &mut mpsc::UnboundedReceiver) -> Vec { + sent(host) + .into_iter() + .filter_map(|m| match m { + AgentToHost::State { quiet, .. } => quiet, + _ => None, + }) + .collect() + } + + #[tokio::test] + async fn the_host_hears_when_nothing_runs_and_gets_a_checkpoint_when_it_asks() + -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + let (mut sup, mut host) = in_a_turn(dir.path())?; + sup.claude = Some(stub_claude(dir.path(), &sup)?); + assert_eq!(quiet_sent(&mut host).last(), Some(&false)); + // The turn ends with background work running: it waits, not quiet. + sup.on_claude_message(task_started("b1", "Run the tests", "local_bash")) + .await; + sup.on_claude_message(result()).await; + sup.tell_quiet(); + assert_eq!(waiting(&sup).0, SessionStatus::Idle); + assert_eq!(quiet_sent(&mut host).last(), Some(&false)); + // The work ends: now nothing runs, and the host hears it once. + sup.on_claude_message(task_ended("b1")).await; + sup.claude_went_idle().await; + sup.tell_quiet(); + assert_eq!(quiet_sent(&mut host).last(), Some(&true)); + sup.tell_quiet(); + assert!(quiet_sent(&mut host).is_empty()); + // A checkpoint of a session that keeps no snapshots saves none, + // and says so without an error. + sup.on_frame(HostToAgent::Checkpoint { id: "c1".into() }) + .await; + let answer = sent(&mut host) + .into_iter() + .find(|m| matches!(m, AgentToHost::Checkpointed { .. })); + assert_eq!( + answer, + Some(AgentToHost::Checkpointed { + id: "c1".into(), + saved: false, + error: None + }) + ); + // At work again, it saves nothing: the host suspends nothing. + sup.turn_active = true; + sup.set_status(SessionStatus::Running, None); + sup.on_frame(HostToAgent::Checkpoint { id: "c2".into() }) + .await; + let answer = sent(&mut host) + .into_iter() + .find(|m| matches!(m, AgentToHost::Checkpointed { .. })); + assert_eq!( + answer, + Some(AgentToHost::Checkpointed { + id: "c2".into(), + saved: false, + error: Some("the session is at work".into()) + }) + ); + // Agents say they can. + let AgentToHost::Hello(hello) = sup.hello() else { + anyhow::bail!("not a hello"); + }; + assert!(hello.features.iter().any(|f| f == FEATURE_CHECKPOINTS)); + Ok(()) + } + #[tokio::test] async fn a_review_agent_that_doesnt_post_is_reminded_then_stops_a_minute_later() -> anyhow::Result<()> { diff --git a/crates/fctl-agent/src/user/accounts.rs b/crates/fctl-agent/src/user/accounts.rs index c58ff733b..0b3f6918b 100644 --- a/crates/fctl-agent/src/user/accounts.rs +++ b/crates/fctl-agent/src/user/accounts.rs @@ -21,6 +21,20 @@ pub fn find(spec: Option<&str>) -> Result { find_in(spec, &passwd, &group) } +/// The user this process runs as, as [`find`] would say them, with `HOME` +/// where the system's files don't know it. +pub fn myself() -> Result { + let uid = nix::unistd::getuid().as_raw(); + let mut me = find(Some(&uid.to_string()))?; + me.gid = nix::unistd::getgid().as_raw(); + if me.name.is_none() + && let Ok(home) = std::env::var("HOME") + { + me.home = home; + } + Ok(me) +} + /// A line of `/etc/passwd`: name, uid, gid, home. fn accounts(passwd: &str) -> impl Iterator { passwd.lines().filter_map(|line| { diff --git a/crates/fctl-agent/src/vm/mod.rs b/crates/fctl-agent/src/vm/mod.rs index 9a76d050b..7c008fddb 100644 --- a/crates/fctl-agent/src/vm/mod.rs +++ b/crates/fctl-agent/src/vm/mod.rs @@ -29,7 +29,7 @@ mod unpack; pub use boot::init; pub use mount::mount; -pub use serve::serve; +pub use serve::{Serving, handle_stream, serve}; /// What the init reports to the host's `hello`. const VERSION: &str = env!("CARGO_PKG_VERSION"); diff --git a/crates/fctl-agent/src/vm/serve.rs b/crates/fctl-agent/src/vm/serve.rs index 34f240be3..34aeb429f 100644 --- a/crates/fctl-agent/src/vm/serve.rs +++ b/crates/fctl-agent/src/vm/serve.rs @@ -62,7 +62,49 @@ async fn reply(w: &mut (impl AsyncWrite + Unpin), r: &Reply) -> Result<()> { } async fn handle(conn: VsockStream) -> Result<()> { - let (r, mut w) = conn.into_split(); + let (r, w) = conn.into_split(); + handle_stream(r, w, &Serving::firecracker()).await +} + +/// What a server of [`fctl_proto::vm`]'s requests is: the init of a +/// Firecracker VM, or `microvm-serve` in an AWS Lambda microVM, which +/// carries them over WebSockets ([`crate::microvm`]). +#[derive(Clone, Debug, Default)] +pub struct Serving { + /// What it adds to its answer to `hello`. + pub hello: Reply, + /// The environment a program gets when the host sends none: the + /// microVM's own, which its image set, as Lambda ran it. Empty: none + /// but `HOME`, `HOSTNAME` and `PATH`, as for a Firecracker VM, whose + /// host sends the image's. + pub env: Vec, + /// Programs run as the server does, whatever user they ask for: it + /// can't take another's identity (it isn't root), as in the dev + /// stack's stand-in for Lambda. + pub as_itself: bool, + /// It may power the machine off when asked (Firecracker's init); in a + /// Lambda microVM, Lambda terminates it. + pub shutdown: bool, +} + +impl Serving { + /// A Firecracker VM's init: it powers the VM off when the host asks, + /// writing what its disks hold first, so that a VM stopped without its + /// memory saved boots again with all its session wrote. + pub fn firecracker() -> Self { + Self { + shutdown: true, + ..Self::default() + } + } +} + +/// Answers one request on a connection, and carries what follows it. +pub async fn handle_stream(r: R, mut w: W, serving: &Serving) -> Result<()> +where + R: AsyncRead + Unpin + Send + 'static, + W: AsyncWrite + Unpin + Send + 'static, +{ let mut r = BufReader::new(r); let mut line = Vec::new(); (&mut r) @@ -82,11 +124,11 @@ async fn handle(conn: VsockStream) -> Result<()> { } let hello = Reply { version: Some(VERSION.into()), - ..Reply::default() + ..serving.hello.clone() }; reply(&mut w, &hello).await } - Request::Exec(exec) => run(exec, r, w).await, + Request::Exec(exec) => run(exec, r, w, serving).await, Request::Unpack { .. } => { reply( &mut w, @@ -94,10 +136,17 @@ async fn handle(conn: VsockStream) -> Result<()> { ) .await } - Request::Shutdown => { + Request::Shutdown if serving.shutdown => { reply(&mut w, &Reply::default()).await?; shutdown().await } + Request::Shutdown => { + reply( + &mut w, + &Reply::failed("Lambda terminates this microVM; it doesn't power off by itself"), + ) + .await + } } } @@ -123,18 +172,27 @@ fn environment(image: &[String], user: &User, hostname: &str) -> Vec<(String, St } /// Runs `exec`, and carries its input and output until it exits. -async fn run( +async fn run( exec: Exec, - from_host: BufReader, - mut to_host: tokio_vsock::OwnedWriteHalf, -) -> Result<()> { + from_host: BufReader, + mut to_host: W, + serving: &Serving, +) -> Result<()> +where + R: AsyncRead + Unpin + Send + 'static, + W: AsyncWrite + Unpin + Send + 'static, +{ if let Some(t) = exec.now_ms { follow_clock(t); } if exec.argv.is_empty() { return reply(&mut to_host, &Reply::failed("no program to run")).await; } - let user = match users::find(exec.user.as_deref()) { + let user = match serving.as_itself { + true => users::myself(), + false => users::find(exec.user.as_deref()), + }; + let user = match user { Ok(user) => user, Err(e) => return reply(&mut to_host, &Reply::failed(e)).await, }; @@ -147,16 +205,35 @@ async fn run( .filter(|c| !c.is_empty()) .unwrap_or_else(|| "/".into()); let groups: Vec = user.groups.iter().map(u32::to_string).collect(); - let mut cmd = tokio::process::Command::new("/proc/self/exe"); - cmd.arg("run-as") - .arg(user.uid.to_string()) - .arg(user.gid.to_string()) - .arg(groups.join(",")) - .arg(&cwd) - .arg("--") - .args(&exec.argv) - .env_clear() - .envs(environment(&exec.env, &user, &hostname)); + let image_env = match exec.env.is_empty() { + true => &serving.env, + false => &exec.env, + }; + let mut cmd = match serving.as_itself { + // A session of its own, as run-as gives one, for the host to stop + // it with everything it started. + true => { + let Some((program, args)) = exec.argv.split_first() else { + return reply(&mut to_host, &Reply::failed("no program to run")).await; + }; + let mut cmd = tokio::process::Command::new(program); + cmd.args(args).current_dir(&cwd).process_group(0); + cmd + } + false => { + let mut cmd = tokio::process::Command::new("/proc/self/exe"); + cmd.arg("run-as") + .arg(user.uid.to_string()) + .arg(user.gid.to_string()) + .arg(groups.join(",")) + .arg(&cwd) + .arg("--") + .args(&exec.argv); + cmd + } + }; + cmd.env_clear() + .envs(environment(image_env, &user, &hostname)); if exec.detach { cmd.stdin(Stdio::null()) .stdout(Stdio::null()) @@ -267,8 +344,8 @@ async fn pump( /// Writes the host's input to the program until the host ends it; returns /// when the host goes away. -async fn take_input( - mut from_host: BufReader, +async fn take_input( + mut from_host: BufReader, mut stdin: Option, ) { let mut buf = vec![0u8; frame::MAX]; @@ -312,6 +389,13 @@ async fn shutdown() -> Result<()> { mod tests { use super::*; + #[test] + fn a_firecracker_vm_powers_off_when_asked_and_a_lambda_microvm_doesnt() { + assert!(Serving::firecracker().shutdown); + assert!(!Serving::firecracker().as_itself); + assert!(!Serving::default().shutdown); + } + #[test] fn programs_get_the_images_environment_and_a_home() { let user = User { diff --git a/crates/fctl-client/src/api.rs b/crates/fctl-client/src/api.rs index 7b250eb32..0d66f9140 100644 --- a/crates/fctl-client/src/api.rs +++ b/crates/fctl-client/src/api.rs @@ -1939,6 +1939,28 @@ impl Api { self.patch(&format!("/runners/{}", enc(id)), req).await } + /// A runner's AWS Lambda microVMs: how they are, every one, with their + /// settings for those who manage it. + pub async fn runner_microvms(&self, id: &str) -> Result { + self.get(&format!("/runners/{}/microvms", enc(id))).await + } + + /// Sets the settings of a runner's microVMs (its owner, the admins of + /// the workspace it belongs to): its host gets them at once. + pub async fn put_runner_microvms( + &self, + id: &str, + settings: &fctl_proto::microvm::MicrovmSettings, + ) -> Result { + self.put( + &format!("/runners/{}/microvms", enc(id)), + &PutRunnerMicrovmsRequest { + settings: settings.clone(), + }, + ) + .await + } + /// A new token for a runner (its owner, or the admins of the workspace /// it belongs to): the old one stops working, and its host /// disconnects until it has the new one. diff --git a/crates/fctl-control/migrations/0079_runner_microvms.sql b/crates/fctl-control/migrations/0079_runner_microvms.sql new file mode 100644 index 000000000..3c06a3456 --- /dev/null +++ b/crates/fctl-control/migrations/0079_runner_microvms.sql @@ -0,0 +1,11 @@ +-- The settings of a runner whose host runs sessions in AWS Lambda +-- microVMs (the `lambda` driver, docs/architecture.md#aws-lambda-microvms): +-- its image, roles, size, network and how long it suspends and keeps them +-- (JSON, `fctl_proto::microvm::MicrovmSettings`), which the people who +-- manage the runner set and its host gets as it connects. NULL until +-- someone sets them, and for other runners. +ALTER TABLE runners ADD COLUMN microvm_settings TEXT; + +-- When they were last changed, and by whom (NULL: by nobody who stayed). +ALTER TABLE runners ADD COLUMN microvm_settings_at INTEGER; +ALTER TABLE runners ADD COLUMN microvm_settings_by TEXT REFERENCES users(id) ON DELETE SET NULL; diff --git a/crates/fctl-control/src/api/microvms.rs b/crates/fctl-control/src/api/microvms.rs new file mode 100644 index 000000000..3776e8ac3 --- /dev/null +++ b/crates/fctl-control/src/api/microvms.rs @@ -0,0 +1,344 @@ +//! `/api/v1/runners/{id}/microvms`: the settings of a runner whose host runs +//! sessions in AWS Lambda microVMs (docs/architecture.md#aws-lambda-microvms), +//! and how its microVMs are, as its host said last. Those who manage the +//! runner set them, and its host gets them at once. + +use crate::api::runners::{require_manager, visible_runner}; +use crate::ctx::{Ctx, now_ms}; +use crate::db::{n, q, s}; +use crate::error::{AppResult, conflict, not_found}; +use crate::http; +use crate::internal; +use fctl_proto::api::{MicrovmSessionRef, PutRunnerMicrovmsRequest, RunnerMicrovms}; +use fctl_proto::microvm::{DRIVER, MicrovmSettings}; +use fctl_proto::session::{SessionStatus, UserRef}; +use fctl_proto::{RunnerId, SessionId}; +use worker::{Method, Request, Response}; + +/// Whether `segs` are this module's ([`route`]). +pub fn routes(segs: &[&str]) -> bool { + matches!(segs, ["runners", _, "microvms"]) +} + +pub async fn route( + ctx: &mut Ctx, + req: &mut Request, + method: Method, + segs: &[&str], +) -> AppResult { + match (method, segs) { + (Method::Get, ["runners", id, "microvms"]) => get(ctx, id).await, + (Method::Put, ["runners", id, "microvms"]) => put(ctx, req, id).await, + _ => Err(not_found("Endpoint")), + } +} + +#[derive(serde::Deserialize)] +struct SettingsRow { + microvm_settings: Option, + #[serde(deserialize_with = "crate::db::opt_int", default)] + microvm_settings_at: Option, + microvm_settings_by: Option, + by_name: Option, + by_avatar: Option, +} + +async fn settings_of(ctx: &Ctx, id: &str) -> AppResult> { + q( + &ctx.db, + "SELECT r.microvm_settings, r.microvm_settings_at, r.microvm_settings_by, \ + u.name AS by_name, u.avatar_url AS by_avatar FROM runners r \ + LEFT JOIN users u ON u.id = r.microvm_settings_by WHERE r.id = ?", + &[s(id)], + )? + .first() + .await +} + +/// `GET /api/v1/runners/{id}/microvms`: for those who see the runner, how +/// its microVMs are, with the sessions of them they may see; for those who +/// manage it, their settings too. +pub async fn get(ctx: &mut Ctx, id: &str) -> AppResult { + http::ok(&view(ctx, id).await?) +} + +async fn view(ctx: &Ctx, id: &str) -> AppResult { + let runner = visible_runner(ctx, id).await?; + let manage = require_manager(ctx, id).await.is_ok(); + let row = settings_of(ctx, id).await?; + let report = match internal::fleet_stub(&ctx.env) { + Ok(stub) => internal::post::<_, internal::MicrovmsReport>( + &stub, + "/microvms-report", + &internal::MicrovmsReportOf { + runner_id: id.to_owned(), + }, + ) + .await + .ok() + .and_then(|r| r.report), + Err(_) => None, + } + // Before it connected, what its hello said last. + .or(runner.microvms.clone()); + let ids: Vec = report + .iter() + .flat_map(|r| r.vms.iter()) + .filter_map(|v| v.session.as_ref().map(|s| s.0.clone())) + .collect(); + let sessions = sessions(&ctx.db, &ids, manage, &ctx.user()?.id).await?; + let (settings, updated_at, updated_by) = match (manage, row) { + (true, Some(row)) => ( + row.microvm_settings + .as_deref() + .and_then(|t| serde_json::from_str::(t).ok()), + row.microvm_settings_at, + row.microvm_settings_by.map(|id| UserRef { + id: fctl_proto::UserId(id), + name: row.by_name.unwrap_or_default(), + avatar_url: row.by_avatar, + }), + ), + _ => (None, None, None), + }; + Ok(RunnerMicrovms { + runner: RunnerId(id.to_owned()), + settings, + updated_at, + updated_by, + report, + sessions, + manage, + }) +} + +/// The sessions of `ids` that `user` sees: every one for those who manage +/// the runner (its workspace's admins, or its owner), their own for others. +async fn sessions( + db: &worker::D1Database, + ids: &[String], + manage: bool, + user: &str, +) -> AppResult> { + #[derive(serde::Deserialize)] + struct Row { + id: String, + #[serde(deserialize_with = "crate::db::int")] + number: i64, + title: String, + status: String, + project_slug: String, + project_name: String, + created_by: Option, + } + if ids.is_empty() { + return Ok(Vec::new()); + } + let mut out = Vec::new(); + // D1 takes up to 100 bound values in a statement. + for chunk in ids.chunks(90) { + let marks = vec!["?"; chunk.len()].join(","); + let args: Vec<_> = chunk.iter().map(|i| s(i)).collect(); + let rows: Vec = q( + db, + &format!( + "SELECT s.id, s.number, s.title, s.status, s.created_by, p.slug AS project_slug, \ + p.name AS project_name FROM sessions s JOIN projects p ON p.id = s.project_id \ + WHERE s.id IN ({marks})" + ), + &args, + )? + .all() + .await?; + out.extend( + rows.into_iter() + .filter(|r| manage || r.created_by.as_deref() == Some(user)) + .map(|r| MicrovmSessionRef { + id: SessionId(r.id), + number: u32::try_from(r.number).unwrap_or(0), + title: r.title, + project_slug: r.project_slug, + project_name: r.project_name, + status: SessionStatus::parse(&r.status).unwrap_or(SessionStatus::Stopped), + }), + ); + } + Ok(out) +} + +/// `PUT /api/v1/runners/{id}/microvms`: sets the settings of a runner's +/// microVMs, for those who manage it. A sensitive action, as adding a +/// runner is: they say what runs everyone's sessions there. +pub async fn put(ctx: &mut Ctx, req: &mut Request, id: &str) -> AppResult { + let body: PutRunnerMicrovmsRequest = http::body(req).await?; + let runner = require_manager(ctx, id).await?; + let seen = visible_runner(ctx, id).await?; + if seen.driver.as_deref().is_some_and(|d| d != DRIVER) { + return Err(conflict(&format!( + "{} runs sessions with the {} driver: only a runner whose host uses the lambda driver runs them in AWS Lambda microVMs", + runner.name, + seen.driver.as_deref().unwrap_or("other") + ))); + } + if let Err(e) = fctl_domain::microvm::check(&body.settings) { + return Err(crate::error::validation( + &format!("settings.{}", e.field), + &e.message, + )); + } + ctx.verified(fctl_domain::verify::Sensitive::AddRunner)?; + let user = ctx.user()?.id.clone(); + let text = serde_json::to_string(&body.settings)?; + q( + &ctx.db, + "UPDATE runners SET microvm_settings = ?, microvm_settings_at = ?, microvm_settings_by = ? WHERE id = ?", + &[s(&text), n(now_ms()), s(&user), s(id)], + )? + .run() + .await?; + let workspace = runner.workspace_id.clone(); + ctx.audit_in( + workspace.as_deref(), + "runner.microvms_updated", + Some(id), + Some(serde_json::to_value(&body.settings)?), + ); + // Its host gets them now, and FleetDO places sessions with them. + let env = ctx.env.clone(); + let (runner_id, settings) = (id.to_owned(), body.settings.clone()); + ctx.defer(async move { + let stub = internal::fleet_stub(&env)?; + let _: serde_json::Value = internal::post( + &stub, + "/runner-microvms", + &internal::RunnerMicrovms { + runner_id, + settings: Some(settings), + }, + ) + .await?; + Ok(()) + }); + http::ok(&view(ctx, id).await?) +} + +#[cfg(all(test, target_arch = "wasm32"))] +mod tests { + use super::*; + use crate::model::{RUNNER_SELECT, RunnerRow, RunnerView}; + use crate::testing; + use wasm_bindgen_test::wasm_bindgen_test; + + async fn seed(db: &worker::D1Database) -> AppResult<()> { + let hello = serde_json::json!({ + "protocol": 1, "version": "0.40.0", "hostname": "fctl-microvms", "os": "linux", + "arch": "aarch64", "cpus": 2, "memory_mb": 4096, "drivers": [], "driver": "lambda", + "capacity": 20, "labels": [], "sessions": [], + "microvms": { + "region": "us-east-1", "configured": true, "running": 2, "suspended": 3, + "warm": 2, "changing": 0, "max": 20, + "vms": [{ "id": "mvm-1", "state": "running", "since": 1, "started_at": 1, "ends_at": 2 }] + } + }); + let settings = serde_json::json!({ + "image": { "kind": "own", "arn": "arn:aws:lambda:us-east-1:123456789012:microvm-image:agents" }, + "memory_mb": 2048, "suspend_after_secs": 90, "terminate_after_minutes": 60, + "warm": 2, "max_microvms": 20 + }); + for (sql, args) in [ + ( + "INSERT INTO users (id, email, name, created_at, updated_at) VALUES ('usr_ada', 'ada@example.com', 'Ada', 0, 0), ('usr_bo', 'bo@example.com', 'Bo', 0, 0)", + vec![], + ), + ( + "INSERT INTO workspaces (id, slug, name, created_at, updated_at) VALUES ('wsp_acme', 'acme', 'Acme', 0, 0)", + vec![], + ), + ( + "INSERT INTO workspace_members (workspace_id, user_id, email, role, created_at) VALUES ('wsp_acme', 'usr_ada', 'ada@example.com', 'admin', 0), ('wsp_acme', 'usr_bo', 'bo@example.com', 'member', 0)", + vec![], + ), + ( + "INSERT INTO runners (id, name, token_hash, enabled, info, created_at, workspace_id, microvm_settings, microvm_settings_at, microvm_settings_by) \ + VALUES ('rnr_mvm', 'microvms', 'hash', 1, ?, 0, 'wsp_acme', ?, 5, 'usr_ada')", + vec![s(&hello.to_string()), s(&settings.to_string())], + ), + ( + "INSERT INTO runner_workspaces (runner_id, workspace_id, created_at) VALUES ('rnr_mvm', 'wsp_acme', 0)", + vec![], + ), + ( + "INSERT INTO projects (id, slug, name, created_by, created_at, updated_at, workspace_id) VALUES ('prj_web', 'web', 'Web', 'usr_ada', 0, 0, 'wsp_acme')", + vec![], + ), + ( + "INSERT INTO sessions (id, project_id, number, title, prompt, status, created_by, claude_session_id, created_at, updated_at) VALUES \ + ('ses_a', 'prj_web', 12, 'Retry uploads', 'x', 'idle', 'usr_ada', 'c1', 0, 0), \ + ('ses_b', 'prj_web', 13, 'Fix the login test', 'x', 'running', 'usr_bo', 'c2', 0, 0)", + vec![], + ), + ] { + q(db, sql, &args)?.run().await?; + } + Ok(()) + } + + /// The runners list shows a microVM runner's counts, without its + /// microVMs, to everyone who sees it, and whether it has settings to + /// those who manage it. + #[wasm_bindgen_test] + async fn runners_say_how_their_microvms_are() -> AppResult<()> { + let db = testing::database(); + seed(&db).await?; + let rows: Vec = q(&db, &format!("{RUNNER_SELECT} WHERE r.id = 'rnr_mvm'"), &[])? + .all() + .await?; + let row = rows.first().ok_or_else(|| not_found("Runner"))?; + let workspaces = ["wsp_acme".to_owned()]; + let admin = RunnerView { + user_id: Some("usr_ada"), + workspaces: Some(&workspaces), + admin_of: Some(&workspaces), + }; + let member = RunnerView { + user_id: Some("usr_bo"), + workspaces: Some(&workspaces), + admin_of: Some(&[]), + }; + let live = internal::LiveRunners::default(); + let seen = row.to_runner(&live, &admin); + let report = seen.microvms.clone().ok_or_else(|| not_found("report"))?; + assert_eq!((report.running, report.suspended, report.warm), (2, 3, 2)); + assert!(report.vms.is_empty(), "the list leaves the microVMs out"); + assert_eq!(seen.microvms_configured, Some(true)); + let by_member = row.to_runner(&live, &member); + assert!(by_member.microvms.is_some()); + assert_eq!(by_member.microvms_configured, None); + Ok(()) + } + + /// Those who manage the runner see every session its microVMs run; + /// others only their own. + #[wasm_bindgen_test] + async fn the_sessions_of_its_microvms_are_for_those_who_may_see_them() -> AppResult<()> { + let db = testing::database(); + seed(&db).await?; + let ids = [ + "ses_a".to_owned(), + "ses_b".to_owned(), + "ses_gone".to_owned(), + ]; + let all = sessions(&db, &ids, true, "usr_ada").await?; + let mut titles: Vec<&str> = all.iter().map(|s| s.title.as_str()).collect(); + titles.sort_unstable(); + assert_eq!(titles, ["Fix the login test", "Retry uploads"]); + let mine = sessions(&db, &ids, false, "usr_bo").await?; + let seen: Vec<(u32, &str, SessionStatus)> = mine + .iter() + .map(|s| (s.number, s.project_slug.as_str(), s.status)) + .collect(); + assert_eq!(seen, [(13, "web", SessionStatus::Running)]); + assert!(sessions(&db, &[], true, "usr_ada").await?.is_empty()); + Ok(()) + } +} diff --git a/crates/fctl-control/src/api/mod.rs b/crates/fctl-control/src/api/mod.rs index 651d5d038..a1ba8fb87 100644 --- a/crates/fctl-control/src/api/mod.rs +++ b/crates/fctl-control/src/api/mod.rs @@ -16,6 +16,7 @@ pub mod hooks; pub mod kept_images; pub mod linear; pub mod memories; +pub mod microvms; pub mod notifications; pub mod passkeys; pub mod projects; diff --git a/crates/fctl-control/src/api/runners.rs b/crates/fctl-control/src/api/runners.rs index e0a18749e..eeb445e28 100644 --- a/crates/fctl-control/src/api/runners.rs +++ b/crates/fctl-control/src/api/runners.rs @@ -146,7 +146,7 @@ async fn managed(ctx: &Ctx, id: &str) -> AppResult { /// remove): who registered it, the admins of the workspace it belongs to, /// or an instance admin (`fctl_domain::workspace::can_manage_runner`). A /// new token is for its owners alone ([`rotate_token`]). -async fn require_manager(ctx: &Ctx, id: &str) -> AppResult { +pub(crate) async fn require_manager(ctx: &Ctx, id: &str) -> AppResult { let runner = managed(ctx, id).await?; let owner = runner.owner(ctx).await?; if fctl_domain::workspace::can_manage_runner(owner, ctx.user()?.is_admin()) { @@ -160,6 +160,24 @@ async fn require_manager(ctx: &Ctx, id: &str) -> AppResult { })) } +/// A runner the caller sees, as they see it; not found otherwise. +pub(crate) async fn visible_runner(ctx: &Ctx, id: &str) -> AppResult { + let viewer = Viewer::instance(ctx).await?; + let view = viewer.view(); + let rows: Vec = q( + &ctx.db, + &format!("{RUNNER_SELECT} WHERE r.id = ?"), + &[s(id)], + )? + .all() + .await?; + let row = rows + .first() + .filter(|r| r.visible_to(&view)) + .ok_or_else(|| not_found("Runner"))?; + Ok(row.to_runner(&live(ctx).await, &view)) +} + /// One runner as the caller sees it. async fn one(ctx: &Ctx, id: &str, live: &LiveRunners) -> AppResult { let viewer = Viewer::instance(ctx).await?; diff --git a/crates/fctl-control/src/do_fleet.rs b/crates/fctl-control/src/do_fleet.rs index 873741339..93844f71e 100644 --- a/crates/fctl-control/src/do_fleet.rs +++ b/crates/fctl-control/src/do_fleet.rs @@ -18,6 +18,7 @@ use fctl_domain::reconcile::{self, Known, Unassigned}; use fctl_domain::schedule::{Home, Slot, TokenWait, Unready, Wait}; use fctl_proto::api::{ClaudeLoginJob, ClaudeLoginState, FeedServer, Placement}; use fctl_proto::event::{Notice, NoticeLevel}; +use fctl_proto::microvm::FEATURE_MICROVMS; use fctl_proto::runner::{ ClaudeLoginUpdate, CredentialKind, DriverInfo, FEATURE_DRIVERS, FEATURE_REVIEWS, FEATURE_SNAPSHOTS, FEATURE_TRIAGE, FleetToHost, HostHello, HostSessionReport, HostToFleet, @@ -196,6 +197,12 @@ struct LiveRow { /// Its enrollment token removes it once it has been offline this long. #[serde(default)] remove_after_ms: Option, + /// The sessions its last heartbeat reported (JSON). + #[serde(default)] + sessions: Option, + /// Its microVM settings have it take sessions before other runners. + #[serde(default)] + microvms_first: Option, } impl LiveRow { @@ -314,6 +321,8 @@ struct Candidate { /// bucket it keeps them in, under its prefix, if it has one of its own. snapshots: bool, snapshot_bucket: Option, + /// Its microVM settings have it take sessions before other runners. + first: bool, } /// Whose sessions a runner runs, and the pool it is in, as D1 had it at @@ -387,6 +396,7 @@ impl Candidate { .as_ref() .map(|(driver, why)| Unready { driver, why }), packed: self.packed, + first: self.first, } } } @@ -516,6 +526,10 @@ impl DurableObject for FleetObject { // What its sessions were told about its disk (JSON, // `fctl_domain::disk::Told`). add_column(&sql, "runners", "disk_told", "TEXT"); + // What its host said last of its microVMs, with every one (JSON, + // `MicrovmReport`), and whether its settings have it go first. + add_column(&sql, "runners", "microvms", "TEXT"); + add_column(&sql, "runners", "microvms_first", "INTEGER"); // What a sign-in needs to go on to another runner (`LoginRow`). add_column(&sql, "logins", "runners", "TEXT"); add_column(&sql, "logins", "user", "TEXT"); @@ -588,6 +602,23 @@ impl DurableObject for FleetObject { } Err(e) => Err(ApiError::bad_request(e.to_string())), }, + (worker::Method::Post, "/runner-microvms") => { + match req.json::().await { + Ok(b) => { + self.microvms_changed(&b.runner_id, b.settings, None).await; + self.feed_runner(&b.runner_id).await; + self.dispatch().await; + Ok(serde_json::json!({ "ok": true })) + } + Err(e) => Err(ApiError::bad_request(e.to_string())), + } + } + (worker::Method::Post, "/microvms-report") => { + match req.json::().await { + Ok(b) => Ok(serde_json::json!(self.microvms_report(&b.runner_id))), + Err(e) => Err(ApiError::bad_request(e.to_string())), + } + } (worker::Method::Post, "/sweep") => { let forgot = self.sweep().await; Ok(serde_json::json!({ "removed": forgot })) @@ -849,7 +880,7 @@ impl FleetObject { fn live_rows(&self) -> Vec { self.sql .exec( - "SELECT id, name, hello, connected, last_seen, memory_available_mb, disk_available_mb, draining_since, drained_by, remove_after_ms FROM runners", + "SELECT id, name, hello, connected, last_seen, memory_available_mb, disk_available_mb, draining_since, drained_by, remove_after_ms, sessions, microvms_first FROM runners", None, ) .and_then(|c| c.to_array::()) @@ -1256,6 +1287,8 @@ impl FleetObject { let token_changed = self.note_claude_token(&rs.id, hb.claude_token).await; let drivers_changed = self.note_drivers(&rs.id, hb.drivers).await; let store_changed = self.note_snapshot_store(&rs.id, hb.snapshot_store).await; + let capacity_changed = self.note_capacity(&rs.id, hb.capacity).await; + let microvms_changed = self.note_microvms(&rs.id, hb.microvms).await; let (told, tell) = fctl_domain::disk::heard( &disk.told, &rs.name, @@ -1282,6 +1315,8 @@ impl FleetObject { if token_changed || drivers_changed || store_changed + || capacity_changed + || microvms_changed || room(hb.disk_available_mb) != room(disk.free_mb) { self.feed_runner(&rs.id).await; @@ -1436,6 +1471,23 @@ impl FleetObject { if let Ok(text) = serde_json::to_string(&Self::welcome(rs, now)) { let _ = ws.send_with_str(&text); } + // A host of microVMs runs them with its runner's settings. + if hello.features.iter().any(|f| f == FEATURE_MICROVMS) { + if let Some(report) = &hello.microvms { + let _ = self.sql.exec( + "UPDATE runners SET microvms = ? WHERE id = ?", + Some(vec![ + sv(&serde_json::to_string(report).unwrap_or_default()), + sv(&rs.id), + ]), + ); + } + // What D1 didn't say, the host goes on without: it keeps its own. + match self.microvm_settings(&rs.id).await { + Ok(settings) => self.microvms_changed(&rs.id, settings, Some(ws)).await, + Err(e) => worker::console_error!("{}'s microVM settings: {e}", rs.name), + } + } self.reconcile(rs, &hello.sessions, now).await; self.stop_idle_if_draining(&rs.id, &hello.sessions).await; self.feed_runner(&rs.id).await; @@ -1573,6 +1625,128 @@ impl FleetObject { .await } + /// Notes how many sessions a runner runs at once, from a heartbeat that + /// says it: a host of microVMs follows its runner's settings. Whether + /// it changed. + async fn note_capacity(&self, runner_id: &str, capacity: Option) -> bool { + let Some(capacity) = capacity else { + return false; + }; + self.change_hello(runner_id, |hello| { + if hello.capacity == capacity { + return false; + } + hello.capacity = capacity; + true + }) + .await + } + + /// Keeps what a heartbeat says of a runner's microVMs: all of it here, + /// for the runner's page, and its counts in the hello, for the runners + /// list. Whether the counts changed. + async fn note_microvms( + &self, + runner_id: &str, + report: Option, + ) -> bool { + let Some(report) = report else { return false }; + let _ = self.sql.exec( + "UPDATE runners SET microvms = ? WHERE id = ?", + Some(vec![ + sv(&serde_json::to_string(&report).unwrap_or_default()), + sv(runner_id), + ]), + ); + let summary = report.summary(); + self.change_hello(runner_id, |hello| { + if hello.microvms.as_ref() == Some(&summary) { + return false; + } + hello.microvms = Some(summary); + true + }) + .await + } + + /// The settings of a runner's microVMs, from D1. + /// A runner's microVM settings in D1: `None` where it has none, an + /// error where D1 didn't say, which leaves its host with what it has. + async fn microvm_settings( + &self, + runner_id: &str, + ) -> std::result::Result, String> { + #[derive(Deserialize)] + struct Row { + microvm_settings: Option, + } + let db = self.env.d1("DB").map_err(|e| e.to_string())?; + let row: Option = crate::db::q( + &db, + "SELECT microvm_settings FROM runners WHERE id = ?", + &[crate::db::s(runner_id)], + ) + .map_err(|e| e.0.message)? + .first() + .await + .map_err(|e| e.0.message)?; + match row.and_then(|r| r.microvm_settings) { + None => Ok(None), + Some(text) => serde_json::from_str(&text) + .map(Some) + .map_err(|e| format!("its settings don't read: {e}")), + } + } + + /// Sends a runner's host its microVM settings, and places sessions with + /// them: on `ws`, the connection that said hello, or the runner's. + async fn microvms_changed( + &self, + runner_id: &str, + settings: Option, + ws: Option<&WebSocket>, + ) { + let first = settings.as_ref().is_some_and(|s| s.first); + let _ = self.sql.exec( + "UPDATE runners SET microvms_first = ? WHERE id = ?", + Some(vec![iv(i64::from(first)), sv(runner_id)]), + ); + let msg = FleetToHost::Microvms { settings }; + match ws { + Some(ws) => { + if let Ok(text) = serde_json::to_string(&msg) { + let _ = ws.send_with_str(&text); + } + } + None => { + self.send_runner(runner_id, &msg); + } + } + } + + /// What a runner's host said last of its microVMs. + fn microvms_report(&self, runner_id: &str) -> internal::MicrovmsReport { + #[derive(Deserialize)] + struct Row { + microvms: Option, + } + let report = self + .sql + .exec( + "SELECT microvms FROM runners WHERE id = ?", + Some(vec![sv(runner_id)]), + ) + .and_then(|c| c.to_array::()) + .ok() + .and_then(|rows| rows.into_iter().next()) + .and_then(|r| r.microvms) + .and_then(|t| serde_json::from_str(&t).ok()); + internal::MicrovmsReport { + report, + connected: self.runner_socket(runner_id).is_some(), + } + } + /// Changes the hello its host said last as `change` does, where that /// changes anything, here and in D1. Whether it did. async fn change_hello( @@ -2674,6 +2848,19 @@ impl FleetObject { .iter() .find(|c| c.runner_id == r.id) .map_or(0, |c| c.n as u32); + // A host of microVMs lets the longest suspended go to make + // room for a new session: those don't hold a place. + let suspended = match hello.features.iter().any(|f| f == FEATURE_MICROVMS) { + true => r + .sessions + .as_deref() + .and_then(|s| serde_json::from_str::>(s).ok()) + .map_or(0, |s| { + s.iter().filter(|r| r.suspended_since.is_some()).count() as u32 + }), + false => 0, + }; + let n = n.saturating_sub(suspended); let serves = self .runner_workspaces .borrow() @@ -2713,6 +2900,7 @@ impl FleetObject { .as_ref() .and_then(|s| fctl_domain::snapshots::Bucket::parse(&s.url).ok()), serves, + first: r.microvms_first.is_some_and(|f| f > 0.0), }) }) .collect() @@ -4191,6 +4379,7 @@ mod tests { packed: false, snapshots, snapshot_bucket: bucket.and_then(|b| fctl_domain::snapshots::Bucket::parse(b).ok()), + first: false, } } diff --git a/crates/fctl-control/src/do_session.rs b/crates/fctl-control/src/do_session.rs index 430994ddd..4cd811bf1 100644 --- a/crates/fctl-control/src/do_session.rs +++ b/crates/fctl-control/src/do_session.rs @@ -131,6 +131,10 @@ struct SocketInfo { /// An uplink: its host paused the sandbox, as it last said. #[serde(default)] sandbox_paused: Option, + /// An uplink: its host suspended the sandbox, a microVM, as it last + /// said. + #[serde(default)] + sandbox_suspended: Option, /// A viewer: when its access was last checked; an uplink: when its /// runner was. #[serde(default)] @@ -160,6 +164,7 @@ struct RunnerView { /// How short of disk it is, as FleetObject last said. disk: Option, sandbox_paused: Option, + sandbox_suspended: Option, } #[derive(Default)] @@ -2565,6 +2570,12 @@ impl SessionObject { { runner_fields.push_str(&format!(r#","sandbox_paused":{p}"#)); } + if let Some(s) = runner + .sandbox_suspended + .and_then(|s| serde_json::to_string(&s).ok()) + { + runner_fields.push_str(&format!(r#","sandbox_suspended":{s}"#)); + } format!( r#"{{"type":"snapshot","session":{session},"role":{role},"events":[{}],"has_more_before":{has_more_before},"next_seq":{},"live":[{live}],"viewers":{viewers},"runner_connected":{}{runner_fields}}}"#, events.join(","), @@ -3264,6 +3275,7 @@ impl SessionObject { UplinkUp::AgentLink { unreachable, paused, + suspended, } => { let unreachable = unreachable.map(|mut a| { clip(&mut a.reason, REASON_MAX_CHARS); @@ -3274,10 +3286,13 @@ impl SessionObject { p }); if let Ok(Some(mut info)) = ws.deserialize_attachment::() - && (info.agent_unreachable != unreachable || info.sandbox_paused != paused) + && (info.agent_unreachable != unreachable + || info.sandbox_paused != paused + || info.sandbox_suspended != suspended) { info.agent_unreachable = unreachable; info.sandbox_paused = paused; + info.sandbox_suspended = suspended; let _ = ws.serialize_attachment(&info); self.broadcast_runner(None); } @@ -3348,10 +3363,11 @@ impl SessionObject { agent_unreachable: None, disk, sandbox_paused: None, + sandbox_suspended: None, }, Some(info) => { - let (agent_unreachable, sandbox_paused) = info - .map(|i| (i.agent_unreachable, i.sandbox_paused)) + let (agent_unreachable, sandbox_paused, sandbox_suspended) = info + .map(|i| (i.agent_unreachable, i.sandbox_paused, i.sandbox_suspended)) .unwrap_or_default(); RunnerView { connected: true, @@ -3359,6 +3375,7 @@ impl SessionObject { agent_unreachable, disk, sandbox_paused, + sandbox_suspended, } } None => RunnerView { @@ -3367,6 +3384,7 @@ impl SessionObject { agent_unreachable: None, disk, sandbox_paused: None, + sandbox_suspended: None, }, } } @@ -3379,6 +3397,7 @@ impl SessionObject { agent_unreachable: view.agent_unreachable, disk: view.disk, sandbox_paused: view.sandbox_paused, + sandbox_suspended: view.sandbox_suspended, }) { self.broadcast(&text); } diff --git a/crates/fctl-control/src/internal.rs b/crates/fctl-control/src/internal.rs index cbca6ec1b..b98f54b16 100644 --- a/crates/fctl-control/src/internal.rs +++ b/crates/fctl-control/src/internal.rs @@ -446,6 +446,32 @@ pub struct WorkspacesChanged { pub user_ids: Vec, } +/// The settings of a runner's microVMs changed (`/runner-microvms`): its +/// host gets them at once, and FleetDO places sessions with them. +#[derive(Serialize, Deserialize)] +pub struct RunnerMicrovms { + pub runner_id: String, + #[serde(default)] + pub settings: Option, +} + +/// Asks FleetDO what a runner's host said last of its microVMs, with +/// every one of them (`/microvms-report`). +#[derive(Serialize, Deserialize)] +pub struct MicrovmsReportOf { + pub runner_id: String, +} + +/// What a runner's host said last of its microVMs, and whether it is +/// connected now. +#[derive(Serialize, Deserialize, Default)] +pub struct MicrovmsReport { + #[serde(default)] + pub report: Option, + #[serde(default)] + pub connected: bool, +} + /// A runner's workspaces or owner changed: feeds hear about it, and queued /// sessions may start on it (`/runner-changed`). #[derive(Serialize, Deserialize)] diff --git a/crates/fctl-control/src/lib.rs b/crates/fctl-control/src/lib.rs index 393cb13f0..fd08dbd58 100644 --- a/crates/fctl-control/src/lib.rs +++ b/crates/fctl-control/src/lib.rs @@ -562,6 +562,10 @@ async fn dispatch_rest( ) -> AppResult { use Method::*; match (method, segs) { + // A runner's AWS Lambda microVMs, as one sub-router. + (method, segs) if api::microvms::routes(segs) => { + Box::pin(api::microvms::route(ctx, req, method, segs)).await + } // Autopilots (experimental) (Get, ["autopilots", "asks"]) => api::autopilots::open_asks(ctx).await, (Get, ["projects", id, "autopilot"]) => api::autopilots::get(ctx, id).await, diff --git a/crates/fctl-control/src/model.rs b/crates/fctl-control/src/model.rs index 938757e8b..15d26fb52 100644 --- a/crates/fctl-control/src/model.rs +++ b/crates/fctl-control/src/model.rs @@ -1222,6 +1222,9 @@ pub struct RunnerRow { pub pending_until: Option, #[serde(deserialize_with = "opt_int", default)] pub remove_offline_after_minutes: Option, + /// It has microVM settings (`runners.microvm_settings`). + #[serde(deserialize_with = "int_bool", default)] + pub microvms_configured: bool, } /// Who looks at runners: what of a runner they see. @@ -1281,6 +1284,17 @@ impl RunnerRow { } } + /// Whether `view` manages it as a machine: its owner, the admins of the + /// workspace it belongs to, instance admins. + fn manager_sees(&self, view: &RunnerView) -> bool { + match (view.workspaces, &self.workspace_id, &self.created_by) { + (None, _, _) => true, + (Some(_), _, Some(owner)) => view.user_id == Some(owner.as_str()), + (Some(_), Some(w), None) => view.admin_of.is_some_and(|a| a.contains(w)), + (Some(_), None, None) => false, + } + } + /// What its host said of the machine as it enrolled. fn facts(&self) -> fctl_proto::api::RunnerFacts { self.facts @@ -1442,6 +1456,15 @@ impl RunnerRow { remove_offline_after_minutes: self .remove_offline_after_minutes .and_then(|h| u32::try_from(h).ok()), + microvms: hello + .as_ref() + .and_then(|h| h.microvms.as_ref()) + .map(|m| m.summary()), + // Whether it has settings is for those who set them. + microvms_configured: hello + .as_ref() + .filter(|h| h.driver == fctl_proto::microvm::DRIVER) + .and_then(|_| self.manager_sees(view).then_some(self.microvms_configured)), } } } @@ -1480,7 +1503,8 @@ pub const RUNNER_SELECT: &str = concat!( r.workspace_id, ow.slug AS owner_slug, ow.name AS owner_name, ow.color AS owner_color, \ ow.avatar_updated_at AS owner_avatar_at, r.enrollment_id, et.name AS enrollment_name, \ et.labels AS enrollment_labels, \ - r.enrolled_ip, r.enrolled_location, r.facts, r.pending_until, r.remove_offline_after_minutes \ + r.enrolled_ip, r.enrolled_location, r.facts, r.pending_until, r.remove_offline_after_minutes, \ + r.microvm_settings IS NOT NULL AS microvms_configured \ FROM runners r LEFT JOIN users u ON u.id = r.created_by \ LEFT JOIN workspaces ow ON ow.id = r.workspace_id \ LEFT JOIN enrollment_tokens et ON et.id = r.enrollment_id" diff --git a/crates/fctl-domain/src/lib.rs b/crates/fctl-domain/src/lib.rs index 0255a137a..534852f79 100644 --- a/crates/fctl-domain/src/lib.rs +++ b/crates/fctl-domain/src/lib.rs @@ -39,6 +39,7 @@ pub mod linear; pub mod memory; pub mod merge_checks; pub mod metadata; +pub mod microvm; pub mod models; pub mod naming; pub mod networks; diff --git a/crates/fctl-domain/src/microvm.rs b/crates/fctl-domain/src/microvm.rs new file mode 100644 index 000000000..ec7680ce0 --- /dev/null +++ b/crates/fctl-domain/src/microvm.rs @@ -0,0 +1,866 @@ +//! AWS Lambda MicroVMs (docs/architecture.md#aws-lambda-microvms): what a +//! runner's microVM settings may say, and when its host suspends, resumes, +//! lets go of and replaces its microVMs. The control plane checks the +//! settings with [`check`]; the host decides with the rest, which reads no +//! clock: callers pass `now`. +//! +//! A session's microVM runs while the session works. Once it has waited +//! `suspend_after_secs` with nothing running, the host saves the session's +//! snapshot and suspends the microVM ([`suspend_at`]); whatever comes for +//! the agent resumes it as it was. Suspended for `terminate_after_minutes` +//! ([`terminate_at`]), it goes: the session stops, and a message carries it +//! on in a new microVM, from its snapshot. Lambda ends every microVM +//! [`MAX_LIFETIME_SECS`] after it ran it, so the host doesn't resume one +//! with less than [`MIN_RUNWAY_MS`] left ([`resumes`]), and lets go of +//! those that near their end ([`ending`]). + +use crate::snapshots::Bucket; +use fctl_proto::Millis; +use fctl_proto::microvm::{ + DEFAULT_MAX_MICROVMS, DEFAULT_MEMORY_MB, DEFAULT_SUSPEND_AFTER_SECS, + DEFAULT_TERMINATE_AFTER_MINUTES, DEFAULT_WARM, MAX_LIFETIME_SECS, MAX_MICROVMS, MicrovmImage, + MicrovmSettings, SUSPEND_AFTER_SECS, TERMINATE_AFTER_MINUTES, WARM, microvm_size, +}; + +/// Settings for a runner with nothing chosen yet but where its image comes +/// from: the defaults. +pub fn defaults(image: MicrovmImage) -> MicrovmSettings { + MicrovmSettings { + image, + memory_mb: DEFAULT_MEMORY_MB, + arch: None, + execution_role_arn: None, + egress_connectors: Vec::new(), + kms_key_arn: None, + log_group: None, + suspend_after_secs: DEFAULT_SUSPEND_AFTER_SECS, + terminate_after_minutes: DEFAULT_TERMINATE_AFTER_MINUTES, + warm: DEFAULT_WARM, + max_microvms: DEFAULT_MAX_MICROVMS, + first: false, + } +} + +/// An ARN's parts: `arn:::::`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Arn<'a> { + pub partition: &'a str, + pub service: &'a str, + pub region: &'a str, + pub account: &'a str, + pub resource: &'a str, +} + +impl<'a> Arn<'a> { + /// Its parts, when it is an ARN of a partition AWS has (`aws`, + /// `aws-cn`, `aws-us-gov`, …). + pub fn parse(arn: &'a str) -> Option { + let mut parts = arn.splitn(6, ':'); + let ( + Some("arn"), + Some(partition), + Some(service), + Some(region), + Some(account), + Some(resource), + ) = ( + parts.next(), + parts.next(), + parts.next(), + parts.next(), + parts.next(), + parts.next(), + ) + else { + return None; + }; + let partition_ok = partition == "aws" + || partition.strip_prefix("aws-").is_some_and(|p| { + !p.is_empty() && p.bytes().all(|b| b.is_ascii_lowercase() || b == b'-') + }); + let region_ok = region + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-'); + (partition_ok && !service.is_empty() && region_ok && !resource.is_empty()).then_some(Self { + partition, + service, + region, + account, + resource, + }) + } +} + +fn account_id(account: &str) -> bool { + account.len() == 12 && account.bytes().all(|b| b.is_ascii_digit()) +} + +fn name_chars(name: &str, max: usize, extra: &[u8]) -> bool { + !name.is_empty() + && name.len() <= max + && name + .bytes() + .all(|b| b.is_ascii_alphanumeric() || extra.contains(&b)) +} + +/// Whether `name` may name a microVM image: 1 to 64 letters, digits, `-` +/// and `_`. +pub fn image_name(name: &str) -> bool { + name_chars(name, 64, b"-_") +} + +/// A microVM image's ARN: `arn:aws:lambda:::microvm-image:`. +pub fn image_arn(arn: &str) -> Option> { + let a = Arn::parse(arn)?; + let name = a.resource.strip_prefix("microvm-image:")?; + (a.service == "lambda" && !a.region.is_empty() && account_id(a.account) && image_name(name)) + .then_some(a) +} + +/// An IAM role's ARN: `arn:aws:iam:::role/`. +pub fn role_arn(arn: &str) -> Option> { + let a = Arn::parse(arn)?; + let name = a.resource.strip_prefix("role/")?; + (a.service == "iam" + && a.region.is_empty() + && account_id(a.account) + && name_chars(name, 512, b"+=,.@_-/")) + .then_some(a) +} + +/// A network connector's ARN: Lambda's own +/// (`arn:aws:lambda::aws:network-connector:aws-network-connector:INTERNET_EGRESS`), +/// or one of the account's (`arn:aws:lambda:::network-connector:nc-…`, +/// with a version after it or not). +pub fn connector_arn(arn: &str) -> Option> { + let a = Arn::parse(arn)?; + let rest = a.resource.strip_prefix("network-connector:")?; + (a.service == "lambda" + && !a.region.is_empty() + && (a.account == "aws" || account_id(a.account)) + && name_chars(rest, 256, b"-_:")) + .then_some(a) +} + +/// A KMS key's ARN, or an alias's. +pub fn kms_arn(arn: &str) -> Option> { + let a = Arn::parse(arn)?; + let (kind, name) = a.resource.split_once('/')?; + (a.service == "kms" + && !a.region.is_empty() + && account_id(a.account) + && matches!(kind, "key" | "alias") + && name_chars(name, 256, b"-_/:")) + .then_some(a) +} + +/// Whether `group` may name a CloudWatch Logs log group. +pub fn log_group(group: &str) -> bool { + name_chars(group, 512, b"_-/.#") +} + +/// Lambda's own connector `name` (`HTTP_INGRESS`, `INTERNET_EGRESS`, …) in +/// `region` of `partition`. +pub fn lambda_connector(partition: &str, region: &str, name: &str) -> String { + format!("arn:{partition}:lambda:{region}:aws:network-connector:aws-network-connector:{name}") +} + +/// Lambda's managed base image for microVMs fctl builds, in `region`. +pub fn base_image(partition: &str, region: &str) -> String { + format!("arn:{partition}:lambda:{region}:aws:microvm-image:al2023-1") +} + +/// What's wrong with settings: the field, and why, in a sentence people +/// read beside it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Invalid { + pub field: &'static str, + pub message: String, +} + +fn invalid(field: &'static str, message: impl Into) -> Invalid { + Invalid { + field, + message: message.into(), + } +} + +fn within(value: u32, (lo, hi): (u32, u32)) -> bool { + (lo..=hi).contains(&value) +} + +/// Checks a runner's microVM settings, the first problem first. +pub fn check(s: &MicrovmSettings) -> Result<(), Invalid> { + // Where they run: the image's region, and the others must agree. + let mut regions: Vec<(String, &'static str)> = Vec::new(); + match &s.image { + MicrovmImage::Own { arn, version } => { + let Some(a) = image_arn(arn) else { + return Err(invalid( + "image.arn", + "Enter a microVM image's ARN: arn:aws:lambda:::microvm-image:", + )); + }; + regions.push((a.region.to_owned(), "image.arn")); + if version + .as_deref() + .is_some_and(|v| v.is_empty() || v.len() > 64 || v.contains(char::is_whitespace)) + { + return Err(invalid( + "image.version", + "Enter the image's version, as Lambda numbers it: 1.0, 2.0, …", + )); + } + } + MicrovmImage::Managed { + artifacts, + build_role_arn, + name, + } => { + if let Err(e) = Bucket::parse(artifacts) { + return Err(invalid( + "image.artifacts", + format!("Enter an S3 location: s3://bucket/prefix ({e})"), + )); + } + if role_arn(build_role_arn).is_none() { + return Err(invalid( + "image.build_role_arn", + "Enter an IAM role's ARN: arn:aws:iam:::role/", + )); + } + if name.as_deref().is_some_and(|n| !image_name(n)) { + return Err(invalid( + "image.name", + "An image's name is 1 to 64 letters, digits, hyphens and underscores", + )); + } + } + } + if microvm_size(s.memory_mb).is_none() { + return Err(invalid( + "memory_mb", + "Choose one of the sizes microVMs come in: 512 MiB, 1, 2, 4 or 8 GiB", + )); + } + if let Some(role) = &s.execution_role_arn + && role_arn(role).is_none() + { + return Err(invalid( + "execution_role_arn", + "Enter an IAM role's ARN: arn:aws:iam:::role/", + )); + } + if s.egress_connectors.len() > 10 { + return Err(invalid( + "egress_connectors", + "A microVM takes at most 10 egress connectors", + )); + } + for c in &s.egress_connectors { + let Some(a) = connector_arn(c) else { + return Err(invalid( + "egress_connectors", + format!( + "{c} isn't a network connector's ARN: arn:aws:lambda:::network-connector:" + ), + )); + }; + regions.push((a.region.to_owned(), "egress_connectors")); + } + if let Some(key) = &s.kms_key_arn { + let Some(a) = kms_arn(key) else { + return Err(invalid( + "kms_key_arn", + "Enter a KMS key's or alias's ARN: arn:aws:kms:::key/", + )); + }; + regions.push((a.region.to_owned(), "kms_key_arn")); + } + if let Some((first, by)) = regions.first() + && let Some((other, field)) = regions.iter().find(|(r, _)| r != first) + { + return Err(invalid( + field, + format!( + "This is in {other}, and the {} in {first}: they must be in one region", + noun(by) + ), + )); + } + if s.log_group.as_deref().is_some_and(|g| !log_group(g)) { + return Err(invalid( + "log_group", + "A log group's name is letters, digits and _-/.#, up to 512 of them", + )); + } + if !within(s.suspend_after_secs, SUSPEND_AFTER_SECS) { + return Err(invalid( + "suspend_after_secs", + "Suspend after 60 seconds to an hour with nothing running", + )); + } + if !within(s.terminate_after_minutes, TERMINATE_AFTER_MINUTES) { + return Err(invalid( + "terminate_after_minutes", + "Let suspended microVMs go after 5 minutes to 7 hours", + )); + } + if !within(s.warm, WARM) { + return Err(invalid("warm", "Keep 0 to 20 microVMs warm")); + } + if !within(s.max_microvms, MAX_MICROVMS) { + return Err(invalid("max_microvms", "Allow 1 to 1,000 microVMs at once")); + } + if s.warm > s.max_microvms { + return Err(invalid( + "warm", + "Keep no more microVMs warm than the runner may have at once", + )); + } + Ok(()) +} + +fn noun(field: &str) -> &'static str { + match field { + "image.arn" => "image", + "egress_connectors" => "first egress connector", + "kms_key_arn" => "KMS key", + _ => "rest", + } +} + +/// The region of the settings' microVMs, where an ARN says it: the image's +/// of your own, else the first connector's or the key's. +pub fn region(s: &MicrovmSettings) -> Option { + let own = match &s.image { + MicrovmImage::Own { arn, .. } => image_arn(arn).map(|a| a.region.to_owned()), + MicrovmImage::Managed { .. } => None, + }; + own.or_else(|| { + s.egress_connectors + .iter() + .find_map(|c| connector_arn(c).map(|a| a.region.to_owned())) + }) + .or_else(|| { + s.kms_key_arn + .as_deref() + .and_then(kms_arn) + .map(|a| a.region.to_owned()) + }) +} + +/// How long a session's agent waits, with nothing running, before it stops +/// by itself, on a runner whose host suspends its microVM: until after its +/// host would have let the microVM go, so that the host decides. Its agent +/// counts on as the microVM resumes, and a message comes then. +pub fn agent_idle_timeout_secs(s: &MicrovmSettings) -> u64 { + u64::from(s.suspend_after_secs) + u64::from(s.terminate_after_minutes) * 60 + 5 * 60 +} + +/// When the host suspends a session's microVM that has waited with nothing +/// running since `quiet_since`. +pub fn suspend_at(quiet_since: Millis, s: &MicrovmSettings) -> Millis { + quiet_since + i64::from(s.suspend_after_secs) * 1000 +} + +/// When the host lets go of a microVM it suspended at `suspended_since`. +pub fn terminate_at(suspended_since: Millis, s: &MicrovmSettings) -> Millis { + suspended_since + i64::from(s.terminate_after_minutes) * 60_000 +} + +/// What Lambda's own idle policy says for the microVMs the host runs: it +/// never suspends one by itself (the host does, knowing when the session's +/// work is done), never resumes one for traffic (the host does, knowing +/// what comes), and terminates one suspended a while after the host would +/// have let it go, in case the host can't: its machine went away, say. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct IdlePolicy { + pub auto_resume: bool, + pub max_idle_secs: u32, + pub suspended_secs: u32, +} + +pub fn idle_policy(s: &MicrovmSettings) -> IdlePolicy { + IdlePolicy { + auto_resume: false, + max_idle_secs: MAX_LIFETIME_SECS, + suspended_secs: s.terminate_after_minutes * 60 + 10 * 60, + } +} + +/// The least a microVM must have left of its lifetime for a session to +/// resume in it, or to start in a warm one: an hour, so that a turn isn't +/// cut off by Lambda ending it. One with less goes, and the session +/// carries on in a new microVM, from its snapshot. +pub const MIN_RUNWAY_MS: Millis = 60 * 60 * 1000; + +/// How long before its end the host lets a microVM go, or, while its +/// session works, stops the session so that its agent saves its work. +pub const ENDING_MS: Millis = 10 * 60 * 1000; + +/// How old a warm microVM may get before the host replaces it, so that a +/// session that takes one has most of its lifetime: two hours. +pub const WARM_MAX_AGE_MS: Millis = 2 * 60 * 60 * 1000; + +/// How many microVMs the host starts at once for its warm pool. +pub const WARM_STARTS_AT_ONCE: usize = 3; + +/// When Lambda ends a microVM it ran at `started_at`. +pub fn ends_at(started_at: Millis) -> Millis { + started_at + i64::from(MAX_LIFETIME_SECS) * 1000 +} + +/// Whether a session may resume in a microVM Lambda ran at `started_at`. +pub fn resumes(started_at: Millis, now: Millis) -> bool { + ends_at(started_at) - now >= MIN_RUNWAY_MS +} + +/// Whether a microVM Lambda ran at `started_at` nears its end. +pub fn ending(started_at: Millis, now: Millis) -> bool { + ends_at(started_at) - now <= ENDING_MS +} + +/// What a microVM does, for the warm pool. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PoolState { + /// Being run, suspended or resumed: on its way to being warm, or to a + /// session. + Changing, + /// Warm and suspended: a session may take it. + Ready, + /// Going. + Going, +} + +/// A microVM of the host's that no session has, as the warm pool sees it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct WarmVm { + pub id: String, + pub state: PoolState, + pub started_at: Millis, + /// What it was run with ([`fingerprint`]): one run with other settings + /// than the runner's now is replaced. + pub fingerprint: String, +} + +/// What the warm pool does next: start this many microVMs, and let these +/// go. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct PoolPlan { + pub start: usize, + pub retire: Vec, +} + +/// What the warm pool does next, keeping `want` ready (the settings' +/// `warm`), within `room`: how many more microVMs the host may have now, +/// beside every one it has (`max_microvms` less those). A microVM run with +/// other settings than `fingerprint`, too old, or near its end, goes; starts +/// go [`WARM_STARTS_AT_ONCE`] at a time. +pub fn plan(warm: &[WarmVm], want: usize, room: usize, fingerprint: &str, now: Millis) -> PoolPlan { + let stale = |v: &WarmVm| { + v.fingerprint != fingerprint + || now - v.started_at >= WARM_MAX_AGE_MS + || !resumes(v.started_at, now) + }; + let retire: Vec = warm + .iter() + .filter(|v| v.state == PoolState::Ready && stale(v)) + .map(|v| v.id.clone()) + .collect(); + let kept = warm + .iter() + .filter(|v| v.state != PoolState::Going && !retire.contains(&v.id)) + .count(); + let changing = warm + .iter() + .filter(|v| v.state == PoolState::Changing) + .count(); + // Those that go free their place as they go; until then, they hold it. + let start = want + .saturating_sub(kept) + .min(room) + .min(WARM_STARTS_AT_ONCE.saturating_sub(changing)); + PoolPlan { start, retire } +} + +/// Of the warm microVMs, the one a session takes: ready, run with the +/// runner's settings now, with the most of its lifetime left. +pub fn pick_warm<'a>(warm: &'a [WarmVm], fingerprint: &str, now: Millis) -> Option<&'a WarmVm> { + warm.iter() + .filter(|v| { + v.state == PoolState::Ready + && v.fingerprint == fingerprint + && resumes(v.started_at, now) + }) + .max_by_key(|v| v.started_at) +} + +/// What a microVM was run with, as one string: microVMs run with the same +/// settings and image version have the same one. +pub fn fingerprint(s: &MicrovmSettings, image_version: &str) -> String { + let image = match &s.image { + MicrovmImage::Own { arn, .. } => arn.clone(), + MicrovmImage::Managed { name, .. } => name.clone().unwrap_or_default(), + }; + let mut connectors = s.egress_connectors.clone(); + connectors.sort(); + format!( + "{image}|{image_version}|{}|{}|{}|{}|{}", + s.execution_role_arn.as_deref().unwrap_or(""), + connectors.join(","), + s.kms_key_arn.as_deref().unwrap_or(""), + s.log_group.as_deref().unwrap_or(""), + s.terminate_after_minutes, + ) +} + +/// A session whose microVM is suspended, as the host weighs letting it go +/// to make room for a new one. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Suspended { + pub session: String, + /// Since when. + pub since: Millis, + /// Its snapshot was saved as it suspended: letting it go loses nothing. + pub checkpointed: bool, + /// Asked already to make room for another. + pub asked: bool, +} + +/// The session whose suspended microVM the host lets go to make room for a +/// new one: of those whose snapshot was saved and that weren't asked +/// already, the one suspended longest. `None`: none can go, and the new +/// session waits for room. +pub fn make_room(suspended: &[Suspended]) -> Option { + suspended + .iter() + .filter(|s| s.checkpointed && !s.asked) + .min_by_key(|s| (s.since, s.session.clone())) + .map(|s| s.session.clone()) +} + +/// "90 seconds", "2 minutes", "1 hour", "1h 30m": a span of seconds as the +/// transcript and the web app say it. +pub fn span(secs: u64) -> String { + let plural = |n: u64, unit: &str| { + if n == 1 { + format!("1 {unit}") + } else { + format!("{n} {unit}s") + } + }; + match secs { + s if s < 120 && s % 60 != 0 => plural(s, "second"), + s if s < 3600 => plural(s.div_ceil(60), "minute"), + s if s % 3600 == 0 => plural(s / 3600, "hour"), + s => format!("{}h {}m", s / 3600, (s % 3600) / 60), + } +} + +/// What a message to a session whose microVM went does: carries it on with +/// its snapshot, `kept`, or starts it again from its task and branch where +/// the session keeps none. +fn carries_on(kept: bool) -> &'static str { + if kept { + "A message carries it on in a new one, with its conversation and the work it hadn't pushed" + } else { + "A message starts it again in a new one, from its task and branch" + } +} + +/// Why a session on a runner of microVMs stopped once its host let its +/// suspended microVM go, `kept` whether its snapshot was. +pub fn let_go_reason(s: &MicrovmSettings, kept: bool) -> String { + format!( + "Stopped after its microVM was suspended for {}. {}", + span(u64::from(s.terminate_after_minutes) * 60), + carries_on(kept) + ) +} + +/// Why a session stopped as its microVM neared the end of its lifetime, +/// which Lambda would have cut it off at. +pub fn ending_reason(kept: bool) -> String { + format!( + "Stopped as its microVM neared the 8 hours Lambda gives one. {}", + carries_on(kept) + ) +} + +/// Why a session stopped to make room for a new one, on a runner with as +/// many microVMs as it may have: only one whose snapshot was kept does. +pub fn evicted_reason() -> String { + format!( + "Stopped to make room for a new session: its microVM had been suspended the longest. {}", + carries_on(true) + ) +} + +/// Why a session stopped when its suspended microVM wouldn't resume. +pub fn unresumed_reason(why: &str, kept: bool) -> String { + let next = if kept { + "the next run carries it on in a new one, with its conversation and the work it hadn't pushed" + } else { + "the next run starts it again in a new one, from its task and branch" + }; + format!("Its microVM couldn't be resumed ({why}): {next}") +} + +#[cfg(test)] +mod tests { + use super::*; + + fn managed() -> MicrovmImage { + MicrovmImage::Managed { + artifacts: "s3://acme-fctl/microvms".into(), + build_role_arn: "arn:aws:iam::123456789012:role/fctl-microvm-build".into(), + name: None, + } + } + + fn own(arn: &str) -> MicrovmImage { + MicrovmImage::Own { + arn: arn.into(), + version: None, + } + } + + const IMAGE: &str = "arn:aws:lambda:us-east-1:123456789012:microvm-image:fctl-sandbox"; + + #[test] + fn arns_are_read_by_their_parts() { + let a = image_arn(IMAGE); + assert_eq!(a.as_ref().map(|a| a.region), Some("us-east-1")); + assert_eq!(a.map(|a| a.account), Some("123456789012")); + assert!(image_arn("arn:aws:lambda:us-east-1:123456789012:function:x").is_none()); + assert!(image_arn("arn:aws:lambda:us-east-1:12345:microvm-image:x").is_none()); + assert!(image_arn("arn:aws:lambda:us-east-1:123456789012:microvm-image:a b").is_none()); + assert!(image_arn("arn:aws-cn:lambda:cn-north-1:123456789012:microvm-image:x").is_some()); + assert!(image_arn("arn:azure:lambda:us-east-1:123456789012:microvm-image:x").is_none()); + assert!(role_arn("arn:aws:iam::123456789012:role/service/fctl-microvms").is_some()); + assert!(role_arn("arn:aws:iam:us-east-1:123456789012:role/x").is_none()); + assert!(role_arn("arn:aws:iam::123456789012:user/x").is_none()); + let internet = lambda_connector("aws", "us-east-1", "INTERNET_EGRESS"); + assert_eq!( + internet, + "arn:aws:lambda:us-east-1:aws:network-connector:aws-network-connector:INTERNET_EGRESS" + ); + assert!(connector_arn(&internet).is_some()); + assert!( + connector_arn("arn:aws:lambda:us-east-1:123456789012:network-connector:nc-1a2b:3") + .is_some() + ); + assert!(kms_arn("arn:aws:kms:us-east-1:123456789012:alias/fctl").is_some()); + assert!(kms_arn("arn:aws:kms:us-east-1:123456789012:secret/x").is_none()); + assert!(log_group("/aws/lambda-microvms/fctl")); + assert!(!log_group("a b")); + } + + #[test] + fn the_defaults_check_and_bad_values_name_their_field() { + assert_eq!(check(&defaults(managed())), Ok(())); + assert_eq!(check(&defaults(own(IMAGE))), Ok(())); + let field = |s: MicrovmSettings| check(&s).err().map(|e| e.field); + assert_eq!(field(defaults(own("nope"))), Some("image.arn")); + let mut s = defaults(managed()); + s.memory_mb = 3000; + assert_eq!(field(s), Some("memory_mb")); + let mut s = defaults(managed()); + s.suspend_after_secs = 30; + assert_eq!(field(s), Some("suspend_after_secs")); + let mut s = defaults(managed()); + s.terminate_after_minutes = 480; + assert_eq!(field(s), Some("terminate_after_minutes")); + let mut s = defaults(managed()); + s.warm = 5; + s.max_microvms = 3; + assert_eq!(field(s), Some("warm")); + let mut s = defaults(managed()); + s.execution_role_arn = Some("arn:aws:iam::123456789012:policy/x".into()); + assert_eq!(field(s), Some("execution_role_arn")); + let mut s = defaults(managed()); + s.image = MicrovmImage::Managed { + artifacts: "https://example.com".into(), + build_role_arn: "arn:aws:iam::123456789012:role/b".into(), + name: None, + }; + assert_eq!(field(s), Some("image.artifacts")); + } + + #[test] + fn everything_runs_in_the_images_region() { + let mut s = defaults(own(IMAGE)); + s.egress_connectors = + vec!["arn:aws:lambda:eu-west-1:123456789012:network-connector:nc-1".into()]; + let e = check(&s).err(); + assert_eq!(e.as_ref().map(|e| e.field), Some("egress_connectors")); + assert_eq!( + e.map(|e| e.message), + Some( + "This is in eu-west-1, and the image in us-east-1: they must be in one region" + .into() + ) + ); + s.egress_connectors = + vec!["arn:aws:lambda:us-east-1:123456789012:network-connector:nc-1".into()]; + assert_eq!(check(&s), Ok(())); + assert_eq!(region(&s).as_deref(), Some("us-east-1")); + let mut s = defaults(managed()); + assert_eq!(region(&s), None); + s.kms_key_arn = Some("arn:aws:kms:eu-north-1:123456789012:key/k".into()); + assert_eq!(region(&s).as_deref(), Some("eu-north-1")); + } + + #[test] + fn suspending_and_letting_go_follow_the_settings() { + let s = defaults(managed()); + assert_eq!(suspend_at(1_000, &s), 91_000); + assert_eq!(terminate_at(0, &s), 3_600_000); + // The agent waits until after its host would have let it go. + assert_eq!(agent_idle_timeout_secs(&s), 90 + 3600 + 300); + let p = idle_policy(&s); + assert!(!p.auto_resume); + assert_eq!(p.max_idle_secs, 28_800); + assert_eq!(p.suspended_secs, 3600 + 600); + } + + #[test] + fn sessions_resume_only_where_an_hour_is_left() { + let ran = 0; + let hour = 3_600_000; + assert!(resumes(ran, 6 * hour)); + assert!(resumes(ran, 7 * hour)); + assert!(!resumes(ran, 7 * hour + 1)); + assert!(!ending(ran, 7 * hour)); + assert!(ending(ran, 8 * hour - ENDING_MS)); + assert_eq!(ends_at(ran), 8 * hour); + } + + fn vm(id: &str, state: PoolState, started_at: Millis, fingerprint: &str) -> WarmVm { + WarmVm { + id: id.into(), + state, + started_at, + fingerprint: fingerprint.into(), + } + } + + #[test] + fn the_pool_keeps_its_warm_microvms_fresh_within_its_room() { + let now = 10 * 3_600_000; + // Empty: starts what it wants, three at a time, within its room. + assert_eq!( + plan(&[], 2, 20, "a", now), + PoolPlan { + start: 2, + retire: vec![] + } + ); + assert_eq!(plan(&[], 5, 20, "a", now).start, WARM_STARTS_AT_ONCE); + assert_eq!(plan(&[], 5, 1, "a", now).start, 1); + // Settings changed: the old one goes, a new one starts. + let old = vm("mvm-old", PoolState::Ready, now - 60_000, "a"); + let p = plan(std::slice::from_ref(&old), 1, 5, "b", now); + assert_eq!( + p, + PoolPlan { + start: 1, + retire: vec!["mvm-old".into()] + } + ); + // Too old goes too. + let aged = vm("mvm-aged", PoolState::Ready, now - WARM_MAX_AGE_MS, "a"); + assert_eq!( + plan(&[aged], 1, 5, "a", now).retire, + vec!["mvm-aged".to_owned()] + ); + // Those on their way count; those going don't. + let warm = [ + vm("mvm-1", PoolState::Ready, now - 1000, "a"), + vm("mvm-2", PoolState::Changing, now - 10, "a"), + vm("mvm-3", PoolState::Going, now - 10, "a"), + ]; + assert_eq!(plan(&warm, 2, 5, "a", now), PoolPlan::default()); + assert_eq!(plan(&warm, 3, 5, "a", now).start, 1); + // No room, no start. + assert_eq!(plan(&warm, 3, 0, "a", now).start, 0); + } + + #[test] + fn a_session_takes_the_freshest_ready_one_run_with_the_settings_now() { + let now = 10 * 3_600_000; + let warm = [ + vm("mvm-1", PoolState::Ready, now - 50_000, "a"), + vm("mvm-2", PoolState::Ready, now - 10_000, "a"), + vm("mvm-3", PoolState::Ready, now - 1_000, "b"), + vm("mvm-4", PoolState::Changing, now - 100, "a"), + ]; + assert_eq!( + pick_warm(&warm, "a", now).map(|v| v.id.as_str()), + Some("mvm-2") + ); + assert_eq!(pick_warm(&warm, "c", now), None); + } + + #[test] + fn the_longest_suspended_whose_snapshot_was_saved_goes_once() { + let s = |session: &str, since, checkpointed, asked| Suspended { + session: session.into(), + since, + checkpointed, + asked, + }; + let mut suspended = vec![ + s("ses_b", 300, true, false), + // The longest, but its snapshot wasn't saved: it would lose + // its conversation, so it doesn't go. + s("ses_a", 100, false, false), + s("ses_c", 200, true, false), + ]; + assert_eq!(make_room(&suspended).as_deref(), Some("ses_c")); + // Asked already: the next start picks the next. + if let Some(c) = suspended.iter_mut().find(|x| x.session == "ses_c") { + c.asked = true; + } + assert_eq!(make_room(&suspended).as_deref(), Some("ses_b")); + if let Some(b) = suspended.iter_mut().find(|x| x.session == "ses_b") { + b.asked = true; + } + assert_eq!(make_room(&suspended), None); + } + + #[test] + fn fingerprints_change_with_what_a_microvm_is_run_with() { + let s = defaults(own(IMAGE)); + let a = fingerprint(&s, "1.0"); + assert_eq!(a, fingerprint(&s, "1.0")); + assert_ne!(a, fingerprint(&s, "2.0")); + let mut t = s.clone(); + t.execution_role_arn = Some("arn:aws:iam::123456789012:role/x".into()); + assert_ne!(a, fingerprint(&t, "1.0")); + // Suspending sooner doesn't change how one is run. + let mut u = s.clone(); + u.suspend_after_secs = 120; + assert_eq!(a, fingerprint(&u, "1.0")); + } + + #[test] + fn spans_read_as_people_say_them() { + assert_eq!(span(90), "90 seconds"); + assert_eq!(span(60), "1 minute"); + assert_eq!(span(600), "10 minutes"); + assert_eq!(span(3600), "1 hour"); + assert_eq!(span(7200), "2 hours"); + assert_eq!(span(5400), "1h 30m"); + assert_eq!( + let_go_reason(&defaults(managed()), true), + "Stopped after its microVM was suspended for 1 hour. A message carries it on in a new one, with its conversation and the work it hadn't pushed" + ); + // A workspace that keeps no snapshots: its sessions start again. + assert_eq!( + ending_reason(false), + "Stopped as its microVM neared the 8 hours Lambda gives one. A message starts it again in a new one, from its task and branch" + ); + } +} diff --git a/crates/fctl-domain/src/pools.rs b/crates/fctl-domain/src/pools.rs index e1d58868d..2d1e0c8c8 100644 --- a/crates/fctl-domain/src/pools.rs +++ b/crates/fctl-domain/src/pools.rs @@ -260,6 +260,7 @@ impl Pool { reviews: shape.reviews, unready: None, packed: self.info.placement == Placement::Packed, + first: false, }; schedule::could_run(&slot, q.labels, q.want, q.image, q.review, false) } diff --git a/crates/fctl-domain/src/schedule.rs b/crates/fctl-domain/src/schedule.rs index 52d89fb37..66a936ff2 100644 --- a/crates/fctl-domain/src/schedule.rs +++ b/crates/fctl-domain/src/schedule.rs @@ -41,6 +41,10 @@ pub struct Slot<'a> { /// the busiest with room, and only once no runner that spreads them /// can ([`pick`]). pub packed: bool, + /// It takes the sessions it could run before the other runners that + /// could: a runner of AWS Lambda microVMs whose settings say so + /// (`fctl_proto::microvm::MicrovmSettings::first`). + pub first: bool, } /// Why a runner's driver can't start sandboxes now. @@ -353,13 +357,19 @@ pub fn pick<'a>( } /// Which of two runners that could both take a session takes it first: one -/// that spreads sessions before one that packs them, so that a fixed fleet +/// whose settings say it goes first ([`Slot::first`]), then one that +/// spreads sessions before one that packs them, so that a fixed fleet /// runs what it can before a pool that grows adds machines; of two that /// spread, the less loaded; of two that pack, the busier, so that its /// other runners empty out and can go. Load is active sessions over /// capacity. pub fn placed_before(a: &Slot<'_>, b: &Slot<'_>) -> std::cmp::Ordering { use std::cmp::Ordering; + match (a.first, b.first) { + (true, false) => return Ordering::Less, + (false, true) => return Ordering::Greater, + _ => {} + } match (a.packed, b.packed) { (false, true) => Ordering::Less, (true, false) => Ordering::Greater, @@ -595,6 +605,7 @@ mod tests { reviews: false, unready: None, packed: false, + first: false, } } @@ -750,6 +761,27 @@ mod tests { )); } + #[test] + fn runners_that_go_first_take_what_they_can_before_the_others() { + let none: [String; 0] = []; + let fleet = slot("fleet", 4, 0, &none); + let microvms = Slot { + first: true, + ..slot("microvms", 20, 12, &none) + }; + assert_eq!(placed_before(µvms, &fleet), std::cmp::Ordering::Less); + assert_eq!( + placed_before(&fleet, µvms), + std::cmp::Ordering::Greater + ); + // Of two that go first, as any two. + let other = Slot { + first: true, + ..slot("other", 20, 2, &none) + }; + assert_eq!(placed_before(&other, µvms), std::cmp::Ordering::Less); + } + #[test] fn packed_pools_fill_their_busiest_runner_after_the_runners_that_spread() { let none: Vec = vec![]; diff --git a/crates/fctl-host/src/agentbin.rs b/crates/fctl-host/src/agentbin.rs index 3a8c3914d..1cd998c02 100644 --- a/crates/fctl-host/src/agentbin.rs +++ b/crates/fctl-host/src/agentbin.rs @@ -43,9 +43,33 @@ pub fn linux_agent_here(cfg: &HostConfig) -> Option { /// Where a download of fctl-agent of this version is kept. fn cached(cfg: &HostConfig) -> PathBuf { + cached_for(cfg, arch()) +} + +fn cached_for(cfg: &HostConfig, arch: &str) -> PathBuf { cfg.data_dir() .join("bin") - .join(format!("fctl-agent-{VERSION}-{}-linux", arch())) + .join(format!("fctl-agent-{VERSION}-{arch}-linux")) +} + +/// [`linux_agent`] for a sandbox of CPU architecture `arch` (`aarch64`, +/// `x86_64`), which may not be this machine's: an AWS Lambda microVM's, +/// say. Another architecture's is the release's, downloaded. +pub async fn linux_agent_for(cfg: &HostConfig, arch: &str) -> Result { + if arch == self::arch() { + return linux_agent(cfg).await; + } + let exe = std::env::current_exe()?; + let bundled = exe.with_file_name(asset_name(arch)); + if bundled.is_file() { + return Ok(bundled); + } + let cached = cached_for(cfg, arch); + if cached.is_file() { + return Ok(cached); + } + download(cfg, arch, &cached).await?; + Ok(cached) } pub async fn linux_agent(cfg: &HostConfig) -> Result { @@ -58,11 +82,19 @@ pub async fn linux_agent(cfg: &HostConfig) -> Result { if let Some(here) = linux_agent_here(cfg) { return Ok(here); } - let cache_dir = cfg.data_dir().join("bin"); let cached = cached(cfg); - std::fs::create_dir_all(&cache_dir)?; + download(cfg, arch(), &cached).await?; + Ok(cached) +} + +/// Downloads the release's fctl-agent for `arch` to `cached`, checked +/// against its `.sha256`. +async fn download(cfg: &HostConfig, arch: &str, cached: &std::path::Path) -> Result<()> { + if let Some(dir) = cached.parent() { + std::fs::create_dir_all(dir)?; + } let base = cfg.download_base.trim_end_matches('/'); - let url = format!("{base}/v{VERSION}/{}", asset_name(arch())); + let url = format!("{base}/v{VERSION}/{}", asset_name(arch)); tracing::info!("downloading {url}"); let http = fctl_client::HttpClient::new(std::time::Duration::from_secs(300)); let bytes = http @@ -89,6 +121,6 @@ pub async fn linux_agent(cfg: &HostConfig) -> Result { use std::os::unix::fs::PermissionsExt; std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o755))?; } - std::fs::rename(&tmp, &cached)?; - Ok(cached) + std::fs::rename(&tmp, cached)?; + Ok(()) } diff --git a/crates/fctl-host/src/aws.rs b/crates/fctl-host/src/aws.rs new file mode 100644 index 000000000..b94312b33 --- /dev/null +++ b/crates/fctl-host/src/aws.rs @@ -0,0 +1,242 @@ +//! AWS keys and regions for what the host asks of AWS itself, beside its +//! sessions' snapshots in a bucket of its own ([`crate::s3`]): the microVMs +//! of the `lambda` driver ([`crate::driver::lambda`]). The keys are the +//! machine's, where AWS's own tools look for them (the `AWS_*` variables, +//! a web identity, a container's credentials, the instance's role), or a +//! role's that those may assume (`[lambda] role_arn` in host.toml). + +use fctl_client::http::HttpClient; +use fctl_domain::sigv4::{self, Credentials}; +use http::Method; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +/// How long keys are used before they are asked for again: every source +/// makes new ones at least 5 minutes before the old expire, and a role's +/// last an hour. +const KEYS_FOR: Duration = Duration::from_secs(5 * 60); + +/// The domain AWS's endpoints are under in `region`'s partition. +pub fn dns_suffix(region: &str) -> &'static str { + if region.starts_with("cn-") { + "amazonaws.com.cn" + } else { + "amazonaws.com" + } +} + +/// `region`'s partition, as ARNs say it. +pub fn partition(region: &str) -> &'static str { + if region.starts_with("cn-") { + "aws-cn" + } else if region.starts_with("us-gov-") { + "aws-us-gov" + } else { + "aws" + } +} + +/// The region to work in: `configured`, else the `AWS_*` variables', else +/// the machine's own on EC2, else `us-east-1`. +pub async fn region(configured: Option<&str>) -> String { + if let Some(r) = configured.map(str::trim).filter(|r| !r.is_empty()) { + return r.to_owned(); + } + if let Some(r) = crate::s3::env_region() { + return r; + } + crate::s3::imds_region() + .await + .unwrap_or_else(|| "us-east-1".into()) +} + +/// A role the machine's keys assume, for what the host does. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Role { + pub arn: String, + /// What its trust policy may ask for (`sts:ExternalId`). + pub external_id: Option, +} + +/// Where keys come from, kept for a while once had. +pub struct Keys { + region: String, + role: Option, + http: HttpClient, + cached: Mutex>, +} + +impl std::fmt::Debug for Keys { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Keys") + .field("region", &self.region) + .field("role", &self.role) + .finish_non_exhaustive() + } +} + +impl Keys { + pub fn new(region: &str, role: Option) -> Self { + Self { + region: region.to_owned(), + role, + http: HttpClient::new(Duration::from_secs(30)), + cached: Mutex::new(None), + } + } + + /// Keys given as they are, for tests and stand-ins. + pub fn fixed(region: &str, creds: Credentials) -> Self { + let keys = Self::new(region, None); + if let Ok(mut c) = keys.cached.lock() { + *c = Some((creds, Instant::now() + Duration::from_secs(365 * 86_400))); + } + keys + } + + pub fn region(&self) -> &str { + &self.region + } + + /// The keys to sign with now. + pub async fn get(&self) -> Result { + if let Ok(cached) = self.cached.lock() + && let Some((creds, at)) = cached.as_ref() + && (at.elapsed() < KEYS_FOR || *at > Instant::now()) + { + return Ok(creds.clone()); + } + let machine = crate::s3::machine_credentials(&self.http, &self.region).await?; + let creds = match &self.role { + Some(role) => assume_role(&self.http, &self.region, &machine, role).await?, + None => machine, + }; + if let Ok(mut cached) = self.cached.lock() { + *cached = Some((creds.clone(), Instant::now())); + } + Ok(creds) + } + + /// Forgets the keys it had: AWS refused them. + pub fn forget(&self) { + if let Ok(mut cached) = self.cached.lock() + && cached.as_ref().is_some_and(|(_, at)| *at <= Instant::now()) + { + *cached = None; + } + } +} + +/// The form of an `AssumeRole` request to STS. +pub fn assume_role_form(role: &Role, session: &str) -> String { + let mut pairs = vec![ + ("Action", "AssumeRole"), + ("DurationSeconds", "3600"), + ("RoleArn", role.arn.as_str()), + ("RoleSessionName", session), + ("Version", "2011-06-15"), + ]; + if let Some(id) = &role.external_id { + pairs.push(("ExternalId", id.as_str())); + } + pairs + .iter() + .map(|(k, v)| format!("{k}={}", sigv4::encode(v, false))) + .collect::>() + .join("&") +} + +/// Has STS give `base`'s keys `role`'s, for an hour. +async fn assume_role( + http: &HttpClient, + region: &str, + base: &Credentials, + role: &Role, +) -> Result { + let host = format!("sts.{region}.{}", dns_suffix(region)); + let body = assume_role_form(role, "fctl-host"); + let content_type = "application/x-www-form-urlencoded; charset=utf-8"; + let signed = sigv4::sign( + &sigv4::Request { + method: "POST", + host: &host, + path: "/", + query: &[], + headers: &[("content-type", content_type)], + payload_sha256: &sigv4::sha256_hex(body.as_bytes()), + }, + base, + region, + "sts", + crate::expiry::now_ms(), + ); + let mut headers: Vec<(&str, &str)> = signed + .iter() + .map(|(n, v)| (n.as_str(), v.as_str())) + .collect(); + headers.push(("content-type", content_type)); + headers.push(("accept", "text/xml")); + let (status, _, answer) = http + .send_with( + Method::POST, + &format!("https://{host}/"), + &headers, + Some(body.into_bytes().into()), + ) + .await + .map_err(|e| format!("asking STS for {}'s keys: {e}", role.arn))?; + if !status.is_success() { + let code = crate::s3::xml_text(&answer, "Code").unwrap_or_else(|| status.to_string()); + let message = crate::s3::xml_text(&answer, "Message").unwrap_or_default(); + return Err(format!( + "STS wouldn't let this machine assume {}: {code} {message}", + role.arn + ) + .trim() + .to_owned()); + } + crate::s3::keys_from_xml(&answer).ok_or_else(|| "STS answered with no keys".into()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn partitions_and_their_domains_follow_the_region() { + assert_eq!(dns_suffix("us-east-1"), "amazonaws.com"); + assert_eq!(dns_suffix("cn-north-1"), "amazonaws.com.cn"); + assert_eq!(partition("cn-northwest-1"), "aws-cn"); + assert_eq!(partition("us-gov-west-1"), "aws-us-gov"); + assert_eq!(partition("eu-north-1"), "aws"); + } + + #[test] + fn assuming_a_role_asks_for_it_by_its_arn_and_external_id() { + let form = assume_role_form( + &Role { + arn: "arn:aws:iam::123456789012:role/fctl-microvms".into(), + external_id: Some("acme fctl".into()), + }, + "fctl-host", + ); + assert_eq!( + form, + "Action=AssumeRole&DurationSeconds=3600&RoleArn=arn%3Aaws%3Aiam%3A%3A123456789012%3Arole%2Ffctl-microvms&RoleSessionName=fctl-host&Version=2011-06-15&ExternalId=acme%20fctl" + ); + } + + #[tokio::test] + async fn fixed_keys_stay() -> Result<(), String> { + let creds = Credentials { + access_key_id: "AKID".into(), + secret_access_key: "secret".into(), + session_token: None, + }; + let keys = Keys::fixed("us-east-1", creds.clone()); + assert_eq!(keys.get().await?, creds); + keys.forget(); + assert_eq!(keys.get().await?, creds); + Ok(()) + } +} diff --git a/crates/fctl-host/src/config.rs b/crates/fctl-host/src/config.rs index 8e47fba20..2e13e78ca 100644 --- a/crates/fctl-host/src/config.rs +++ b/crates/fctl-host/src/config.rs @@ -3,7 +3,7 @@ //! ```toml //! server = "https://app.fctl.sh" //! name = "studio-mac" -//! driver = "auto" # apple | docker | firecracker | lima | process | auto +//! driver = "auto" # apple | docker | firecracker | lambda | lima | process | auto //! capacity = 4 //! image = "ghcr.io/acme/agent:1" # unset: the published image of this version //! cpus = 4 # per sandbox, when its project sets none @@ -37,6 +37,10 @@ //! url = "s3://acme-fctl/sessions" //! region = "eu-north-1" # unset: AWS_REGION, the machine's own on EC2, else us-east-1 //! +//! [lambda] # the lambda driver: sessions in AWS Lambda MicroVMs +//! region = "us-east-1" # unset: the image's, AWS_REGION, the machine's own on EC2 +//! role_arn = "arn:aws:iam::123456789012:role/fctl-microvms" # assume it (unset: the machine's keys) +//! //! [firecracker] # the firecracker driver //! firecracker = "/usr/local/bin/firecracker" # unset: the release fctl pins, downloaded //! kernel = "/var/lib/fctl/vmlinux" # a file, or an image with /vmlinux (unset: the published one) @@ -179,6 +183,39 @@ pub struct HostConfig { /// organization's own rather than the control plane. #[serde(skip_serializing_if = "SnapshotsConfig::is_default")] pub snapshots: SnapshotsConfig, + /// The `lambda` driver's: how the host reaches AWS. What its microVMs + /// are comes from the control plane, where the runner's settings are. + #[serde(skip_serializing_if = "LambdaConfig::is_default")] + pub lambda: LambdaConfig, +} + +/// How a host of the `lambda` driver reaches AWS Lambda MicroVMs: +/// `[lambda]` in `host.toml` (`crate::driver::lambda`). The image, the +/// roles, the size and the rest are the runner's settings, which its +/// managers keep in the control plane. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct LambdaConfig { + /// The region its microVMs run in. Unset: the image's, where its + /// settings name one of the account's own; else `AWS_REGION`, the + /// machine's own on EC2, or `us-east-1`. + pub region: Option, + /// A role the machine's keys assume to manage microVMs: one of + /// another account's, say. Unset: the machine's own keys (the `AWS_*` + /// variables, a web identity or a container's credentials on EKS and + /// ECS, the instance's role on EC2). + pub role_arn: Option, + /// What the role's trust policy asks for (`sts:ExternalId`). + pub external_id: Option, + /// Lambda's API somewhere else: the dev stack's stand-in + /// (`http://127.0.0.1:8792`). Unset: AWS's. + pub endpoint: Option, +} + +impl LambdaConfig { + fn is_default(&self) -> bool { + self == &Self::default() + } } /// A bucket of the organization's own that the host keeps its sessions' @@ -320,6 +357,7 @@ impl Default for HostConfig { kubernetes: KubernetesConfig::default(), firecracker: FirecrackerConfig::default(), snapshots: SnapshotsConfig::default(), + lambda: LambdaConfig::default(), } } } diff --git a/crates/fctl-host/src/daemon.rs b/crates/fctl-host/src/daemon.rs index c070641a7..e7ce8a040 100644 --- a/crates/fctl-host/src/daemon.rs +++ b/crates/fctl-host/src/daemon.rs @@ -68,6 +68,12 @@ pub struct Daemon { /// Starts that wait for the previous run of the same session to finish, /// or for a chore on its sandbox. pending_starts: HashMap>, + /// Sessions asked to let their suspended microVM go, to make room for + /// another, with when the suspension they were asked in began: each is + /// asked once a suspension, and the next start picks another. An ask + /// ends with the session's run, or as it resumes (one that resumes as + /// it is asked declines). + letting_go: HashMap, next_request: u64, /// When to remove expired stopped sandboxes (see `expiry`). sweep: tokio::time::Interval, @@ -112,6 +118,9 @@ pub struct Daemon { /// The drivers as the control plane last heard of them, in the hello /// or a heartbeat since: a heartbeat says them again once they change. drivers_said: Vec, + /// The capacity and microVMs the control plane last heard of. + capacity_said: u32, + microvms_said: u64, /// Since when nothing has run here, for a machine that retires once /// idle (`retire_idle_minutes`). idle: retire::Idle, @@ -241,6 +250,8 @@ const DISK_EVERY: Duration = Duration::from_secs(30); /// [`DISK_EVERY`]. const DISK_LOW_EVERY: Duration = Duration::from_secs(5); const HEARTBEAT_EVERY: Duration = Duration::from_secs(15); +/// How often a host of microVMs looks for news of them between heartbeats. +const MICROVMS_EVERY: Duration = Duration::from_secs(2); /// How often the host probes its drivers while the one it uses isn't ready. const NOT_READY_EVERY: Duration = Duration::from_secs(30); /// How often the host probes the driver it uses alone while it is ready, @@ -379,6 +390,7 @@ impl Daemon { chores_rx, outbox: VecDeque::new(), pending_starts: HashMap::new(), + letting_go: HashMap::new(), next_request: 0, sweep: tokio::time::interval_at(tokio::time::Instant::now() + SWEEP_EVERY, SWEEP_EVERY), sweeping: false, @@ -397,6 +409,8 @@ impl Daemon { waiting_for_approval: false, awake: None, drivers_said: Vec::new(), + capacity_said: 0, + microvms_said: 0, idle: retire::Idle::default(), retiring: None, owe_undrain, @@ -1464,6 +1478,7 @@ impl Daemon { session_id: id.clone(), status: r.status, agent_seq: r.agent_seq, + suspended_since: r.suspended_since, }) }) .collect() @@ -1481,7 +1496,7 @@ impl Daemon { memory_mb: sysinfo::memory_mb(), drivers: self.ctx.drivers(), driver: self.ctx.driver.name().into(), - capacity: self.ctx.cfg.capacity, + capacity: self.capacity(), labels: self.ctx.cfg.labels.clone(), sessions: self.reports(), image: Some(images.own), @@ -1493,16 +1508,51 @@ impl Daemon { // know agents that triage, and save and restore snapshots; it // says when its driver becomes ready or stops being, and takes // no session while it isn't. - features: vec![ - fctl_proto::runner::FEATURE_REVIEWS.to_owned(), - fctl_proto::runner::FEATURE_TRIAGE.to_owned(), - fctl_proto::runner::FEATURE_DRIVERS.to_owned(), - fctl_proto::runner::FEATURE_SNAPSHOTS.to_owned(), - ], + features: [ + fctl_proto::runner::FEATURE_REVIEWS, + fctl_proto::runner::FEATURE_TRIAGE, + fctl_proto::runner::FEATURE_DRIVERS, + fctl_proto::runner::FEATURE_SNAPSHOTS, + ] + .into_iter() + // It runs sessions in microVMs, and suspends them. + .chain( + self.ctx + .driver + .lambda() + .map(|_| fctl_proto::microvm::FEATURE_MICROVMS), + ) + .map(str::to_owned) + .collect(), claude_token: Some(claude_token::announce(&self.ctx.cfg.claude_token())), auto_update: Some(self.updates.is_some()), snapshot_store: self.ctx.snapshot_store.as_ref().map(|s| s.report()), + microvms: self.ctx.driver.lambda().map(|d| d.report().summary()), + } + } + + /// How many sessions it runs at once: `capacity` in host.toml, or, with + /// the lambda driver, as many as its runner may have microVMs. + fn capacity(&self) -> u32 { + self.ctx + .driver + .lambda() + .and_then(|d| d.capacity()) + .unwrap_or(self.ctx.cfg.capacity) + } + + /// Whether a host of microVMs has news for the control plane: its + /// microVMs changed, or whether its driver is ready did (its settings + /// came, its image is ready), which it probes again then. + async fn microvms_changed(&mut self) -> bool { + let Some(d) = self.ctx.driver.lambda() else { + return false; + }; + let info = d.probe().await; + if !self.ctx.drivers().contains(&info) { + self.ctx.recheck_driver().await; } + d.version() != self.microvms_said || self.ctx.drivers_differ(&self.drivers_said) } /// The hello for a new connection. Heartbeats that waited for one go: @@ -1514,6 +1564,8 @@ impl Daemon { .retain(|m| !matches!(m, HostToFleet::Heartbeat(_))); let hello = self.hello(); self.drivers_said = hello.drivers.clone(); + self.capacity_said = hello.capacity; + self.microvms_said = self.ctx.driver.lambda().map_or(0, |d| d.version()); hello } @@ -1524,6 +1576,20 @@ impl Daemon { if changed { self.drivers_said = drivers.clone(); } + // Its runner's settings may have changed how many microVMs it has. + let capacity = self.capacity(); + let capacity = (capacity != self.capacity_said).then(|| { + self.capacity_said = capacity; + capacity + }); + // Its microVMs, when anything of them changed. + let microvms = self.ctx.driver.lambda().and_then(|d| { + let version = d.version(); + (version != self.microvms_said).then(|| { + self.microvms_said = version; + d.report() + }) + }); HostHeartbeat { sessions: self.reports(), load1: sysinfo::load1(), @@ -1533,6 +1599,8 @@ impl Daemon { claude_token: Some(claude_token::announce(&self.ctx.cfg.claude_token())), drivers: changed.then_some(drivers), snapshot_store: self.ctx.snapshot_store.as_ref().map(|s| s.report()), + capacity, + microvms, } } @@ -1560,6 +1628,9 @@ impl Daemon { wait = (wait * 2).min(Duration::from_secs(60)); } // Once the runtime answers. + if let Some(d) = self.ctx.driver.lambda() { + d.start_upkeep(); + } self.refresh_image(); self.start_sweep(); refresh_facts_every(self.ctx.clone(), FACTS_EVERY, self.chores_tx.clone()); @@ -1614,6 +1685,9 @@ impl Daemon { ws::send_json(&mut sink, &HostToFleet::Hello(Box::new(hello))).await?; let mut heartbeat = tokio::time::interval(HEARTBEAT_EVERY); heartbeat.tick().await; + // A host of microVMs says how they are within seconds of a change. + let mut microvms = tokio::time::interval(MICROVMS_EVERY); + microvms.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); loop { // The drivers changed since the control plane last heard of // them: it hears now, rather than at the next beat, since it @@ -1653,6 +1727,13 @@ impl Daemon { self.outbox.push_back(HostToFleet::Heartbeat(hb)); self.check_idle(); } + _ = microvms.tick(), if self.ctx.driver.lambda().is_some() => { + if self.microvms_changed().await { + let hb = self.heartbeat(); + self.outbox.push_back(HostToFleet::Heartbeat(hb)); + heartbeat.reset(); + } + } _ = &mut *shutdown, if self.may_stop() => { tracing::info!("shutting down; sessions keep running in their sandboxes"); std::process::exit(0); @@ -1789,6 +1870,9 @@ impl Daemon { } None => tracing::info!("registered as {} ({})", runner.name, runner.id), } + if let Some(d) = self.ctx.driver.lambda() { + d.set_runner(runner.id.as_str()); + } if let Ok(mut r) = self.ctx.runner_id.lock() { *r = Some(runner.id); } @@ -1797,6 +1881,29 @@ impl Daemon { } } FleetToHost::Ping => self.outbox.push_back(HostToFleet::Pong), + FleetToHost::Microvms { settings } => match self.ctx.driver.lambda() { + Some(d) => { + tracing::info!( + "{} microVM settings", + if settings.is_some() { + "got its" + } else { + "has no" + } + ); + d.set_settings(settings); + // How ready it is follows them: the next heartbeat says. + let (ctx, chores) = (self.ctx.clone(), self.chores_tx.clone()); + tokio::spawn(async move { + ctx.recheck_driver().await; + let _ = chores.send(Chore::Drivers); + }); + } + None => tracing::debug!( + "microVM settings for a host of the {} driver", + self.ctx.driver.name() + ), + }, FleetToHost::StartSession { spec } => { let id = spec.session_id.clone(); // A machine that retires takes nothing more: the control @@ -1893,6 +2000,13 @@ impl Daemon { /// Takes on a session, or says why not. fn start_session(&mut self, mut spec: Box) -> Result<(), String> { let id = spec.session_id.clone(); + // A session waits for a message, suspended, until its host lets its + // microVM go: its agent mustn't stop by itself before. + if let Some(t) = self.ctx.driver.lambda().and_then(|d| d.idle_timeout_secs()) + && spec.review.is_none() + { + spec.idle_timeout_secs = spec.idle_timeout_secs.max(t); + } // Its person keeps their Claude token on their runners: this one's. claude_token::fill( &self.ctx.cfg.claude_token(), @@ -1963,9 +2077,37 @@ impl Daemon { .keys() .filter(|id| !self.sessions.contains_key(*id)) .count(); - if (self.sessions.len() + waiting) as u32 >= self.ctx.cfg.capacity { + // Sessions whose microVMs are suspended make room: the one + // suspended longest goes as a new one needs it. + let suspended: Vec<(String, i64)> = self + .sessions + .iter() + .filter_map(|(id, h)| { + let since = h.report.lock().ok()?.suspended_since?; + Some((id.as_str().to_owned(), since)) + }) + .collect(); + let running = self.sessions.len() - suspended.len(); + if (running + waiting) as u32 >= self.capacity() { return Err("the host is at capacity".into()); } + // Only one whose snapshot was saved lets its microVM go (losing + // nothing), and only once a suspension: one already asked holds no + // room for this. + if let Some(d) = self.ctx.driver.lambda() { + let weighed = weigh_suspended(&suspended, &mut self.letting_go, |s| { + d.checkpointed(&sandbox_name(s)) + }); + if d.full() + && let Some(longest) = fctl_domain::microvm::make_room(&weighed) + && let Some(h) = self.sessions.get(&SessionId(longest.clone())) + && let Some((_, since)) = suspended.iter().find(|(s, _)| *s == longest) + { + tracing::info!("{longest}'s microVM goes to make room for {id}'s"); + let _ = h.tx.send(SessionCmd::LetGo); + self.letting_go.insert(SessionId(longest), *since); + } + } if self.busy.contains_key(&sandbox_name(id.as_str())) { tracing::info!("{id} starts once its sandbox is stopped or removed"); self.pending_starts.insert(id, spec); @@ -2218,6 +2360,31 @@ fn updates_itself(cfg: &HostConfig) -> Result { } } +/// The sessions whose microVMs are suspended, as the host weighs letting +/// one go to make room for a new session. Drops the asks that no longer +/// hold first: those whose session's run ended, or that resumed since they +/// were asked (a session that resumes as it is asked declines). +fn weigh_suspended( + suspended: &[(String, i64)], + asked: &mut HashMap, + checkpointed: impl Fn(&str) -> bool, +) -> Vec { + asked.retain(|s, asked_in| { + suspended + .iter() + .any(|(id, since)| id == s.as_str() && since == asked_in) + }); + suspended + .iter() + .map(|(s, since)| fctl_domain::microvm::Suspended { + session: s.clone(), + since: *since, + checkpointed: checkpointed(s), + asked: asked.get(&SessionId(s.clone())) == Some(since), + }) + .collect() +} + #[cfg(test)] mod tests { use super::*; @@ -2226,6 +2393,25 @@ mod tests { const GIB: u64 = 1024; const MINUTE: i64 = 60_000; + #[test] + fn an_ask_to_make_room_holds_for_one_suspension_of_a_running_session() { + let mut asked: HashMap = HashMap::new(); + asked.insert(SessionId("ses_a".into()), 100); + asked.insert(SessionId("ses_b".into()), 100); + asked.insert(SessionId("ses_gone".into()), 100); + // ses_a still suspended since it was asked; ses_b resumed and + // suspended again; ses_gone's run ended. + let suspended = [("ses_a".to_owned(), 100), ("ses_b".to_owned(), 300)]; + let weighed = weigh_suspended(&suspended, &mut asked, |_| true); + let asked_now: Vec<(&str, bool)> = weighed + .iter() + .map(|w| (w.session.as_str(), w.asked)) + .collect(); + assert_eq!(asked_now, [("ses_a", true), ("ses_b", false)]); + assert_eq!(asked.len(), 1); + assert!(asked.contains_key(&SessionId("ses_a".into()))); + } + /// A process-driver daemon whose data directory has stopped session /// sandboxes, each stopped `minutes` ago. /// A machine that retires once idle drains first, but only once @@ -2490,6 +2676,7 @@ mod tests { let (tx, _rx) = mpsc::unbounded_channel(); let report = Arc::new(std::sync::Mutex::new(session::Report { status: SessionStatus::Running, + suspended_since: None, agent_seq: 0, })); d.sessions @@ -2924,6 +3111,7 @@ mod tests { tx, report: Arc::new(std::sync::Mutex::new(session::Report { status: SessionStatus::Running, + suspended_since: None, agent_seq: 0, })), }, @@ -3269,6 +3457,7 @@ mod tests { let (tx, _rx) = mpsc::unbounded_channel(); let report = Arc::new(std::sync::Mutex::new(session::Report { status, + suspended_since: None, agent_seq: 0, })); d.sessions.insert( diff --git a/crates/fctl-host/src/driver/firecracker/vsock.rs b/crates/fctl-host/src/driver/firecracker/vsock.rs index dc444487a..cc988d699 100644 --- a/crates/fctl-host/src/driver/firecracker/vsock.rs +++ b/crates/fctl-host/src/driver/firecracker/vsock.rs @@ -40,7 +40,7 @@ pub async fn connect(socket: &Path, port: u32) -> Result<(Reader, OwnedWriteHalf } /// Reads one reply line. -pub async fn read_reply(r: &mut Reader) -> Result { +pub async fn read_reply(r: &mut BufReader) -> Result { let mut line = Vec::new(); r.take(MAX_LINE as u64).read_until(b'\n', &mut line).await?; if line.is_empty() { @@ -120,7 +120,11 @@ pub async fn wait_ready( } } -async fn send_frame(w: &mut OwnedWriteHalf, kind: u8, data: &[u8]) -> std::io::Result<()> { +async fn send_frame( + w: &mut W, + kind: u8, + data: &[u8], +) -> std::io::Result<()> { w.write_all(&frame::header(kind, data.len())).await?; w.write_all(data).await } @@ -140,7 +144,17 @@ const MAX_OUTPUT: usize = 64 * 1024 * 1024; pub async fn run(socket: &Path, mut exec: Exec, input: Option<&[u8]>) -> Result { exec.stdin = input.is_some(); exec.now_ms = Some(now_ms()); - let (mut r, mut w) = request(socket, &Request::Exec(exec)).await?; + let (r, w) = request(socket, &Request::Exec(exec)).await?; + run_on(r, w, input).await +} + +/// [`run`]'s program on a connection that has sent its request and read +/// the first reply: feeds it `input`, and reads its output to its exit. +pub async fn run_on(mut r: BufReader, mut w: W, input: Option<&[u8]>) -> Result +where + R: AsyncRead + Unpin, + W: AsyncWrite + Unpin, +{ let feed = async { if let Some(input) = input { for chunk in input.chunks(frame::MAX) { @@ -260,7 +274,17 @@ pub async fn start(socket: &Path, mut exec: Exec) -> Result { exec.stdin = true; exec.detach = false; exec.now_ms = Some(now_ms()); - let (mut from_vm, mut to_vm) = request(socket, &Request::Exec(exec)).await?; + let (from_vm, to_vm) = request(socket, &Request::Exec(exec)).await?; + Ok(start_on(from_vm, to_vm)) +} + +/// [`start`]'s program on a connection that has sent its request and read +/// the first reply: its input and output as pipes. +pub fn start_on(mut from_vm: BufReader, mut to_vm: W) -> Started +where + R: AsyncRead + Unpin + Send + 'static, + W: AsyncWrite + Unpin + Send + 'static, +{ let (stdin, mut stdin_rx) = tokio::io::duplex(256 * 1024); let (mut stdout_tx, stdout) = tokio::io::duplex(256 * 1024); let (mut stderr_tx, stderr) = tokio::io::duplex(64 * 1024); @@ -320,7 +344,7 @@ pub async fn start(socket: &Path, mut exec: Exec) -> Result { std::future::pending::<()>().await; }); let tasks = Arc::new(Tasks(vec![output, input])); - Ok(Started { + Started { stdin: Pipe { inner: stdin, _tasks: tasks.clone(), @@ -334,7 +358,7 @@ pub async fn start(socket: &Path, mut exec: Exec) -> Result { _tasks: tasks, }, exit, - }) + } } /// What a VM unpacked of an image's layers. diff --git a/crates/fctl-host/src/driver/lambda/api.rs b/crates/fctl-host/src/driver/lambda/api.rs new file mode 100644 index 000000000..6b95d229b --- /dev/null +++ b/crates/fctl-host/src/driver/lambda/api.rs @@ -0,0 +1,947 @@ +//! AWS Lambda MicroVMs' API (`lambda-microvms`, version 2025-09-09): REST +//! with JSON bodies on Lambda's regional endpoint, signed with SigV4 for +//! the `lambda` service ([`fctl_domain::sigv4`]), as the AWS SDKs send it. +//! Only what the driver uses: microVMs (run, get, list, suspend, resume, +//! terminate, auth tokens) and images (get, versions, create, update). +//! +//! Paths name images by name and microVMs by id, which need no escaping: +//! SigV4 would encode an ARN in a path twice. + +use crate::aws::Keys; +use fctl_client::http::HttpClient; +use fctl_domain::sigv4; +use http::Method; +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::sync::Arc; +use std::time::Duration; + +pub const VERSION: &str = "2025-09-09"; + +/// How many times a request goes in all while AWS asks to try again +/// (throttling, a 5xx, no capacity just now). +pub(crate) const TRIES: u32 = 4; + +/// What AWS answered instead of what was asked. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Error { + /// The HTTP status, 0 when AWS didn't answer. + pub status: u16, + /// `ServiceQuotaExceededException`, …; `Unreachable` when AWS didn't + /// answer. + pub code: String, + pub message: String, + pub retry_after: Option, + /// With no answer: the request may have reached Lambda (it timed out, + /// or the connection broke once made), rather than never left. + pub reached: bool, + /// An earlier try of the same call may have been carried out: a later + /// throttle doesn't undo a microVM an earlier try started. + pub before: bool, +} + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let code = self.code.trim_end_matches("Exception"); + match self.message.is_empty() { + true => write!(f, "{code}"), + false => write!(f, "{code}: {}", self.message), + } + } +} + +impl std::error::Error for Error {} + +impl Error { + fn unreachable(e: impl std::fmt::Display) -> Self { + Self { + status: 0, + code: "Unreachable".into(), + message: e.to_string(), + retry_after: None, + reached: false, + before: false, + } + } + + /// A transport error, which says whether the request may have reached + /// Lambda: a timeout or a connection that broke may have; one that + /// never connected, or found no address, didn't. + fn of_transport(e: &fctl_client::http::Error) -> Self { + let reached = match e { + fctl_client::http::Error::Timeout(_) => true, + fctl_client::http::Error::Network { message, .. } => { + !(message.contains("(Connect)") || message.contains("dns error")) + } + _ => false, + }; + Self { + reached, + ..Self::unreachable(e) + } + } + + /// Whether Lambda may have done what was asked though it said it + /// failed or said nothing: no answer to a request that may have reached + /// it, or a failure within it (a 5xx). A throttle, no capacity, a + /// refusal or a request that never left did nothing. + pub fn may_have_happened(&self) -> bool { + self.before + || match self.status { + 0 => self.reached, + // Carried out, though its answer didn't read. + 200..=299 => true, + s if s >= 500 => !matches!( + self.code.as_str(), + "ThrottlingException" + | "InsufficientCapacityException" + | "ServiceUnavailableException" + | "TooManyRequestsException" + ), + _ => false, + } + } + + pub fn not_found(&self) -> bool { + self.status == 404 || self.code == "ResourceNotFoundException" + } + + /// A request in a state that takes none: suspending one that is + /// suspended, say. + pub fn conflict(&self) -> bool { + self.status == 409 || self.code == "ConflictException" + } + + /// Whether trying again later may work. + pub fn transient(&self) -> bool { + self.status == 0 + || self.status == 429 + || self.status >= 500 + || matches!( + self.code.as_str(), + "ThrottlingException" | "InternalServerException" | "InsufficientCapacityException" + ) + } + + /// Lambda refused the request itself as one it would never carry out: + /// asked again, the same request never ran before either. + pub fn invalid_request(&self) -> bool { + self.status == 400 + && matches!( + self.code.as_str(), + "ValidationException" + | "InvalidParameterValueException" + | "InvalidRequestContentException" + | "SerializationException" + ) + } + + /// What kind of trouble it is, as [`fctl_proto::microvm::MicrovmProblem::kind`] + /// says. + pub fn kind(&self) -> &'static str { + match self.code.as_str() { + "AccessDeniedException" + | "UnrecognizedClientException" + | "InvalidSignatureException" + | "ExpiredTokenException" => "access", + "ServiceQuotaExceededException" => "quota", + "InsufficientCapacityException" => "capacity", + "ThrottlingException" | "TooManyRequestsException" => "throttled", + "ValidationException" | "ResourceNotFoundException" => "settings", + "Credentials" => "credentials", + "Unreachable" => "unreachable", + _ if self.status == 403 => "access", + _ => "other", + } + } +} + +/// A microVM, as `RunMicrovm` and `GetMicrovm` answer. +#[derive(Clone, Debug, Default, PartialEq, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Microvm { + pub microvm_id: String, + /// `PENDING`, `RUNNING`, `SUSPENDING`, `SUSPENDED`, `TERMINATING`, + /// `TERMINATED`. + pub state: String, + #[serde(default)] + pub endpoint: Option, + #[serde(default)] + pub image_arn: Option, + #[serde(default)] + pub image_version: Option, + /// Seconds since the epoch. + #[serde(default)] + pub started_at: Option, + #[serde(default)] + pub state_reason: Option, + #[serde(default)] + pub maximum_duration_in_seconds: Option, +} + +impl Microvm { + pub fn started_at_ms(&self) -> Option { + self.started_at.map(|s| (s * 1000.0) as i64) + } + + pub fn gone(&self) -> bool { + matches!(self.state.as_str(), "TERMINATING" | "TERMINATED") + } +} + +/// A microVM, as `ListMicrovms` lists it. +#[derive(Clone, Debug, PartialEq, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MicrovmItem { + pub microvm_id: String, + pub state: String, + #[serde(default)] + pub image_version: Option, + #[serde(default)] + pub started_at: Option, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Page { + items: Vec, + #[serde(default)] + next_token: Option, +} + +/// Lambda's idle policy for a microVM. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct IdlePolicy { + pub auto_resume_enabled: bool, + pub max_idle_duration_seconds: u32, + pub suspended_duration_seconds: u32, +} + +/// `{"cloudWatch": {"logGroup": …}}`. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Logging { + pub cloud_watch: CloudWatch, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CloudWatch { + pub log_group: String, +} + +/// What `RunMicrovm` takes. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RunRequest { + pub client_token: String, + pub image_identifier: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub image_version: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub execution_role_arn: Option, + pub idle_policy: IdlePolicy, + pub ingress_network_connectors: Vec, + pub egress_network_connectors: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + pub kms_key_identifier: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub logging: Option, + pub maximum_duration_in_seconds: u32, + pub run_hook_payload: String, +} + +/// A microVM image, as `GetMicrovmImage` answers. +#[derive(Clone, Debug, Default, PartialEq, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Image { + pub image_arn: String, + #[serde(default)] + pub name: String, + /// `CREATING`, `CREATED`, `CREATE_FAILED`, `UPDATING`, `UPDATED`, … + pub state: String, + #[serde(default)] + pub latest_active_image_version: Option, + #[serde(default)] + pub latest_failed_image_version: Option, + /// From `CreateMicrovmImage` and `UpdateMicrovmImage`: the version it + /// builds. + #[serde(default)] + pub image_version: Option, +} + +/// A version of an image. +#[derive(Clone, Debug, Default, PartialEq, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ImageVersion { + #[serde(default)] + pub image_arn: String, + pub image_version: String, + /// `PENDING`, `IN_PROGRESS`, `SUCCESSFUL`, `FAILED`, … + pub state: String, + /// `ACTIVE` or `INACTIVE`. + #[serde(default)] + pub status: Option, + #[serde(default)] + pub description: Option, + #[serde(default)] + pub state_reason: Option, + #[serde(default)] + pub resources: Vec, + #[serde(default)] + pub cpu_configurations: Vec, + #[serde(default)] + pub created_at: Option, +} + +impl ImageVersion { + /// Whether microVMs run from it. + pub fn runs(&self) -> bool { + self.state == "SUCCESSFUL" && self.status.as_deref().unwrap_or("ACTIVE") == "ACTIVE" + } + + pub fn memory_mb(&self) -> Option { + self.resources.first().map(|r| r.minimum_memory_in_mi_b) + } + + pub fn arch(&self) -> Option<&str> { + self.cpu_configurations + .first() + .map(|c| c.architecture.as_str()) + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Resources { + #[serde(rename = "minimumMemoryInMiB")] + pub minimum_memory_in_mi_b: u32, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CpuConfiguration { + pub architecture: String, +} + +/// Lambda's lifecycle hooks, as an image enables them. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Hooks { + pub port: u16, + pub microvm_image_hooks: BTreeMap, + pub microvm_hooks: BTreeMap, +} + +/// What `CreateMicrovmImage` and `UpdateMicrovmImage` take. +#[derive(Clone, Debug, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ImageRequest { + /// Absent from an update, whose path names the image. + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + pub client_token: String, + pub base_image_arn: String, + pub build_role_arn: String, + pub description: String, + pub code_artifact: CodeArtifact, + pub cpu_configurations: Vec, + pub resources: Vec, + pub additional_os_capabilities: Vec, + pub hooks: Hooks, + pub environment_variables: BTreeMap, + #[serde(skip_serializing_if = "Option::is_none")] + pub kms_key_identifier: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub logging: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct CodeArtifact { + pub uri: String, +} + +/// The API of one region, or of a stand-in for it. +pub struct Api { + http: HttpClient, + keys: Arc, + region: String, + /// `https://lambda..amazonaws.com`, or a stand-in's. + base: String, + /// The host it signs requests for. + host: String, + /// How long the second try waits; each after it three times as long. + first_wait: Duration, +} + +impl std::fmt::Debug for Api { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Api") + .field("region", &self.region) + .field("base", &self.base) + .finish_non_exhaustive() + } +} + +impl Api { + /// The API in `keys`' region, at AWS's endpoint unless `endpoint` + /// (`http://127.0.0.1:8792`, a stand-in's) says another. + pub fn new(keys: Arc, endpoint: Option<&str>) -> Result { + let region = keys.region().to_owned(); + let base = match endpoint { + Some(e) => e.trim_end_matches('/').to_owned(), + None => format!( + "https://lambda.{region}.{}", + crate::aws::dns_suffix(®ion) + ), + }; + let url = url::Url::parse(&base).map_err(|e| format!("the Lambda endpoint {base}: {e}"))?; + let host = match (url.host_str(), url.port()) { + (Some(h), Some(p)) => format!("{h}:{p}"), + (Some(h), None) => h.to_owned(), + (None, _) => return Err(format!("the Lambda endpoint {base} has no host")), + }; + Ok(Self { + http: HttpClient::new(Duration::from_secs(60)), + keys, + region, + base, + host, + first_wait: Duration::from_millis(500), + }) + } + + /// The same, trying again sooner: for tests. + #[cfg(test)] + pub fn with_first_wait(mut self, wait: Duration) -> Self { + self.first_wait = wait; + self + } + + /// The keys it signs with, for what else the host asks of AWS as it + /// does: the image's archive in S3. + pub fn keys(&self) -> Arc { + self.keys.clone() + } + + pub fn region(&self) -> &str { + &self.region + } + + async fn call( + &self, + method: Method, + path: &str, + query: &[(&str, &str)], + body: Option<&serde_json::Value>, + ) -> Result { + let body = body.map(|b| b.to_string()).unwrap_or_default(); + let mut wait = self.first_wait; + let mut tries = 1; + // Whether a try so far may have been carried out. + let mut before = false; + loop { + let answer = self.send(method.clone(), path, query, &body).await; + match answer { + Ok(bytes) => { + let bytes = if bytes.is_empty() { + &b"{}"[..] + } else { + &bytes[..] + }; + return serde_json::from_slice(bytes).map_err(|e| Error { + status: 200, + code: "Decode".into(), + message: format!("reading Lambda's answer: {e}"), + retry_after: None, + reached: true, + before, + }); + } + Err(e) if e.transient() && tries < TRIES => { + before |= e.may_have_happened(); + let after = e.retry_after.map(Duration::from_secs).unwrap_or(wait); + tracing::debug!("{method} {path}: {e}; again in {after:?}"); + tokio::time::sleep(after.min(Duration::from_secs(20))).await; + wait *= 3; + tries += 1; + } + Err(mut e) => { + if e.kind() == "access" { + self.keys.forget(); + } + e.before |= before; + return Err(e); + } + } + } + } + + async fn send( + &self, + method: Method, + path: &str, + query: &[(&str, &str)], + body: &str, + ) -> Result { + let creds = self.keys.get().await.map_err(|e| Error { + status: 0, + code: "Credentials".into(), + message: e, + retry_after: None, + reached: false, + before: false, + })?; + let content_type = "application/json"; + let sha = sigv4::sha256_hex(body.as_bytes()); + let signed = sigv4::sign( + &sigv4::Request { + method: method.as_str(), + host: &self.host, + path, + query, + headers: &[("content-type", content_type)], + payload_sha256: &sha, + }, + &creds, + &self.region, + "lambda", + crate::expiry::now_ms(), + ); + let mut headers: Vec<(&str, &str)> = signed + .iter() + .map(|(n, v)| (n.as_str(), v.as_str())) + .collect(); + headers.push(("content-type", content_type)); + let query = query + .iter() + .map(|(k, v)| format!("{}={}", sigv4::encode(k, false), sigv4::encode(v, false))) + .collect::>() + .join("&"); + let url = format!( + "{}{path}{}{query}", + self.base, + if query.is_empty() { "" } else { "?" } + ); + let body = match method { + Method::GET | Method::DELETE if body.is_empty() => None, + _ => Some(bytes::Bytes::from(body.to_owned())), + }; + let (status, headers, answer) = self + .http + .send_with(method, &url, &headers, body) + .await + .map_err(|e| Error::of_transport(&e))?; + if status.is_success() { + return Ok(answer); + } + Err(error_of(status.as_u16(), &headers, &answer)) + } + + /// Runs a microVM. + pub async fn run(&self, req: &RunRequest) -> Result { + let body = serde_json::to_value(req).map_err(Error::unreachable)?; + self.call( + Method::POST, + &format!("/{VERSION}/microvms"), + &[], + Some(&body), + ) + .await + } + + pub async fn get(&self, id: &str) -> Result { + self.call(Method::GET, &format!("/{VERSION}/microvms/{id}"), &[], None) + .await + } + + pub async fn suspend(&self, id: &str) -> Result<(), Error> { + let empty = serde_json::json!({}); + self.call::( + Method::POST, + &format!("/{VERSION}/microvms/{id}/suspend"), + &[], + Some(&empty), + ) + .await + .map(drop) + } + + pub async fn resume(&self, id: &str) -> Result<(), Error> { + let empty = serde_json::json!({}); + self.call::( + Method::POST, + &format!("/{VERSION}/microvms/{id}/resume"), + &[], + Some(&empty), + ) + .await + .map(drop) + } + + pub async fn terminate(&self, id: &str) -> Result<(), Error> { + self.call::( + Method::DELETE, + &format!("/{VERSION}/microvms/{id}"), + &[], + None, + ) + .await + .map(drop) + } + + /// A token for the microVM's endpoint, to `port` alone, for `minutes` + /// (60 at most): `X-aws-proxy-auth`'s value. + pub async fn token(&self, id: &str, port: u16, minutes: u32) -> Result { + let body = serde_json::json!({ + "expirationInMinutes": minutes.clamp(1, 60), + "allowedPorts": [{ "port": port }], + }); + let answer: serde_json::Value = self + .call( + Method::POST, + &format!("/{VERSION}/microvms/{id}/auth-token"), + &[], + Some(&body), + ) + .await?; + answer + .get("authToken") + .and_then(|t| t.get("X-aws-proxy-auth")) + .and_then(|t| t.as_str()) + .map(str::to_owned) + .ok_or_else(|| Error { + status: 200, + code: "Decode".into(), + message: "Lambda's answer had no X-aws-proxy-auth token".into(), + retry_after: None, + reached: false, + before: false, + }) + } + + /// The account's microVMs of `image` (an ARN or name), every page. + pub async fn list(&self, image: &str) -> Result, Error> { + let mut items = Vec::new(); + let mut next: Option = None; + for _ in 0..100 { + let mut query = vec![("imageIdentifier", image), ("maxResults", "50")]; + if let Some(t) = next.as_deref() { + query.push(("nextToken", t)); + } + let page: Page = self + .call(Method::GET, &format!("/{VERSION}/microvms"), &query, None) + .await?; + items.extend(page.items); + match page.next_token.filter(|t| !t.is_empty()) { + Some(t) => next = Some(t), + None => break, + } + } + Ok(items) + } + + /// Whether the keys may list the account's microVMs: one, of any image. + pub async fn reachable(&self) -> Result<(), Error> { + self.call::( + Method::GET, + &format!("/{VERSION}/microvms"), + &[("maxResults", "1")], + None, + ) + .await + .map(drop) + } + + /// An image, by its name. + pub async fn image(&self, name: &str) -> Result { + self.call( + Method::GET, + &format!("/{VERSION}/microvm-images/{name}"), + &[], + None, + ) + .await + } + + pub async fn image_version(&self, name: &str, version: &str) -> Result { + self.call( + Method::GET, + &format!( + "/{VERSION}/microvm-images/{name}/versions/{}", + sigv4::encode(version, false) + ), + &[], + None, + ) + .await + } + + pub async fn create_image(&self, req: &ImageRequest) -> Result { + let body = serde_json::to_value(req).map_err(Error::unreachable)?; + self.call( + Method::POST, + &format!("/{VERSION}/microvm-images"), + &[], + Some(&body), + ) + .await + } + + pub async fn update_image(&self, name: &str, req: &ImageRequest) -> Result { + let body = serde_json::to_value(req).map_err(Error::unreachable)?; + self.call( + Method::PUT, + &format!("/{VERSION}/microvm-images/{name}"), + &[], + Some(&body), + ) + .await + } +} + +/// An error answer: its type from `x-amzn-ErrorType` (before any `:`), or +/// the body's `__type`, and its message. +fn error_of(status: u16, headers: &http::HeaderMap, body: &[u8]) -> Error { + let v: serde_json::Value = serde_json::from_slice(body).unwrap_or_default(); + let header = headers + .get("x-amzn-errortype") + .and_then(|h| h.to_str().ok()) + .map(|t| t.split(':').next().unwrap_or(t).to_owned()); + let code = header + .or_else(|| { + v.get("__type") + .and_then(|t| t.as_str()) + .map(|t| t.rsplit('#').next().unwrap_or(t).to_owned()) + }) + .unwrap_or_else(|| format!("HTTP {status}")); + let message = ["message", "Message"] + .iter() + .find_map(|k| v.get(*k).and_then(|m| m.as_str())) + .unwrap_or_default() + .to_owned(); + let retry_after = headers + .get("retry-after") + .and_then(|h| h.to_str().ok()) + .and_then(|h| h.trim().parse().ok()); + Error { + status, + code, + message, + retry_after, + reached: true, + before: false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn errors_read_their_type_from_the_header_or_the_body() { + let mut headers = http::HeaderMap::new(); + headers.insert( + "x-amzn-errortype", + http::HeaderValue::from_static( + "ServiceQuotaExceededException:http://internal.amazon.com/coral/", + ), + ); + let e = error_of(402, &headers, br#"{"message":"Memory quota reached"}"#); + assert_eq!(e.code, "ServiceQuotaExceededException"); + assert_eq!(e.kind(), "quota"); + assert!(!e.transient()); + assert_eq!(e.to_string(), "ServiceQuotaExceeded: Memory quota reached"); + let mut headers = http::HeaderMap::new(); + headers.insert("retry-after", http::HeaderValue::from_static("3")); + let e = error_of( + 429, + &headers, + br#"{"__type":"com.amazonaws#ThrottlingException","Message":"Slow down"}"#, + ); + assert_eq!(e.code, "ThrottlingException"); + assert_eq!(e.retry_after, Some(3)); + assert!(e.transient()); + let e = error_of(404, &http::HeaderMap::new(), b""); + assert!(e.not_found()); + assert_eq!(e.code, "HTTP 404"); + let e = error_of(403, &http::HeaderMap::new(), b"{}"); + assert_eq!(e.kind(), "access"); + } + + #[test] + fn only_a_request_lambda_may_have_carried_out_counts_as_happened() { + let of = |status, code: &str| { + error_of( + status, + &http::HeaderMap::new(), + format!(r#"{{"__type":"{code}"}}"#).as_bytes(), + ) + }; + assert!(of(500, "InternalServerException").may_have_happened()); + assert!(of(502, "").may_have_happened()); + assert!(!of(429, "ThrottlingException").may_have_happened()); + assert!(!of(500, "InsufficientCapacityException").may_have_happened()); + assert!(!of(503, "ServiceUnavailableException").may_have_happened()); + assert!(!of(400, "ValidationException").may_have_happened()); + assert!(!of(402, "ServiceQuotaExceededException").may_have_happened()); + } + + fn api(url: &str) -> Result { + let keys = Keys::fixed( + "us-east-1", + sigv4::Credentials { + access_key_id: "AKIDTEST".into(), + secret_access_key: "test".into(), + session_token: None, + }, + ); + Ok(Api::new(Arc::new(keys), Some(url))?.with_first_wait(Duration::from_millis(1))) + } + + /// A request that never connected did nothing; one whose connection + /// broke as it waited for its answer may have. + #[tokio::test] + async fn requests_say_whether_they_may_have_reached_lambda() -> anyhow::Result<()> { + let closed = std::net::TcpListener::bind("127.0.0.1:0")?.local_addr()?; + let refused = api(&format!("http://{closed}")) + .map_err(anyhow::Error::msg)? + .get("mvm-1") + .await + .err() + .ok_or_else(|| anyhow::anyhow!("nothing answers there"))?; + assert!(!refused.may_have_happened(), "{refused:?}"); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; + let url = format!("http://{}", listener.local_addr()?); + tokio::spawn(async move { + use tokio::io::AsyncReadExt; + while let Ok((mut conn, _)) = listener.accept().await { + // Takes the request, and hangs up without an answer. + let mut buf = [0u8; 4096]; + let _ = conn.read(&mut buf).await; + drop(conn); + } + }); + let broke = api(&url) + .map_err(anyhow::Error::msg)? + .get("mvm-1") + .await + .err() + .ok_or_else(|| anyhow::anyhow!("no answer came"))?; + assert!(broke.may_have_happened(), "{broke:?}"); + Ok(()) + } + + /// Answers each request in turn with `answers`, hanging up without one + /// where it says `None`, and the last one again once they run out. + async fn answering( + answers: Vec>, + ) -> anyhow::Result { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; + let url = format!("http://{}", listener.local_addr()?); + tokio::spawn(async move { + let mut n = 0; + while let Ok((mut conn, _)) = listener.accept().await { + let mut buf = [0u8; 8192]; + let _ = conn.read(&mut buf).await; + let answer = answers.get(n).or(answers.last()).cloned().flatten(); + n += 1; + let Some((status, body)) = answer else { + drop(conn); + continue; + }; + let text = format!( + "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", + body.len() + ); + let _ = conn.write_all(text.as_bytes()).await; + let _ = conn.shutdown().await; + } + }); + Ok(url) + } + + /// A throttle on a later try doesn't undo what an earlier try may have + /// started, and an answer that doesn't read was carried out still. + #[tokio::test] + async fn a_run_remembers_what_its_earlier_tries_may_have_done() -> anyhow::Result<()> { + let throttled = ( + "429 Too Many Requests", + r#"{"__type":"ThrottlingException"}"#, + ); + let url = answering(vec![None, Some(throttled)]).await?; + let e = api(&url) + .map_err(anyhow::Error::msg)? + .get("mvm-1") + .await + .err() + .ok_or_else(|| anyhow::anyhow!("it was throttled"))?; + assert_eq!(e.status, 429); + assert!(e.may_have_happened(), "{e:?}"); + let url = answering(vec![Some(throttled)]).await?; + let e = api(&url) + .map_err(anyhow::Error::msg)? + .get("mvm-1") + .await + .err() + .ok_or_else(|| anyhow::anyhow!("it was throttled"))?; + assert!(!e.may_have_happened(), "{e:?}"); + let url = answering(vec![Some(("200 OK", "not what Lambda writes"))]).await?; + let e = api(&url) + .map_err(anyhow::Error::msg)? + .get("mvm-1") + .await + .err() + .ok_or_else(|| anyhow::anyhow!("its answer doesn't read"))?; + assert_eq!(e.code, "Decode"); + assert!(e.may_have_happened(), "{e:?}"); + Ok(()) + } + + #[test] + fn requests_and_answers_are_as_lambda_writes_them() -> serde_json::Result<()> { + let req = RunRequest { + client_token: "fctl-1".into(), + image_identifier: "arn:aws:lambda:us-east-1:123456789012:microvm-image:fctl-sandbox" + .into(), + image_version: Some("2.0".into()), + execution_role_arn: None, + idle_policy: IdlePolicy { + auto_resume_enabled: false, + max_idle_duration_seconds: 28_800, + suspended_duration_seconds: 4_200, + }, + ingress_network_connectors: vec!["in".into()], + egress_network_connectors: vec!["out".into()], + kms_key_identifier: None, + logging: None, + maximum_duration_in_seconds: 28_800, + run_hook_payload: "{}".into(), + }; + let json = serde_json::to_value(&req)?; + assert_eq!(json["idlePolicy"]["suspendedDurationSeconds"], 4_200); + assert_eq!(json["ingressNetworkConnectors"][0], "in"); + assert!(json.get("executionRoleArn").is_none()); + let vm: Microvm = serde_json::from_value(serde_json::json!({ + "microvmId": "mvm-01234567-abcd", + "state": "PENDING", + "endpoint": "mvm-01234567-abcd.lambda-microvm.us-east-1.on.aws", + "startedAt": 1_764_000_000.5, + "maximumDurationInSeconds": 28_800 + }))?; + assert_eq!(vm.started_at_ms(), Some(1_764_000_000_500)); + assert!(!vm.gone()); + let version: ImageVersion = serde_json::from_value(serde_json::json!({ + "imageArn": "arn", "imageVersion": "3.0", "state": "SUCCESSFUL", "status": "ACTIVE", + "resources": [{ "minimumMemoryInMiB": 4096 }], + "cpuConfigurations": [{ "architecture": "X86_64" }] + }))?; + assert!(version.runs()); + assert_eq!(version.memory_mb(), Some(4096)); + assert_eq!(version.arch(), Some("X86_64")); + Ok(()) + } +} diff --git a/crates/fctl-host/src/driver/lambda/image.rs b/crates/fctl-host/src/driver/lambda/image.rs new file mode 100644 index 000000000..3a6d141c9 --- /dev/null +++ b/crates/fctl-host/src/driver/lambda/image.rs @@ -0,0 +1,257 @@ +//! The image a runner's microVMs run from: one of the account's own, as +//! its settings name it, or one fctl builds and keeps up to date +//! ([`MicrovmImage::Managed`]): from the sandbox image of the host's +//! version, with that version's fctl-agent, which `microvm-serve`s from the +//! image's `CMD`. The host uploads the archive Lambda builds it from (a +//! `Dockerfile` and fctl-agent) to the settings' `artifacts`, and has +//! Lambda build a version of the image for each fctl, size and +//! architecture; the version's description says which +//! ([`description`]). MicroVMs run from the last version that built +//! meanwhile. + +use super::api::{ + self, Api, CloudWatch, CodeArtifact, CpuConfiguration, Hooks, ImageRequest, ImageVersion, + Logging, Resources, +}; +use super::zip; +use fctl_proto::microvm::{ + DEFAULT_IMAGE_NAME, HOOKS_PORT, MicrovmArch, MicrovmImage, MicrovmImageReport, + MicrovmImageStatus, MicrovmSettings, microvm_size, +}; +use std::collections::BTreeMap; + +/// The `Dockerfile` of an image fctl builds: the sandbox image `from`, +/// with fctl-agent in `/opt/fctl/bin`, which runs `microvm-serve` as root +/// and the image's sessions as `user`. +pub fn dockerfile(from: &str, user: &str) -> String { + format!( + "# An fctl runner's AWS Lambda microVM image, which the runner's host\n\ + # builds (docs/architecture.md#aws-lambda-microvms): the sandbox image,\n\ + # and fctl-agent, which answers Lambda's lifecycle hooks and runs what\n\ + # the host asks, over WebSockets through the microVM's endpoint.\n\ + FROM {from}\n\ + USER root\n\ + COPY fctl-agent /opt/fctl/bin/fctl-agent\n\ + RUN chmod 755 /opt/fctl/bin/fctl-agent\n\ + ENV FCTL_SANDBOX_USER={user}\n\ + CMD [\"/opt/fctl/bin/fctl-agent\", \"microvm-serve\"]\n" + ) +} + +/// The archive Lambda builds the image from. +pub fn artifact(from: &str, user: &str, agent: &[u8]) -> std::io::Result> { + let dockerfile = dockerfile(from, user); + zip::write(&[ + zip::Entry { + name: "Dockerfile", + mode: 0o644, + data: dockerfile.as_bytes(), + }, + zip::Entry { + name: "fctl-agent", + mode: 0o755, + data: agent, + }, + ]) +} + +/// The lifecycle hooks the image turns on, on [`HOOKS_PORT`]: `/ready` +/// and `/validate` as it builds, then each microVM's `/run`, `/suspend`, +/// `/resume` and `/terminate`. +pub fn hooks() -> Hooks { + let enabled = |list: &[(&str, u32)]| { + let mut hooks = BTreeMap::new(); + for (name, timeout) in list { + hooks.insert((*name).to_owned(), serde_json::json!("ENABLED")); + hooks.insert( + format!("{name}TimeoutInSeconds"), + serde_json::json!(timeout), + ); + } + hooks + }; + Hooks { + port: HOOKS_PORT, + microvm_image_hooks: enabled(&[("ready", 120), ("validate", 60)]), + microvm_hooks: enabled(&[ + ("run", 10), + ("resume", 10), + ("suspend", 30), + ("terminate", 10), + ]), + } +} + +/// What the image's version says it was built for: `fctl 0.40.0, 2048 +/// MiB, arm64`. +pub fn description(fctl: &str, memory_mb: u32, arch: MicrovmArch) -> String { + let arch = match arch { + MicrovmArch::Arm64 => "arm64", + MicrovmArch::X86_64 => "x86_64", + }; + format!("fctl {fctl}, {memory_mb} MiB, {arch}") +} + +/// The fctl a version was built for, from its [`description`]. +pub fn built_for(description: &str) -> Option<&str> { + description + .strip_prefix("fctl ")? + .split(',') + .next() + .map(str::trim) + .filter(|v| !v.is_empty()) +} + +/// The image's name: the settings' own, or the ARN's last part. +pub fn name(image: &MicrovmImage) -> String { + match image { + MicrovmImage::Managed { name, .. } => name + .clone() + .filter(|n| !n.is_empty()) + .unwrap_or_else(|| DEFAULT_IMAGE_NAME.to_owned()), + MicrovmImage::Own { arn, .. } => arn + .rsplit_once(':') + .map_or_else(|| arn.clone(), |(_, n)| n.to_owned()), + } +} + +/// The request that has Lambda build a version of the managed image. +pub struct Build<'a> { + pub settings: &'a MicrovmSettings, + pub fctl: &'a str, + pub artifact_uri: String, + pub build_role_arn: &'a str, + pub base_image_arn: String, + pub client_token: String, + /// It exists: an update, not a create. + pub update: bool, +} + +pub fn request(b: &Build<'_>) -> ImageRequest { + let arch = b.settings.arch.unwrap_or_default(); + ImageRequest { + name: (!b.update).then(|| name(&b.settings.image)), + client_token: b.client_token.clone(), + base_image_arn: b.base_image_arn.clone(), + build_role_arn: b.build_role_arn.to_owned(), + description: description(b.fctl, b.settings.memory_mb, arch), + code_artifact: CodeArtifact { + uri: b.artifact_uri.clone(), + }, + cpu_configurations: vec![CpuConfiguration { + architecture: arch.api().to_owned(), + }], + resources: vec![Resources { + minimum_memory_in_mi_b: b.settings.memory_mb, + }], + // fctl-agent runs as root, as a user of its own for the session, + // and keeps itself from the OOM killer. + additional_os_capabilities: vec!["ALL".into()], + hooks: hooks(), + environment_variables: BTreeMap::new(), + kms_key_identifier: b.settings.kms_key_arn.clone(), + logging: b.settings.log_group.clone().map(|g| Logging { + cloud_watch: CloudWatch { log_group: g }, + }), + } +} + +/// Whether `version` is what the managed settings want, for this fctl. +pub fn current(version: &ImageVersion, settings: &MicrovmSettings, fctl: &str) -> bool { + let arch = settings.arch.unwrap_or_default(); + version.description.as_deref() == Some(&description(fctl, settings.memory_mb, arch)) +} + +/// The report of an image's version that microVMs run. +pub fn report( + arn: &str, + version: Option<&ImageVersion>, + status: MicrovmImageStatus, + error: Option, + since: Option, +) -> MicrovmImageReport { + let size = version.and_then(|v| v.memory_mb()).and_then(microvm_size); + MicrovmImageReport { + arn: arn.to_owned(), + status, + version: version.map(|v| v.image_version.clone()), + fctl_version: version + .and_then(|v| v.description.as_deref()) + .and_then(built_for) + .map(str::to_owned), + building: None, + since, + error, + size, + arch: version.and_then(|v| v.arch()).and_then(MicrovmArch::parse), + } +} + +/// The latest version of `name` that microVMs run from, and the image. +pub async fn runnable( + api: &Api, + name: &str, + pinned: Option<&str>, +) -> Result<(api::Image, Option), api::Error> { + let image = api.image(name).await?; + let version = match pinned.or(image.latest_active_image_version.as_deref()) { + Some(v) => Some(api.image_version(name, v).await?), + None => None, + }; + Ok((image, version)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_dockerfile_runs_microvm_serve_as_root_and_sessions_as_the_user() { + let d = dockerfile("ghcr.io/hyperstructure/sandbox:0.40.0", "agent"); + assert!(d.contains("FROM ghcr.io/hyperstructure/sandbox:0.40.0\nUSER root\n")); + assert!(d.ends_with("CMD [\"/opt/fctl/bin/fctl-agent\", \"microvm-serve\"]\n")); + assert!(d.contains("ENV FCTL_SANDBOX_USER=agent")); + } + + #[test] + fn versions_say_what_they_were_built_for() { + let d = description("0.40.0", 2048, MicrovmArch::Arm64); + assert_eq!(d, "fctl 0.40.0, 2048 MiB, arm64"); + assert_eq!(built_for(&d), Some("0.40.0")); + assert_eq!(built_for("built by hand"), None); + let mut settings = fctl_domain::microvm::defaults(MicrovmImage::Managed { + artifacts: "s3://acme/fctl".into(), + build_role_arn: "arn:aws:iam::123456789012:role/b".into(), + name: None, + }); + let version = ImageVersion { + description: Some(d), + ..ImageVersion::default() + }; + assert!(current(&version, &settings, "0.40.0")); + assert!(!current(&version, &settings, "0.41.0")); + settings.memory_mb = 4096; + assert!(!current(&version, &settings, "0.40.0")); + assert_eq!(name(&settings.image), "fctl-sandbox"); + assert_eq!( + name(&MicrovmImage::Own { + arn: "arn:aws:lambda:us-east-1:123456789012:microvm-image:agents".into(), + version: None + }), + "agents" + ); + } + + #[test] + fn the_image_turns_on_every_hook_with_a_timeout() -> serde_json::Result<()> { + let hooks = serde_json::to_value(hooks())?; + assert_eq!(hooks["port"], 9000); + assert_eq!(hooks["microvmImageHooks"]["ready"], "ENABLED"); + assert_eq!(hooks["microvmImageHooks"]["readyTimeoutInSeconds"], 120); + for hook in ["run", "resume", "suspend", "terminate"] { + assert_eq!(hooks["microvmHooks"][hook], "ENABLED"); + assert!(hooks["microvmHooks"][format!("{hook}TimeoutInSeconds")].is_number()); + } + Ok(()) + } +} diff --git a/crates/fctl-host/src/driver/lambda/link.rs b/crates/fctl-host/src/driver/lambda/link.rs new file mode 100644 index 000000000..11973b9ee --- /dev/null +++ b/crates/fctl-host/src/driver/lambda/link.rs @@ -0,0 +1,220 @@ +//! The host's requests to `fctl-agent microvm-serve` in a microVM: each a +//! WebSocket through the microVM's endpoint, with the endpoint's auth +//! token, the port, and the key the host ran the microVM with +//! ([`fctl_proto::microvm::KEY_HEADER`]), carrying one of +//! [`fctl_proto::vm`]'s requests and what follows it, as a vsock +//! connection does to a Firecracker VM's init. + +use crate::driver::firecracker::vsock::{self, Output, Started}; +use anyhow::{Context, Result, bail}; +use fctl_proto::microvm::{KEY_HEADER, SERVE_PATH, SERVE_PORT}; +use fctl_proto::vm::{Exec, Reply, Request}; +use futures::{SinkExt, StreamExt}; +use std::time::Duration; +use tokio::io::{AsyncReadExt, AsyncWriteExt, BufReader, DuplexStream, ReadHalf, WriteHalf}; +use tokio_tungstenite::tungstenite::Message; +use tokio_tungstenite::tungstenite::client::IntoClientRequest; +use tokio_tungstenite::tungstenite::http::HeaderValue; + +/// How long connecting to a microVM, and its first answer, may take. +pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(30); + +/// Where a microVM's `microvm-serve` is, and what reaches it. +#[derive(Clone)] +pub struct Target { + /// The microVM's endpoint, as Lambda says it: a host name + /// (`mvm-….lambda-microvm.us-east-1.on.aws`), or a stand-in's + /// `127.0.0.1:`. + pub endpoint: String, + /// `X-aws-proxy-auth`'s value. + pub token: String, + /// The key the microVM was run with. + pub key: String, +} + +impl std::fmt::Debug for Target { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Target") + .field("endpoint", &self.endpoint) + .finish_non_exhaustive() + } +} + +/// The WebSocket's URL: TLS, but to a stand-in on this machine. +pub fn url(endpoint: &str) -> String { + let host = match endpoint.strip_prefix('[') { + // An IPv6 address, in brackets before its port. + Some(rest) => rest.split(']').next().unwrap_or(rest), + None => endpoint.split(':').next().unwrap_or(endpoint), + }; + let local = matches!(host, "127.0.0.1" | "localhost" | "::1"); + let scheme = if local { "ws" } else { "wss" }; + format!("{scheme}://{endpoint}{SERVE_PATH}") +} + +pub type Reader = BufReader>; +pub type Writer = WriteHalf; + +/// Opens a WebSocket to the microVM, as a byte stream. +pub async fn connect(target: &Target) -> Result<(Reader, Writer)> { + let mut req = url(&target.endpoint).into_client_request()?; + let headers = req.headers_mut(); + headers.insert("x-aws-proxy-auth", HeaderValue::from_str(&target.token)?); + headers.insert("x-aws-proxy-port", HeaderValue::from(SERVE_PORT)); + headers.insert(KEY_HEADER, HeaderValue::from_str(&target.key)?); + headers.insert( + "user-agent", + HeaderValue::from_str(&format!("fctl-host/{}", crate::agentbin::VERSION))?, + ); + let connector = tokio_tungstenite::Connector::Rustls(fctl_client::tls_config()); + let config = tokio_tungstenite::tungstenite::protocol::WebSocketConfig::default() + .max_message_size(Some(64 << 20)) + .max_frame_size(Some(32 << 20)); + let connecting = + tokio_tungstenite::connect_async_tls_with_config(req, Some(config), true, Some(connector)); + let (ws, _) = tokio::time::timeout(CONNECT_TIMEOUT, connecting) + .await + .map_err(|_| anyhow::anyhow!("the microVM's endpoint didn't answer within 30 seconds"))? + .map_err(|e| anyhow::anyhow!("connecting to the microVM's endpoint: {e}"))?; + let (mut sink, mut stream) = ws.split(); + let (ours, theirs) = tokio::io::duplex(1024 * 1024); + let (mut from_us, mut to_us) = tokio::io::split(ours); + // The microVM's messages, as the stream's bytes. + let inbound = tokio::spawn(async move { + while let Some(msg) = stream.next().await { + let data = match msg { + Ok(Message::Binary(b)) => b.to_vec(), + Ok(Message::Text(t)) => t.as_bytes().to_vec(), + Ok(Message::Close(_)) | Err(_) => break, + Ok(_) => continue, + }; + if to_us.write_all(&data).await.is_err() { + break; + } + } + let _ = to_us.shutdown().await; + }); + // The stream's bytes, as messages. + tokio::spawn(async move { + let mut buf = vec![0u8; 64 * 1024]; + loop { + match from_us.read(&mut buf).await { + Ok(0) | Err(_) => break, + Ok(n) => { + if sink.send(Message::binary(buf[..n].to_vec())).await.is_err() { + break; + } + } + } + } + let _ = sink.send(Message::Close(None)).await; + inbound.abort(); + }); + let (r, w) = tokio::io::split(theirs); + Ok((BufReader::new(r), w)) +} + +/// Sends `request`; the connection and the first reply. +pub async fn ask(target: &Target, request: &Request) -> Result<(Reader, Writer, Reply)> { + let asking = async { + let (mut r, mut w) = connect(target).await?; + let mut line = serde_json::to_vec(request)?; + line.push(b'\n'); + w.write_all(&line).await?; + let reply = vsock::read_reply(&mut r).await?; + Ok::<_, anyhow::Error>((r, w, reply)) + }; + tokio::time::timeout(CONNECT_TIMEOUT * 2, asking) + .await + .map_err(|_| anyhow::anyhow!("the microVM didn't answer within a minute"))? +} + +/// Sends `request`, failing with the error it answers with. +async fn request(target: &Target, request: &Request) -> Result<(Reader, Writer)> { + let (r, w, reply) = ask(target, request).await?; + if let Some(e) = reply.error { + bail!("{e}"); + } + Ok((r, w)) +} + +/// What `microvm-serve` says of itself: its version, its user, its +/// architecture, Lambda's id for the microVM and who ran it. +pub async fn hello(target: &Target) -> Result { + let (_, _, reply) = ask( + target, + &Request::Hello { + now_ms: Some(vsock::now_ms()), + }, + ) + .await?; + Ok(reply) +} + +/// Runs `exec` with `input`, to its end. +pub async fn run(target: &Target, mut exec: Exec, input: Option<&[u8]>) -> Result { + exec.stdin = input.is_some(); + exec.now_ms = Some(vsock::now_ms()); + let (r, w) = request(target, &Request::Exec(exec)).await?; + vsock::run_on(r, w, input).await +} + +/// Starts `exec` without waiting for it, with nothing in or out. +pub async fn detach(target: &Target, mut exec: Exec) -> Result<()> { + exec.detach = true; + exec.stdin = false; + exec.now_ms = Some(vsock::now_ms()); + request(target, &Request::Exec(exec)).await.map(drop) +} + +/// Starts `exec` with its input and output piped. +pub async fn start(target: &Target, mut exec: Exec) -> Result { + exec.stdin = true; + exec.detach = false; + exec.now_ms = Some(vsock::now_ms()); + let (r, w) = request(target, &Request::Exec(exec)).await?; + Ok(vsock::start_on(r, w)) +} + +/// Runs `script` with `sh -c` as `user`, and returns what it wrote; an +/// error with what it wrote to stderr when it fails. +pub async fn sh(target: &Target, user: Option<&str>, script: &str) -> Result { + let out = run( + target, + Exec { + argv: vec!["/bin/sh".into(), "-c".into(), script.into()], + user: user.map(str::to_owned), + ..Exec::default() + }, + None, + ) + .await + .context("running a command in the microVM")?; + if out.code != 0 { + bail!( + "a command in the microVM failed ({}): {}", + out.code, + String::from_utf8_lossy(&out.stderr).trim() + ); + } + Ok(String::from_utf8_lossy(&out.stdout).into_owned()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn microvms_are_reached_over_tls_but_a_stand_in_here() { + assert_eq!( + url("mvm-1.lambda-microvm.us-east-1.on.aws"), + "wss://mvm-1.lambda-microvm.us-east-1.on.aws/fctl/v1/vm" + ); + assert_eq!(url("127.0.0.1:41234"), "ws://127.0.0.1:41234/fctl/v1/vm"); + assert_eq!(url("localhost:9"), "ws://localhost:9/fctl/v1/vm"); + assert_eq!(url("[::1]:9"), "ws://[::1]:9/fctl/v1/vm"); + // A host that only starts like one isn't one. + assert!(url("127.0.0.1.evil.example").starts_with("wss://")); + assert!(url("[2001:db8::1]:9").starts_with("wss://")); + } +} diff --git a/crates/fctl-host/src/driver/lambda/mod.rs b/crates/fctl-host/src/driver/lambda/mod.rs new file mode 100644 index 000000000..fd0b8490c --- /dev/null +++ b/crates/fctl-host/src/driver/lambda/mod.rs @@ -0,0 +1,2334 @@ +//! The `lambda` driver: each session in an AWS Lambda microVM of its own +//! (docs/architecture.md#aws-lambda-microvms, ADR 0106). +//! +//! The host runs on a machine that may manage the account's microVMs (or +//! assume a role that may: `[lambda]` in host.toml), and its runner's +//! settings come from the control plane ([`MicrovmSettings`]). A session's +//! sandbox is a microVM: [`LambdaDriver::ensure`] resumes the one it has, +//! takes a warm one, or runs a new one, and the host reaches +//! `fctl-agent microvm-serve` in it through its endpoint ([`link`]) to put +//! fctl-agent in, start it and attach, as it would through Firecracker's +//! vsock. The session's host suspends the microVM once the session has +//! waited with nothing running for the settings' `suspend_after_secs` +//! (crate::session), resumes it for whatever comes for the agent, and lets +//! it go once it has been suspended for `terminate_after_minutes`. +//! +//! In the background ([`LambdaDriver::upkeep`]) the driver keeps the image +//! ready ([`image`]), keeps `warm` microVMs started and suspended for new +//! sessions, follows its microVMs' states, lets go of those whose session +//! stopped once they have been suspended for long enough, and of those no +//! session or pool needs, and says how they are ([`LambdaDriver::report`]). +//! +//! What it knows of its microVMs is in `lambda/microvms.json` in the data +//! directory, with each one's key (only the host's requests carry it), so +//! that a host that restarts finds them again. + +pub mod api; +pub mod image; +pub mod link; +mod zip; + +use crate::aws::{self, Keys, Role}; +use crate::config::HostConfig; +use crate::driver::{AgentIo, Running, Sandbox, SandboxInfo, SandboxSpec, Socket}; +use anyhow::{Context, Result, bail}; +use api::Api; +use fctl_domain::microvm::{self as rules, PoolState, WarmVm}; +use fctl_proto::Millis; +use fctl_proto::microvm::{ + DRIVER, MAX_LIFETIME_SECS, MicrovmImage, MicrovmImageReport, MicrovmImageStatus, + MicrovmProblem, MicrovmReport, MicrovmSettings, MicrovmSize, MicrovmState, MicrovmVm, + RunPayload, SERVE_PORT, microvm_size, +}; +use fctl_proto::runner::{DriverInfo, SandboxSize}; +use fctl_proto::vm::Exec; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::{Duration, Instant}; +use tokio::sync::Notify; + +/// How long a microVM may take to run, or to resume. +const START_TIMEOUT: Duration = Duration::from_secs(3 * 60); +/// How long `microvm-serve` may take to answer once Lambda says it runs. +const ANSWER_TIMEOUT: Duration = Duration::from_secs(90); +/// How long a new session waits for room among the runner's microVMs. +const ROOM_TIMEOUT: Duration = Duration::from_secs(90); +/// How often the background upkeep runs, besides when something nudges it. +const UPKEEP_EVERY: Duration = Duration::from_secs(5); +/// How often it reads every microVM's state from Lambda. +const LIST_EVERY: Duration = Duration::from_secs(30); +/// How often it looks at the image again while it is ready. +const IMAGE_EVERY: Duration = Duration::from_secs(10 * 60); +/// How often it looks at an image that builds. +const BUILDING_EVERY: Duration = Duration::from_secs(15); +/// How long after a failed build it builds again. +const REBUILD_AFTER: Duration = Duration::from_secs(30 * 60); +/// How long the host waits before it tries again to terminate a microVM +/// AWS hasn't let go of. +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); + +fn now_ms() -> Millis { + crate::expiry::now_ms() +} + +fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { + m.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// A microVM, as the host keeps it. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +struct Vm { + /// What the host calls it: its session's sandbox's name, or `warm-…` + /// while it waits for one. + name: String, + /// Lambda's id, once Lambda answered. + #[serde(default)] + id: Option, + /// What `RunMicrovm` was asked with, so that asking again after a + /// restart runs no second one. + client_token: String, + /// The key `microvm-serve` takes the host's requests with. + key: String, + #[serde(default)] + endpoint: Option, + state: MicrovmState, + since: Millis, + started_at: Millis, + #[serde(default)] + image_version: Option, + fingerprint: String, + /// When the host last suspended it. + #[serde(default)] + suspended_at: Option, + /// What `microvm-serve` said of itself. + #[serde(default)] + agent: Option, + #[serde(default)] + user: Option, + #[serde(default)] + arch: Option, + /// Its session's run ended (the sandbox stopped): it waits, suspended, + /// for the session's next run, or to go. + #[serde(default)] + ended: bool, + /// The agent saved the session's snapshot as the host last suspended + /// it: letting it go loses nothing. + #[serde(default)] + checkpointed: bool, + /// What `RunMicrovm` was asked, until Lambda answered with its id: the + /// same request again (its client token) finds a microVM that Lambda + /// ran though its answer never came. + #[serde(default, skip_serializing_if = "Option::is_none")] + run: Option, +} + +impl Vm { + fn warm(&self) -> bool { + self.name.starts_with("warm-") + } + + /// One the host lets go of, which AWS hasn't said is gone yet. + fn going(&self) -> bool { + self.name.starts_with("going-") + } +} + +#[derive(Debug, Default, Serialize, Deserialize)] +struct Saved { + #[serde(default)] + vms: Vec, + /// The settings it last had, for a host that starts before the control + /// plane sends them again. + #[serde(default)] + settings: Option, + /// The image version it last had Lambda build, and when. + #[serde(default)] + building: Option<(String, String, Millis)>, +} + +/// What the driver found of its image. +#[derive(Clone, Debug, Default)] +struct ImageView { + /// What microVMs run from: its ARN, version, and what it is. + arn: Option, + version: Option, + size: Option, + report: Option, + looked_at: Option, + failed_at: Option, +} + +struct Inner { + cfg: HostConfig, + dir: PathBuf, + runner: Mutex, + settings: Mutex>, + api: Mutex>>, + saved: Mutex, + image: Mutex, + tokens: Mutex>, + problem: Mutex>, + /// Sandboxes whose microVM a session's host works on now (runs, + /// resumes, suspends): the upkeep leaves them be. + busy: Mutex>, + wake: Notify, + changed: AtomicU64, + upkeep_started: AtomicBool, + listed_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. + save_lock: Mutex<()>, +} + +/// Runs sessions in AWS Lambda microVMs. +#[derive(Clone)] +pub struct LambdaDriver { + inner: Arc, +} + +impl std::fmt::Debug for LambdaDriver { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("LambdaDriver").finish_non_exhaustive() + } +} + +/// Holds a sandbox's microVM for a session's host while it works on it. +struct Busy<'a>(&'a Inner, String); + +impl Drop for Busy<'_> { + fn drop(&mut self) { + let mut busy = lock(&self.0.busy); + if let Some(n) = busy.get_mut(&self.1) { + *n -= 1; + if *n == 0 { + busy.remove(&self.1); + } + } + } +} + +impl LambdaDriver { + pub fn new(cfg: &HostConfig) -> Self { + let dir = cfg.data_dir().join("lambda"); + let saved: Saved = std::fs::read_to_string(dir.join("microvms.json")) + .ok() + .and_then(|t| serde_json::from_str(&t).ok()) + .unwrap_or_default(); + let settings = saved.settings.clone(); + Self { + inner: Arc::new(Inner { + cfg: cfg.clone(), + dir, + runner: Mutex::new(String::new()), + settings: Mutex::new(settings), + api: Mutex::new(None), + saved: Mutex::new(saved), + image: Mutex::new(ImageView::default()), + tokens: Mutex::new(HashMap::new()), + problem: Mutex::new(None), + busy: Mutex::new(HashMap::new()), + wake: Notify::new(), + changed: AtomicU64::new(1), + upkeep_started: AtomicBool::new(false), + save_lock: Mutex::new(()), + listed_at: Mutex::new(None), + region: Mutex::new(None), + }), + } + } + + fn busy(&self, name: &str) -> Busy<'_> { + *lock(&self.inner.busy).entry(name.to_owned()).or_default() += 1; + Busy(&self.inner, name.to_owned()) + } + + /// The runner the host runs as, for the microVMs it runs from now on. + pub fn set_runner(&self, runner: &str) { + *lock(&self.inner.runner) = runner.to_owned(); + } + + /// The settings the control plane sent, kept for the next start; and + /// the upkeep, from the first. + pub fn set_settings(&self, settings: Option) { + let changed = { + let mut current = lock(&self.inner.settings); + let changed = *current != settings; + current.clone_from(&settings); + changed + }; + if changed { + // Where they run may have changed with them. + *lock(&self.inner.api) = None; + *lock(&self.inner.region) = None; + *lock(&self.inner.image) = ImageView::default(); + *lock(&self.inner.problem) = None; + lock(&self.inner.saved).settings = settings; + self.save(); + self.note_changed(); + } + self.start_upkeep(); + self.inner.wake.notify_one(); + } + + pub fn settings(&self) -> Option { + lock(&self.inner.settings).clone() + } + + /// Starts the background upkeep, once. + pub fn start_upkeep(&self) { + if self.inner.upkeep_started.swap(true, Ordering::SeqCst) { + return; + } + let me = self.clone(); + tokio::spawn(async move { + loop { + me.upkeep().await; + let _ = tokio::time::timeout(UPKEEP_EVERY, me.inner.wake.notified()).await; + } + }); + } + + fn note_changed(&self) { + self.inner.changed.fetch_add(1, Ordering::SeqCst); + } + + /// A number that changes whenever the report would. + pub fn version(&self) -> u64 { + self.inner.changed.load(Ordering::SeqCst) + } + + fn save(&self) { + let _one = lock(&self.inner.save_lock); + let text = match serde_json::to_string_pretty(&*lock(&self.inner.saved)) { + Ok(t) => t, + Err(e) => { + tracing::warn!("saving the microVMs: {e}"); + return; + } + }; + if let Err(e) = std::fs::create_dir_all(&self.inner.dir) + .map_err(anyhow::Error::from) + .and_then(|()| { + crate::config::write_private(&self.inner.dir.join("microvms.json"), &text) + }) + { + tracing::warn!("saving the microVMs: {e:#}"); + } + } + + fn vm(&self, name: &str) -> Option { + lock(&self.inner.saved) + .vms + .iter() + .find(|v| v.name == name) + .cloned() + } + + fn put(&self, vm: Vm) { + { + let mut saved = lock(&self.inner.saved); + match saved.vms.iter_mut().find(|v| v.name == vm.name) { + Some(v) => *v = vm, + None => saved.vms.push(vm), + } + } + self.save(); + self.note_changed(); + } + + fn update(&self, name: &str, f: impl FnOnce(&mut Vm)) { + { + let mut saved = lock(&self.inner.saved); + if let Some(v) = saved.vms.iter_mut().find(|v| v.name == name) { + f(v); + } + } + self.save(); + self.note_changed(); + } + + fn forget(&self, name: &str) { + let id = { + let mut saved = lock(&self.inner.saved); + let id = saved + .vms + .iter() + .find(|v| v.name == name) + .and_then(|v| v.id.clone()); + saved.vms.retain(|v| v.name != name); + id + }; + if let Some(id) = id { + lock(&self.inner.tokens).remove(&id); + } + self.save(); + self.note_changed(); + } + + /// The region its microVMs run in: host.toml's, the settings', or the + /// machine's. + async fn region(&self) -> String { + if let Some(r) = lock(&self.inner.region).clone() { + return r; + } + let from_settings = self.settings().as_ref().and_then(rules::region); + let configured = self.inner.cfg.lambda.region.clone().or(from_settings); + let region = aws::region(configured.as_deref()).await; + *lock(&self.inner.region) = Some(region.clone()); + region + } + + async fn api(&self) -> Result> { + if let Some(api) = lock(&self.inner.api).clone() { + return Ok(api); + } + let region = self.region().await; + let lambda = &self.inner.cfg.lambda; + let role = lambda.role_arn.clone().map(|arn| Role { + arn, + external_id: lambda.external_id.clone(), + }); + let keys = match &lambda.endpoint { + // The dev stack's stand-in takes any keys. + Some(e) if e.starts_with("http://127.0.0.1") || e.starts_with("http://localhost") => { + Keys::fixed( + ®ion, + fctl_domain::sigv4::Credentials { + access_key_id: "AKIDSTANDIN".into(), + secret_access_key: "stand-in".into(), + session_token: None, + }, + ) + } + _ => Keys::new(®ion, role), + }; + let api = Arc::new( + Api::new(Arc::new(keys), lambda.endpoint.as_deref()).map_err(anyhow::Error::msg)?, + ); + *lock(&self.inner.api) = Some(api.clone()); + Ok(api) + } + + /// Notes what AWS answered, for the report: a problem it stops on, or + /// that it no longer does. + fn note(&self, result: Result<(), &api::Error>, doing: &str) { + let mut problem = lock(&self.inner.problem); + let before = problem.clone(); + match result { + Ok(()) => *problem = None, + Err(e) => { + let message = problem_words(e, doing); + let same = problem.as_ref().is_some_and(|p| p.message == message); + if !same { + *problem = Some(MicrovmProblem { + kind: e.kind().to_owned(), + message, + since: now_ms(), + }); + } + } + } + if *problem != before { + drop(problem); + self.note_changed(); + } + } + + fn fail(&self, e: api::Error, doing: &str) -> anyhow::Error { + self.note(Err(&e), doing); + anyhow::anyhow!("{}", problem_words(&e, doing)) + } + + // ───────────────────────────── the driver ───────────────────────────── + + pub fn name(&self) -> &'static str { + DRIVER + } + + /// Whether it can start sandboxes now, and why not. + pub async fn probe(&self) -> DriverInfo { + let info = |available: bool, detail: Option, version: Option| DriverInfo { + name: DRIVER.into(), + available, + isolation: "vm".into(), + version, + detail, + }; + let region = lock(&self.inner.region).clone(); + let Some(settings) = self.settings() else { + return info( + false, + Some("its microVMs have no settings yet: set them on the runner's page, in its workspace's Runners tab".into()), + region, + ); + }; + if let Err(e) = rules::check(&settings) { + return info( + false, + Some(format!("its microVM settings don't work: {}", e.message)), + region, + ); + } + if let Some(p) = lock(&self.inner.problem).clone() + && matches!(p.kind.as_str(), "access" | "credentials" | "settings") + { + return info(false, Some(p.message), region); + } + let image = lock(&self.inner.image).clone(); + match (&image.version, &image.report) { + (Some(_), _) => info(true, None, region), + (None, Some(r)) if r.status == MicrovmImageStatus::Building => info( + false, + Some(format!( + "Lambda is building its microVM image ({}), which takes a few minutes", + r.building + .as_deref() + .map_or_else(|| "fctl".to_owned(), |v| format!("fctl {v}")) + )), + region, + ), + (None, Some(r)) => info( + false, + Some(r.error.clone().unwrap_or_else(|| { + format!("its microVM image {} has no version to run", r.arn) + })), + region, + ), + (None, None) => info(false, Some("looking at its microVM image".into()), region), + } + } + + /// Whether this machine may manage the account's microVMs, as `fctl + /// host install` checks before it registers the runner: the region it + /// works in, or what AWS answered. + pub async fn check_access(&self) -> Result { + let api = self.api().await?; + match api.reachable().await { + Ok(()) => Ok(format!("AWS Lambda microVMs in {}", api.region())), + Err(e) => Err(anyhow::anyhow!( + "{}", + problem_words(&e, "listing its microVMs") + )), + } + } + + /// The size of its microVMs, as it bursts to: what each sandbox has. + pub fn sandbox_size(&self) -> Option { + let image = lock(&self.inner.image).size; + image + .or_else(|| self.settings().and_then(|s| microvm_size(s.memory_mb))) + .map(MicrovmSize::peak) + } + + /// How many sessions it runs at once: as many as it may have microVMs. + pub fn capacity(&self) -> Option { + self.settings().map(|s| s.max_microvms) + } + + /// How long a session's agent waits with nothing running before it + /// stops by itself: after the host would have let its microVM go. + pub fn idle_timeout_secs(&self) -> Option { + self.settings().as_ref().map(rules::agent_idle_timeout_secs) + } + + pub fn exists(&self, name: &str) -> bool { + self.vm(name).is_some() + } + + /// The sandboxes it has, for the host: those of sessions, running or + /// suspended (as running, which the host attaches to or finds + /// suspended) while their run goes on, and stopped once it ended. + pub fn list(&self) -> Vec { + lock(&self.inner.saved) + .vms + .iter() + .filter(|v| !v.warm() && v.state != MicrovmState::Terminating) + .map(|v| SandboxInfo { + name: v.name.clone(), + running: !v.ended, + }) + .collect() + } + + /// Notes whether the agent saved the session's snapshot as the host + /// suspended its microVM. + pub fn set_checkpointed(&self, name: &str, saved: bool) { + self.update(name, |v| v.checkpointed = saved); + } + + pub fn checkpointed(&self, name: &str) -> bool { + self.vm(name).is_some_and(|v| v.checkpointed) + } + + /// Whether the session's microVM is suspended, and since when. + pub fn suspended(&self, name: &str) -> Option { + self.vm(name) + .filter(|v| matches!(v.state, MicrovmState::Suspended | MicrovmState::Suspending)) + .map(|v| v.suspended_at.unwrap_or(v.since)) + } + + /// When Lambda ends the session's microVM. + pub fn ends_at(&self, name: &str) -> Option { + self.vm(name).map(|v| rules::ends_at(v.started_at)) + } + + /// Lambda's id for the session's microVM. + pub fn microvm_id(&self, name: &str) -> Option { + self.vm(name).and_then(|v| v.id) + } + + /// Makes the session's sandbox ready: resumes its microVM, takes a + /// warm one, or runs a new one, and waits for `microvm-serve` to + /// answer in it. + pub async fn ensure( + &self, + spec: &SandboxSpec, + log: &(dyn Fn(String) + Send + Sync), + ) -> Result { + let name = spec.name.clone(); + let _busy = self.busy(&name); + for _ in 0..3 { + match self.vm(&name) { + Some(vm) => match self.bring_back(&vm, log).await? { + true => {} + // Gone, or too near its end: another one. + false => continue, + }, + None => self.take_or_run(&name, log).await?, + } + self.answer(&name).await?; + self.update(&name, |v| { + v.ended = false; + v.checkpointed = false; + }); + return Ok(Sandbox { name, root: None }); + } + bail!("couldn't get a microVM for the session") + } + + /// Readies the microVM a session has: true once it runs, false when it + /// is gone (and forgotten). + async fn bring_back(&self, vm: &Vm, log: &(dyn Fn(String) + Send + Sync)) -> Result { + let api = self.api().await?; + let Some(id) = vm.id.clone() else { + // Asked to run, with no answer (a host that stopped mid-call): + // the upkeep finds and lets go of what Lambda may have run, and + // the session takes another, as its agent never started there. + match vm.run { + Some(_) => self.let_go(&vm.name), + None => self.forget(&vm.name), + } + log("Its microVM's start got no answer, so it starts in another".into()); + return Ok(false); + }; + let live = match api.get(&id).await { + Ok(live) => live, + Err(e) if e.not_found() => { + self.forget(&vm.name); + log(format!( + "Its microVM {id} is gone, so it starts in a new one, from its snapshot" + )); + return Ok(false); + } + Err(e) => return Err(self.fail(e, "reading its microVM")), + }; + let now = now_ms(); + match live.state.as_str() { + "RUNNING" => { + self.update(&vm.name, |v| { + v.state = MicrovmState::Running; + v.endpoint = live.endpoint.clone().or(v.endpoint.take()); + }); + Ok(true) + } + "SUSPENDED" | "SUSPENDING" if !rules::resumes(vm.started_at, now) => { + log(format!( + "Its microVM {id} has less than an hour of the 8 Lambda gives one, so it starts in a new one, from its snapshot" + )); + self.terminate_vm(&vm.name).await; + Ok(false) + } + "SUSPENDED" | "SUSPENDING" => { + let since = vm.suspended_at.unwrap_or(vm.since); + log(format!( + "Resuming its microVM {id}, suspended {} ago", + rules::span(u64::try_from((now - since) / 1000).unwrap_or(0)) + )); + self.resume_vm(&vm.name).await?; + Ok(true) + } + "PENDING" => { + self.wait_running(&vm.name, &id).await?; + Ok(true) + } + _ => { + self.forget(&vm.name); + log(format!( + "Its microVM {id} is gone, so it starts in a new one, from its snapshot" + )); + Ok(false) + } + } + } + + /// A warm microVM becomes the session's, or a new one runs for it. + async fn take_or_run(&self, name: &str, log: &(dyn Fn(String) + Send + Sync)) -> Result<()> { + let (settings, fingerprint, _) = self.ready()?; + let now = now_ms(); + let warm = { + let mut saved = lock(&self.inner.saved); + let candidates: Vec = saved + .vms + .iter() + .filter(|v| v.warm() && v.id.is_some()) + .map(warm_of) + .collect(); + let picked = rules::pick_warm(&candidates, &fingerprint, now).map(|w| w.id.clone()); + match picked.and_then(|p| saved.vms.iter_mut().find(|v| v.name == p)) { + Some(v) => { + v.name = name.to_owned(); + Some(v.clone()) + } + None => None, + } + }; + self.save(); + self.note_changed(); + self.inner.wake.notify_one(); + if let Some(vm) = warm { + let id = vm.id.clone().unwrap_or_default(); + log(format!("Starting in a warm microVM, {id}")); + match self.resume_vm(name).await { + Ok(()) => return Ok(()), + Err(e) => { + log(format!( + "The warm microVM {id} didn't resume ({e:#}), so a new one runs" + )); + self.terminate_vm(name).await; + } + } + } + self.wait_for_room(&settings).await?; + let vm = self.new_vm(name, &fingerprint); + log(format!( + "Running a new microVM of {} MiB", + settings.memory_mb + )); + self.run_vm(name, vm).await + } + + /// Settings, the fingerprint of the microVMs they run, and the image + /// version: or why there are none to run. + fn ready(&self) -> Result<(MicrovmSettings, String, String)> { + let Some(settings) = self.settings() else { + bail!("its microVMs have no settings yet") + }; + let version = lock(&self.inner.image).version.clone(); + let Some(version) = version else { + bail!("its microVM image has no version to run yet") + }; + let fingerprint = rules::fingerprint(&settings, &version); + Ok((settings, fingerprint, version)) + } + + fn new_vm(&self, name: &str, fingerprint: &str) -> Vm { + Vm { + name: name.to_owned(), + id: None, + client_token: format!("fctl-{}", hex::encode(fctl_domain::random_bytes::<16>())), + key: hex::encode(fctl_domain::random_bytes::<32>()), + endpoint: None, + state: MicrovmState::Starting, + since: now_ms(), + started_at: now_ms(), + image_version: lock(&self.inner.image).version.clone(), + fingerprint: fingerprint.to_owned(), + suspended_at: None, + agent: None, + user: None, + arch: None, + ended: false, + checkpointed: false, + run: None, + } + } + + /// How many more microVMs it may have now. + /// How many more microVMs it may have: every one it keeps counts, those + /// it lets go of too until AWS says they're gone. + fn room(&self, settings: &MicrovmSettings) -> usize { + let have = lock(&self.inner.saved).vms.len(); + (settings.max_microvms as usize).saturating_sub(have) + } + + /// Whether a new session would wait for room that sessions hold: no + /// warm microVM, and as many sessions' and warm ones as it may have. + /// The host lets the longest suspended go then. Those it lets go of make + /// room by themselves as AWS lets them go: letting a session's go too + /// would free nothing sooner. + pub fn full(&self) -> bool { + let Some(settings) = self.settings() else { + return false; + }; + let saved = lock(&self.inner.saved); + let warm = saved + .vms + .iter() + .any(|v| v.warm() && v.state == MicrovmState::Suspended); + let held = saved.vms.iter().filter(|v| !v.going()).count(); + !warm && held >= settings.max_microvms as usize + } + + async fn wait_for_room(&self, settings: &MicrovmSettings) -> Result<()> { + let until = Instant::now() + ROOM_TIMEOUT; + loop { + if self.room(settings) > 0 { + return Ok(()); + } + // A warm one that would take a place goes first. + let warm = lock(&self.inner.saved) + .vms + .iter() + .find(|v| v.warm() && v.state == MicrovmState::Suspended) + .map(|v| v.name.clone()); + if let Some(w) = warm { + self.terminate_vm(&w).await; + continue; + } + if Instant::now() > until { + bail!( + "the runner has as many microVMs as it may ({}): a session's suspended one goes to make room, or raise its most microVMs", + settings.max_microvms + ); + } + tokio::time::sleep(Duration::from_millis(500)).await; + } + } + + /// Runs `vm` (new, or one whose answer never came), and waits for it. + async fn run_vm(&self, name: &str, vm: Vm) -> Result<()> { + let (settings, _, version) = self.ready()?; + let api = self.api().await?; + let region = api.region().to_owned(); + let partition = aws::partition(®ion); + let image_arn = lock(&self.inner.image).arn.clone().unwrap_or_default(); + let runner = lock(&self.inner.runner).clone(); + let payload = serde_json::to_string(&RunPayload { + fctl: 1, + runner, + name: vm.name.clone(), + key: vm.key.clone(), + })?; + let policy = rules::idle_policy(&settings); + let egress = match settings.egress_connectors.is_empty() { + true => vec![rules::lambda_connector( + partition, + ®ion, + "INTERNET_EGRESS", + )], + false => settings.egress_connectors.clone(), + }; + let req = api::RunRequest { + client_token: vm.client_token.clone(), + image_identifier: image_arn, + image_version: Some(version), + execution_role_arn: settings.execution_role_arn.clone(), + idle_policy: api::IdlePolicy { + auto_resume_enabled: policy.auto_resume, + max_idle_duration_seconds: policy.max_idle_secs, + suspended_duration_seconds: policy.suspended_secs, + }, + ingress_network_connectors: vec![rules::lambda_connector( + partition, + ®ion, + "HTTP_INGRESS", + )], + egress_network_connectors: egress, + kms_key_identifier: settings.kms_key_arn.clone(), + logging: settings.log_group.clone().map(|g| api::Logging { + cloud_watch: api::CloudWatch { log_group: g }, + }), + maximum_duration_in_seconds: MAX_LIFETIME_SECS, + run_hook_payload: payload, + }; + // Kept before it runs, with what it asks: a host that stops now, + // or whose answer never comes, finds it again. + self.put(Vm { + name: name.to_owned(), + run: Some(req.clone()), + ..vm + }); + let ran = match api.run(&req).await { + Ok(ran) => ran, + // Lambda may have run it though no answer came: the upkeep asks + // again, and lets it go. One it throttled, had no room for, or + // never got ran nothing. + Err(e) if e.may_have_happened() => { + self.let_go(name); + return Err(self.fail(e, "running a microVM")); + } + Err(e) => { + self.forget(name); + return Err(self.fail(e, "running a microVM")); + } + }; + self.note(Ok(()), ""); + let id = ran.microvm_id.clone(); + self.update(name, |v| { + v.id = Some(id.clone()); + v.run = None; + v.endpoint.clone_from(&ran.endpoint); + v.started_at = ran.started_at_ms().unwrap_or(v.started_at); + v.image_version.clone_from(&ran.image_version); + }); + if let Err(e) = self.wait_running(name, &id).await { + // One that never ran, or went, is let go of; none is left behind. + self.terminate_vm(name).await; + return Err(e); + } + Ok(()) + } + + /// Waits for Lambda to say the microVM runs. + async fn wait_running(&self, name: &str, id: &str) -> Result<()> { + let api = self.api().await?; + let until = Instant::now() + START_TIMEOUT; + let mut wait = Duration::from_millis(150); + loop { + match api.get(id).await { + Ok(live) if live.state == "RUNNING" => { + self.update(name, |v| { + v.state = MicrovmState::Running; + v.since = now_ms(); + v.endpoint = live.endpoint.clone().or(v.endpoint.take()); + v.started_at = live.started_at_ms().unwrap_or(v.started_at); + }); + return Ok(()); + } + Ok(live) if live.gone() => { + self.forget(name); + bail!( + "its microVM {id} ended as it started{}", + live.state_reason + .map(|r| format!(": {r}")) + .unwrap_or_default() + ); + } + Ok(_) => {} + Err(e) if e.not_found() => { + self.forget(name); + bail!("its microVM {id} is gone"); + } + Err(e) if e.transient() => {} + Err(e) => return Err(self.fail(e, "waiting for its microVM")), + } + if Instant::now() > until { + bail!( + "its microVM {id} didn't run within {} minutes", + START_TIMEOUT.as_secs() / 60 + ); + } + tokio::time::sleep(wait).await; + wait = (wait * 2).min(Duration::from_secs(2)); + } + } + + /// Resumes the microVM `name` has, and waits for it to run. + async fn resume_vm(&self, name: &str) -> Result<()> { + let Some(vm) = self.vm(name) else { + bail!("no microVM for {name}") + }; + let Some(id) = vm.id.clone() else { + bail!("its microVM never ran") + }; + let api = self.api().await?; + self.update(name, |v| { + v.state = MicrovmState::Resuming; + v.since = now_ms(); + }); + // One still suspending resumes once it has. + let until = Instant::now() + START_TIMEOUT; + loop { + match api.resume(&id).await { + Ok(()) => break, + Err(e) if e.conflict() || e.transient() => { + if Instant::now() > until { + return Err(self.fail(e, "resuming its microVM")); + } + if let Ok(live) = api.get(&id).await + && live.state == "RUNNING" + { + break; + } + tokio::time::sleep(Duration::from_millis(500)).await; + } + Err(e) if e.not_found() => { + self.forget(name); + bail!("its microVM {id} is gone"); + } + Err(e) => return Err(self.fail(e, "resuming its microVM")), + } + } + self.wait_running(name, &id).await?; + self.update(name, |v| v.suspended_at = None); + Ok(()) + } + + /// Waits for `microvm-serve` to answer in the microVM, and notes what + /// it says of itself. + async fn answer(&self, name: &str) -> Result<()> { + let until = Instant::now() + ANSWER_TIMEOUT; + loop { + let last = match self.target(name).await { + Ok(target) => match link::hello(&target).await { + Ok(hello) => { + if let Some(e) = hello.error { + anyhow::anyhow!("{e}") + } else { + self.update(name, |v| { + v.agent.clone_from(&hello.version); + v.user = hello.user.clone().or(v.user.take()); + v.arch = hello.arch.clone().or(v.arch.take()); + }); + return Ok(()); + } + } + Err(e) => e, + }, + Err(e) => e, + }; + if Instant::now() > until { + bail!( + "fctl-agent didn't answer in the microVM within {} seconds: {last:#}", + ANSWER_TIMEOUT.as_secs() + ); + } + tokio::time::sleep(Duration::from_millis(300)).await; + } + } + + /// Where its requests to `name`'s microVM go, with a token good for a + /// while yet. + async fn target(&self, name: &str) -> Result { + let Some(vm) = self.vm(name) else { + bail!("no microVM for {name}") + }; + let (Some(id), Some(endpoint)) = (vm.id.clone(), vm.endpoint.clone()) else { + bail!("its microVM has no endpoint yet") + }; + let cached = lock(&self.inner.tokens).get(&id).cloned(); + let token = match cached { + Some((t, until)) if until > Instant::now() + Duration::from_secs(5 * 60) => t, + _ => { + let api = self.api().await?; + let t = api + .token(&id, SERVE_PORT, 60) + .await + .map_err(|e| self.fail(e, "asking for a token to its microVM"))?; + lock(&self.inner.tokens).insert( + id.clone(), + (t.clone(), Instant::now() + Duration::from_secs(55 * 60)), + ); + t + } + }; + Ok(link::Target { + endpoint, + token, + key: vm.key, + }) + } + + /// The user the image's sessions run as. + fn user(&self, name: &str) -> String { + self.vm(name) + .and_then(|v| v.user) + .unwrap_or_else(|| "agent".into()) + } + + /// Puts this host's fctl-agent in the microVM, unless the image's is + /// this version already, as images fctl builds have it. + pub async fn install_agent(&self, sb: &Sandbox, _binary: &Path) -> Result<()> { + let vm = self.vm(&sb.name).context("no microVM for the session")?; + if vm.agent.as_deref() == Some(crate::agentbin::VERSION) { + return Ok(()); + } + let arch = vm.arch.clone().unwrap_or_else(|| "aarch64".into()); + let bin = crate::agentbin::linux_agent_for(&self.inner.cfg, &arch) + .await + .context("getting fctl-agent for the microVM")?; + let bytes = tokio::fs::read(&bin).await?; + let target = self.target(&sb.name).await?; + let script = format!( + "{}; cat > /opt/fctl/bin/fctl-agent.new && chmod 755 /opt/fctl/bin/fctl-agent.new && mv -f /opt/fctl/bin/fctl-agent.new /opt/fctl/bin/fctl-agent", + crate::driver::AGENT_DIR_SCRIPT + ); + let out = link::run( + &target, + Exec { + argv: vec![ + crate::driver::SH.into(), + "-c".into(), + crate::driver::system_script(&script), + ], + ..Exec::default() + }, + Some(&bytes), + ) + .await?; + if out.code != 0 { + bail!( + "putting fctl-agent in the microVM failed: {}", + String::from_utf8_lossy(&out.stderr).trim() + ); + } + Ok(()) + } + + /// Starts the supervisor, detached. + pub async fn start_agent(&self, sb: &Sandbox) -> Result<()> { + let target = self.target(&sb.name).await?; + let user = self.user(&sb.name); + let exec = match self.inner.cfg.agent_as_root { + true => Exec { + argv: crate::driver::serve_as_root(&user), + ..Exec::default() + }, + false => Exec { + argv: vec![ + "/bin/sh".into(), + "-c".into(), + crate::driver::serve_as_user_script(), + ], + user: Some(user), + ..Exec::default() + }, + }; + link::detach(&target, exec).await + } + + /// A channel to one of the supervisor's sockets. + pub async fn attach(&self, sb: &Sandbox, socket: Socket) -> Result { + let target = self.target(&sb.name).await?; + let user = self.user(&sb.name); + let exec = match self.inner.cfg.agent_as_root { + true => Exec { + argv: crate::driver::attach_as_root(socket), + ..Exec::default() + }, + false => Exec { + argv: vec![ + "/bin/sh".into(), + "-c".into(), + crate::driver::attach_as_user_script(socket), + ], + user: Some(user), + ..Exec::default() + }, + }; + let started = link::start(&target, exec).await?; + Ok(AgentIo { + reader: Box::new(started.stdout), + writer: Box::new(started.stdin), + child: None, + }) + } + + /// Runs `script` as the image's user; its output. + pub async fn exec(&self, sb: &Sandbox, script: &str) -> Result { + let target = self.target(&sb.name).await?; + link::sh(&target, Some(&self.user(&sb.name)), script).await + } + + /// Runs `script` as the image's user, with its input and output piped. + pub async fn spawn(&self, sb: &Sandbox, script: &str) -> Result { + let target = self.target(&sb.name).await?; + let started = link::start( + &target, + Exec { + argv: vec!["/bin/sh".into(), "-c".into(), script.into()], + user: Some(self.user(&sb.name)), + ..Exec::default() + }, + ) + .await?; + Ok(Running::vm(started)) + } + + /// Suspends the session's microVM: its memory and disk are kept, and it + /// costs no compute until it resumes. + pub async fn suspend(&self, sb: &Sandbox) -> Result<()> { + let _busy = self.busy(&sb.name); + let vm = self.vm(&sb.name).context("no microVM for the session")?; + let id = vm.id.clone().context("its microVM never ran")?; + let api = self.api().await?; + self.update(&sb.name, |v| { + v.state = MicrovmState::Suspending; + v.since = now_ms(); + v.suspended_at = Some(now_ms()); + }); + match api.suspend(&id).await { + Ok(()) => {} + // Suspended already, or about to be. + Err(e) if e.conflict() => {} + Err(e) if e.not_found() => { + self.forget(&sb.name); + bail!("its microVM {id} is gone"); + } + Err(e) => { + self.update(&sb.name, |v| { + v.state = MicrovmState::Running; + v.suspended_at = None; + }); + return Err(self.fail(e, "suspending its microVM")); + } + } + let until = Instant::now() + Duration::from_secs(60); + loop { + match api.get(&id).await { + Ok(live) if live.state == "SUSPENDED" => break, + Ok(live) if live.gone() => { + self.forget(&sb.name); + bail!("its microVM {id} ended as it suspended"); + } + _ if Instant::now() > until => break, + _ => tokio::time::sleep(Duration::from_millis(300)).await, + } + } + self.update(&sb.name, |v| { + v.state = MicrovmState::Suspended; + v.since = now_ms(); + }); + Ok(()) + } + + /// Resumes the session's microVM, and waits for `microvm-serve`. + pub async fn resume(&self, sb: &Sandbox) -> Result<()> { + let _busy = self.busy(&sb.name); + self.resume_vm(&sb.name).await?; + self.answer(&sb.name).await + } + + /// Stops the sandbox, which keeps it: its microVM suspends, and goes + /// once it has been suspended for the settings' while. + pub async fn stop(&self, sb: &Sandbox) -> Result<()> { + if self.vm(&sb.name).is_none() { + return Ok(()); + } + self.update(&sb.name, |v| v.ended = true); + match self.vm(&sb.name) { + Some(vm) if vm.state == MicrovmState::Running => self.suspend(sb).await, + _ => Ok(()), + } + } + + /// Lets the sandbox's microVM go. + pub async fn remove(&self, sb: &Sandbox) -> Result<()> { + self.terminate_vm(&sb.name).await; + Ok(()) + } + + /// Lets the microVM `name` has go, and forgets it. + async fn terminate_vm(&self, name: &str) { + let Some(vm) = self.vm(name) else { return }; + let Some(id) = vm.id.clone() else { + // Asked to run with no answer yet: the upkeep asks again for its + // id, then lets it go. Never asked: nothing ran. + match vm.run { + Some(_) => self.let_go(name), + None => self.forget(name), + } + return; + }; + self.update(name, |v| { + v.state = MicrovmState::Terminating; + v.since = now_ms(); + }); + let api = match self.api().await { + Ok(api) => api, + Err(e) => { + tracing::warn!("terminating {id}: {e:#}"); + self.let_go(name); + return; + } + }; + match api.terminate(&id).await { + Ok(()) => self.forget(name), + Err(e) if e.not_found() => self.forget(name), + Err(e) => { + tracing::warn!("terminating {id}: {e}"); + self.note(Err(&e), "letting a microVM go"); + // Kept, and tried again, until AWS says it's gone: one left + // running costs and counts against the quota for hours. + self.let_go(name); + } + } + } + + /// Keeps a microVM the host lets go of, which AWS hasn't said is gone, + /// as `going-…`, which the upkeep terminates: its sandbox's name is + /// free for the next run. + fn let_go(&self, name: &str) { + { + let mut saved = lock(&self.inner.saved); + let taken: Vec = saved.vms.iter().map(|v| v.name.clone()).collect(); + let Some(v) = saved.vms.iter_mut().find(|v| v.name == name) else { + return; + }; + if !v.going() { + let tag: String = + v.id.as_deref() + .unwrap_or(&v.client_token) + .trim_start_matches("mvm-") + .chars() + .filter(char::is_ascii_alphanumeric) + .take(12) + .collect(); + let mut going = format!("going-{tag}"); + let mut n = 1; + while taken.contains(&going) { + n += 1; + going = format!("going-{tag}-{n}"); + } + v.name = going; + } + v.state = MicrovmState::Terminating; + v.ended = true; + v.since = now_ms(); + } + self.save(); + self.note_changed(); + } + + /// Terminates the microVMs the host let go of that AWS hasn't said are + /// gone, every [`GOING_AGAIN`]: asking again to run one whose answer + /// never came (its client token finds it) to learn its id first. Lambda + /// ends any microVM 8 hours after it started, so one older than that is + /// forgotten. + async fn retry_going(&self) { + let now = now_ms(); + // Asked to run, with no answer for longer than any call takes: a + // host that stopped mid-call left them, warm ones included. + let busy: Vec = lock(&self.inner.busy).keys().cloned().collect(); + let unanswered: Vec = lock(&self.inner.saved) + .vms + .iter() + .filter(|v| !v.going() && v.id.is_none() && v.run.is_some()) + .filter(|v| { + !busy.contains(&v.name) && now - v.since > UNANSWERED_AFTER.as_millis() as i64 + }) + .map(|v| v.name.clone()) + .collect(); + for name in unanswered { + tracing::info!("{name}: its run got no answer; letting what Lambda ran go"); + self.let_go(&name); + } + let due: Vec = lock(&self.inner.saved) + .vms + .iter() + .filter(|v| v.going() && now - v.since >= GOING_AGAIN.as_millis() as i64) + .cloned() + .collect(); + if due.is_empty() { + return; + } + let Ok(api) = self.api().await else { return }; + for vm in due { + if now > rules::ends_at(vm.started_at) + rules::ENDING_MS { + tracing::info!("{}: Lambda has ended it by now", vm.name); + self.forget(&vm.name); + continue; + } + let id = match (&vm.id, &vm.run) { + (Some(id), _) => id.clone(), + (None, Some(req)) => match api.run(req).await { + Ok(ran) => { + let id = ran.microvm_id.clone(); + self.update(&vm.name, |v| { + v.id = Some(id.clone()); + v.run = None; + }); + id + } + // A request Lambda would never carry out: the first try + // ran nothing either. Anything else, a throttle or no + // capacity among them, says nothing of the first try, + // which may have run it: asked again later. + Err(e) if e.invalid_request() => { + tracing::info!("{}: {e}", vm.name); + self.forget(&vm.name); + continue; + } + Err(e) => { + tracing::warn!("{}: asking again for its microVM: {e}", vm.name); + self.update(&vm.name, |v| v.since = now_ms()); + continue; + } + }, + (None, None) => { + self.forget(&vm.name); + continue; + } + }; + match api.terminate(&id).await { + Ok(()) => self.forget(&vm.name), + Err(e) if e.not_found() => self.forget(&vm.name), + Err(e) => { + tracing::warn!("terminating {id} again: {e}"); + self.note(Err(&e), "letting a microVM go"); + self.update(&vm.name, |v| v.since = now_ms()); + } + } + } + } + + // ───────────────────────────── upkeep ───────────────────────────── + + /// What the driver does in the background: keeps the image ready, its + /// microVMs' states current, the warm pool full, and lets go of the + /// microVMs no session or pool needs. + async fn upkeep(&self) { + self.retry_going().await; + let Some(settings) = self.settings() else { + return; + }; + if rules::check(&settings).is_err() { + return; + } + if let Err(e) = self.keep_image(&settings).await { + tracing::debug!("the microVM image: {e:#}"); + } + self.follow_states().await; + self.let_go_of_stale(&settings).await; + self.keep_warm(&settings).await; + } + + /// Looks at the image, and has Lambda build the one fctl keeps when it + /// isn't what the settings and this fctl want. + async fn keep_image(&self, settings: &MicrovmSettings) -> Result<()> { + let view = lock(&self.inner.image).clone(); + let building = view + .report + .as_ref() + .is_some_and(|r| r.status == MicrovmImageStatus::Building); + let due = match view.looked_at { + None => true, + Some(at) if building => at.elapsed() >= BUILDING_EVERY, + Some(at) => at.elapsed() >= IMAGE_EVERY, + }; + if !due { + return Ok(()); + } + let api = self.api().await?; + let name = image::name(&settings.image); + let pinned = match &settings.image { + MicrovmImage::Own { version, .. } => version.clone(), + MicrovmImage::Managed { .. } => None, + }; + let found = image::runnable(&api, &name, pinned.as_deref()).await; + let mut view = ImageView { + looked_at: Some(Instant::now()), + failed_at: view.failed_at, + ..ImageView::default() + }; + match (&settings.image, found) { + (MicrovmImage::Own { arn, .. }, Ok((_, Some(v)))) if v.runs() => { + self.note(Ok(()), ""); + view.size = v.memory_mb().and_then(microvm_size); + view.arn = Some(arn.clone()); + view.version = Some(v.image_version.clone()); + view.report = Some(image::report( + arn, + Some(&v), + MicrovmImageStatus::Ready, + None, + Some(now_ms()), + )); + } + (MicrovmImage::Own { arn, .. }, Ok((_, v))) => { + let why = v.as_ref().map_or_else( + || format!("{arn} has no active version to run"), + |v| { + format!( + "{arn}'s version {} can't run: it is {}", + v.image_version, + v.state.to_lowercase() + ) + }, + ); + view.report = Some(image::report( + arn, + v.as_ref(), + MicrovmImageStatus::Missing, + Some(why), + Some(now_ms()), + )); + } + (MicrovmImage::Own { arn, .. }, Err(e)) => { + let why = problem_words(&e, "reading its image"); + self.note(Err(&e), "reading its image"); + view.report = Some(image::report( + arn, + None, + MicrovmImageStatus::Missing, + Some(why), + Some(now_ms()), + )); + } + (MicrovmImage::Managed { .. }, found) => { + self.keep_managed(&api, settings, &name, found, &mut view) + .await?; + } + } + *lock(&self.inner.image) = view; + self.note_changed(); + Ok(()) + } + + /// The managed image: ready when its latest active version is this + /// fctl's, at the settings' size; otherwise built, while the version + /// before (if any) runs. + async fn keep_managed( + &self, + api: &Api, + settings: &MicrovmSettings, + name: &str, + found: Result<(api::Image, Option), api::Error>, + view: &mut ImageView, + ) -> Result<()> { + let fctl = crate::agentbin::VERSION; + let region = api.region().to_owned(); + let (image, active) = match found { + Ok((image, active)) => (Some(image), active), + Err(e) if e.not_found() => (None, None), + Err(e) => { + self.note(Err(&e), "reading its image"); + return Err(anyhow::anyhow!("{e}")); + } + }; + let arn = image + .as_ref() + .map(|i| i.image_arn.clone()) + .unwrap_or_default(); + // What runs meanwhile, whatever it was built for. + if let Some(v) = active.as_ref().filter(|v| v.runs()) { + view.arn = Some(v.image_arn.clone()) + .filter(|a| !a.is_empty()) + .or(Some(arn.clone())); + view.version = Some(v.image_version.clone()); + view.size = v.memory_mb().and_then(microvm_size); + } + if active + .as_ref() + .is_some_and(|v| v.runs() && image::current(v, settings, fctl)) + { + self.note(Ok(()), ""); + view.report = Some(image::report( + &arn, + active.as_ref(), + MicrovmImageStatus::Ready, + None, + Some(now_ms()), + )); + lock(&self.inner.saved).building = None; + return Ok(()); + } + // A build under way: how it goes. + let building = lock(&self.inner.saved).building.clone(); + if let Some((for_fctl, version, since)) = building.clone() + && for_fctl + == image::description(fctl, settings.memory_mb, settings.arch.unwrap_or_default()) + { + match api.image_version(name, &version).await { + Ok(v) if v.state == "SUCCESSFUL" => { + view.arn = Some(v.image_arn.clone()) + .filter(|a| !a.is_empty()) + .or(Some(arn.clone())); + view.version = Some(v.image_version.clone()); + view.size = v.memory_mb().and_then(microvm_size); + view.report = Some(image::report( + &arn, + Some(&v), + MicrovmImageStatus::Ready, + None, + Some(now_ms()), + )); + lock(&self.inner.saved).building = None; + self.save(); + return Ok(()); + } + Ok(v) if v.state == "FAILED" => { + let why = format!( + "Lambda couldn't build the image for fctl {fctl}: {}", + v.state_reason.unwrap_or_else(|| { + "its build failed (its CloudWatch logs say why)".into() + }) + ); + let mut r = image::report( + &arn, + active.as_ref(), + MicrovmImageStatus::Failed, + Some(why), + Some(since), + ); + r.building = Some(fctl.to_owned()); + view.report = Some(r); + view.failed_at = Some(Instant::now()); + lock(&self.inner.saved).building = None; + self.save(); + return Ok(()); + } + Ok(_) => { + let mut r = image::report( + &arn, + active.as_ref(), + MicrovmImageStatus::Building, + None, + Some(since), + ); + r.building = Some(fctl.to_owned()); + view.report = Some(r); + return Ok(()); + } + Err(e) if !e.not_found() => { + self.note(Err(&e), "following its image's build"); + return Err(anyhow::anyhow!("{e}")); + } + Err(_) => {} + } + } + // A build that failed lately waits before the next. + if view + .failed_at + .is_some_and(|at| at.elapsed() < REBUILD_AFTER) + { + 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(now_ms()), + ); + r.building = Some(fctl.to_owned()); + view.report = Some(r); + return Ok(()); + } + let MicrovmImage::Managed { + artifacts, + build_role_arn, + .. + } = &settings.image + else { + return Ok(()); + }; + let arch = settings.arch.unwrap_or_default(); + let uri = self + .upload_artifact(artifacts, ®ion, arch, api.keys()) + .await?; + let req = image::request(&image::Build { + settings, + fctl, + artifact_uri: uri, + build_role_arn, + base_image_arn: rules::base_image(aws::partition(®ion), ®ion), + client_token: format!("fctl-{fctl}-{}-{}", settings.memory_mb, arch.rust()) + .replace('.', "-"), + update: image.is_some(), + }); + let answer = match image { + Some(_) => api.update_image(name, &req).await, + None => api.create_image(&req).await, + }; + let answer = match answer { + Ok(a) => a, + Err(e) => { + self.note(Err(&e), "having Lambda build its image"); + view.failed_at = Some(Instant::now()); + let mut r = image::report( + &arn, + active.as_ref(), + MicrovmImageStatus::Failed, + Some(problem_words(&e, "having Lambda build its image")), + Some(now_ms()), + ); + r.building = Some(fctl.to_owned()); + view.report = Some(r); + return Ok(()); + } + }; + self.note(Ok(()), ""); + let version = answer + .image_version + .or(answer.latest_active_image_version) + .unwrap_or_default(); + tracing::info!("Lambda builds {name} version {version} for fctl {fctl}"); + lock(&self.inner.saved).building = Some(( + image::description(fctl, settings.memory_mb, arch), + version, + now_ms(), + )); + self.save(); + let arn = if arn.is_empty() { + answer.image_arn + } else { + arn + }; + let mut r = image::report( + &arn, + active.as_ref(), + MicrovmImageStatus::Building, + None, + Some(now_ms()), + ); + r.building = Some(fctl.to_owned()); + view.report = Some(r); + Ok(()) + } + + /// Puts the archive Lambda builds the image from in `artifacts`, with + /// the keys the host calls Lambda with (a role it assumes, say); its + /// `s3://` URI. + async fn upload_artifact( + &self, + artifacts: &str, + region: &str, + arch: fctl_proto::microvm::MicrovmArch, + keys: Arc, + ) -> Result { + let bucket = + fctl_domain::snapshots::Bucket::parse(artifacts).map_err(anyhow::Error::msg)?; + let agent = crate::agentbin::linux_agent_for(&self.inner.cfg, arch.rust()) + .await + .context("getting fctl-agent for the image")?; + let agent = tokio::fs::read(&agent).await?; + let zip = image::artifact(&self.inner.cfg.image(), "agent", &agent)?; + std::fs::create_dir_all(&self.inner.dir)?; + let file = self.inner.dir.join("artifact.zip"); + std::fs::write(&file, &zip)?; + let sha = fctl_domain::sigv4::sha256_hex(&zip); + let store = crate::s3::Store::open(&crate::config::SnapshotsConfig { + url: Some(artifacts.to_owned()), + region: Some(region.to_owned()), + ..crate::config::SnapshotsConfig::default() + }) + .await? + .context("no bucket for the image's archive")? + .with_keys(keys); + let key = match bucket.prefix.as_str() { + "" => format!("fctl-{}-{}.zip", crate::agentbin::VERSION, arch.rust()), + p => format!("{p}/fctl-{}-{}.zip", crate::agentbin::VERSION, arch.rust()), + }; + store + .put(&key, &file, &sha) + .await + .map_err(|e| anyhow::anyhow!("putting the image's archive in {artifacts}: {e}"))?; + let _ = std::fs::remove_file(&file); + Ok(format!("s3://{}/{key}", bucket.name)) + } + + /// Reads every microVM's state from Lambda now and then, and those that + /// change more often: what it suspended, resumed or let go of, and what + /// Lambda ended by itself. + async fn follow_states(&self) { + let due = lock(&self.inner.listed_at).is_none_or(|at| at.elapsed() >= LIST_EVERY); + if !due { + return; + } + let Ok(api) = self.api().await else { return }; + let arn = lock(&self.inner.image).arn.clone(); + let Some(arn) = arn else { return }; + let listed = match api.list(&arn).await { + Ok(items) => items, + Err(e) => { + self.note(Err(&e), "listing its microVMs"); + return; + } + }; + *lock(&self.inner.listed_at) = Some(Instant::now()); + let live: HashMap = listed + .into_iter() + .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) + .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); + } + } + + /// 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. + 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) + .vms + .iter() + .filter(|v| v.ended && !v.warm() && !v.going() && !busy.contains(&v.name)) + .filter(|v| { + let suspended = v.state == MicrovmState::Suspended + && rules::terminate_at(v.suspended_at.unwrap_or(v.since), settings) <= now; + suspended || rules::ending(v.started_at, now) + }) + .map(|v| v.name.clone()) + .collect(); + for name in stale { + tracing::info!("letting {name}'s microVM go"); + self.terminate_vm(&name).await; + } + } + + /// Keeps the settings' `warm` microVMs started and suspended. + async fn keep_warm(&self, settings: &MicrovmSettings) { + let Ok((_, fingerprint, _)) = self.ready() else { + return; + }; + // Not while AWS refuses, slows the host down or can't be reached: + // a quota reached, say. + if lock(&self.inner.problem).as_ref().is_some_and(|p| { + matches!( + p.kind.as_str(), + "quota" | "access" | "credentials" | "capacity" | "throttled" | "unreachable" + ) + }) && now_ms() - lock(&self.inner.problem).as_ref().map_or(0, |p| p.since) < 5 * 60_000 + { + return; + } + let now = now_ms(); + let warm: Vec = lock(&self.inner.saved) + .vms + .iter() + .filter(|v| v.warm()) + .map(warm_of) + .collect(); + let plan = rules::plan( + &warm, + settings.warm as usize, + self.room(settings), + &fingerprint, + now, + ); + for name in plan.retire { + let me = self.clone(); + tokio::spawn(async move { me.terminate_vm(&name).await }); + } + for _ in 0..plan.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. + self.put(vm.clone()); + let me = self.clone(); + tokio::spawn(async move { + if let Err(e) = me.warm_up(&name, vm).await { + tracing::warn!("a warm microVM: {e:#}"); + me.terminate_vm(&name).await; + } + me.inner.wake.notify_one(); + }); + } + } + + /// Runs a microVM for the pool, waits for `microvm-serve`, and suspends + /// it. + async fn warm_up(&self, name: &str, vm: Vm) -> Result<()> { + self.run_vm(name, vm).await?; + self.answer(name).await?; + // A session may have taken it meanwhile. + if self.vm(name).is_none() { + return Ok(()); + } + let sb = Sandbox { + name: name.to_owned(), + root: None, + }; + self.suspend(&sb).await + } + + /// How its microVMs are, for the runner's heartbeats: with every one, + /// the sessions they run named by the sandboxes' names. + pub fn report(&self) -> MicrovmReport { + let settings = self.settings(); + let vms = lock(&self.inner.saved).vms.clone(); + let image = lock(&self.inner.image).report.clone(); + let mut r = MicrovmReport { + region: lock(&self.inner.region).clone(), + account: image + .as_ref() + .and_then(|i| rules::image_arn(&i.arn).map(|a| a.account.to_owned())), + configured: settings.is_some(), + image, + max: settings.as_ref().map_or(0, |s| s.max_microvms), + problem: lock(&self.inner.problem).clone(), + ..MicrovmReport::default() + }; + for v in &vms { + let counted = match (v.warm(), v.state) { + (true, MicrovmState::Suspended) => &mut r.warm, + (false, MicrovmState::Suspended) => &mut r.suspended, + (false, MicrovmState::Running) => &mut r.running, + _ => &mut r.changing, + }; + *counted += 1; + let Some(id) = v.id.clone() else { continue }; + r.vms.push(MicrovmVm { + id, + state: v.state, + session: (!v.warm()) + .then(|| crate::driver::session_of(&v.name)) + .flatten() + .map(fctl_proto::SessionId), + since: v.since, + started_at: v.started_at, + ends_at: rules::ends_at(v.started_at), + terminates_at: settings.as_ref().and_then(|s| { + (v.state == MicrovmState::Suspended && !v.warm()) + .then(|| rules::terminate_at(v.suspended_at.unwrap_or(v.since), s)) + }), + image_version: v.image_version.clone(), + }); + } + r + } +} + +fn warm_of(v: &Vm) -> WarmVm { + WarmVm { + id: v.name.clone(), + state: match v.state { + MicrovmState::Suspended if v.id.is_some() => PoolState::Ready, + MicrovmState::Terminating => PoolState::Going, + _ => PoolState::Changing, + }, + started_at: v.started_at, + fingerprint: v.fingerprint.clone(), + } +} + +/// What AWS's answer means for the runner, in a sentence for people. +pub fn problem_words(e: &api::Error, doing: &str) -> String { + let doing = if doing.is_empty() { + "asking Lambda" + } else { + doing + }; + match e.kind() { + "access" => format!( + "AWS refused {doing}: the host's role lacks a permission ({e}). Open the runner on its workspace's Runners tab for the policy it needs" + ), + "credentials" => format!("The host has no AWS keys for {doing}: {}", e.message), + "quota" => format!( + "The account's quota for Lambda microVMs is reached ({e}): new sessions wait. Lower the runner's most microVMs, or ask AWS for more" + ), + "capacity" => { + format!("Lambda has no capacity for more microVMs just now ({e}): it tries again") + } + "throttled" => format!("Lambda asks the host to slow down ({e})"), + "unreachable" => format!("The host couldn't reach Lambda for {doing}: {}", e.message), + "settings" => format!("Lambda refused {doing}: {e}"), + _ => format!("Lambda failed {doing}: {e}"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + /// 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. + async fn lambda( + fail: usize, + throttled: usize, + ) -> anyhow::Result<(String, Arc>>)> { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; + let url = format!("http://{}", listener.local_addr()?); + let had: Arc>> = Arc::default(); + let log = had.clone(); + tokio::spawn(async move { + while let Ok((mut conn, _)) = listener.accept().await { + let log = log.clone(); + tokio::spawn(async move { + let mut buf = Vec::new(); + let mut chunk = vec![0u8; 1 << 14]; + let end = loop { + let n = match conn.read(&mut chunk).await { + Ok(0) | Err(_) => return, + Ok(n) => n, + }; + buf.extend(chunk.iter().take(n)); + if let Some(i) = buf.windows(4).position(|w| w == b"\r\n\r\n") { + break i + 4; + } + }; + let head = + String::from_utf8_lossy(buf.get(..end).unwrap_or_default()).to_string(); + let length: usize = head + .lines() + .find_map(|l| { + l.split_once(':') + .filter(|(n, _)| n.eq_ignore_ascii_case("content-length")) + }) + .and_then(|(_, v)| v.trim().parse().ok()) + .unwrap_or(0); + while buf.len() < end + length { + match conn.read(&mut chunk).await { + Ok(0) | Err(_) => break, + Ok(n) => buf.extend(chunk.iter().take(n)), + } + } + let first = head.lines().next().unwrap_or_default().to_owned(); + let mut parts = first.split(' '); + let request = format!( + "{} {}", + parts.next().unwrap_or_default(), + parts.next().unwrap_or_default() + ); + 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(), + ) + }; + 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) { + if runs <= throttled { + ( + "429 Too Many Requests", + r#"{"__type":"ThrottlingException"}"#, + ) + } else { + ("200 OK", r#"{"microvmId":"mvm-found","state":"PENDING"}"#) + } + } else { + ("404 Not Found", r#"{"message":"no such thing"}"#) + }; + let answer = format!( + "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", + body.len() + ); + let _ = conn.write_all(answer.as_bytes()).await; + let _ = conn.shutdown().await; + }); + } + }); + Ok((url, had)) + } + + fn driver(dir: &std::path::Path, url: &str) -> anyhow::Result { + let mut cfg = HostConfig { + data_dir: Some(dir.to_path_buf()), + ..HostConfig::default() + }; + cfg.lambda.endpoint = Some(url.to_owned()); + cfg.lambda.region = Some("us-east-1".into()); + let d = LambdaDriver::new(&cfg); + let keys = Keys::fixed( + "us-east-1", + fctl_domain::sigv4::Credentials { + access_key_id: "AKIDTEST".into(), + secret_access_key: "test".into(), + session_token: None, + }, + ); + let api = Api::new(Arc::new(keys), Some(url)) + .map_err(anyhow::Error::msg)? + .with_first_wait(Duration::from_millis(1)); + *lock(&d.inner.api) = Some(Arc::new(api)); + Ok(d) + } + + fn run_request(token: &str) -> api::RunRequest { + api::RunRequest { + client_token: token.to_owned(), + image_identifier: "arn:aws:lambda:us-east-1:123456789012:microvm-image:fctl-sandbox" + .into(), + image_version: Some("1".into()), + execution_role_arn: None, + idle_policy: api::IdlePolicy { + auto_resume_enabled: false, + max_idle_duration_seconds: 28_800, + suspended_duration_seconds: 4_200, + }, + ingress_network_connectors: vec![], + egress_network_connectors: vec![], + kms_key_identifier: None, + logging: None, + maximum_duration_in_seconds: MAX_LIFETIME_SECS, + run_hook_payload: "{}".into(), + } + } + + fn names(d: &LambdaDriver) -> Vec { + lock(&d.inner.saved) + .vms + .iter() + .map(|v| v.name.clone()) + .collect() + } + + /// Makes the records due for the upkeep's next try. + fn age(d: &LambdaDriver) { + for v in &mut lock(&d.inner.saved).vms { + v.since -= GOING_AGAIN.as_millis() as i64 + 1_000; + } + } + + #[tokio::test] + async fn microvms_aws_hasnt_let_go_of_are_kept_and_terminated_again() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + // Each call tries four times: the first call fails throughout. + let (url, had) = lambda(api::TRIES as usize, 0).await?; + let d = driver(dir.path(), &url)?; + let mut vm = d.new_vm("fctl-ses-a", "f"); + vm.id = Some("mvm-a1b2c3d4".into()); + vm.state = MicrovmState::Suspended; + d.put(vm); + + d.terminate_vm("fctl-ses-a").await; + // Its sandbox's name is free, and the host keeps it as going. + assert_eq!(names(&d), ["going-a1b2c3d4"]); + assert!(d.list().is_empty()); + let kept = d + .vm("going-a1b2c3d4") + .ok_or_else(|| anyhow::anyhow!("not kept"))?; + assert_eq!(kept.state, MicrovmState::Terminating); + // It survives a restart. + let again = driver(dir.path(), &url)?; + assert_eq!(names(&again), ["going-a1b2c3d4"]); + + // Not yet due: nothing is asked. + d.retry_going().await; + assert_eq!(names(&d), ["going-a1b2c3d4"]); + age(&d); + d.retry_going().await; + assert!(names(&d).is_empty()); + let deletes = lock(&had) + .iter() + .filter(|r| r.as_str() == format!("DELETE /{}/microvms/mvm-a1b2c3d4", api::VERSION)) + .count(); + assert_eq!(deletes, api::TRIES as usize + 1); + Ok(()) + } + + #[tokio::test] + async fn a_microvm_whose_run_went_unanswered_is_found_by_its_token_and_let_go() + -> 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("warm-1", "f"); + vm.run = Some(run_request(&vm.client_token)); + d.put(vm); + d.terminate_vm("warm-1").await; + let going = names(&d); + assert_eq!(going.len(), 1); + assert!(going.iter().all(|n| n.starts_with("going-")), "{going:?}"); + age(&d); + d.retry_going().await; + assert!(names(&d).is_empty()); + let asked = lock(&had).clone(); + assert_eq!( + asked, + [ + format!("POST /{}/microvms", api::VERSION), + format!("DELETE /{}/microvms/mvm-found", api::VERSION), + ] + ); + Ok(()) + } + + #[tokio::test] + async fn the_upkeep_lets_go_only_of_microvms_whose_run_ended() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + let (url, had) = lambda(0, 0).await?; + let d = driver(dir.path(), &url)?; + let settings = rules::defaults(MicrovmImage::Own { + arn: "arn:aws:lambda:us-east-1:123456789012:microvm-image:agents".into(), + version: None, + }); + // Both near Lambda's end for them, and both suspended past the + // settings' while: the session that runs lets its own go. + let long_ago = now_ms() - MAX_LIFETIME_SECS as i64 * 1000 + 5 * 60_000; + for (name, ended) in [("fctl-ses-live", false), ("fctl-ses-done", true)] { + let mut vm = d.new_vm(name, "f"); + vm.id = Some(format!("mvm-{name}")); + vm.state = MicrovmState::Suspended; + vm.started_at = long_ago; + vm.suspended_at = Some(long_ago); + vm.ended = ended; + d.put(vm); + } + d.let_go_of_stale(&settings).await; + assert_eq!(names(&d), ["fctl-ses-live"]); + assert_eq!( + lock(&had).clone(), + [format!( + "DELETE /{}/microvms/mvm-fctl-ses-done", + api::VERSION + )] + ); + Ok(()) + } + + #[tokio::test] + async fn microvms_aws_may_still_run_count_against_the_most() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + let (url, _) = lambda(0, 0).await?; + let d = driver(dir.path(), &url)?; + let mut settings = rules::defaults(MicrovmImage::Own { + arn: "arn:aws:lambda:us-east-1:123456789012:microvm-image:agents".into(), + version: None, + }); + settings.max_microvms = 2; + let mut session = d.new_vm("fctl-ses-a", "f"); + session.id = Some("mvm-a".into()); + d.put(session); + assert_eq!(d.room(&settings), 1); + let mut going = d.new_vm("going-b", "f"); + going.id = Some("mvm-b".into()); + going.state = MicrovmState::Terminating; + d.put(going); + assert_eq!(d.room(&settings), 0); + Ok(()) + } + + #[tokio::test] + async fn sessions_make_room_only_where_they_hold_it() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + let (url, _) = lambda(0, 0).await?; + let d = driver(dir.path(), &url)?; + let mut settings = rules::defaults(MicrovmImage::Own { + arn: "arn:aws:lambda:us-east-1:123456789012:microvm-image:agents".into(), + version: None, + }); + settings.max_microvms = 2; + settings.warm = 0; + *lock(&d.inner.settings) = Some(settings); + let mut session = d.new_vm("fctl-ses-a", "f"); + session.id = Some("mvm-a".into()); + session.state = MicrovmState::Suspended; + d.put(session); + let mut going = d.new_vm("going-b", "f"); + going.id = Some("mvm-b".into()); + going.state = MicrovmState::Terminating; + d.put(going); + // No room, but what holds it goes by itself: no session is let go. + assert!(!d.full()); + let mut other = d.new_vm("fctl-ses-c", "f"); + other.id = Some("mvm-c".into()); + d.put(other); + assert!(d.full()); + Ok(()) + } + + #[tokio::test] + async fn a_warm_run_a_restart_cut_short_is_let_go_of() -> 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("warm-1", "f"); + vm.run = Some(run_request(&vm.client_token)); + d.put(vm); + // Just asked: it may still be answered. + d.retry_going().await; + assert_eq!(names(&d), ["warm-1"]); + d.update("warm-1", |v| { + v.since -= UNANSWERED_AFTER.as_millis() as i64 + 1_000; + }); + d.retry_going().await; + let going = names(&d); + assert!( + going.len() == 1 && going.iter().all(|n| n.starts_with("going-")), + "{going:?}" + ); + // Asked again, its client token finds what Lambda ran, which goes. + age(&d); + d.retry_going().await; + assert!(names(&d).is_empty()); + assert_eq!( + lock(&had).clone(), + [ + format!("POST /{}/microvms", api::VERSION), + format!("DELETE /{}/microvms/mvm-found", api::VERSION), + ] + ); + Ok(()) + } + + #[tokio::test] + async fn a_throttled_replay_asks_again_rather_than_forget() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + // A whole call's tries throttled, then answered. + let (url, had) = lambda(0, api::TRIES as usize).await?; + let d = driver(dir.path(), &url)?; + let mut vm = d.new_vm("going-run", "f"); + vm.run = Some(run_request(&vm.client_token)); + vm.state = MicrovmState::Terminating; + vm.ended = true; + d.put(vm); + age(&d); + d.retry_going().await; + // The first try may have run it: kept, for the next. + assert_eq!(names(&d), ["going-run"]); + age(&d); + d.retry_going().await; + assert!(names(&d).is_empty()); + let asked = lock(&had).clone(); + assert_eq!( + asked.last(), + Some(&format!("DELETE /{}/microvms/mvm-found", api::VERSION)) + ); + Ok(()) + } + + #[tokio::test] + async fn one_past_lambdas_end_for_it_is_forgotten_without_asking() -> 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("going-old", "f"); + vm.id = Some("mvm-old".into()); + vm.state = MicrovmState::Terminating; + vm.started_at = now_ms() - 9 * 3_600_000; + d.put(vm); + age(&d); + d.retry_going().await; + assert!(names(&d).is_empty()); + assert!(lock(&had).is_empty()); + Ok(()) + } +} diff --git a/crates/fctl-host/src/driver/lambda/zip.rs b/crates/fctl-host/src/driver/lambda/zip.rs new file mode 100644 index 000000000..6f67e7b0a --- /dev/null +++ b/crates/fctl-host/src/driver/lambda/zip.rs @@ -0,0 +1,142 @@ +//! Just enough of the ZIP format for the archive Lambda builds an image +//! from: a `Dockerfile` and the files it copies, deflated, with their Unix +//! modes. No ZIP64: the archive stays well under 4 GiB. + +use flate2::Compression; +use flate2::write::DeflateEncoder; +use std::io::Write; + +/// A file to put in the archive. +pub struct Entry<'a> { + pub name: &'a str, + pub mode: u32, + pub data: &'a [u8], +} + +/// January 1st, 1980: the first day ZIP's MS-DOS dates have. +const DOS_TIME: u16 = 0; +const DOS_DATE: u16 = (1 << 5) | 1; + +/// The archive of `entries`, in their order. +pub fn write(entries: &[Entry<'_>]) -> std::io::Result> { + let mut out = Vec::new(); + let mut central = Vec::new(); + for e in entries { + let mut crc = flate2::Crc::new(); + crc.update(e.data); + let mut deflate = DeflateEncoder::new(Vec::new(), Compression::default()); + deflate.write_all(e.data)?; + let packed = deflate.finish()?; + let (size, packed_size) = (len32(e.data.len())?, len32(packed.len())?); + let name_len = u16::try_from(e.name.len()).map_err(|_| too_big())?; + let offset = len32(out.len())?; + // The local header, then the data. + out.extend_from_slice(&0x0403_4b50u32.to_le_bytes()); + out.extend_from_slice(&20u16.to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out.extend_from_slice(&8u16.to_le_bytes()); + out.extend_from_slice(&DOS_TIME.to_le_bytes()); + out.extend_from_slice(&DOS_DATE.to_le_bytes()); + out.extend_from_slice(&crc.sum().to_le_bytes()); + out.extend_from_slice(&packed_size.to_le_bytes()); + out.extend_from_slice(&size.to_le_bytes()); + out.extend_from_slice(&name_len.to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out.extend_from_slice(e.name.as_bytes()); + out.extend_from_slice(&packed); + // Its entry in the central directory: made on Unix, so that the + // mode in its external attributes counts. + central.extend_from_slice(&0x0201_4b50u32.to_le_bytes()); + central.extend_from_slice(&((3u16 << 8) | 20).to_le_bytes()); + central.extend_from_slice(&20u16.to_le_bytes()); + central.extend_from_slice(&0u16.to_le_bytes()); + central.extend_from_slice(&8u16.to_le_bytes()); + central.extend_from_slice(&DOS_TIME.to_le_bytes()); + central.extend_from_slice(&DOS_DATE.to_le_bytes()); + central.extend_from_slice(&crc.sum().to_le_bytes()); + central.extend_from_slice(&packed_size.to_le_bytes()); + central.extend_from_slice(&size.to_le_bytes()); + central.extend_from_slice(&name_len.to_le_bytes()); + central.extend_from_slice(&0u16.to_le_bytes()); + central.extend_from_slice(&0u16.to_le_bytes()); + central.extend_from_slice(&0u16.to_le_bytes()); + central.extend_from_slice(&0u16.to_le_bytes()); + central.extend_from_slice(&((0o100_000 | e.mode) << 16).to_le_bytes()); + central.extend_from_slice(&offset.to_le_bytes()); + central.extend_from_slice(e.name.as_bytes()); + } + let count = u16::try_from(entries.len()).map_err(|_| too_big())?; + let (central_at, central_len) = (len32(out.len())?, len32(central.len())?); + out.extend_from_slice(¢ral); + out.extend_from_slice(&0x0605_4b50u32.to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out.extend_from_slice(&count.to_le_bytes()); + out.extend_from_slice(&count.to_le_bytes()); + out.extend_from_slice(¢ral_len.to_le_bytes()); + out.extend_from_slice(¢ral_at.to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + Ok(out) +} + +fn too_big() -> std::io::Error { + std::io::Error::other("too big for a ZIP archive without ZIP64") +} + +fn len32(n: usize) -> std::io::Result { + u32::try_from(n).map_err(|_| too_big()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn unzip_reads_what_it_writes() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + let zip = dir.path().join("app.zip"); + let binary: Vec = (0..200_000u32).map(|i| (i % 251) as u8).collect(); + std::fs::write( + &zip, + write(&[ + Entry { + name: "Dockerfile", + mode: 0o644, + data: b"FROM scratch\n", + }, + Entry { + name: "fctl-agent", + mode: 0o755, + data: &binary, + }, + ])?, + )?; + // Python's zipfile reads ZIP archives as unzip does; it's in every + // image the tests run in. + let out = std::process::Command::new("python3") + .args(["-I", "-c"]) + .arg( + "import sys, zipfile\n\ + z = zipfile.ZipFile(sys.argv[1])\n\ + assert z.testzip() is None\n\ + for i in z.infolist(): print(i.filename, oct(i.external_attr >> 16), i.file_size)\n\ + print(z.read('Dockerfile').decode().strip())", + ) + .arg(&zip) + .output(); + let Ok(out) = out else { + // No Python here: nothing to compare with. + return Ok(()); + }; + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + assert_eq!( + String::from_utf8_lossy(&out.stdout), + "Dockerfile 0o100644 13\nfctl-agent 0o100755 200000\nFROM scratch\n" + ); + Ok(()) + } +} diff --git a/crates/fctl-host/src/driver/mod.rs b/crates/fctl-host/src/driver/mod.rs index fa16e2611..ca13c0a41 100644 --- a/crates/fctl-host/src/driver/mod.rs +++ b/crates/fctl-host/src/driver/mod.rs @@ -6,6 +6,7 @@ //! | `apple` | a lightweight VM per session | Apple `container`, Apple silicon, macOS 26+ | //! | `docker` | a container per session | Docker, OrbStack, Colima, Podman (`docker` CLI) | //! | `firecracker` | a microVM per session | Linux with KVM; experimental | +//! | `lambda` | an AWS Lambda microVM per session | a machine that may manage the account's microVMs | //! | `lima` | a VM per session, cloned from `fctl-base` | experimental | //! | `process` | none | development and trusted hosts | @@ -13,6 +14,7 @@ pub mod container; #[cfg(test)] pub(crate) mod fake; pub mod firecracker; +pub mod lambda; pub mod lima; pub mod network; pub mod process; @@ -359,6 +361,7 @@ pub enum Driver { Process(process::ProcessDriver), Container(container::ContainerDriver), Firecracker(firecracker::FirecrackerDriver), + Lambda(lambda::LambdaDriver), Lima(lima::LimaDriver), } @@ -388,6 +391,7 @@ impl Driver { "firecracker" => Some(Driver::Firecracker(firecracker::FirecrackerDriver::new( cfg, ))), + "lambda" => Some(Driver::Lambda(lambda::LambdaDriver::new(cfg))), "lima" => Some(Driver::Lima( lima::LimaDriver::new().agent_as_root(cfg.agent_as_root), )), @@ -397,7 +401,7 @@ impl Driver { if name != "auto" { return pick(name).ok_or_else(|| { anyhow::anyhow!( - "unknown driver `{name}` (use apple, docker, firecracker, lima, process or auto)" + "unknown driver `{name}` (use apple, docker, firecracker, lambda, lima, process or auto)" ) }); } @@ -440,10 +444,48 @@ impl Driver { Self::Process(_) => "process", Self::Container(c) => c.flavor_name(), Self::Firecracker(_) => "firecracker", + Self::Lambda(_) => "lambda", Self::Lima(_) => "lima", } } + /// The `lambda` driver, when it is this one: what only it does. + pub fn lambda(&self) -> Option<&lambda::LambdaDriver> { + match self { + Self::Lambda(d) => Some(d), + _ => None, + } + } + + /// Whether the host suspends a session's sandbox as it waits with + /// nothing running, and resumes it for what comes for the agent: AWS + /// Lambda's microVMs, which cost no compute suspended. + pub fn suspends(&self) -> bool { + matches!(self, Self::Lambda(_)) + } + + /// Suspends a session's sandbox ([`suspends`](Self::suspends)). + pub async fn suspend(&self, sb: &Sandbox) -> Result<()> { + match self { + Self::Lambda(d) => d.suspend(sb).await, + _ => anyhow::bail!("the {} driver doesn't suspend sandboxes", self.name()), + } + } + + /// Resumes a session's suspended sandbox. + pub async fn resume_suspended(&self, sb: &Sandbox) -> Result<()> { + match self { + Self::Lambda(d) => d.resume(sb).await, + _ => anyhow::bail!("the {} driver doesn't suspend sandboxes", self.name()), + } + } + + /// Whether every sandbox is of one size, its own, whatever a session + /// asks for: a microVM is of its image's. + pub fn sizes_itself(&self) -> bool { + matches!(self, Self::Lambda(_)) + } + /// Whether agents inside need a Linux fctl-agent binary copied in. pub fn needs_linux_agent(&self) -> bool { !matches!(self, Self::Process(_)) @@ -559,6 +601,7 @@ impl Driver { match self { Self::Container(d) => d.exists(name).await, Self::Firecracker(d) => d.exists(name).await, + Self::Lambda(d) => Ok(d.exists(name)), _ => Ok(false), } } @@ -579,6 +622,7 @@ impl Driver { Self::Process(d) => d.probe().await, Self::Container(d) => d.probe().await, Self::Firecracker(d) => d.probe().await, + Self::Lambda(d) => d.probe().await, Self::Lima(d) => d.probe().await, } } @@ -595,6 +639,7 @@ impl Driver { pub async fn measure(&self) -> Option { match self { Self::Container(d) if d.flavor_name() == "docker" => d.resources().await, + Self::Lambda(d) => d.sandbox_size(), _ => Some(machine()), } } @@ -608,6 +653,7 @@ impl Driver { Self::Process(_) => Some(DiskSpot::Dir(data_dir.to_owned())), Self::Container(d) => d.disk_spot(data_dir).await, Self::Firecracker(d) => Some(d.disk_spot(data_dir)), + Self::Lambda(_) => Some(DiskSpot::Dir(data_dir.to_owned())), Self::Lima(_) => Some(DiskSpot::Dir( lima::home() .filter(|h| h.is_dir()) @@ -647,7 +693,7 @@ impl Driver { } Self::Container(_) => (!dir.to_string_lossy().contains(',')).then_some(Spot::Dir(dir)), Self::Process(_) | Self::Firecracker(_) => Some(Spot::Dir(dir)), - Self::Lima(_) => None, + Self::Lambda(_) | Self::Lima(_) => None, } } @@ -666,7 +712,7 @@ impl Driver { Self::Container(_) | Self::Process(_) | Self::Firecracker(_) => { Ok(caches::dirs(data_dir)) } - Self::Lima(_) => Ok(Vec::new()), + Self::Lambda(_) | Self::Lima(_) => Ok(Vec::new()), } } @@ -712,6 +758,7 @@ impl Driver { Self::Process(d) => d.ensure(spec).await, Self::Container(d) => d.ensure(spec, log).await, Self::Firecracker(d) => d.ensure(spec, log).await, + Self::Lambda(d) => d.ensure(spec, log).await, Self::Lima(d) => d.ensure(spec, log).await, } } @@ -722,6 +769,7 @@ impl Driver { Self::Process(_) => Ok(()), Self::Container(d) => d.install_agent(sb, binary).await, Self::Firecracker(d) => d.install_agent(sb, binary).await, + Self::Lambda(d) => d.install_agent(sb, binary).await, Self::Lima(d) => d.install_agent(sb, binary).await, } } @@ -734,7 +782,7 @@ impl Driver { pub async fn retire_raw_sandbox(&self, name: &str) -> Result { match self { Self::Container(d) => d.retire_raw_sandbox(name).await, - Self::Process(_) | Self::Firecracker(_) | Self::Lima(_) => Ok(false), + Self::Process(_) | Self::Firecracker(_) | Self::Lambda(_) | Self::Lima(_) => Ok(false), } } @@ -746,7 +794,7 @@ impl Driver { pub async fn keep_off_metadata(&self, sb: &Sandbox, agent: &Path) -> Result<()> { match self { Self::Container(d) => d.keep_off_metadata(sb, agent).await, - Self::Process(_) | Self::Firecracker(_) | Self::Lima(_) => Ok(()), + Self::Process(_) | Self::Firecracker(_) | Self::Lambda(_) | Self::Lima(_) => Ok(()), } } @@ -756,6 +804,7 @@ impl Driver { Self::Process(d) => d.start_agent(sb).await, Self::Container(d) => d.start_agent(sb).await, Self::Firecracker(d) => d.start_agent(sb).await, + Self::Lambda(d) => d.start_agent(sb).await, Self::Lima(d) => d.start_agent(sb).await, } } @@ -772,6 +821,7 @@ impl Driver { Self::Process(d) => d.attach(sb, socket).await, Self::Container(d) => d.attach(sb, socket).await, Self::Firecracker(d) => d.attach(sb, socket).await, + Self::Lambda(d) => d.attach(sb, socket).await, Self::Lima(d) => d.attach(sb, socket).await, } } @@ -782,6 +832,7 @@ impl Driver { Self::Process(d) => d.exec(sb, script).await, Self::Container(d) => d.exec(sb, script).await, Self::Firecracker(d) => d.exec(sb, script).await, + Self::Lambda(d) => d.exec(sb, script).await, Self::Lima(d) => d.exec(sb, script).await, } } @@ -792,6 +843,7 @@ impl Driver { Self::Process(d) => d.spawn(sb, script).await.map(Running::child), Self::Container(d) => d.spawn(sb, script).await.map(Running::child), Self::Firecracker(d) => d.spawn(sb, script).await, + Self::Lambda(d) => d.spawn(sb, script).await, Self::Lima(d) => d.spawn(sb, script).await.map(Running::child), } } @@ -845,6 +897,7 @@ impl Driver { Self::Process(d) => d.stop(sb).await, Self::Container(d) => d.stop(sb).await, Self::Firecracker(d) => d.stop(sb).await, + Self::Lambda(d) => d.stop(sb).await, Self::Lima(d) => d.stop(sb).await, } } @@ -854,7 +907,7 @@ impl Driver { /// state of a VM nothing resumes; others are, as Apple's `container` /// sometimes needs its stop's second try. pub async fn finish(&self, sb: &Sandbox, destroy: bool) -> (Result<()>, Result<()>) { - if destroy && matches!(self, Self::Firecracker(_)) { + if destroy && matches!(self, Self::Firecracker(_) | Self::Lambda(_)) { return (Ok(()), self.remove(sb).await); } let stopped = self.stop(sb).await; @@ -871,6 +924,7 @@ impl Driver { Self::Process(d) => d.remove(sb).await, Self::Container(d) => d.remove(sb).await, Self::Firecracker(d) => d.remove(sb).await, + Self::Lambda(d) => d.remove(sb).await, Self::Lima(d) => d.remove(sb).await, } } @@ -955,6 +1009,7 @@ impl Driver { Self::Process(d) => d.list().await, Self::Container(d) => d.list().await, Self::Firecracker(d) => d.list().await, + Self::Lambda(d) => Ok(d.list()), Self::Lima(d) => d.list().await, } } diff --git a/crates/fctl-host/src/lib.rs b/crates/fctl-host/src/lib.rs index b9a164b38..411c3a073 100644 --- a/crates/fctl-host/src/lib.rs +++ b/crates/fctl-host/src/lib.rs @@ -4,6 +4,7 @@ //! config and a launchd/systemd service. See docs/architecture.md. pub mod agentbin; +pub mod aws; pub mod build; pub mod caches; pub mod claude_relay; diff --git a/crates/fctl-host/src/s3.rs b/crates/fctl-host/src/s3.rs index f14f920fe..98d36287a 100644 --- a/crates/fctl-host/src/s3.rs +++ b/crates/fctl-host/src/s3.rs @@ -15,7 +15,7 @@ use fctl_proto::runner::SnapshotStore; use http::Method; use sha2::{Digest, Sha256}; use std::path::{Path, PathBuf}; -use std::sync::Mutex; +use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; /// Objects up to this size go in one PUT; larger ones in parts of @@ -53,6 +53,9 @@ enum Source { /// The machine's: the `AWS_*` variables, a web identity, a container's /// credentials, or the instance's role. Machine, + /// Another part of the host's, which keeps them: a lambda host's, + /// which may be a role it assumes (`[lambda] role_arn`). + Keys(Arc), } pub struct Store { @@ -426,7 +429,17 @@ impl Store { Ok((url, signed)) } + /// The same bucket, reached with `keys` rather than the machine's. + pub fn with_keys(mut self, keys: Arc) -> Self { + self.source = Source::Keys(keys); + self + } + async fn credentials(&self) -> Result { + // They keep and renew their own. + if let Source::Keys(keys) = &self.source { + return keys.get().await; + } if let Ok(cached) = self.cached.lock() && let Some((creds, at)) = cached.as_ref() && at.elapsed() < CREDENTIALS_FOR @@ -443,6 +456,7 @@ impl Store { session_token: None, }, Source::Machine => machine_credentials(&self.http, &self.region).await?, + Source::Keys(keys) => keys.get().await?, }; if let Ok(mut cached) = self.cached.lock() { *cached = Some((creds.clone(), Instant::now())); @@ -484,7 +498,7 @@ fn endpoint(endpoint: Option<&str>, bucket: &str, region: &str) -> anyhow::Resul } } -fn env_region() -> Option { +pub(crate) fn env_region() -> Option { ["AWS_REGION", "AWS_DEFAULT_REGION"] .iter() .find_map(|v| std::env::var(v).ok().filter(|r| !r.trim().is_empty())) @@ -524,7 +538,7 @@ async fn imds_get(http: &HttpClient, token: &str, path: &str) -> Option } /// The machine's region, on EC2. -async fn imds_region() -> Option { +pub(crate) async fn imds_region() -> Option { let quick = HttpClient::new(Duration::from_secs(2)); let token = imds_token(&quick).await?; imds_get(&quick, &token, "placement/region").await @@ -533,7 +547,10 @@ async fn imds_region() -> Option { /// The machine's keys, where AWS's own tools look for them: the `AWS_*` /// variables, a web identity (EKS), a container's credentials (EKS Pod /// Identity, ECS), the instance's role (EC2). -async fn machine_credentials(http: &HttpClient, region: &str) -> Result { +pub(crate) async fn machine_credentials( + http: &HttpClient, + region: &str, +) -> Result { let var = |name: &str| std::env::var(name).ok().filter(|v| !v.trim().is_empty()); if let (Some(id), Some(secret)) = (var("AWS_ACCESS_KEY_ID"), var("AWS_SECRET_ACCESS_KEY")) { return Ok(Credentials { @@ -627,7 +644,7 @@ fn keys_from_json(body: &[u8]) -> Option { } /// Keys in STS's XML answer. -fn keys_from_xml(body: &[u8]) -> Option { +pub(crate) fn keys_from_xml(body: &[u8]) -> Option { Some(Credentials { access_key_id: xml_text(body, "AccessKeyId")?, secret_access_key: xml_text(body, "SecretAccessKey")?, @@ -636,7 +653,7 @@ fn keys_from_xml(body: &[u8]) -> Option { } /// The text of the first `` in an XML answer. -fn xml_text(body: &[u8], tag: &str) -> Option { +pub(crate) fn xml_text(body: &[u8], tag: &str) -> Option { let text = std::str::from_utf8(body).ok()?; let start = text.find(&format!("<{tag}>"))? + tag.len() + 2; let end = start + text.get(start..)?.find(&format!(""))?; diff --git a/crates/fctl-host/src/session.rs b/crates/fctl-host/src/session.rs index f4a8b0e1c..c5c5c0690 100644 --- a/crates/fctl-host/src/session.rs +++ b/crates/fctl-host/src/session.rs @@ -16,11 +16,12 @@ use fctl_domain::disk; use fctl_domain::image::ImageWant; use fctl_domain::size::{self, Want}; use fctl_proto::agent::{ - AgentConfig, AgentToHost, ClaudeRelay, FEATURE_CLAUDE_RELAY, HostToAgent, MAX_FRAME_BYTES, - SandboxCache, + AgentConfig, AgentToHost, ClaudeRelay, FEATURE_CHECKPOINTS, FEATURE_CLAUDE_RELAY, HostToAgent, + MAX_FRAME_BYTES, SandboxCache, }; use fctl_proto::api::{AgentAnswer, AgentCall}; use fctl_proto::event::{LogLevel, LogLine, LogSource, Notice, NoticeLevel, PublishedFile}; +use fctl_proto::microvm::SandboxSuspended; use fctl_proto::runner::{ CLAUDE_STAND_IN, ClaudeCredential, CredentialKind, DriverInfo, GithubCredential, SandboxLimits, SandboxSize, SessionSpec, StopReason, @@ -214,6 +215,10 @@ impl HostCtx { self.driver.measure(), self.driver.disk_spot(&data_dir) ); + // The lambda driver only the host that uses it probes. + if !drivers.iter().any(|d| d.name == self.driver.name()) { + drivers.push(self.driver.probe().await); + } // What holds up the driver this host uses only it knows: a VM that // doesn't answer, which the host doesn't stop (`driver::stuck`), or // sandboxes that lost their network, which it couldn't bring back @@ -233,8 +238,15 @@ impl HostCtx { } *self.drivers.lock().unwrap_or_else(PoisonError::into_inner) = drivers; if let Some(size) = size { - *self.sandbox.lock().unwrap_or_else(PoisonError::into_inner) = - self.cfg.sandbox_limits(size); + // A microVM is of its image's size, whatever a session asks for. + let limits = match self.driver.sizes_itself() { + true => SandboxLimits { + default: size, + max: size, + }, + false => self.cfg.sandbox_limits(size), + }; + *self.sandbox.lock().unwrap_or_else(PoisonError::into_inner) = limits; } if let Some(spot) = spot { *self @@ -328,6 +340,10 @@ pub enum SessionCmd { }, /// A newer run of this session waits to start: skip the final status. Superseded, + /// Let the session's suspended microVM go to make room for a new + /// session's, its session stopping (`driver::lambda`): nothing, unless + /// its sandbox is suspended with its snapshot saved. + LetGo, Credentials { request_id: Option, claude: Option, @@ -361,6 +377,8 @@ pub enum SessionEvent { pub struct Report { pub status: SessionStatus, pub agent_seq: u64, + /// Since when its sandbox, a microVM, has been suspended. + pub suspended_since: Option, } pub struct SessionHandle { @@ -377,6 +395,7 @@ pub fn spawn( let report = Arc::new(Mutex::new(Report { status: SessionStatus::Provisioning, agent_seq: 0, + suspended_since: None, })); let r = report.clone(); tokio::spawn(async move { @@ -962,9 +981,35 @@ fn report_reach(uplink: &Uplink, reached: Reached, paused: Option<&SandboxPaused uplink.send(UplinkUp::AgentLink { unreachable, paused: paused.cloned(), + suspended: None, }); } +/// What the host says as it suspended a session's microVM, and as it +/// resumed it. +fn suspended_words(after_secs: u32) -> String { + format!( + "Suspended its microVM after {} with nothing running. Anything for the agent resumes it as it was, in a second or two", + fctl_domain::microvm::span(u64::from(after_secs)) + ) +} + +fn resumed_words(took: Duration, suspended_for_ms: Millis) -> String { + format!( + "Resumed its microVM in {:.1} s, after {} suspended", + took.as_secs_f64(), + fctl_domain::microvm::span(u64::try_from(suspended_for_ms / 1000).unwrap_or(0)) + ) +} + +/// A checkpoint the host asked of the agent before it suspends the sandbox. +struct Checkpoint { + id: String, + asked: Instant, + /// What the agent answered: whether it saved a snapshot. + saved: Option, +} + /// `t` as milliseconds since the Unix epoch. fn wall_ms(t: Instant) -> Millis { let ago = Instant::now().saturating_duration_since(t).as_millis(); @@ -1311,6 +1356,21 @@ async fn run( } } }; + let set_suspended = |since: Option| { + if let Ok(mut r) = report.lock() { + r.suspended_since = since; + } + }; + let reported_seq = || report.lock().map(|r| r.agent_seq).unwrap_or(u64::MAX); + // A session's sandbox the host suspends as it waits with nothing + // running, a microVM (`driver::lambda`): not a review agent's, which + // stops as soon as its review is posted. + let microvms = ctx + .driver + .lambda() + .filter(|_| spec.as_ref().is_none_or(|s| s.review.is_none())); + // The sandbox, while the host holds it suspended. + let mut suspended: Option = None; // Where the agent finds the project's package caches. let mut cache = None; // A sandbox found paused as the host restarted. @@ -1409,9 +1469,31 @@ async fn run( } None => { let sb = ctx.driver.handle(&sandbox_name(session_id.as_str())); + // Suspended as it waited with nothing running: it stays so + // until something comes for the agent, which runs on as it was. + let found_suspended = microvms.and_then(|d| d.suspended(&sb.name)); + if let (Some(d), Some(since)) = (microvms, found_suspended) { + tracing::info!("{} is suspended since {since}", sb.name); + let s = SandboxSuspended { + since, + until: d + .settings() + .map(|st| fctl_domain::microvm::terminate_at(since, &st)), + microvm: d.microvm_id(&sb.name), + }; + uplink.send(UplinkUp::AgentLink { + unreachable: None, + paused: None, + suspended: Some(s.clone()), + }); + set_suspended(Some(since)); + set_report(SessionStatus::Idle, None); + suspended = Some(s); + } // Paused while the disk was nearly full: it stays so until the // disk has room, and its agent runs on once it resumes. - if ctx.driver.pauses() && ctx.driver.paused(&sb).await { + if suspended.is_some() { + } else if ctx.driver.pauses() && ctx.driver.paused(&sb).await { tracing::info!("{} is paused until there is room on the disk", sb.name); found_paused = true; } else if let Err(e) = start_again(&ctx, &sb, &uplink).await { @@ -1507,6 +1589,7 @@ async fn run( uplink.send(UplinkUp::AgentLink { unreachable: None, paused: Some(p.clone()), + suspended: None, }); held = Some(p); } @@ -1517,12 +1600,42 @@ async fn run( // Whether the transcript said why the host starts fctl-agent again, // since the agent last said hello. let mut told_restart = false; + // When the agent last said that the session waits with nothing + // running, and whether it saves a snapshot when asked to: the host + // suspends a microVM after the settings' while. + let mut quiet_since: Option = None; + let mut agent_checkpoints = false; + let mut checkpoint: Option = None; + // The agent saved its snapshot as the host last suspended the sandbox: + // a microVM let go of then loses nothing. + let mut checkpointed = spec.is_none() && microvms.is_some_and(|d| d.checkpointed(&sb.name)); + // Why the session stopped, where the host stopped it for its microVM + // rather than the agent saying. + let mut ending_reason: Option = None; + // Suspending (true) or resuming the sandbox, in a task of its own: what + // came of it, and since when. + let mut changing: Option, Instant)>> = None; let outcome = loop { + // Something for the agent comes while its microVM is suspended: it + // resumes, and the host attaches once it has. + if let Some(d) = microvms + && suspended.is_some() + && changing.is_none() + && (!queued.is_empty() || !unconfirmed.is_empty()) + { + let (d, sb) = (d.clone(), sb.clone()); + changing = Some(tokio::spawn(async move { + let at = Instant::now(); + (false, d.resume(&sb).await, at) + })); + } if link.is_none() && attaching.is_none() && exited.is_none() && held.is_none() + && suspended.is_none() + && changing.is_none() && attach_at.is_some_and(|at| Instant::now() >= at) { attach_at = None; @@ -1620,6 +1733,7 @@ async fn run( agent_files = h.features.iter().any(|f| f == FEATURE_ATTACHMENTS); agent_settings = h.features.iter().any(|f| f == FEATURE_SETTINGS); agent_relays = h.features.iter().any(|f| f == FEATURE_CLAUDE_RELAY); + agent_checkpoints = h.features.iter().any(|f| f == FEATURE_CHECKPOINTS); hello_seen = true; if h.configured && h.claude_relay { relaying = true; @@ -1691,9 +1805,24 @@ async fn run( uplink.send(UplinkUp::Stream { event }); } } - AgentToHost::State { state: st } => { + AgentToHost::State { state: st, quiet } => { set_report(st.status, None); uplink.state(st); + if let Some(q) = quiet { + quiet_since = if q { quiet_since.or(Some(Instant::now())) } else { None }; + } + } + AgentToHost::Checkpointed { id, saved, error } => { + match checkpoint.as_mut().filter(|c| c.id == id) { + // At work again: the next quiet while counts. + Some(_) if error.is_some() && !saved => { + tracing::info!("{session_id}: no checkpoint: {}", error.unwrap_or_default()); + checkpoint = None; + quiet_since = None; + } + Some(c) => c.saved = Some(saved), + None => tracing::debug!("{session_id}: an answer to a checkpoint it didn't ask for"), + } } AgentToHost::Log { line } => uplink.log(line), AgentToHost::Diff { files } => uplink.diffs(files), @@ -1947,7 +2076,7 @@ async fn run( Ok(()) => { let p = paused_for(free); tracing::warn!("paused {}: {}", sb.name, p.reason); - uplink.send(UplinkUp::AgentLink { unreachable: None, paused: Some(p.clone()) }); + uplink.send(UplinkUp::AgentLink { unreachable: None, paused: Some(p.clone()), suspended: None }); uplink.send(UplinkUp::Notice { notice: paused_notice(&ctx.cfg.name, free) }); held = Some(p); // The viewers hear of the pause now, not of the link. @@ -1980,7 +2109,88 @@ async fn run( _ => {} } } + r = async { match changing.as_mut() { Some(c) => c.await, None => std::future::pending().await } } => { + changing = None; + let Some(d) = microvms else { continue }; + let (suspending, result, at) = match r { + Ok(r) => r, + Err(e) => (suspended.is_none(), Err(anyhow::Error::from(e)), Instant::now()), + }; + match (suspending, result) { + (true, Ok(())) => { + let since = crate::expiry::now_ms(); + let settings = d.settings(); + let s = SandboxSuspended { + since, + until: settings.as_ref().map(|st| fctl_domain::microvm::terminate_at(since, st)), + microvm: d.microvm_id(&sb.name), + }; + tracing::info!("suspended {}", sb.name); + uplink.send(UplinkUp::AgentLink { unreachable: None, paused: None, suspended: Some(s.clone()) }); + if let Some(st) = &settings { + host_log(&uplink, LogLevel::Info, suspended_words(st.suspend_after_secs)); + } + set_suspended(Some(since)); + reach.told_nothing(Instant::now()); + suspended = Some(s); + } + (true, Err(e)) => { + tracing::warn!("suspending {}: {e:#}", sb.name); + host_log(&uplink, LogLevel::Warn, format!("Its host couldn't suspend its microVM, which runs on: {e:#}")); + quiet_since = None; + attach_at = Some(Instant::now()); + } + (false, Ok(())) => { + let since = suspended.take().map_or(0, |s| crate::expiry::now_ms() - s.since); + tracing::info!("resumed {} in {:?}", sb.name, at.elapsed()); + uplink.send(UplinkUp::AgentLink { unreachable: None, paused: None, suspended: None }); + host_log(&uplink, LogLevel::Info, resumed_words(at.elapsed(), since)); + set_suspended(None); + reach.told_nothing(Instant::now()); + quiet_since = None; + checkpointed = false; + attach_at = Some(Instant::now()); + } + (false, Err(e)) => { + // Gone, or it won't resume: what came for the agent + // waits for the session's next run, in a new one. + tracing::warn!("resuming {}: {e:#}", sb.name); + let _ = d.remove(&sb).await; + break ( + SessionStatus::Stopped, + Some(fctl_domain::microvm::unresumed_reason(&format!("{e:#}"), checkpointed)), + ); + } + } + } c = cmds.recv() => match c { + Some(SessionCmd::LetGo) => { + if let Some(d) = microvms + && suspended.is_some() + && changing.is_none() + && checkpointed + { + tracing::info!("letting {} go to make room", sb.name); + let _ = d.remove(&sb).await; + break (SessionStatus::Stopped, Some(fctl_domain::microvm::evicted_reason())); + } + } + // Its microVM suspended with its snapshot saved: it goes, and + // the session's next run carries on in a new one. One without + // a snapshot resumes, so that its agent stops as it would. + Some(SessionCmd::Stop { reason, destroy }) if microvms.is_some() && suspended.is_some() && changing.is_none() && checkpointed => { + let _ = (reason, destroy); + if let Some(d) = microvms { + let _ = d.remove(&sb).await; + } + let why = match reason { + StopReason::User => "Stopped", + StopReason::Idle => "Stopped after being idle", + StopReason::Deleted => "Stopped because the session was deleted", + StopReason::Shutdown => "Stopped because the host is shutting down", + }; + break (SessionStatus::Stopped, Some(why.to_owned())); + } Some(SessionCmd::Stop { reason, destroy }) => { // The agent stops what it does, and the sandbox writes // out its disk, only once it runs: one that stays paused @@ -2069,9 +2279,123 @@ async fn run( resume_again_at = None; free_disk.mark_changed(); } + if let Some(d) = microvms { + let now = crate::expiry::now_ms(); + let settings = d.settings(); + let ends = d.ends_at(&sb.name); + let nears_end = ends.is_some_and(|e| e - now <= fctl_domain::microvm::ENDING_MS); + // Suspended: it goes once its while is up, or as Lambda's + // end for it nears; with its snapshot saved, at once, + // otherwise once its agent has stopped and saved one. + if let Some(sus) = &suspended { + let due = sus.until.is_some_and(|u| now >= u); + if changing.is_none() && (due || nears_end) { + // Its snapshot: saved, or saved as its agent stops now. + let kept = checkpointed || saves_by_spec(spec.as_deref()); + let why = match (due, &settings) { + (true, Some(st)) => fctl_domain::microvm::let_go_reason(st, kept), + _ => fctl_domain::microvm::ending_reason(kept), + }; + if checkpointed || !saves_by_spec(spec.as_deref()) { + tracing::info!("letting {} go: {why}", sb.name); + let _ = d.remove(&sb).await; + break (SessionStatus::Stopped, Some(why)); + } + if stop.is_none() { + stop = Some((true, Instant::now() + crate::snapshots::STOP_SAVING)); + stop_since = Some(Instant::now()); + ending_reason = Some(why); + queued.push(HostToAgent::Stop { reason: StopReason::Idle, grace_ms: 30_000 }); + } + } + continue; + } + // Waited with nothing running for the settings' while: + // the agent saves the session's snapshot, then the host + // suspends the microVM. + if let Some(st) = &settings + && changing.is_none() + && stop.is_none() + && exited.is_none() + && held.is_none() + { + let quiet_for = Duration::from_secs(st.suspend_after_secs.into()); + match &checkpoint { + None if agent_checkpoints + && welcomed + && said_hello + && link.is_some() + && quiet_since.is_some_and(|t| t.elapsed() >= quiet_for) + && unconfirmed.is_empty() + && queued.is_empty() + && in_flight == 0 + && spool.is_none() + && upload.is_none() + && acked >= reported_seq() => + { + let id = fctl_domain::ids::new_id("ckp", now); + if let Some(l) = &link { + l.send(HostToAgent::Checkpoint { id: id.clone() }); + } + checkpoint = Some(Checkpoint { id, asked: Instant::now(), saved: None }); + } + Some(c) if c.saved.is_some() && spool.is_none() && upload.as_ref().is_none_or(|u| u.is_finished()) => { + let mut saved = c.saved == Some(true); + if let Some(up) = upload.take() { + match up.await { + Ok(Ok(())) => {} + Ok(Err(e)) => { + saved = false; + host_log(&uplink, LogLevel::Warn, format!("The session's snapshot wasn't saved as its microVM suspended: {}. Its agent saves one as the session stops", e.why)); + } + Err(e) => { + saved = false; + tracing::warn!("{session_id}: its snapshot's upload: {e}"); + } + } + } + checkpoint = None; + checkpointed = saved; + d.set_checkpointed(&sb.name, saved); + // What came meanwhile keeps it running. + if quiet_since.is_some() && unconfirmed.is_empty() && queued.is_empty() { + link = None; + if let Some(a) = attaching.take() { + a.abort(); + } + let (d, sb) = (d.clone(), sb.clone()); + changing = Some(tokio::spawn(async move { + let at = Instant::now(); + (true, d.suspend(&sb).await, at) + })); + continue; + } + } + Some(c) if c.asked.elapsed() > Duration::from_secs(5 * 60) => { + tracing::warn!("{session_id}: its agent never answered the checkpoint"); + checkpoint = None; + quiet_since = None; + } + _ => {} + } + } + // At work as Lambda's end for its microVM nears: the + // agent stops, saving its work, and a message carries the + // session on in a new one. + if stop.is_none() && exited.is_none() && changing.is_none() && nears_end { + stop = Some((true, Instant::now() + crate::snapshots::STOP_SAVING)); + stop_since = Some(Instant::now()); + ending_reason = Some(fctl_domain::microvm::ending_reason(saves_by_spec(spec.as_deref()))); + let frame = HostToAgent::Stop { reason: StopReason::Shutdown, grace_ms: 30_000 }; + match &link { + Some(l) => l.send(frame), + None => queued.push(frame), + } + } + } // A link that goes quiet is replaced. A paused sandbox's // says nothing, and the viewers know why. - if held.is_some() { + if held.is_some() || suspended.is_some() || changing.is_some() { continue; } if let Some(l) = link.as_mut() { @@ -2155,6 +2479,11 @@ async fn run( }); } let destroy = stop.map(|(d, _)| d).unwrap_or(false); + // Stopped for its microVM: the host's reason is the session's. + let outcome = match (ending_reason, outcome) { + (Some(why), (SessionStatus::Stopped, _)) => (SessionStatus::Stopped, Some(why)), + (_, outcome) => outcome, + }; let (stopped, removed) = ctx.driver.finish(&sb, destroy).await; if let Err(e) = stopped { tracing::warn!("stopping {}: {e:#}", sb.name); @@ -2200,6 +2529,7 @@ async fn resume(ctx: &HostCtx, sb: &Sandbox, uplink: &Uplink, notice: Notice) -> uplink.send(UplinkUp::AgentLink { unreachable: None, paused: None, + suspended: None, }); if resumed { uplink.send(UplinkUp::Notice { notice }); diff --git a/crates/fctl-proto/src/agent.rs b/crates/fctl-proto/src/agent.rs index e968e2c76..aeb0941d1 100644 --- a/crates/fctl-proto/src/agent.rs +++ b/crates/fctl-proto/src/agent.rs @@ -201,6 +201,15 @@ pub enum HostToAgent { #[cfg_attr(feature = "ts", ts(optional))] error: Option, }, + /// Save the session's snapshot now, as it waits with nothing running, + /// and hand it over as at a stop ([`AgentToHost::SnapshotPart`]), then + /// say so ([`AgentToHost::Checkpointed`]): its host is about to suspend + /// the sandbox, a microVM that may be let go before the agent runs + /// again ([`crate::microvm`]). Only to agents that announce + /// [`FEATURE_CHECKPOINTS`]. + Checkpoint { + id: String, + }, Ping, } @@ -245,6 +254,12 @@ pub enum AgentToHost { }, State { state: SessionState, + /// The session waits with nothing running: no background task, + /// and Claude said last that it is done. Its idle timeout counts + /// from then. Absent from older agents. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "ts", ts(optional))] + quiet: Option, }, /// A log line that should not be journaled (progress noise). Log { @@ -323,6 +338,16 @@ pub enum AgentToHost { SnapshotWanted { id: String, }, + /// The answer to [`HostToAgent::Checkpoint`], after the snapshot's + /// last part: whether it saved one, and why not. A session whose + /// workspace keeps no snapshots saves none, and says nothing of it. + Checkpointed { + id: String, + saved: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "ts", ts(optional))] + error: Option, + }, /// The supervisor is exiting. Exited { status: SessionStatus, @@ -358,6 +383,12 @@ pub struct SnapshotSaved { /// hello ([`AgentHello::features`]). pub const FEATURE_AGENT_SNAPSHOTS: &str = "snapshots"; +/// What agents announce that say when the session waits with nothing +/// running ([`AgentToHost::State`]'s `quiet`) and save a snapshot when +/// asked to ([`HostToAgent::Checkpoint`]): their host may suspend their +/// sandbox then. +pub const FEATURE_CHECKPOINTS: &str = "checkpoints"; + /// The environment variable that holds the session socket's path, set for /// Claude and everything it runs. pub const SESSION_SOCKET_ENV: &str = "FCTL_SESSION_SOCKET"; diff --git a/crates/fctl-proto/src/api.rs b/crates/fctl-proto/src/api.rs index 7a1fdd514..97de3cd18 100644 --- a/crates/fctl-proto/src/api.rs +++ b/crates/fctl-proto/src/api.rs @@ -3071,6 +3071,60 @@ pub struct Runner { /// It is removed once it has been offline this many minutes, as its /// enrollment token said. Absent: it stays until someone removes it. pub remove_offline_after_minutes: Option, + /// How its microVMs are, for a runner whose host runs sessions in AWS + /// Lambda MicroVMs: counts, its image and what stops it, without the + /// list of microVMs (`GET /api/v1/runners/{id}/microvms` has it). + /// Absent for other runners. + pub microvms: Option, + /// Whether it has microVM settings (`PUT /api/v1/runners/{id}/microvms`), + /// for those who manage it. Absent for other runners and people. + pub microvms_configured: Option, +} + +/// A runner's microVMs: their settings, for those who manage it, and how +/// they are, with every one of them and the sessions they run +/// (`GET /api/v1/runners/{id}/microvms`). +#[skip_serializing_none] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS), ts(optional_fields))] +pub struct RunnerMicrovms { + pub runner: RunnerId, + /// Absent while nobody has set them. + pub settings: Option, + /// When they were last changed, and by whom. + pub updated_at: Option, + pub updated_by: Option, + /// What its host said last, while it is connected or was recently. + pub report: Option, + /// The sessions its microVMs run, of those you can see. + #[serde(default)] + #[cfg_attr(feature = "ts", ts(as = "Option>", optional))] + pub sessions: Vec, + /// Whether you may change the settings: you manage the runner. + #[serde(default)] + pub manage: bool, +} + +/// A session one of a runner's microVMs runs. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct MicrovmSessionRef { + pub id: SessionId, + /// Sequential per project (`#12`). + pub number: u32, + pub title: String, + /// Its project's slug and name. + pub project_slug: String, + pub project_name: String, + pub status: SessionStatus, +} + +/// `PUT /api/v1/runners/{id}/microvms`: the settings of a runner's +/// microVMs, all of them. Its host gets them at once. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct PutRunnerMicrovmsRequest { + pub settings: crate::microvm::MicrovmSettings, } /// How a runner enrolled in its workspace: what its workspace's admins see diff --git a/crates/fctl-proto/src/lib.rs b/crates/fctl-proto/src/lib.rs index 8ac788a8a..963abaf98 100644 --- a/crates/fctl-proto/src/lib.rs +++ b/crates/fctl-proto/src/lib.rs @@ -17,6 +17,7 @@ //! | [`runner`] | FleetDO ⇄ hosts (control connection) | //! | [`uplink`] | SessionDO ⇄ hosts (one connection per session) | //! | [`agent`] | hosts ⇄ fctl-agent inside a sandbox, and `fctl` ⇄ fctl-agent within it | +//! | [`microvm`] | AWS Lambda MicroVMs: a runner's settings for them, and what its host says of them | //! | [`tickets`] | tickets in a project's tracker, whatever the tracker, and Linear's connections | //! | [`slack`] | Slack's connections, people's Slack accounts, and what agents read and post there | //! | [`vm`] | hosts ⇄ the init of a Firecracker microVM, over its vsock | @@ -29,6 +30,7 @@ pub mod event; pub mod hooks; pub mod identity; pub mod ids; +pub mod microvm; pub mod runner; pub mod service_accounts; pub mod session; diff --git a/crates/fctl-proto/src/microvm.rs b/crates/fctl-proto/src/microvm.rs new file mode 100644 index 000000000..8ed0be7e2 --- /dev/null +++ b/crates/fctl-proto/src/microvm.rs @@ -0,0 +1,496 @@ +//! AWS Lambda MicroVMs: the settings a runner whose host uses the `lambda` +//! driver runs its sessions' microVMs with, which the people who manage the +//! runner keep in the control plane, and what its host says of them. +//! +//! A runner of the `lambda` driver is one host (`fctl host`, on a machine +//! that may manage the account's microVMs) that runs each session in a +//! microVM of its own: it takes one from its warm pool or runs a new one, +//! suspends it once the session has waited `suspend_after_secs` with +//! nothing running, resumes it as soon as something comes for the agent, +//! and lets it go `terminate_after_minutes` after it suspended, when the +//! session stops and a message carries it on in a new microVM from its +//! snapshot (docs/architecture.md#aws-lambda-microvms). +//! +//! The control plane sends a host its runner's settings +//! ([`crate::runner::FleetToHost::Microvms`]) after its welcome and +//! whenever they change; the host says how its microVMs are +//! ([`MicrovmReport`]) in its hello and in the heartbeats after a change. +//! In the microVM, `fctl-agent microvm-serve` answers Lambda's lifecycle +//! hooks on [`HOOKS_PORT`] and serves [`crate::vm`]'s requests on +//! [`SERVE_PORT`], over WebSockets that the host opens through the +//! microVM's endpoint. + +use crate::{Millis, SessionId}; +use serde::{Deserialize, Serialize}; +use serde_with::skip_serializing_none; + +/// What hosts that run sessions in AWS Lambda MicroVMs announce in their +/// hello ([`crate::runner::HostHello::features`]): FleetDO sends them their +/// runner's settings, and counts the sessions they say are suspended +/// ([`crate::runner::HostSessionReport::suspended_since`]) as room, since +/// the host lets the longest suspended go to make room for a new one. +pub const FEATURE_MICROVMS: &str = "microvms"; + +/// The driver's name, as hosts say it. +pub const DRIVER: &str = "lambda"; + +/// The port in the microVM where `fctl-agent microvm-serve` takes the +/// host's WebSockets, each carrying one [`crate::vm::Request`] and what +/// follows it, as a vsock connection does for Firecracker's VMs. Lambda +/// sends the endpoint's traffic here unless a request names another port. +pub const SERVE_PORT: u16 = 8080; + +/// The port where `fctl-agent microvm-serve` answers Lambda's lifecycle +/// hooks. The auth tokens the host makes don't reach it. +pub const HOOKS_PORT: u16 = 9000; + +/// The path of the WebSocket on [`SERVE_PORT`]. +pub const SERVE_PATH: &str = "/fctl/v1/vm"; + +/// The header that carries the key the host gave the microVM as it ran it +/// ([`RunPayload::key`]): `microvm-serve` takes no request without it, so +/// that a program in the microVM can't ask it to run what it likes as root. +pub const KEY_HEADER: &str = "x-fctl-microvm-key"; + +/// Where Lambda calls the lifecycle hooks, before each hook's name. +pub const HOOKS_PATH: &str = "/aws/lambda-microvms/runtime/v1"; + +/// The longest a microVM lives, running and suspended together: Lambda's +/// limit, after which it terminates it. +pub const MAX_LIFETIME_SECS: u32 = 28_800; + +/// What a runner's settings start from, where the people who set them +/// choose nothing else. +pub const DEFAULT_SUSPEND_AFTER_SECS: u32 = 90; +pub const DEFAULT_TERMINATE_AFTER_MINUTES: u32 = 60; +pub const DEFAULT_WARM: u32 = 2; +pub const DEFAULT_MAX_MICROVMS: u32 = 20; +pub const DEFAULT_MEMORY_MB: u32 = 2048; + +/// The ranges they take, both ends included. +pub const SUSPEND_AFTER_SECS: (u32, u32) = (60, 3600); +pub const TERMINATE_AFTER_MINUTES: (u32, u32) = (5, 420); +pub const WARM: (u32, u32) = (0, 20); +pub const MAX_MICROVMS: (u32, u32) = (1, 1000); + +/// The image fctl builds, unless its settings name another. +pub const DEFAULT_IMAGE_NAME: &str = "fctl-sandbox"; + +/// What the host hands a microVM as it runs it, as the `/run` hook's +/// `runHookPayload`: who runs it, and the key `microvm-serve` asks for. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct RunPayload { + /// The payload's version. + pub fctl: u32, + /// The runner whose host ran it. + pub runner: String, + /// What the host calls it, until a session takes it: `warm-…`. + pub name: String, + /// 32 random bytes, hex: [`KEY_HEADER`]'s value. + pub key: String, +} + +/// The settings of a runner's microVMs. +#[skip_serializing_none] +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS), ts(optional_fields))] +pub struct MicrovmSettings { + /// The image its microVMs run from. + pub image: MicrovmImage, + /// Each microVM's baseline memory, in MiB, with half a vCPU per GiB: + /// 512, 1024, 2048, 4096 or 8192 ([`MICROVM_SIZES`]). A microVM bursts to + /// four times as much when it needs it. Images fctl builds get it; an + /// image of your own says its own. + pub memory_mb: u32, + /// The CPU architecture of the images fctl builds. Absent: arm64. + pub arch: Option, + /// The IAM role the microVMs run as, whose permissions the agents in + /// them have. Absent: none, and no AWS credentials in the microVMs. + pub execution_role_arn: Option, + /// The egress network connectors the microVMs reach out through: a + /// connector of your VPC's, say. Empty: Lambda's public internet + /// (`INTERNET_EGRESS`). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[cfg_attr(feature = "ts", ts(as = "Option>", optional))] + pub egress_connectors: Vec, + /// The KMS key that encrypts the microVMs' configuration and the + /// images fctl builds. Absent: an AWS owned key. + pub kms_key_arn: Option, + /// The CloudWatch Logs log group the microVMs' output goes to. Absent: + /// Lambda's own for the image (`/aws/lambda-microvms/`). + pub log_group: Option, + /// How long a session waits for a message, with nothing running, + /// before its host suspends its microVM: 60 to 3,600 seconds. + pub suspend_after_secs: u32, + /// How long a microVM stays suspended before its host lets it go, its + /// session stopping: 5 to 420 minutes. A message before then resumes it + /// as it was, in a second or two; one after, in a new microVM from the + /// session's snapshot. + pub terminate_after_minutes: u32, + /// How many microVMs the host keeps started and suspended, waiting for + /// a session: 0 to 20. + pub warm: u32, + /// The most microVMs it has at once, running and suspended, warm ones + /// included: what fits the account's quota. 1 to 1,000. + pub max_microvms: u32, + /// Sessions that could run on another of the workspace's runners run + /// here first. Absent or false: as on any runner. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + #[cfg_attr(feature = "ts", ts(as = "Option", optional))] + pub first: bool, +} + +/// The image a runner's microVMs run from. +#[skip_serializing_none] +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS), ts(optional_fields))] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum MicrovmImage { + /// fctl builds it, from the sandbox image of its host's version, and + /// builds it again as the host updates: the host uploads what Lambda + /// builds it from to `artifacts` and has Lambda build it as + /// `build_role_arn`. + Managed { + /// `s3://bucket/prefix`, in the image's region. + artifacts: String, + /// The role Lambda builds the image as, which reads `artifacts`. + build_role_arn: String, + /// The image's name in the account. Absent: [`DEFAULT_IMAGE_NAME`]. + name: Option, + }, + /// One of your own, from fctl's template (`fctl host microvm-image`). + Own { + /// `arn:aws:lambda:::microvm-image:`. + arn: String, + /// Its version to run. Absent: its latest active one. + version: Option, + }, +} + +/// A CPU architecture of Lambda's microVMs. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +#[serde(rename_all = "snake_case")] +pub enum MicrovmArch { + #[default] + Arm64, + X86_64, +} + +impl MicrovmArch { + /// As Lambda's API says it. + pub fn api(self) -> &'static str { + match self { + Self::Arm64 => "ARM_64", + Self::X86_64 => "X86_64", + } + } + + /// As Rust (and fctl's release archives) say it. + pub fn rust(self) -> &'static str { + match self { + Self::Arm64 => "aarch64", + Self::X86_64 => "x86_64", + } + } + + /// From Lambda's API, or Rust's word. + pub fn parse(s: &str) -> Option { + match s { + "ARM_64" | "arm64" | "aarch64" => Some(Self::Arm64), + "X86_64" | "x86_64" | "amd64" => Some(Self::X86_64), + _ => None, + } + } +} + +/// One of the sizes Lambda's microVMs come in: a baseline, which the +/// microVM bursts to four times when it needs to, and its disk. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct MicrovmSize { + /// Baseline memory, MiB. + pub memory_mb: u32, + /// Baseline vCPUs, in thousandths: 250 is a quarter of one. + pub vcpu_milli: u32, + /// The most disk it has, GiB. + pub disk_gb: u32, +} + +impl MicrovmSize { + /// What it bursts to: four times its baseline. + pub fn peak(self) -> crate::runner::SandboxSize { + crate::runner::SandboxSize { + cpus: (self.vcpu_milli * 4).div_ceil(1000), + memory_mb: self.memory_mb * 4, + } + } +} + +/// The sizes Lambda's microVMs come in, smallest first (a GiB of memory to +/// half a vCPU; Lambda's default is 2 GiB). +pub const MICROVM_SIZES: [MicrovmSize; 5] = [ + MicrovmSize { + memory_mb: 512, + vcpu_milli: 250, + disk_gb: 10, + }, + MicrovmSize { + memory_mb: 1024, + vcpu_milli: 500, + disk_gb: 16, + }, + MicrovmSize { + memory_mb: 2048, + vcpu_milli: 1000, + disk_gb: 32, + }, + MicrovmSize { + memory_mb: 4096, + vcpu_milli: 2000, + disk_gb: 64, + }, + MicrovmSize { + memory_mb: 8192, + vcpu_milli: 4000, + disk_gb: 128, + }, +]; + +/// The size with `memory_mb` of baseline memory, if microVMs come in it. +pub fn microvm_size(memory_mb: u32) -> Option { + MICROVM_SIZES.into_iter().find(|s| s.memory_mb == memory_mb) +} + +/// A microVM as its host knows it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +#[serde(rename_all = "snake_case")] +pub enum MicrovmState { + /// Lambda runs it from its image (`PENDING`), and the host waits for + /// `microvm-serve` to answer. + Starting, + /// It runs: a session's agent works or waits in it, or a warm one is + /// about to be suspended. + Running, + /// The host has asked Lambda to suspend it (`SUSPENDING`). + Suspending, + /// Suspended: its memory and disk are kept, and it costs no compute. + Suspended, + /// The host has asked Lambda to resume it, and waits for it. + Resuming, + /// The host has asked Lambda to terminate it (`TERMINATING`). + Terminating, +} + +/// One of a runner's microVMs. +#[skip_serializing_none] +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS), ts(optional_fields))] +pub struct MicrovmVm { + /// Lambda's id: `mvm-…`. + pub id: String, + pub state: MicrovmState, + /// The session it runs. Absent for a warm one, which waits for one. + pub session: Option, + /// Since when it has been in `state`. + pub since: Millis, + /// When Lambda ran it. + pub started_at: Millis, + /// When Lambda terminates it whatever it does ([`MAX_LIFETIME_SECS`] + /// after `started_at`). + pub ends_at: Millis, + /// For a suspended one, when its host lets it go. + pub terminates_at: Option, + /// The image version it runs. + pub image_version: Option, +} + +/// How a runner's image is. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +#[serde(rename_all = "snake_case")] +pub enum MicrovmImageStatus { + /// MicroVMs run from it. + Ready, + /// Lambda builds a version of it: for a new fctl, or a new size. + /// MicroVMs run from the version before meanwhile, where there is one. + Building, + /// Its last build failed (`error` says why); microVMs run from the + /// version before, where there is one. + Failed, + /// It isn't there, or has no version to run. + Missing, +} + +/// A runner's image, as its host last found it. +#[skip_serializing_none] +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS), ts(optional_fields))] +pub struct MicrovmImageReport { + pub arn: String, + pub status: MicrovmImageStatus, + /// The version microVMs run from now. + pub version: Option, + /// For an image fctl builds: the fctl the version it runs was built + /// for, and the one it builds now. + pub fctl_version: Option, + pub building: Option, + /// Since when it has been in `status`. + pub since: Option, + /// Why its last build failed, or why it can't be read. + pub error: Option, + /// What its microVMs are, as its version says: its size and + /// architecture. + pub size: Option, + pub arch: Option, +} + +/// What stops a runner's host from running microVMs as it should, as AWS +/// answered it last: a permission it lacks, the account's quota. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct MicrovmProblem { + /// `access`, `quota`, `capacity`, `throttled`, `settings`, + /// `credentials`, `unreachable` or `other`. + pub kind: String, + /// What happened, in a sentence: what AWS said, and what it stops. + pub message: String, + pub since: Millis, +} + +/// How a runner's microVMs are, as its host says in its hello and in the +/// heartbeats after they change ([`crate::runner::HostHeartbeat::microvms`]). +#[skip_serializing_none] +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS), ts(optional_fields))] +pub struct MicrovmReport { + /// The region its microVMs run in, and the account. + pub region: Option, + pub account: Option, + /// Whether it has settings from the control plane: without them, it + /// runs nothing. + #[serde(default)] + pub configured: bool, + pub image: Option, + /// Its microVMs by what they do: running a session (working or + /// waiting), suspended with one, warm (waiting for one, suspended), + /// and starting, suspending, resuming or terminating. + #[serde(default)] + pub running: u32, + #[serde(default)] + pub suspended: u32, + #[serde(default)] + pub warm: u32, + #[serde(default)] + pub changing: u32, + /// The most it has at once ([`MicrovmSettings::max_microvms`]). + #[serde(default)] + pub max: u32, + /// What stops it, while something does. + pub problem: Option, + /// Every microVM it has, in heartbeats and in + /// `GET /api/v1/runners/{id}/microvms`; absent from the runner's hello + /// as the API shows it. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[cfg_attr(feature = "ts", ts(as = "Option>", optional))] + pub vms: Vec, +} + +impl MicrovmReport { + /// The report without its list of microVMs, as the runner's hello + /// keeps it. + pub fn summary(&self) -> Self { + Self { + vms: Vec::new(), + ..self.clone() + } + } +} + +/// The host suspended the session's sandbox, an AWS Lambda microVM, as its +/// session waited for a message with nothing running: anything for the +/// agent resumes it, in a second or two, as it was. +#[skip_serializing_none] +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS), ts(optional_fields))] +pub struct SandboxSuspended { + pub since: Millis, + /// When the host lets it go unless something comes for the agent: the + /// session stops then, and a message carries it on in a new microVM + /// from its snapshot. + pub until: Option, + /// The microVM's id. + pub microvm: Option, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn settings_read_as_the_api_writes_them() -> serde_json::Result<()> { + let settings: MicrovmSettings = serde_json::from_value(serde_json::json!({ + "image": { + "kind": "managed", + "artifacts": "s3://acme-fctl/microvms", + "build_role_arn": "arn:aws:iam::123456789012:role/fctl-microvm-build" + }, + "memory_mb": 2048, + "suspend_after_secs": 90, + "terminate_after_minutes": 60, + "warm": 2, + "max_microvms": 20 + }))?; + assert_eq!(settings.arch, None); + assert!(settings.egress_connectors.is_empty()); + assert!(!settings.first); + let json = serde_json::to_value(&settings)?; + assert!(json.get("egress_connectors").is_none()); + assert!(json.get("first").is_none()); + assert!(json["image"].get("name").is_none()); + let own: MicrovmImage = serde_json::from_value(serde_json::json!({ + "kind": "own", + "arn": "arn:aws:lambda:us-east-1:123456789012:microvm-image:agents" + }))?; + assert!(matches!(own, MicrovmImage::Own { version: None, .. })); + Ok(()) + } + + #[test] + fn sizes_burst_to_four_times_their_baseline() { + let two = microvm_size(2048).map(|s| s.peak()); + assert_eq!( + two, + Some(crate::runner::SandboxSize { + cpus: 4, + memory_mb: 8192 + }) + ); + let half = microvm_size(512).map(|s| s.peak()); + assert_eq!(half.map(|p| p.cpus), Some(1)); + assert_eq!(microvm_size(3000), None); + assert_eq!(MicrovmArch::parse("ARM_64"), Some(MicrovmArch::Arm64)); + assert_eq!(MicrovmArch::X86_64.rust(), "x86_64"); + } + + #[test] + fn a_summary_leaves_the_microvms_out() { + let report = MicrovmReport { + running: 1, + vms: vec![MicrovmVm { + id: "mvm-1".into(), + state: MicrovmState::Running, + session: None, + since: 1, + started_at: 1, + ends_at: 2, + terminates_at: None, + image_version: None, + }], + ..MicrovmReport::default() + }; + assert!(report.summary().vms.is_empty()); + assert_eq!(report.summary().running, 1); + } +} diff --git a/crates/fctl-proto/src/runner.rs b/crates/fctl-proto/src/runner.rs index 00473a906..ce9cf5798 100644 --- a/crates/fctl-proto/src/runner.rs +++ b/crates/fctl-proto/src/runner.rs @@ -59,6 +59,14 @@ pub struct HostSessionReport { pub status: SessionStatus, /// The last event sequence number the agent produced. pub agent_seq: u64, + /// Since when its sandbox has been suspended, a microVM its host + /// suspended as the session waited with nothing running + /// ([`crate::microvm`]): it costs no compute, and the host lets it go + /// to make room for a new session. Absent while it runs, and from + /// other hosts. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "ts", ts(optional))] + pub suspended_since: Option, } #[skip_serializing_none] @@ -119,6 +127,9 @@ pub struct HostHello { /// each is. Absent where they go to the control plane, and from older /// hosts. pub snapshot_store: Option, + /// How its microVMs are, for a host of the `lambda` driver + /// ([`crate::microvm`]). Absent from other hosts. + pub microvms: Option, } /// A bucket of an organization's own that a host keeps its sessions' @@ -178,6 +189,14 @@ pub struct HostHeartbeat { /// Its snapshots' bucket, as in its hello ([`HostHello::snapshot_store`]), /// when what it says changed: an upload failed, or worked again. pub snapshot_store: Option, + /// How many sessions it runs at once, as in its hello + /// ([`HostHello::capacity`]), when that changed since it last said: a + /// host of the `lambda` driver runs as many as its runner's settings + /// allow microVMs. Absent when it didn't, and from older hosts. + pub capacity: Option, + /// Its microVMs, as in its hello ([`HostHello::microvms`]), with every + /// one of them, when they changed since it last said. + pub microvms: Option, } /// How short of room a runner is on the disk where its sandboxes are @@ -821,6 +840,15 @@ pub enum FleetToHost { ClaudeLoginCancel { job_id: LoginJobId, }, + /// The settings of the runner's microVMs, to a host that announces + /// [`crate::microvm::FEATURE_MICROVMS`]: after its welcome, and + /// whenever the people who manage the runner change them. Absent while + /// nobody has set them, when the host runs no microVMs. + Microvms { + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "ts", ts(optional))] + settings: Option, + }, Ping, } @@ -851,6 +879,35 @@ mod tests { }) } + #[test] + fn microvm_hosts_say_their_microvms_in_fields_older_peers_ignore() -> serde_json::Result<()> { + // Older hosts say nothing of microVMs, nor of suspended sessions. + let beat: HostHeartbeat = serde_json::from_value(serde_json::json!({ + "sessions": [{ "session_id": "ses_1", "status": "idle", "agent_seq": 4 }] + }))?; + assert_eq!(beat.microvms, None); + assert_eq!(beat.capacity, None); + assert_eq!(beat.sessions[0].suspended_since, None); + let json = serde_json::to_value(&beat)?; + assert!(json.get("microvms").is_none() && json.get("capacity").is_none()); + assert!(json["sessions"][0].get("suspended_since").is_none()); + // A host of the lambda driver says which of its sessions are + // suspended, and how its microVMs are. + let report = HostSessionReport { + suspended_since: Some(1_000), + ..beat.sessions[0].clone() + }; + assert_eq!(serde_json::to_value(&report)?["suspended_since"], 1_000); + // Settings travel to it in a message older hosts log and ignore. + let msg: FleetToHost = serde_json::from_value(serde_json::json!({ "type": "microvms" }))?; + assert_eq!(msg, FleetToHost::Microvms { settings: None }); + assert_eq!( + serde_json::to_string(&FleetToHost::Microvms { settings: None })?, + r#"{"type":"microvms"}"# + ); + Ok(()) + } + #[test] fn a_sign_in_that_failed_says_so_as_older_hosts_and_control_planes_read_it() -> serde_json::Result<()> { diff --git a/crates/fctl-proto/src/ts_export.rs b/crates/fctl-proto/src/ts_export.rs index 79663b565..d078ceb42 100644 --- a/crates/fctl-proto/src/ts_export.rs +++ b/crates/fctl-proto/src/ts_export.rs @@ -12,8 +12,8 @@ pub fn export_typescript(dir: &Path) -> Result<(), ExportError> { }; } use crate::{ - agent, api, autopilot, event, hooks, identity, runner, service_accounts, session, slack, - tickets, uplink, viewer, + agent, api, autopilot, event, hooks, identity, microvm, runner, service_accounts, session, + slack, tickets, uplink, viewer, }; export!( crate::ApiError, @@ -215,6 +215,20 @@ pub fn export_typescript(dir: &Path) -> Result<(), ExportError> { api::WorkspaceDemand, api::SnapshotCommit, runner::SnapshotStore, + microvm::MicrovmSettings, + microvm::MicrovmImage, + microvm::MicrovmArch, + microvm::MicrovmSize, + microvm::MicrovmState, + microvm::MicrovmVm, + microvm::MicrovmImageStatus, + microvm::MicrovmImageReport, + microvm::MicrovmProblem, + microvm::MicrovmReport, + microvm::SandboxSuspended, + api::RunnerMicrovms, + api::MicrovmSessionRef, + api::PutRunnerMicrovmsRequest, api::ProjectList, api::CreateProjectRequest, api::UpdateProjectRequest, @@ -449,6 +463,22 @@ pub fn export_typescript(dir: &Path) -> Result<(), ExportError> { .map_err(std::io::Error::other)?; let slack = serde_json::to_string(slack::DEFAULT_SLACK_INSTRUCTIONS).map_err(std::io::Error::other)?; + let sizes = serde_json::to_string(µvm::MICROVM_SIZES).map_err(std::io::Error::other)?; + let microvm_defaults = serde_json::json!({ + "suspend_after_secs": microvm::DEFAULT_SUSPEND_AFTER_SECS, + "terminate_after_minutes": microvm::DEFAULT_TERMINATE_AFTER_MINUTES, + "warm": microvm::DEFAULT_WARM, + "max_microvms": microvm::DEFAULT_MAX_MICROVMS, + "memory_mb": microvm::DEFAULT_MEMORY_MB, + "image_name": microvm::DEFAULT_IMAGE_NAME, + }); + let microvm_limits = serde_json::json!({ + "suspend_after_secs": microvm::SUSPEND_AFTER_SECS, + "terminate_after_minutes": microvm::TERMINATE_AFTER_MINUTES, + "warm": microvm::WARM, + "max_microvms": microvm::MAX_MICROVMS, + "lifetime_secs": microvm::MAX_LIFETIME_SECS, + }); std::fs::write( dir.join(DEFAULTS_FILE), format!( @@ -458,7 +488,13 @@ pub fn export_typescript(dir: &Path) -> Result<(), ExportError> { /**\n * How agents write what they post in Slack, where their workspace chooses nothing else\n * (`SlackSettings.instructions`).\n */\n\ export const DEFAULT_SLACK_INSTRUCTIONS = {slack};\n\n\ /** The most a workspace's Slack instructions hold, in characters. */\n\ - export const MAX_SLACK_INSTRUCTIONS = {max};\n", + export const MAX_SLACK_INSTRUCTIONS = {max};\n\n\ + /** The sizes AWS Lambda's microVMs come in, smallest first (`MICROVM_SIZES`). */\n\ + export const MICROVM_SIZES = {sizes};\n\n\ + /** What a runner's microVM settings start from (`fctl_proto::microvm`). */\n\ + export const MICROVM_DEFAULTS = {microvm_defaults};\n\n\ + /** The ranges a runner's microVM settings take, both ends included, and a microVM's lifetime. */\n\ + export const MICROVM_LIMITS = {microvm_limits};\n", max = slack::MAX_SLACK_INSTRUCTIONS, ), )?; diff --git a/crates/fctl-proto/src/uplink.rs b/crates/fctl-proto/src/uplink.rs index b68a9983e..0b25966e1 100644 --- a/crates/fctl-proto/src/uplink.rs +++ b/crates/fctl-proto/src/uplink.rs @@ -245,6 +245,12 @@ pub enum UplinkUp { #[serde(default, skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "ts", ts(optional))] paused: Option, + /// The host suspended the sandbox, a microVM, as the session waited + /// with nothing running, and resumes it for whatever comes for the + /// agent. Absent while it runs, and from other hosts. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "ts", ts(optional))] + suspended: Option, }, /// Something the host itself says in the transcript, such as that it /// paused the sandbox (`sandbox_paused`). Older hosts send none, and @@ -286,6 +292,7 @@ mod tests { reason: "nothing came from fctl-agent for a minute".into(), }), paused: None, + suspended: None, }; let json = serde_json::to_value(&down)?; assert_eq!(json["type"], "agent_link"); @@ -296,6 +303,7 @@ mod tests { let up = UplinkUp::AgentLink { unreachable: None, paused: None, + suspended: None, }; assert_eq!( serde_json::to_string(&up)?, @@ -316,6 +324,7 @@ mod tests { since: 2_000, reason: "it is nearly out of disk, with 800 MiB free".into(), }), + suspended: None, }; let json = serde_json::to_value(&paused)?; assert_eq!(json["paused"]["since"], 2_000); diff --git a/crates/fctl-proto/src/viewer.rs b/crates/fctl-proto/src/viewer.rs index d3b440bb3..35a29c4fd 100644 --- a/crates/fctl-proto/src/viewer.rs +++ b/crates/fctl-proto/src/viewer.rs @@ -67,6 +67,11 @@ pub struct Snapshot { #[serde(default, skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "ts", ts(optional))] pub sandbox_paused: Option, + /// The connected runner suspended the session's sandbox, a microVM, as + /// it waited with nothing running: a message resumes it as it was. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "ts", ts(optional))] + pub sandbox_suspended: Option, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -113,6 +118,10 @@ pub enum ViewerServer { #[serde(default, skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "ts", ts(optional))] sandbox_paused: Option, + /// As the snapshot's `sandbox_suspended`. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "ts", ts(optional))] + sandbox_suspended: Option, }, /// The outcome of a client command, matched by `client_id`. Result { @@ -173,6 +182,7 @@ mod tests { agent_unreachable: None, disk: None, sandbox_paused: None, + sandbox_suspended: None, } ); // Nothing to say leaves the new fields out, for older clients. diff --git a/crates/fctl-proto/src/vm.rs b/crates/fctl-proto/src/vm.rs index 33d919542..4d36e35d1 100644 --- a/crates/fctl-proto/src/vm.rs +++ b/crates/fctl-proto/src/vm.rs @@ -1,5 +1,7 @@ //! Host ⇄ the init of a Firecracker microVM (`fctl-agent` as the VM's PID 1), -//! over the VM's vsock. +//! over the VM's vsock, and ⇄ `fctl-agent microvm-serve` in an AWS Lambda +//! microVM, over WebSockets through the microVM's endpoint +//! ([`crate::microvm`]), each carrying what a vsock connection would. //! //! Firecracker puts a VM's vsock on the host as a unix socket. The host //! connects to it, asks for [`PORT`] (`CONNECT 1024\n`, which Firecracker @@ -203,6 +205,20 @@ pub struct Reply { /// The init's version of fctl (to `hello`). #[serde(default)] pub version: Option, + /// In an AWS Lambda microVM (`fctl-agent microvm-serve`, to `hello`): + /// the user its sessions run as, its CPU architecture (`aarch64`, + /// `x86_64`), Lambda's id for it, and the runner and name its host + /// gave it as it ran it ([`crate::microvm::RunPayload`]). + #[serde(default)] + pub user: Option, + #[serde(default)] + pub arch: Option, + #[serde(default)] + pub microvm: Option, + #[serde(default)] + pub runner: Option, + #[serde(default)] + pub name: Option, /// What unpacking wrote (its second reply): files and bytes. #[serde(default)] pub files: Option, diff --git a/crates/fctl/src/cmd/attach.rs b/crates/fctl/src/cmd/attach.rs index 92797c352..b2a66a5ac 100644 --- a/crates/fctl/src/cmd/attach.rs +++ b/crates/fctl/src/cmd/attach.rs @@ -116,6 +116,9 @@ pub async fn follow_after( if let Some(l) = watch.disk(snap.runner_disk.as_ref()) { r.note(&l); } + if let Some(l) = watch.suspended(snap.sandbox_suspended.as_ref()) { + r.note(&l); + } } ViewerServer::Events { events } => { for ev in &events { @@ -125,13 +128,16 @@ pub async fn follow_after( } ViewerServer::Stream { event } => r.stream(&event), ViewerServer::Session { session } => watch.session(&session), - ViewerServer::RunnerConnected { connected, last_seen_at, agent_unreachable, disk, sandbox_paused } => { + ViewerServer::RunnerConnected { connected, last_seen_at, agent_unreachable, disk, sandbox_paused, sandbox_suspended } => { if let Some(l) = watch.runner(connected, last_seen_at, agent_unreachable.as_ref(), sandbox_paused.as_ref(), Instant::now(), style::now_ms()) { r.note(&l); } if let Some(l) = watch.disk(disk.as_ref()) { r.note(&l); } + if let Some(l) = watch.suspended(sandbox_suspended.as_ref()) { + r.note(&l); + } } ViewerServer::Result { ok: false, error: Some(e), .. } => eprintln!("{}", style::red(&e.message)), ViewerServer::Error { error } => eprintln!("{}", style::red(&error.message)), diff --git a/crates/fctl/src/cmd/host.rs b/crates/fctl/src/cmd/host.rs index f865ac4db..f0b86e1af 100644 --- a/crates/fctl/src/cmd/host.rs +++ b/crates/fctl/src/cmd/host.rs @@ -33,7 +33,9 @@ pub enum HostCmd { /// Runner name (default: the hostname). #[arg(long)] name: Option, - /// apple, docker, firecracker, lima, process, or auto. + /// apple, docker, firecracker, lambda (sessions in AWS Lambda + /// microVMs, from a machine that may manage them), lima, process, + /// or auto. #[arg(long, default_value = "auto")] driver: String, /// Maximum concurrent sessions. @@ -147,6 +149,38 @@ pub enum HostCmd { /// Pull the sandbox image, or build it with this runner's driver. #[command(subcommand)] Image(ImageCmd), + /// Write what AWS Lambda builds a microVM image of your own from, for a + /// runner of the lambda driver whose settings name it: a Dockerfile + /// from the sandbox image (or yours, with --from) and this fctl's + /// fctl-agent, in a ZIP archive, and print the commands that build it. + /// A runner can have fctl build and update one instead (its settings' + /// --artifacts and --build-role). + #[command( + name = "microvm-image", + after_help = "Examples: + fctl host microvm-image # ./fctl-microvm-image.zip, arm64 + fctl host microvm-image --arch x86_64 --memory 4g --out x86.zip + fctl host microvm-image --from ghcr.io/acme/agent:3 --user dev" + )] + MicrovmImage { + /// Where to write the archive. + #[arg(long, default_value = "fctl-microvm-image.zip")] + out: std::path::PathBuf, + /// The image's CPU architecture: arm64 or x86_64. + #[arg(long, default_value = "arm64")] + arch: String, + /// The container image to build it from: one made from the sandbox + /// image, or with what it has (default: the sandbox image of this + /// version). + #[arg(long)] + from: Option, + /// The user the image's sessions run as. + #[arg(long, default_value = "agent")] + user: String, + /// Its microVMs' baseline memory, for the commands: 512m, 1g, 2g, 4g or 8g. + #[arg(long, default_value = "2g", value_parser = memory_arg)] + memory: u32, + }, /// Keep your Claude token on this runner rather than in fctl. #[command(subcommand)] Claude(super::host_claude::HostClaudeCmd), @@ -355,25 +389,43 @@ pub async fn run(server: Option<&str>, cmd: HostCmd, json: bool) -> Result<()> { if build_image { fctl_host::image::build(&d, &cfg.image(), &cfg.download_base, None).await?; } - let info = d.probe().await; - if !info.available { - bail!( - "The {} driver is not ready: {}. Nothing was registered; run this again once it is.", - info.name, - info.detail.unwrap_or_default() - ); + match d.lambda() { + // Its microVMs' settings come once it is a runner: what + // matters now is that this machine may manage them. + Some(lambda) => { + let reach = lambda.check_access().await.map_err(|e| { + anyhow::anyhow!( + "The lambda driver can't manage microVMs from this machine: {e:#}. Nothing was registered; run this again once it can." + ) + })?; + println!("{} Driver: lambda ({reach})", style::accent("✓")); + println!( + "{} Sandboxes: a microVM each, of the size its settings say, which you set on the runner's page once it is online", + style::accent("✓"), + ); + } + None => { + let info = d.probe().await; + if !info.available { + bail!( + "The {} driver is not ready: {}. Nothing was registered; run this again once it is.", + info.name, + info.detail.unwrap_or_default() + ); + } + println!( + "{} Driver: {} ({})", + style::accent("✓"), + info.name, + info.detail.unwrap_or_default() + ); + println!( + "{} Sandboxes: {}", + style::accent("✓"), + size::limits(&cfg.sandbox_limits(d.resources().await)) + ); + } } - println!( - "{} Driver: {} ({})", - style::accent("✓"), - info.name, - info.detail.unwrap_or_default() - ); - println!( - "{} Sandboxes: {}", - style::accent("✓"), - size::limits(&cfg.sandbox_limits(d.resources().await)) - ); // The service would fail to install after the runner exists. if !no_service { service::preflight()?; @@ -648,6 +700,53 @@ pub async fn run(server: Option<&str>, cmd: HostCmd, json: bool) -> Result<()> { Ok(None) => bail!("{}", service::why_no_log()), Err(e) => Err(e), }, + HostCmd::MicrovmImage { + out, + arch, + from, + user, + memory, + } => { + let cfg = HostConfig::load().unwrap_or_default(); + let Some(arch) = fctl_proto::microvm::MicrovmArch::parse(&arch.to_lowercase()) else { + bail!("--arch: use arm64 or x86_64"); + }; + if fctl_proto::microvm::microvm_size(memory).is_none() { + bail!("--memory: use 512m, 1g, 2g, 4g or 8g"); + } + let agent = fctl_host::agentbin::linux_agent_for(&cfg, arch.rust()) + .await + .context("getting fctl-agent for the image")?; + let agent = std::fs::read(&agent)?; + let from = from.unwrap_or_else(|| cfg.image()); + let zip = fctl_host::driver::lambda::image::artifact(&from, &user, &agent)?; + std::fs::write(&out, &zip)?; + let hooks = serde_json::to_string(&fctl_host::driver::lambda::image::hooks())?; + let name = out.display().to_string(); + println!( + "{} Wrote {name}: a Dockerfile from {from}, and fctl-agent {} for {}.", + style::accent("✓"), + fctl_host::agentbin::VERSION, + arch.rust() + ); + println!(); + println!( + "Build the image in the runner's region with it, as a role that reads the bucket:" + ); + println!(); + println!(" aws s3 cp {name} s3://BUCKET/{name}"); + println!( + " aws lambda-microvms create-microvm-image --name fctl-sandbox \\\n --code-artifact uri=s3://BUCKET/{name} \\\n --base-image-arn arn:aws:lambda:REGION:aws:microvm-image:al2023-1 \\\n --build-role-arn BUILD_ROLE_ARN \\\n --cpu-configurations architecture={} \\\n --resources minimumMemoryInMiB={memory} \\\n --additional-os-capabilities ALL \\\n --hooks '{hooks}'", + arch.api() + ); + println!(); + println!("Then name it in the runner's settings:"); + println!(); + println!( + " fctl runners microvms set RUNNER --image arn:aws:lambda:REGION:ACCOUNT:microvm-image:fctl-sandbox" + ); + Ok(()) + } HostCmd::Image(ImageCmd::Pull) => { let cfg = HostConfig::load().unwrap_or_default(); let d = Driver::select(&cfg.driver, &cfg).await?; diff --git a/crates/fctl/src/cmd/microvms.rs b/crates/fctl/src/cmd/microvms.rs new file mode 100644 index 000000000..90d43031b --- /dev/null +++ b/crates/fctl/src/cmd/microvms.rs @@ -0,0 +1,523 @@ +//! `fctl runners microvms …`: a runner whose host runs sessions in AWS +//! Lambda microVMs (`fctl host install --driver lambda`): how its microVMs +//! are, and their settings, which its host gets at once. + +use crate::style; +use anyhow::{Result, bail}; +use clap::Subcommand; +use fctl_client::Api; +use fctl_proto::api::RunnerMicrovms; +use fctl_proto::microvm::{ + MicrovmArch, MicrovmImage, MicrovmImageStatus, MicrovmSettings, MicrovmState, microvm_size, +}; + +#[derive(Subcommand)] +pub enum MicrovmsCmd { + /// How a runner's microVMs are: its image, each microVM and the session + /// it runs, and their settings, for those who manage it (the default). + Show { + /// The runner's name or id. + runner: String, + }, + /// Change the settings of a runner's microVMs: what you name changes, + /// the rest stays. A runner with none yet needs its image: --image, or + /// --artifacts and --build-role for one fctl builds. + #[command(after_help = "Examples: + fctl runners microvms set microvms --artifacts s3://acme-fctl/microvms \\ + --build-role arn:aws:iam::123456789012:role/fctl-microvm-build + fctl runners microvms set microvms \\ + --image arn:aws:lambda:us-east-1:123456789012:microvm-image:agents + fctl runners microvms set microvms --memory 4g --warm 4 --max 50 + fctl runners microvms set microvms --suspend-after 2m --terminate-after 3h + fctl runners microvms set microvms \\ + --egress arn:aws:lambda:us-east-1:123456789012:network-connector:nc-0a1b2c + fctl runners microvms set microvms --first")] + Set { + /// The runner's name or id. + runner: String, + /// An image of your own, by its ARN (`fctl host microvm-image` + /// writes what to build it from). + #[arg(long, value_name = "ARN", conflicts_with_all = ["artifacts", "build_role", "image_name"])] + image: Option, + /// With --image, the version to run (default: its latest active one). + #[arg(long, value_name = "VERSION", requires = "image")] + image_version: Option, + /// For an image fctl builds: where its host puts what Lambda builds + /// it from (s3://bucket/prefix, in the image's region). + #[arg(long, value_name = "S3_URI")] + artifacts: Option, + /// For an image fctl builds: the role Lambda builds it as, which + /// reads --artifacts. + #[arg(long, value_name = "ARN")] + build_role: Option, + /// For an image fctl builds: its name in the account (default: + /// fctl-sandbox). + #[arg(long, value_name = "NAME")] + image_name: Option, + /// Each microVM's baseline memory, which it bursts to four times: + /// 512m, 1g, 2g, 4g or 8g, half a vCPU per GiB. + #[arg(long, value_name = "SIZE", value_parser = memory_arg)] + memory: Option, + /// The CPU architecture of an image fctl builds: arm64 or x86_64. + #[arg(long, value_parser = arch_arg)] + arch: Option, + /// The IAM role the microVMs run as, whose permissions their agents + /// have; none for none. + #[arg(long, value_name = "ARN|none")] + execution_role: Option, + /// The egress network connectors they reach out through, separated + /// by commas; none for Lambda's public internet. + #[arg(long, value_name = "ARNS|none", value_delimiter = ',')] + egress: Option>, + /// A KMS key that encrypts their configuration; none for an AWS + /// owned key. + #[arg(long, value_name = "ARN|none")] + kms_key: Option, + /// The CloudWatch Logs log group their output goes to; none for + /// Lambda's own. + #[arg(long, value_name = "NAME|none")] + log_group: Option, + /// Suspend a session's microVM once it has waited this long with + /// nothing running: 60s to 1h. + #[arg(long, value_name = "DURATION", value_parser = seconds_arg)] + suspend_after: Option, + /// Let a suspended microVM go after this long, its session stopping + /// until a message carries it on in a new one: 5m to 7h. + #[arg(long, value_name = "DURATION", value_parser = seconds_arg)] + terminate_after: Option, + /// How many microVMs to keep started and suspended for new + /// sessions: 0 to 20. + #[arg(long, value_name = "N")] + warm: Option, + /// The most microVMs at once, running and suspended, warm ones + /// included: what fits the account's quota. + #[arg(long, value_name = "N")] + max: Option, + /// Run sessions here before the workspace's other runners. + #[arg(long, conflicts_with = "no_first")] + first: bool, + /// Run sessions here as on any other runner. + #[arg(long)] + no_first: bool, + }, +} + +/// `512m`, `2g`, `2048`. +fn memory_arg(s: &str) -> std::result::Result { + let t = s.trim().to_lowercase(); + let mb = if let Some(g) = t + .strip_suffix("gib") + .or(t.strip_suffix("gb")) + .or(t.strip_suffix('g')) + { + g.trim().parse::().map(|g| g * 1024).ok() + } else if let Some(m) = t + .strip_suffix("mib") + .or(t.strip_suffix("mb")) + .or(t.strip_suffix('m')) + { + m.trim().parse::().ok() + } else { + t.parse::().ok() + }; + mb.filter(|mb| microvm_size(*mb).is_some()) + .ok_or_else(|| format!("{s:?}: use 512m, 1g, 2g, 4g or 8g")) +} + +fn arch_arg(s: &str) -> std::result::Result { + MicrovmArch::parse(&s.trim().to_lowercase()) + .ok_or_else(|| format!("{s:?}: use arm64 or x86_64")) +} + +/// `90s`, `2m`, `1h`, `1h30m`, in seconds. +fn seconds_arg(s: &str) -> std::result::Result { + let t = s.trim().to_lowercase(); + let mut total: u64 = 0; + let mut digits = String::new(); + for c in t.chars() { + match c { + '0'..='9' => digits.push(c), + 's' | 'm' | 'h' if !digits.is_empty() => { + let n: u64 = digits + .parse() + .map_err(|_| format!("{s:?}: not a duration"))?; + total += n * match c { + 's' => 1, + 'm' => 60, + _ => 3600, + }; + digits.clear(); + } + _ => return Err(format!("{s:?} needs units: 90s, 2m, 1h or 1h30m")), + } + } + if !digits.is_empty() || total == 0 { + return Err(format!("{s:?} needs units: 90s, 2m, 1h or 1h30m")); + } + u32::try_from(total).map_err(|_| format!("{s:?} is too long")) +} + +/// `none` (or empty) for nothing, else the value. +fn or_none(v: String) -> Option { + let t = v.trim(); + (!t.is_empty() && !t.eq_ignore_ascii_case("none")).then(|| t.to_owned()) +} + +pub async fn run(api: &Api, cmd: MicrovmsCmd, json: bool) -> Result<()> { + match cmd { + MicrovmsCmd::Show { runner } => { + let r = crate::cmd::admin::find_runner(api, &runner).await?; + let m = api.runner_microvms(r.id.as_str()).await?; + if json { + return style::print_json(&m); + } + print(&r.name, &m); + Ok(()) + } + MicrovmsCmd::Set { + runner, + image, + image_version, + artifacts, + build_role, + image_name, + memory, + arch, + execution_role, + egress, + kms_key, + log_group, + suspend_after, + terminate_after, + warm, + max, + first, + no_first, + } => { + let r = crate::cmd::admin::find_runner(api, &runner).await?; + let now = api.runner_microvms(r.id.as_str()).await?; + if !now.manage { + bail!( + "Only {}'s owner, the admins of the workspace it belongs to, and instance admins change its microVMs", + r.name + ); + } + // The image first: the rest starts from what it has, or the + // defaults. + let image = match ( + image, + artifacts, + build_role, + now.settings.as_ref().map(|s| &s.image), + ) { + (Some(arn), _, _, _) => Some(MicrovmImage::Own { + arn, + version: image_version, + }), + (None, artifacts, role, current) + if artifacts.is_some() || role.is_some() || image_name.is_some() => + { + let (a0, r0, n0) = match current { + Some(MicrovmImage::Managed { + artifacts, + build_role_arn, + name, + }) => ( + Some(artifacts.clone()), + Some(build_role_arn.clone()), + name.clone(), + ), + _ => (None, None, None), + }; + let (Some(artifacts), Some(build_role_arn)) = (artifacts.or(a0), role.or(r0)) + else { + bail!("An image fctl builds needs --artifacts and --build-role"); + }; + Some(MicrovmImage::Managed { + artifacts, + build_role_arn, + name: image_name.or(n0), + }) + } + _ => None, + }; + let mut s = match (now.settings.clone(), image) { + (Some(mut s), Some(image)) => { + s.image = image; + s + } + (Some(s), None) => s, + (None, Some(image)) => fctl_domain::microvm::defaults(image), + (None, None) => bail!( + "{} has no microVM settings yet: name its image, with --image for one of your own, or --artifacts and --build-role for one fctl builds", + r.name + ), + }; + if let Some(m) = memory { + s.memory_mb = m; + } + if let Some(a) = arch { + s.arch = Some(a); + } + if let Some(role) = execution_role { + s.execution_role_arn = or_none(role); + } + if let Some(egress) = egress { + s.egress_connectors = egress.into_iter().filter_map(or_none).collect(); + } + if let Some(k) = kms_key { + s.kms_key_arn = or_none(k); + } + if let Some(g) = log_group { + s.log_group = or_none(g); + } + if let Some(secs) = suspend_after { + s.suspend_after_secs = secs; + } + if let Some(secs) = terminate_after { + if secs % 60 != 0 { + bail!("--terminate-after takes whole minutes: 5m to 7h"); + } + s.terminate_after_minutes = secs / 60; + } + if let Some(w) = warm { + s.warm = w; + } + if let Some(m) = max { + s.max_microvms = m; + } + if first { + s.first = true; + } + if no_first { + s.first = false; + } + if let Err(e) = fctl_domain::microvm::check(&s) { + bail!("{}: {}", e.field.replace('_', "-"), e.message); + } + let m = api.put_runner_microvms(r.id.as_str(), &s).await?; + if json { + return style::print_json(&m); + } + println!( + "{} Saved {}'s microVM settings: its host runs new microVMs with them.", + style::accent("✓"), + style::bold(&r.name) + ); + println!(); + print(&r.name, &m); + Ok(()) + } + } +} + +fn mib(mb: u32) -> String { + match mb { + m if m % 1024 == 0 => format!("{} GiB", m / 1024), + m => format!("{m} MiB"), + } +} + +fn vcpus(milli: u32) -> String { + match milli { + m if m % 1000 == 0 => format!("{} vCPU{}", m / 1000, if m == 1000 { "" } else { "s" }), + m => format!("{} vCPU", f64::from(m) / 1000.0), + } +} + +fn print(name: &str, m: &RunnerMicrovms) { + let report = m.report.as_ref(); + let place = report + .and_then(|r| r.region.clone()) + .map(|r| format!(" in {r}")) + .unwrap_or_default(); + println!("{} · AWS Lambda microVMs{place}", style::bold(name)); + if let Some(p) = report.and_then(|r| r.problem.as_ref()) { + println!("{}", style::amber(&format!(" {}", p.message))); + } + if let Some(i) = report.and_then(|r| r.image.as_ref()) { + let size = i + .size + .map(|s| { + let peak = s.peak(); + format!( + ", {} · {} (bursts to {} · {} vCPUs)", + mib(s.memory_mb), + vcpus(s.vcpu_milli), + mib(peak.memory_mb), + peak.cpus + ) + }) + .unwrap_or_default(); + let state = match i.status { + MicrovmImageStatus::Ready => style::accent("ready"), + MicrovmImageStatus::Building => style::blue(&format!( + "building for fctl {}", + i.building.as_deref().unwrap_or("?") + )), + MicrovmImageStatus::Failed => style::red("its last build failed"), + MicrovmImageStatus::Missing => style::red("missing"), + }; + let version = i + .version + .as_deref() + .map(|v| format!(" {v}")) + .unwrap_or_default(); + let fctl = i + .fctl_version + .as_deref() + .map(|v| format!(" (fctl {v})")) + .unwrap_or_default(); + println!( + " Image {}{version}{fctl}{size}: {state}", + i.arn.rsplit(':').next().unwrap_or(&i.arn) + ); + if let Some(e) = &i.error { + println!("{}", style::dim(&format!(" {e}"))); + } + } + if let Some(r) = report { + println!( + " MicroVMs {} running · {} suspended · {} warm{}: {} of {}", + r.running, + r.suspended, + r.warm, + if r.changing > 0 { + format!(" · {} changing", r.changing) + } else { + String::new() + }, + r.running + r.suspended + r.warm + r.changing, + r.max + ); + } else { + println!( + "{}", + style::dim(" Its host hasn't said how its microVMs are yet.") + ); + } + if let Some(s) = &m.settings { + print_settings(s); + } else if m.manage { + println!( + "{}", + style::amber( + " No settings yet: `fctl runners microvms set` names its image, and its host starts." + ) + ); + } + let vms = report.map(|r| r.vms.as_slice()).unwrap_or_default(); + if vms.is_empty() { + return; + } + println!(); + println!(" {:<11} {:<44} {:<10} ID", "STATE", "SESSION", "SINCE"); + let now = style::now_ms(); + for v in vms { + let state = match (v.session.is_some(), v.state) { + (false, MicrovmState::Suspended) => "warm", + (_, MicrovmState::Running) => "running", + (_, MicrovmState::Suspended) => "suspended", + (_, MicrovmState::Starting) => "starting", + (_, MicrovmState::Suspending) => "suspending", + (_, MicrovmState::Resuming) => "resuming", + (_, MicrovmState::Terminating) => "going", + }; + let session = match &v.session { + Some(id) => match m.sessions.iter().find(|s| &s.id == id) { + Some(s) => format!("{}#{} {}", s.project_slug, s.number, s.title), + None => "a session".to_owned(), + }, + None => "—".to_owned(), + }; + let session: String = session.chars().take(44).collect(); + let since = style::ago_from(v.since, now); + let note = match v.terminates_at { + Some(t) => format!(" goes {}", style::until(t)), + None => String::new(), + }; + println!( + " {state:<11} {session:<44} {since:<10} {}{}", + v.id, + style::dim(¬e) + ); + } +} + +fn print_settings(s: &MicrovmSettings) { + let image = match &s.image { + MicrovmImage::Managed { + artifacts, + build_role_arn, + name, + } => format!( + "fctl builds {} from {artifacts}, as {build_role_arn}", + name.as_deref() + .unwrap_or(fctl_proto::microvm::DEFAULT_IMAGE_NAME) + ), + MicrovmImage::Own { arn, version } => format!( + "{arn}{}", + version + .as_deref() + .map(|v| format!(" version {v}")) + .unwrap_or_default() + ), + }; + let size = microvm_size(s.memory_mb) + .map(|z| format!("{} · {}", mib(z.memory_mb), vcpus(z.vcpu_milli))) + .unwrap_or_else(|| mib(s.memory_mb)); + let span = |secs: u64| fctl_domain::microvm::span(secs); + println!(" Settings {image}"); + println!( + " {size}, {}", + match s.arch.unwrap_or_default() { + MicrovmArch::Arm64 => "arm64", + MicrovmArch::X86_64 => "x86_64", + } + ); + println!( + " suspends after {} with nothing running, lets go after {} suspended", + span(u64::from(s.suspend_after_secs)), + span(u64::from(s.terminate_after_minutes) * 60) + ); + println!( + " keeps {} warm, {} at most{}", + s.warm, + s.max_microvms, + if s.first { + ", runs sessions here first" + } else { + "" + } + ); + println!( + " runs as {}, reaches out through {}", + s.execution_role_arn.as_deref().unwrap_or("no role"), + if s.egress_connectors.is_empty() { + "Lambda's public internet".to_owned() + } else { + s.egress_connectors.join(", ") + } + ); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sizes_and_durations_read_as_people_write_them() { + assert_eq!(memory_arg("2g"), Ok(2048)); + assert_eq!(memory_arg("512m"), Ok(512)); + assert_eq!(memory_arg("4GiB"), Ok(4096)); + assert!(memory_arg("3g").is_err()); + assert_eq!(seconds_arg("90s"), Ok(90)); + assert_eq!(seconds_arg("2m"), Ok(120)); + assert_eq!(seconds_arg("1h30m"), Ok(5400)); + assert!(seconds_arg("90").is_err()); + assert!(seconds_arg("m").is_err()); + assert_eq!(arch_arg("x86_64"), Ok(MicrovmArch::X86_64)); + assert_eq!(or_none("none".into()), None); + assert_eq!(or_none(" arn ".into()).as_deref(), Some("arn")); + } +} diff --git a/crates/fctl/src/cmd/mod.rs b/crates/fctl/src/cmd/mod.rs index 1d3929887..962ca9271 100644 --- a/crates/fctl/src/cmd/mod.rs +++ b/crates/fctl/src/cmd/mod.rs @@ -12,6 +12,7 @@ pub mod host; pub mod host_claude; pub mod id_token; pub mod memory; +pub mod microvms; pub mod notifications; pub mod passkeys; pub mod project_members; diff --git a/crates/fctl/src/cmd/runners.rs b/crates/fctl/src/cmd/runners.rs index 426d687ad..6b9f2c4a1 100644 --- a/crates/fctl/src/cmd/runners.rs +++ b/crates/fctl/src/cmd/runners.rs @@ -145,6 +145,19 @@ the name isn't ASCII, which CloudWatch takes only): once, or every #[arg(long, env = "FCTL_ENROLL_TOKEN", hide_env_values = true, hide = true)] enroll_token: Option, }, + /// A runner whose host runs sessions in AWS Lambda microVMs (`fctl host + /// install --driver lambda`): how its microVMs are, and their settings + /// (image, size, roles, network, when they suspend and go, the warm + /// pool), which its host gets at once. + #[command(after_help = "Examples: + fctl runners microvms show microvms + fctl runners microvms set microvms --artifacts s3://acme-fctl/microvms \\ + --build-role arn:aws:iam::123456789012:role/fctl-microvm-build + fctl runners microvms set microvms --memory 4g --warm 4 --suspend-after 2m")] + Microvms { + #[command(subcommand)] + cmd: crate::cmd::microvms::MicrovmsCmd, + }, /// A workspace's enrollment tokens: machines enroll themselves with one /// (`fctl host install --enroll`), without anyone signing in on them, /// as autoscaling creates them, and the runners each enrolls are a @@ -465,6 +478,7 @@ pub async fn run(server: Option<&str>, cmd: RunnersCmd, json: bool) -> Result<() ); Ok(()) } + RunnersCmd::Microvms { cmd } => crate::cmd::microvms::run(&api, cmd, json).await, RunnersCmd::Rename { runner, name } => { let r = find_runner(&api, &runner).await?; let r = update(&api, &r, |u| u.name = Some(name.clone())).await?; diff --git a/crates/fctl/src/stall.rs b/crates/fctl/src/stall.rs index b4cd6a6da..cbd279edd 100644 --- a/crates/fctl/src/stall.rs +++ b/crates/fctl/src/stall.rs @@ -37,6 +37,8 @@ pub struct Watch { said: Option, /// How short of disk the runner was, as last told. disk_said: Option, + /// Whether the session's microVM was suspended, as last told. + suspended_said: bool, } impl Watch { @@ -95,6 +97,30 @@ impl Watch { Some(line) } + /// Whether the runner suspended the session's sandbox, a microVM, from + /// the snapshot or `runner_connected`. Returns a line to print when + /// that changed. + pub fn suspended( + &mut self, + suspended: Option<&fctl_proto::microvm::SandboxSuspended>, + ) -> Option { + let now = suspended.is_some() && self.active; + if now == self.suspended_said { + return None; + } + self.suspended_said = now; + match suspended.filter(|_| now) { + Some(s) => Some(style::dim(&format!( + "☾ Its microVM is suspended, as it waits with nothing running: your next message resumes it, in a second or two{}", + s.until + .map(|u| format!(" (until {})", style::until(u))) + .unwrap_or_default() + ))), + None if self.active => Some(style::dim("● Its microVM resumed")), + None => None, + } + } + /// `runner now`, or `the runner`. fn who(&self) -> String { self.runner diff --git a/docs/adr/0106-runners-run-sessions-in-aws-lambda-microvms.md b/docs/adr/0106-runners-run-sessions-in-aws-lambda-microvms.md new file mode 100644 index 000000000..3906b9a15 --- /dev/null +++ b/docs/adr/0106-runners-run-sessions-in-aws-lambda-microvms.md @@ -0,0 +1,101 @@ +# 0106: Runners run sessions in AWS Lambda microVMs + +2026-12-01 · accepted + +## Context + +A runner is a machine: sessions take its CPUs and memory while they +wait as much as while they work, and a workspace that wants more of them +runs more machines, or a group of them that grows and shrinks +([Runners in your cloud](../runners-in-your-cloud.md)). Most of a +session's life is waiting, though: for its people to reply, for CI to +finish, for a review. + +AWS Lambda microVMs are Firecracker microVMs that Lambda runs in an AWS +account: started from an image in milliseconds, suspended with their +memory and disk kept (paying only for the snapshot's storage), resumed +in about a second, and ended 8 hours after they started at the latest. +Each one has an endpoint, which reaches a port of the microVM with a +token of the account's, WebSockets included. + +Carl Oscar asked for a workspace to run its sessions in microVMs in its +own AWS account, managed by an fctl host on a machine that may manage +them, with the image, execution role, egress connector, size and the +rest chosen per workspace; for a session's microVM to suspend 90 +seconds (by default) after its turn ended with no background task +running, never while it works; to be let go after 60 minutes suspended +(by default), long enough for CI to report; for anything that comes for +the agent to resume it, or, once it went, to carry the session on in a +new one from its snapshot; and for warm microVMs, started then +suspended, that any kind of session takes as it starts. Most workspaces +won't use them, so they come beside runners rather than instead of +them, unless a workspace makes them its sessions' first choice. + +## Decision + +- **A driver, `lambda`, on one host.** The host runs anywhere that may + manage the account's microVMs (an instance's or a task's role, keys, + or a role it assumes) and drives them through Lambda's API and each + microVM's endpoint. It is a runner like any other to the control + plane: one machine, one host, one runner, whose capacity is how many + microVMs it may have. The control plane never talks to AWS, and needs + no credentials of the workspace's. +- **Settings in the control plane.** People who manage the runner set + its microVMs' image, size, roles, network and whiles on its Runners + tab or with `fctl runners microvms set`; FleetDO hands them to the + host, which keeps them. Hosts of many machines would otherwise each + need the same `host.toml`, and changing a whole workspace's microVMs + would mean editing files on a machine. +- **fctl-agent is the microVM's program.** The image's command is + `fctl-agent microvm-serve`, which answers Lambda's lifecycle hooks + and serves the host the same exec protocol as the Firecracker driver's + vsock, over a WebSocket through the microVM's endpoint, only with a + key the host gave the microVM as it started. The host doesn't need to + reach a network of the microVM's, and the rest of the host (attaching, + delivering, snapshots, diffs) is unchanged. +- **fctl builds the image, or the workspace names one.** From the + host's sandbox image and fctl-agent, in a bucket of the workspace's, + with a build role of its own; again as fctl updates. A workspace with + an image of its own names it instead. +- **Suspended as idle, not stopped.** A session's status doesn't change + as its microVM suspends: it waits, as any idle session does, and a + message resumes it as it was, its processes and all. Before it + suspends, its agent saves the session's snapshot, so that a microVM + Lambda loses, or that goes, costs the session nothing but its + processes. People see that it is suspended, beside its status, and + what a message does. +- **Let go into a snapshot.** After its while suspended, or as Lambda's + 8 hours near, the host lets the microVM go and the session stops, + saying why; a message carries it on in a new microVM, from its + snapshot, as a session resumed on another runner does + ([ADR 0096](0096-sessions-keep-their-conversation-in-encrypted-snapshots.md)). +- **A warm pool on the same host.** Its warm microVMs are suspended + microVMs of no session, which the first session to start takes, + whatever its kind; the host starts others to keep their number. +- **First, if a workspace says so.** A runner whose settings say + `first` takes the sessions any of the workspace's runners could run + before the others, while it has room, so that a workspace makes + microVMs its preferred way without giving up its other runners. + +## Consequences + +- A workspace with microVMs pays for sessions while they work and for + their snapshots while they wait, rather than for machines. +- A suspended session isn't using its runner's capacity: the scheduler + doesn't count it, and a runner at its limit lets the longest-suspended + session's microVM go for a new session. +- What runs in a session's sandbox stops as its microVM suspends: + servers and watchers an agent started in the background count as + background tasks and keep it running, but processes started outside + Claude Code's tasks, which fctl doesn't see, are frozen until a + message resumes the microVM, and gone after the let-go. +- Agents in a microVM can use its execution role's permissions: the + settings' copy says so, and there is none by default. +- The microVMs' state lives with the host, in its data directory: a + host whose data directory is lost loses track of its microVMs. Lambda + ends a suspended one by itself 10 minutes after the host would have + let it go, and any other at its 8 hours; their sessions resume from + their snapshots. +- `cargo xtask dev --microvms` runs a stand-in for Lambda, so the whole + path, the warm pool, suspends, resumes and let-gos, runs locally + without AWS. diff --git a/docs/adr/README.md b/docs/adr/README.md index bb00ddbbf..8145bcf08 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -111,3 +111,4 @@ supersede an earlier one. Copy the newest record to start a new one. | [0103](0103-workspaces-require-their-members-to-sign-in-with-google.md) | Workspaces require their members to sign in with Google | | [0104](0104-workspaces-start-and-steer-agents-from-slack-through-fctls-app.md) | Workspaces start and steer agents from Slack through fctl's app | | [0105](0105-autopilots-manage-the-sessions-people-start-once-people-let-them.md) | Autopilots manage the sessions people start, once people let them (experimental) | +| [0106](0106-runners-run-sessions-in-aws-lambda-microvms.md) | Runners run sessions in AWS Lambda microVMs | diff --git a/docs/architecture.md b/docs/architecture.md index c691f9d97..2505d157e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -5495,6 +5495,7 @@ be reached. |---|---|---| | `apple` | one lightweight VM per session (Apple `container`) | Apple silicon, macOS 26+ | | `firecracker` | one microVM per session, with a kernel of its own ([Firecracker](#firecracker)) | Linux with KVM | +| `lambda` | one AWS Lambda microVM per session, in the workspace's AWS account ([AWS Lambda microVMs](#aws-lambda-microvms)) | any machine that may manage them | | `lima` | one full VM per session | macOS, Linux | | `docker` | containers in Docker/OrbStack/Colima (a VM on macOS) | macOS, Linux | | `process` | none: a directory and a process | development, trusted hosts | @@ -6066,6 +6067,146 @@ server listens in the VM's socket directory, whose path stays short, and the host links that socket, given to the jail's user, into the chroot, where Firecracker connects for the VM. +### AWS Lambda microVMs + +A runner can run each of its sessions in an +[AWS Lambda microVM](https://docs.aws.amazon.com/lambda/latest/dg/microvms.html) +of its own, in its workspace's AWS account: the `lambda` driver +([ADR 0106](adr/0106-runners-run-sessions-in-aws-lambda-microvms.md), +`crates/fctl-host/src/driver/lambda`). One host runs them all, on any +machine that may manage the account's microVMs: an EC2 instance or an +ECS task with a role, or a machine with AWS keys (`aws.rs`: the +environment's keys, then the instance's role through IMDSv2, or a role it +assumes, `[lambda] role_arn` with its `external_id`, renewed 5 minutes +before it ends). Nothing reaches the host from outside, and the microVMs +reach nothing of it: the host calls Lambda's API, and each microVM's +endpoint, with SigV4. A host's owner chooses the driver +(`fctl host install --driver lambda`; `auto` never does), and a session +starts there only once its runner has settings and its image is ready. + +- **Settings, from the control plane.** A runner's microVMs differ from + workspace to workspace, and its managers choose them + (`fctl_proto::microvm::MicrovmSettings`): the image, a size from + `MICROVM_SIZES` (512 MiB to 8 GiB of baseline memory, half a vCPU for + each GiB, bursting to four times both), the architecture, an execution + role, egress connectors, a KMS key, a log group, when a session's + microVM suspends (`suspend_after_secs`, 60 to 3,600, 90 by default) + and goes (`terminate_after_minutes`, 5 to 420, 60 by default), how + many wait warm (`warm`, 0 to 20, 2 by default), how many it may have + at once (`max_microvms`, 20 by default) and whether sessions start + there first (`first`). `PUT /api/v1/runners/{id}/microvms` keeps them + in D1 (`runners.microvm_settings`, migration 0079) for the runner's + owner or its workspace's admins, as they confirm it's them + (`Sensitive::AddRunner`), after `fctl_domain::microvm::check` (ARNs of + the right service, kind and partition, all in one region, the limits); + the audit log says who changed them (`runner.microvms_updated`). + FleetDO hands them to the host with its welcome and again as they + change (`FleetToHost::Microvms`), and the host keeps them, with its + microVMs, in `lambda/microvms.json` in its data directory. A host that + restarts carries on with what it kept until the control plane answers. +- **What the host says of them.** Its hello and heartbeats say + `FEATURE_MICROVMS` and a `MicrovmReport`: the region and account, the + image and how it is, how many microVMs run, are suspended with a + session, wait warm or change, each one with its session and when it + ends, and what stops it (`MicrovmProblem`: access, credentials, its + settings, quota, the image). The host looks for news every 2 seconds, + in memory, and sends a heartbeat when there is some. FleetDO keeps the + report (`runners.microvms`); `GET /api/v1/runners/{id}/microvms` shows + it with the sessions those who ask may see, and the settings to those + who manage the runner. The runner's capacity is `max_microvms`, and its + sandbox size the one its microVMs burst to. +- **The image.** fctl builds one and keeps it current (`image.rs`), or + the workspace names one of its own (`MicrovmImage::Own`, an ARN and + optionally a version, from the template `fctl host microvm-image` + writes). For one fctl builds, the host puts an archive in a bucket of + the workspace's (`artifacts`): a Dockerfile `FROM` the host's sandbox + image that adds the Linux fctl-agent of the host's version and the + microVMs' architecture, and runs `fctl-agent microvm-serve` as root. + Lambda builds it with the build role, on its `al2023-1` base, at the + settings' memory and architecture, with Lambda's lifecycle hooks; the + 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. +- **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' + connectors, the execution role (none by default: no AWS credentials in + the microVM) and an idle policy that never resumes by itself and lets + Lambda end one the host forgot 10 minutes after the host would have. + Its payload (`RunPayload`) names the runner and the sandbox and carries + a random key. In the microVM, `fctl-agent microvm-serve` + (`crates/fctl-agent/src/microvm`) answers Lambda's hooks on port 9000 + (`ready`, `validate`, `run`, which takes the payload, `suspend`, + `resume`, `terminate`) and serves the host on port 8080: a WebSocket + at `/fctl/v1/vm` that carries `fctl_proto::vm`'s frames, as the + Firecracker guest's vsock does, only with the payload's key + (`x-fctl-microvm-key`, compared in constant time). The host reaches it + through the microVM's endpoint with a token of 60 minutes + (`CreateMicrovmAuthToken`, renewed after 55), `X-aws-proxy-auth` and + `X-aws-proxy-port`. It runs fctl-agent as in any sandbox, putting in + its own version first when the image's differs; Lambda ends a microVM + 8 hours after it started. +- **Suspended while the session waits.** fctl-agent tells the host when + the session waits with nothing running (`AgentToHost::State` with + `quiet`): its turn ended, and no background task or Claude Code runs. + Once that has lasted `suspend_after_secs`, with nothing on its way to + the agent, the host asks it for a checkpoint + (`HostToAgent::Checkpoint`, `FEATURE_CHECKPOINTS`): fctl-agent saves + the session's snapshot as a stopping session does + ([Session snapshots](#session-snapshots)), the host uploads it, and + then suspends the microVM (`SuspendMicrovm`). An agent at work again + meanwhile refuses, and the wait starts over. The session stays idle: + SessionDO hears that its sandbox is suspended (`AgentLink.suspended`, + `HostSessionReport.suspended_since`), viewers see it + (`sandbox_suspended`: the session page says so beside the status, in + its details and in its message box), and the transcript says how long + it waited. Lambda keeps a suspended microVM's memory and disk, and + charges its snapshot's storage only. Anything for the agent (a + message, a follow-up, an interrupt, a change of model) resumes it + (`ResumeMicrovm`): the host attaches again and delivers it, and the + transcript says how long the resume took, a second or two. +- **Gone, and carried on.** After `terminate_after_minutes` suspended, + or within 10 minutes of the 8 hours Lambda gives one, the host lets + the microVM go (`TerminateMicrovm`) and the session stops, saying why + and what a message does (`fctl_domain::microvm::let_go_reason`). A + session whose checkpoint saved no snapshot, where it keeps them, is + resumed first and stops as an idle session does, which saves one. The + next message resumes the session in a new microVM, from its snapshot, + as on any other runner. A session at work as its microVM's 8 hours + near stops (`StopReason::Shutdown`), saving its snapshot, and a + message carries it on. Its agent's idle timeout is raised past the + let-go (`agent_idle_timeout_secs`), so that it never stops by itself + 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. +- **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 + 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 + the seconds a new microVM takes; one with no warm microVM to take runs + a new one. All of them, warm ones included, count against + `max_microvms`. +- **Room.** A suspended session doesn't count against its runner's + capacity in FleetDO's scheduling. A session that starts on a runner + with as many microVMs as it may have takes the place of the one + suspended the longest, whose snapshot was saved: that session stops, + and a message carries it on. Sessions start on runners whose settings + say `first` before others that could run them + (`fctl_domain::schedule::Slot::first`), so that a workspace can make + its microVMs the way its sessions run while its other runners take + what doesn't fit. + +`cargo xtask dev --microvms` runs a stand-in for Lambda +(`xtask/lambda`) and a runner of its microVMs, each one an `fctl-agent +microvm-serve` process that the stand-in stops and continues to suspend +and resume it ([Development](development.md#aws-lambda-microvms)). + ### Package caches A project can share its package managers' downloads between its sessions diff --git a/docs/cli.md b/docs/cli.md index 360442e48..b534f8022 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -1193,6 +1193,7 @@ service and is one runner. fctl host install # register this machine as a runner and start the host service fctl host install --driver lima --capacity 2 --build-image fctl host install --driver firecracker # Linux with KVM: each session in a microVM of its own +fctl host install --driver lambda --workspace acme # each session in an AWS Lambda microVM, in Acme's AWS account fctl host install --cpus 4 --memory 8g --max-cpus 8 --max-memory 12g # sandbox sizes fctl host install --name studio-mac --image ghcr.io/acme/agent:1 # its name (default: the hostname), and the image for projects that choose none fctl host install --allow-image 'ghcr.io/acme/*' --allow-build 'acme/*' # what projects may run and build @@ -1310,7 +1311,7 @@ into the host's settings in `~/.config/fctl/host.toml`: ```toml server = "https://app.fctl.sh" name = "studio-mac" -driver = "apple" # apple | lima | docker | firecracker | process | auto (picks at every start) +driver = "apple" # apple | lima | docker | firecracker | lambda | process | auto (picks at every start) capacity = 4 # concurrent sessions # image = "ghcr.io/acme/agent:1" # unset: the published image of the host's version cpus = 4 # per sandbox, when the project sets none @@ -1347,6 +1348,11 @@ pod_deletion_cost = true # keep the pod's deletion cost at its number of session disk_gb = 64 # each sandbox's own disk, which takes only what its session writes snapshots = true # a stopped sandbox keeps its VM's memory, and resumes as it was # jailer = true # on a host that runs as root: each VM as a user of its own, in a chroot and a cgroup + +[lambda] # with the lambda driver: AWS Lambda microVMs, whose settings come from the control plane +# region = "us-east-1" # unset: the settings' image's, AWS_REGION, the machine's own on EC2, else us-east-1 +# role_arn = "arn:aws:iam::123456789012:role/fctl-microvms" # a role it assumes (unset: the machine's role or AWS_* variables) +# external_id = "…" # what that role's trust policy asks for ``` With Docker on Linux, the daemon's socket lets in only root and the @@ -1452,6 +1458,25 @@ projects' images with BuildKit in a VM of each project's own; projects' own images run as with Docker. [Architecture](architecture.md#firecracker) has the details. +`--driver lambda` runs each session in an +[AWS Lambda microVM](https://docs.aws.amazon.com/lambda/latest/dg/microvms.html) +of its own, in your AWS account, from a host on any machine that may +manage its microVMs: an EC2 instance or ECS task with a role, or a +machine with AWS keys. The host runs no sandbox itself, and its microVMs' +settings come from the control plane: until the runner has them (`fctl +runners microvms set`, or its card on the Runners tab), it runs no +sessions. `fctl host install` checks that the machine may list the +account's microVMs. A session's microVM suspends while the session waits +with nothing running, resumes for the next message, and goes after a while +suspended, its session carrying on in a new one from its snapshot: +[Runners of microVMs](#runners-of-microvms) and +[Runners in your cloud](runners-in-your-cloud.md#aws-lambda-microvms). + +```sh +fctl host install --driver lambda --workspace acme +fctl host microvm-image --arch x86_64 --memory 4g # what Lambda builds an image of your own from, and the commands that build it +``` + Sessions start from their project's image or, without one, the host's: unless `image` sets another, the published image of the host's own version, `ghcr.io/hyperstructure/sandbox:`, which the host pulls when it @@ -1732,6 +1757,38 @@ ASCII, which CloudWatch takes only): once, or every minute with `--watch` (`--every`). Admins see every pool of the workspace, members their own; a service account reads them too. +### Runners of microVMs + +A runner whose host has the lambda driver runs sessions in AWS Lambda +microVMs ([Hosts](#hosts)), with settings its managers choose: the image, +each microVM's size, roles, network, when a session's microVM suspends and +when it goes, and how many wait warm. Its host gets them within seconds: +new microVMs start with them, and those that run keep theirs until they go. + +```sh +fctl runners microvms show microvms # its image, each microVM and its session, and its settings (--json) +fctl runners microvms set microvms --artifacts s3://acme-fctl/microvms \ + --build-role arn:aws:iam::123456789012:role/fctl-microvm-build # fctl builds the image, and keeps it current +fctl runners microvms set microvms \ + --image arn:aws:lambda:us-east-1:123456789012:microvm-image:agents # or one of yours +fctl runners microvms set microvms --memory 4g --arch x86_64 --warm 4 --max 50 +fctl runners microvms set microvms --suspend-after 2m --terminate-after 3h +fctl runners microvms set microvms --execution-role none --egress none --log-group /aws/lambda-microvms/fctl +fctl runners microvms set microvms --first # sessions start here before the workspace's other runners +``` + +`set` changes what it names and keeps the rest; a runner with no settings +yet needs its image. Without the others, a session's microVM is 2 GiB +(1 vCPU, bursting to 8 GiB and 4 vCPUs), suspends once the session has +waited 90 seconds with nothing running (no turn, no background task), +and goes after an hour suspended; 2 microVMs wait warm, of 20 at most, +warm and suspended ones included. A message to a session whose microVM +is suspended resumes it as it was, in a second or two; one after it went +carries the session on in a new microVM from its snapshot, where the +workspace keeps them. Only the runner's owner and its workspace's admins +see and change its settings, and they confirm it's them as they do; +everyone who sees the runner sees its microVMs. + ## Admin Instance admins manage people and invitations, the GitHub App's diff --git a/docs/development.md b/docs/development.md index 75c436b85..b1f58df7c 100644 --- a/docs/development.md +++ b/docs/development.md @@ -419,6 +419,40 @@ The project's Autopilot tab (`/p/playground?tab=autopilot`) shows the same, live. The local D1 keeps its wakes: `UPDATE autopilots SET wake_at = 0` in `crates/fctl-control` makes it due, as for schedules. +### AWS Lambda microVMs + +```sh +cargo xtask dev --microvms +``` + +This also starts a stand-in for AWS Lambda microVMs (`xtask/lambda`, at +http://127.0.0.1:8792, account `123456789012` in `us-east-1`) and a second +runner, `dev-microvms`, whose host has the lambda driver +([AWS Lambda microVMs](architecture.md#aws-lambda-microvms)). The stand-in +answers Lambda's API, with SigV4 checked for its form only, and each +microVM's endpoint, with its tokens; a microVM is an `fctl-agent +microvm-serve` process with a home of its own under the temporary +directory, its session's fake-claude in it. Suspending one stops every +process in it (`SIGSTOP`) and resuming continues them, so a session's +processes are kept as Lambda keeps them, and a microVM ends after +`--lifetime` (8 hours) as Lambda's do. `dev-microvms` goes first, so new +sessions start there while it has room, with settings that make the +whiles short: a microVM suspends after a minute with nothing running and +goes after 5 minutes suspended, and one waits warm. + +```sh +cargo run -p fctl -- run -p playground "write notes.md" # takes the warm microVM; a new one warms +cargo run -p fctl -- runners microvms show dev-microvms # each microVM and its session +cargo run -p fctl -- send "watch 30" # a minute after the turn: resumes it +cargo run -p fctl -- runners microvms set dev-microvms --warm 3 --suspend-after 90s +``` + +The Runners tab's microVMs section shows the same, and a session's page +says when its microVM is suspended. The stand-in logs what it does with +`[lambda]` in the stack's output and in `.fctl-dev/lambda/standin.log`; +`cd xtask/lambda && npm test` runs its tests. On macOS the stand-in can't +run: it reads `/proc` to find a microVM's processes. + ## The demo stack ```sh @@ -517,7 +551,7 @@ cargo xtask dev --smoke # and CI's other check: a session through the local s That is `cargo fmt --check`, a check that `web/src/gen` matches the Rust types, Biome and TypeScript for the web app, Biome for the standalone -server and the Linear and Slack stand-ins, Clippy (native and wasm) with +server and the Linear, Slack and Lambda stand-ins, Clippy (native and wasm) with warnings as errors, `cargo test`, the control plane's tests (in Node, as [Working on the control plane](#working-on-the-control-plane) says), the web app's Vitest suite, the standalone server's and the stand-ins' tests @@ -664,6 +698,7 @@ the lockfile, so their directories open none. | `xtask` | `cargo xtask`: dev, check, gen, serve, deploy, secrets, dist, publish | | `xtask/linear` | The Linear stand-in: Linear's sign-in, GraphQL API (on Linear's schema) and webhook deliveries | | `xtask/slack` | The Slack stand-in: Slack's Web API, its install and Sign in with Slack, and the events, interactions and commands it signs | +| `xtask/lambda` | The AWS Lambda microVMs stand-in: Lambda's microVM API and each microVM's endpoint, with `fctl-agent microvm-serve` as the microVM | | `web` | The web app (React, TanStack Router and Query, Tailwind, WebGL) | | `deploy/instances` | Instance descriptions for `cargo xtask deploy` | | `deploy/standalone` | The control plane without Cloudflare: its server, container image, Compose and Kubernetes examples | diff --git a/docs/llms.txt b/docs/llms.txt index 1e9b685e0..c14dacdec 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -26,7 +26,7 @@ web app · fctl CLI · HTTP API · Claude apps · Linear · Slack · GitHub webh │ control plane (an instance) users, workspaces, projects, sessions' event logs, │ (hosts dial out) scheduling, credentials, GitHub App, Linear and Slack apps - fctl host on a machine (runner) one sandbox per session: apple · lima · docker · firecracker · process + fctl host on a machine (runner) one sandbox per session: apple · lima · docker · firecracker · lambda · process │ fctl-agent + Claude Code in the sandbox: journals events, pushes, reports git state ``` @@ -218,6 +218,7 @@ Each recipe says who does what: some steps take a person with a role in the proj 14. **Keep agents informed**: `fctl memory add -p my-app "Deploys happen on Thursdays: merge migrations by Tuesday."`; delete every stale note at once with `fctl memory delete --stale -p my-app` (a project keeps 1,000 notes, stale ones included), or have fctl delete notes once they have been stale a number of days with `fctl projects set -p my-app --stale-note-days 7` (1 to 365; `never` by default); read what they learned with `fctl memory -p my-app` and `fctl retro list -p my-app --outcome blocked`. 15. **Hand a session to someone** (its owners): `fctl share grace@example.com` lets someone in its workspace view it and message its agent (`--role viewer` only views it, `--role owner` also stops, resumes, archives and shares it), `fctl share ` lists who it is shared with, `fctl unshare grace@example.com` takes it back. Anyone who can message the agent can have it hand over the sandbox's secrets and tokens. `fctl archive ` takes a finished session out of the lists and stops follow-ups reaching it (`fctl unarchive`, `fctl sessions --archived`). 16. **Slack**: a workspace admin connects a Slack workspace with `fctl workspaces slack connect` (a self-hosted instance's admins create its app first, from `fctl admin slack --manifest yaml`, with `SLACK_CLIENT_ID`, `SLACK_CLIENT_SECRET` and `SLACK_SIGNING_SECRET`, or `SLACK_APP_TOKEN` for Socket Mode); optionally maps channels to projects (`fctl workspaces slack map web-team web`) and makes public channels readable for agents (`fctl workspaces slack readable incidents deploys`; the shell takes a leading `#` for a comment); a project's maintainers choose whether its agents read those and a channel its events go to (`fctl projects slack -p web --events web-alerts`); each person links their Slack account once (`fctl account slack link`, or the link fctl sends them the first time they ask; on a self-hosted instance whose admins allow it, `fctl admin slack --match-email on`, a workspace can know people by their verified address instead); a link is held to the sign-in that made it, so where the instance's sign-in rules or a workspace's Google requirement cover someone, they link it while signed in that way (an address match meets no rule). Then a mention of fctl in a channel, a message to it in its messages, `/fctl ` or Send to fctl… on any message in a conversation fctl can see starts a session as that person, on their subscription, in the channel's project, their only one or the one they choose: what they wrote is the task, the thread's earlier messages come as information. Its card in the thread changes in place (status, plan, pull requests and checks), each turn's last message comes back as a reply (cut at 3,000 characters with a link), `fctl ask` questions get a button per answer, replies there reach the agent as their writers' messages where they may message the session, and Slack's stop button interrupts the turn. In the sandbox, `fctl slack thread` reads the thread and `fctl slack history|read|search` the readable channels, never the rest of private channels, other people's messages with fctl or Slack Connect channels; `fctl slack reply` posts in its own thread. Agents write what they post there as the workspace's admins ask (`fctl workspaces slack set --instructions-file slack.md`; `fctl workspaces slack instructions` prints it), else as fctl's guidance has it: short replies that lead with the answer. `fctl notifications set --slack on` sends someone's notifications in Slack too. Enterprise Grid org-wide installs, Slack Connect channels and guests aren't supported yet; on app.fctl.sh, Slack lets fctl read threads and channels once a minute, 15 messages at a time, until it lists the app in its Marketplace. +17. **Sessions in AWS Lambda microVMs** (a workspace whose sessions should run in its own AWS account): on a machine whose role may manage the account's microVMs (the policy is on the Runners tab, [Runners in your cloud](https://fctl.sh/docs/runners-in-your-cloud.md#aws-lambda-microvms)), `fctl host install --driver lambda --workspace acme --name microvms`; then its owner or a workspace admin sets its settings: `fctl runners microvms set microvms --artifacts s3://acme-fctl/microvms --build-role arn:aws:iam::123456789012:role/fctl-microvm-build` (fctl builds the image from the sandbox image and keeps it current; `--image ` for one of yours, from `fctl host microvm-image`), `--memory 512m|1g|2g|4g|8g` (half a vCPU per GiB, bursting to four times), `--arch arm64|x86_64`, `--execution-role |none` (whose permissions every agent there has; none by default), `--egress |none`, `--kms-key`, `--log-group`, `--suspend-after 90s` (60s to 1h: once a session has waited that long with nothing running, no turn and no background task, its snapshot is saved and its microVM suspended), `--terminate-after 1h` (5m to 7h suspended, then the microVM goes and the session stops; a message carries it on in a new one from its snapshot), `--warm 2` (started and suspended, taken by new sessions of any kind), `--max 20` (all of them, warm and suspended too), `--first` (sessions start there before the workspace's other runners). A message to a session whose microVM is suspended resumes it as it was in a second or two: the session stays `idle` meanwhile, and `fctl attach`, the session's page and the runner's card say so. `fctl runners microvms show microvms --json` lists each microVM, its state and session, and its image. ## Web app @@ -267,7 +268,7 @@ Each recipe says who does what: some steps take a person with a role in the proj - [Identity tokens](https://fctl.sh/docs/architecture.md#identity-tokens): issuers per workspace, the instance's signing keys and their rotation, how a mint reaches the control plane, the clouds fctl-agent sets up. - [Workspaces](https://fctl.sh/docs/architecture.md#workspaces), [GitHub accounts](https://fctl.sh/docs/architecture.md#github-accounts) and [runners and workspaces](https://fctl.sh/docs/architecture.md#runners-and-workspaces). - [Claude credentials](https://fctl.sh/docs/architecture.md#claude-credentials), [tokens on your runners](https://fctl.sh/docs/architecture.md#tokens-on-your-runners), [keeping the token out of sandboxes](https://fctl.sh/docs/architecture.md#keeping-the-token-out-of-sandboxes) and [plan usage](https://fctl.sh/docs/architecture.md#plan-usage). -- [Sandboxes and drivers](https://fctl.sh/docs/architecture.md#sandboxes-and-drivers), [package caches](https://fctl.sh/docs/architecture.md#package-caches), [draining a runner](https://fctl.sh/docs/architecture.md#draining-a-runner), [host updates](https://fctl.sh/docs/architecture.md#host-updates). +- [Sandboxes and drivers](https://fctl.sh/docs/architecture.md#sandboxes-and-drivers), [AWS Lambda microVMs](https://fctl.sh/docs/architecture.md#aws-lambda-microvms), [package caches](https://fctl.sh/docs/architecture.md#package-caches), [draining a runner](https://fctl.sh/docs/architecture.md#draining-a-runner), [host updates](https://fctl.sh/docs/architecture.md#host-updates). - [Event flow and reliability](https://fctl.sh/docs/architecture.md#event-flow-and-reliability) and [viewers](https://fctl.sh/docs/architecture.md#viewers): journaling, replay, the live socket. - [Model and effort](https://fctl.sh/docs/architecture.md#model-and-effort), [commits](https://fctl.sh/docs/architecture.md#commits), [pull request descriptions](https://fctl.sh/docs/architecture.md#pull-request-descriptions). - [Sandboxes' security](https://fctl.sh/docs/security.md#sandboxes): what an agent can reach, and why project secrets and Claude tokens are readable by what it runs. diff --git a/docs/runners-in-your-cloud.md b/docs/runners-in-your-cloud.md index 5f43fa5a1..8855297bc 100644 --- a/docs/runners-in-your-cloud.md +++ b/docs/runners-in-your-cloud.md @@ -997,6 +997,177 @@ clouds give machines with nested virtualization, such as EC2's C8i, M8i and R8i, Compute Engine's N2 and Azure's Dsv6. It hasn't been tried on the clouds' machines yet, so this guide uses Docker. +## AWS Lambda microVMs + +Rather than a group of machines, Acme's sessions can each run in an +[AWS Lambda microVM](https://docs.aws.amazon.com/lambda/latest/dg/microvms.html) +of their own, in its AWS account. One host runs them all, on a machine +that may manage the account's microVMs, and runs no sandbox itself: + +```text +a session starts ─────▶ takes a warm microVM, or runs a new one +its turn ends ────────▶ 90 s with nothing running: its snapshot is saved, + the microVM suspends (no compute while it waits) +a message comes ──────▶ the microVM resumes as it was, in a second or two +an hour suspended ────▶ the microVM goes; the session stops +a message comes ──────▶ a new microVM, from the session's snapshot +``` + +The diagram: each session takes a microVM as it starts. Once it has +waited 90 seconds with nothing running, fctl saves its snapshot and +suspends its microVM, which keeps its memory and disk; a message +resumes it in a second or two. After an hour suspended the microVM goes +and the session stops, and the next message carries it on in a new one +from its snapshot. Both whiles, the microVMs' size, their image and how +many wait warm are the runner's settings, which its workspace's admins +change on the Runners tab. + +You need an AWS account in a region with Lambda microVMs, quota for as +many as Acme runs at once, and a machine for the host: a small EC2 +instance or ECS task, with a role. It reaches Lambda's API and the +microVMs' endpoints, and nothing reaches it. + +1. **The host's role.** Give the machine's role this policy, with your + region, account and bucket. `Images`' last two actions, `Roles` and + `Artifacts` are for an image fctl builds and keeps current; `Roles` + also covers an execution role named `fctl-microvm-…`: + + ```json + { + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "MicroVMs", + "Effect": "Allow", + "Action": [ + "lambda:RunMicrovm", + "lambda:GetMicrovm", + "lambda:ListMicrovms", + "lambda:SuspendMicrovm", + "lambda:ResumeMicrovm", + "lambda:TerminateMicrovm", + "lambda:CreateMicrovmAuthToken" + ], + "Resource": "*" + }, + { + "Sid": "Images", + "Effect": "Allow", + "Action": [ + "lambda:GetMicrovmImage", + "lambda:GetMicrovmImageVersion", + "lambda:CreateMicrovmImage", + "lambda:UpdateMicrovmImage" + ], + "Resource": "arn:aws:lambda:us-east-1:123456789012:microvm-image:*" + }, + { + "Sid": "Connectors", + "Effect": "Allow", + "Action": "lambda:PassNetworkConnector", + "Resource": [ + "arn:aws:lambda:us-east-1:aws:network-connector:aws-network-connector:*", + "arn:aws:lambda:us-east-1:123456789012:network-connector:*" + ] + }, + { + "Sid": "Roles", + "Effect": "Allow", + "Action": "iam:PassRole", + "Resource": ["arn:aws:iam::123456789012:role/fctl-microvm-*"] + }, + { + "Sid": "Artifacts", + "Effect": "Allow", + "Action": "s3:PutObject", + "Resource": "arn:aws:s3:::acme-fctl/microvms/*" + } + ] + } + ``` + + The Runners tab shows the same policy while the workspace has no + runner of microVMs. On a machine of another account, put it on a role + in Acme's that the machine assumes: `role_arn` and `external_id` in + the `[lambda]` table of the host's `host.toml`. +2. **The build role**, for an image fctl builds: one Lambda assumes as + it builds it (`fctl-microvm-build`), which trusts + `lambda.amazonaws.com`, reads the bucket, and writes the build's logs: + + ```json + { + "Version": "2012-10-17", + "Statement": [ + { "Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::acme-fctl/microvms/*" }, + { + "Effect": "Allow", + "Action": ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"], + "Resource": "arn:aws:logs:*:*:*" + } + ] + } + ``` + + Its image is the sandbox image with fctl-agent, which answers Lambda + and runs the sessions. An image of your own, built from an image of + yours made from the sandbox image, needs no bucket nor build role + here: `fctl host microvm-image --from ghcr.io/acme/agent:3` writes + what Lambda builds it from, and prints the commands that build it. +3. **The host.** On the machine, signed in as an admin of `acme`: + + ```sh + curl -fsSL https://fctl.sh/install | sh + fctl login https://fctl.acme.dev + fctl host install --driver lambda --workspace acme --name microvms + ``` + + From a boot script, give it an enrollment token instead + (`FCTL_ENROLL_TOKEN`, [step 1](#1-make-an-enrollment-token)). + `fctl host install` checks that the machine may list the account's + microVMs, and the runner shows on the Runners tab, with no settings + yet. +4. **Its settings.** On the runner's card on the Runners tab, **Set up**, + or with the CLI: + + ```sh + fctl runners microvms set microvms --artifacts s3://acme-fctl/microvms \ + --build-role arn:aws:iam::123456789012:role/fctl-microvm-build + fctl runners microvms show microvms + ``` + + The host puts what Lambda builds the image from in the bucket, and + Lambda builds it in a few minutes; the card says how it goes. Then + the warm microVMs start, and sessions with them. The host builds the + image again as fctl updates, and sessions run on the version before + meanwhile. + +The defaults are a microVM of 2 GiB and 1 vCPU, which bursts to 8 GiB +and 4 vCPUs as the session needs, suspended after 90 seconds with +nothing running, gone after an hour suspended, and 2 waiting warm of 20 +at most (`--memory`, `--suspend-after`, `--terminate-after`, `--warm`, +`--max`: [the CLI](cli.md#runners-of-microvms)). Two settings deserve a +choice: + +- **What its agents reach.** Without egress connectors, microVMs reach + the internet through Lambda's. To reach a VPC of Acme's, its + databases or a proxy, make a + [network connector](https://docs.aws.amazon.com/lambda/latest/dg/microvms-networking.html) + of it (`aws lambda-core create-network-connector`) and give its ARN + (`--egress`). An execution role (`--execution-role`) gives every + agent in the microVMs its permissions: none, the default, puts no AWS + credentials in them. +- **Whether sessions go there first.** `--first` makes the workspace's + sessions start in microVMs while the runner has room, before its other + runners, which take what doesn't fit; without it, the runner is one + more among them. + +Sessions of every kind run there, review agents' and schedules' too, +and take warm microVMs as they start. A review agent's microVM never +suspends: its session stops once its review is posted. `cargo xtask dev +--microvms` runs all of it locally, against a stand-in for Lambda +([Development](development.md#aws-lambda-microvms)), and +[Architecture](architecture.md#aws-lambda-microvms) has the details. + ## What goes wrong | What you see | Why | What to do | @@ -1005,6 +1176,8 @@ the clouds' machines yet, so this guide uses Docker. | This enrollment token for Acme expired on 2027-11-23 | Tokens expire | Make another, put it in the secret store | | The host service is a systemd user unit, and fctl's systemd manager doesn't answer | The image has no lingering for `fctl` | `loginctl enable-linger fctl` in `provision.sh` | | `AccessDeniedException`, `PERMISSION_DENIED` or `403` reading the secret | The machine's role doesn't reach the secret, or not yet | Check the role's scope; the boot script tries for a few minutes | +| AWS refused …: the host's role lacks a permission, on the runner's card | The host's role lacks an action of [its policy](#aws-lambda-microvms), which the runner's sheet shows for its settings | Add it; the host tries again within a minute | +| Lambda couldn't build the image for fctl 0.40.0 | The build role can't read the bucket, or the sandbox image couldn't be pulled; the build's CloudWatch logs say which | Fix the role; the host tries again after 30 minutes | - **The machine runs, but no runner shows.** Its boot log (`/var/log/cloud-init-output.log`, or `journalctl -u diff --git a/package-lock.json b/package-lock.json index a02c07aaf..50e30313e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,6 +8,7 @@ "workspaces": [ "web", "deploy/standalone", + "xtask/lambda", "xtask/linear", "xtask/slack" ], @@ -735,6 +736,10 @@ "node": ">=18" } }, + "node_modules/@fctl/lambda-standin": { + "resolved": "xtask/lambda", + "link": true + }, "node_modules/@fctl/linear-standin": { "resolved": "xtask/linear", "link": true @@ -4750,6 +4755,15 @@ "vitest": "5.0.5" } }, + "xtask/lambda": { + "name": "@fctl/lambda-standin", + "devDependencies": { + "@biomejs/biome": "2.5.15" + }, + "engines": { + "node": ">=22" + } + }, "xtask/linear": { "name": "@fctl/linear-standin", "dependencies": { diff --git a/package.json b/package.json index 5dfe0eaf3..d6a6d2e65 100644 --- a/package.json +++ b/package.json @@ -1,10 +1,11 @@ { "name": "fctl-monorepo", "private": true, - "description": "JavaScript tooling for fctl: the web app, wrangler, the standalone control plane and the Linear and Slack stand-ins", + "description": "JavaScript tooling for fctl: the web app, wrangler, the standalone control plane and the Lambda, Linear and Slack stand-ins", "workspaces": [ "web", "deploy/standalone", + "xtask/lambda", "xtask/linear", "xtask/slack" ], diff --git a/web/src/components/session/composer.tsx b/web/src/components/session/composer.tsx index a14caeae8..d5b3337ef 100644 --- a/web/src/components/session/composer.tsx +++ b/web/src/components/session/composer.tsx @@ -35,6 +35,7 @@ export function Composer({ onTakeOver, limitOf, movedOn, + suspended, }: { status?: G.SessionStatus; role?: G.SessionRole; @@ -56,6 +57,8 @@ export function Composer({ limitOf?: string; /** An earlier session of an autopilot's own: where it works now, which a message goes to instead. */ movedOn?: MovedOn; + /** Its microVM is suspended: a message resumes it first. */ + suspended?: boolean; }) { const [text, setText] = useState(""); const [sending, setSending] = useState<"here" | "there">(); @@ -221,7 +224,9 @@ export function Composer({ ? "Message the agent to resume the session…" : running ? "Message the agent (it reads it after this step)…" - : "Message the agent…" + : suspended + ? "Message the agent (its microVM resumes for it)…" + : "Message the agent…" } className="block px-4 pt-3.5 text-[14.5px] leading-[1.55] text-ink" aria-label="Message the agent" diff --git a/web/src/components/ui/sheet.tsx b/web/src/components/ui/sheet.tsx index 2b7fe6866..37169c48b 100644 --- a/web/src/components/ui/sheet.tsx +++ b/web/src/components/ui/sheet.tsx @@ -73,11 +73,14 @@ export function Sheet({ title, description, onClose, + wide, children, }: { title: ReactNode; description?: ReactNode; onClose: () => void; + /** 520 px rather than 340 from 768 px, for a form in two columns. */ + wide?: boolean; children: ReactNode; }) { const ref = useRef(null); @@ -204,7 +207,8 @@ export function Sheet({ // Phones: along the bottom, as tall as what it holds, up to most of the screen. "inset-x-0 top-auto -bottom-(--viewport-shift) max-h-[min(88dvh,calc(100dvh-2.5rem))] w-full max-w-none rounded-t-[18px] border-t shadow-[0_-16px_60px_rgb(0_0_0/0.35)] " + // From 768 px: along the right, the screen's height. - "md:top-(--viewport-shift) md:right-0 md:left-auto md:h-dvh md:max-h-none md:w-[340px] md:rounded-none md:border-t-0 md:border-l md:pt-(--safe-top) md:shadow-[-16px_0_60px_rgb(0_0_0/0.3)]" + "md:top-(--viewport-shift) md:right-0 md:left-auto md:h-dvh md:max-h-none md:rounded-none md:border-t-0 md:border-l md:pt-(--safe-top) md:shadow-[-16px_0_60px_rgb(0_0_0/0.3)] " + + (wide ? "md:w-[520px]" : "md:w-[340px]") } >
diff --git a/web/src/components/workspace/microvms.test.tsx b/web/src/components/workspace/microvms.test.tsx new file mode 100644 index 000000000..0b7e9c329 --- /dev/null +++ b/web/src/components/workspace/microvms.test.tsx @@ -0,0 +1,415 @@ +import { QueryClientProvider } from "@tanstack/react-query"; +import type { ReactNode } from "react"; +import { act } from "react"; +import { createRoot } from "react-dom/client"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import type * as G from "@/gen"; +import { keys, queryClient } from "@/lib/queries"; +import { MicrovmsSection } from "./microvms"; + +// No request is answered but saving settings, which is noted: the section shows what the cache holds. +const saves = vi.hoisted(() => [] as { id: string; settings: G.MicrovmSettings }[]); +vi.mock("@/lib/api", () => { + const pending = () => new Promise(() => {}); + return { + api: new Proxy( + {}, + { + get: (_, k) => + k === "putRunnerMicrovms" + ? (id: string, settings: G.MicrovmSettings) => { + saves.push({ id, settings }); + // As the server answers: empty lists and what is off left out. + const kept = JSON.parse( + JSON.stringify(settings, (_, v) => + (Array.isArray(v) && !v.length) || v === false ? undefined : v, + ), + ); + return Promise.resolve({ runner: id, settings: kept, manage: true, sessions: [] }); + } + : pending, + }, + ), + workspaces: new Proxy({}, { get: () => pending }), + ApiFailure: class extends Error {}, + }; +}); + +vi.mock("@tanstack/react-router", () => ({ + Link: ({ children }: { children: ReactNode }) => {children}, +})); + +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +const roots: (() => void)[] = []; +afterEach(() => { + for (const unmount of roots.splice(0)) unmount(); + document.body.innerHTML = ""; + queryClient.clear(); + saves.splice(0); +}); + +const acme = { + id: "wsp_acme", + slug: "acme", + name: "Acme", + role: "admin", + primary: { id: "usr_ada", name: "Ada" }, +} as G.Workspace; +const now = Date.now(); +const IMAGE = "arn:aws:lambda:us-east-1:123456789012:microvm-image:fctl-sandbox"; + +const report = (r: Partial = {}): G.MicrovmReport => ({ + region: "us-east-1", + account: "123456789012", + configured: true, + image: { + arn: IMAGE, + status: "ready", + version: "3.0", + fctl_version: "0.40.0", + size: { memory_mb: 2048, vcpu_milli: 1000, disk_gb: 32 }, + arch: "arm64", + }, + running: 3, + suspended: 1, + warm: 2, + changing: 0, + max: 20, + ...r, +}); + +const runner = (r: Partial = {}): G.Runner => + ({ + id: "run_lambda", + name: "microvms", + status: "online", + driver: "lambda", + drivers: [], + labels: [], + workspace: { id: acme.id, slug: acme.slug, name: acme.name }, + microvms: report(), + microvms_configured: true, + ...r, + }) as G.Runner; + +const settings = (s: Partial = {}): G.MicrovmSettings => ({ + image: { kind: "own", arn: IMAGE }, + memory_mb: 2048, + egress_connectors: [], + suspend_after_secs: 90, + terminate_after_minutes: 60, + warm: 2, + max_microvms: 20, + first: false, + ...s, +}); + +const vm = (id: string, state: G.MicrovmState, session?: string): G.MicrovmVm => ({ + id, + state, + session, + since: now - 5 * 60_000, + started_at: now - 60 * 60_000, + ends_at: now + 7 * 3_600_000, + terminates_at: state === "suspended" && session ? now + 55 * 60_000 : undefined, +}); + +function show(node: ReactNode, microvms?: G.RunnerMicrovms) { + if (microvms) queryClient.setQueryData(keys.runnerMicrovms(microvms.runner), microvms); + const container = document.createElement("div"); + document.body.append(container); + const root = createRoot(container); + act(() => root.render({node})); + roots.push(() => act(() => root.unmount())); + return container; +} + +const button = (label: string) => { + const b = [...document.querySelectorAll("button")].find((x) => x.textContent?.trim() === label); + if (!b) throw new Error(`no button ${label}`); + return b; +}; + +/** Types into a controlled input, as a person does. */ +function type(input: HTMLInputElement | null | undefined, value: string) { + if (!input) throw new Error("no input"); + const set = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set; + act(() => { + set?.call(input, value); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); +} + +const input = (label: string) => { + const l = [...document.querySelectorAll("label")].find((x) => x.textContent?.startsWith(label)); + const id = l?.getAttribute("for"); + return id ? document.querySelector(`[id="${id}"]`) : null; +}; + +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 ?? ""; + 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", + ); + expect(text).toContain("After 1 hour suspended it goes"); + expect(text).toContain("fctl host install --driver lambda --workspace acme"); + expect(text).toContain("lambda:SuspendMicrovm"); + // The drawing of a session's microVM over its life. + expect(text).toContain("90 seconds with nothing running"); + expect(text).toContain("1 hour suspended"); + }); + + it("say a session starts again from its task and branch where the workspace keeps no snapshots", () => { + 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.", + ); + expect(text).toContain("a message starts the session again in a new one"); + }); + + it("show each runner of them, with what its microVMs do and the room left", () => { + 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. + const facts = (n: number) => + [...(card?.querySelectorAll(".flex-wrap.gap-y-1")[n]?.children ?? [])].map((f) => f.textContent); + expect(facts(0)).toEqual(["3 running", "1 suspended", "2 warm", "14 free of 20"]); + expect(facts(1)).toEqual(["AWS Lambda in us-east-1", "fctl-sandbox", "2 GiB, 1 vCPU"]); + // A pip for each microVM it may have. + const pips = view.querySelector('[role="img"]'); + expect(pips?.getAttribute("aria-label")).toBe("3 running · 1 suspended · 2 warm, 14 free of 20"); + expect(pips?.children).toHaveLength(20); + // Nothing to set up: no steps. + expect(view.textContent).not.toContain("To run sessions in microVMs"); + }); + + it("say, in the section, when its sessions' microVMs suspend and go", () => { + const r = runner(); + const text = show(, { + runner: r.id, + settings: settings({ suspend_after_secs: 120, terminate_after_minutes: 30 }), + manage: true, + sessions: [], + }).textContent; + expect(text).toContain("once it has waited 2 minutes with nothing running"); + expect(text).toContain("After 30 minutes suspended it goes"); + }); + + it("ask those who manage a runner without settings to set it up, in amber", () => { + const view = show( + , + ); + expect(view.querySelector(".text-amber")?.textContent).toBe( + "Its microVMs have no settings yet: until they do, it runs no sessions.", + ); + expect(button("Set up")).toBeTruthy(); + // Members open it, to see. + const member = show( + , + ); + expect([...member.querySelectorAll("button")].map((b) => b.textContent)).toContain("Open"); + }); + + it("say what stops its sessions, as its host says it", () => { + const text = show( + , + ).textContent; + expect(text).toContain("Its host may not run microVMs: lambda:RunMicrovm is denied."); + }); +}); + +describe("a runner's microVMs sheet", () => { + const sessions: G.MicrovmSessionRef[] = [ + { + id: "ses_1", + number: 4, + title: "Retry failed uploads", + project_slug: "playground", + project_name: "Playground", + status: "idle", + }, + { + id: "ses_2", + number: 7, + title: "Fix the login redirect", + project_slug: "web", + project_name: "Web", + status: "running", + }, + ]; + const microvms = (m: Partial = {}): G.RunnerMicrovms => ({ + runner: "run_lambda", + settings: settings(), + updated_at: now - 3_600_000, + updated_by: { id: "usr_ada", name: "Ada" }, + report: report({ + vms: [ + vm("mvm-warm-0000001", "suspended"), + vm("mvm-suspended-01", "suspended", "ses_1"), + vm("mvm-running-0001", "running", "ses_2"), + ], + }), + sessions, + manage: true, + ...m, + }); + + const open = (m: G.RunnerMicrovms, admin = true) => { + 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")); + }; + + it("lists its microVMs, sessions at work first and warm ones last", () => { + const sheet = open(microvms()); + expect(sheet?.textContent).toContain("microvms's microVMs"); + expect(sheet?.textContent).toContain("AWS Lambda in us-east-1 · account 123456789012"); + const rows = [...(sheet?.querySelectorAll("ul > li") ?? [])].map((li) => li.textContent); + expect(rows).toHaveLength(3); + expect(rows[0]).toContain("web#7 Fix the login redirect"); + expect(rows[0]).toContain("Running for 5m"); + expect(rows[1]).toContain("playground#4 Retry failed uploads"); + expect(rows[1]).toContain("Suspended for 5m · goes in 55 min"); + expect(rows[2]).toContain("Waiting for a session"); + expect(rows[2]).toContain("Warm for 5m"); + }); + + it("saves the settings its host runs new microVMs with, once they are right", async () => { + const sheet = open(microvms()); + expect(sheet?.textContent).toContain("Saved 1 hour ago by Ada."); + // Nothing changed: nothing to save. + expect(button("Save").disabled).toBe(true); + type(input("Warm"), "30"); + expect(button("Save").disabled).toBe(false); + await act(async () => button("Save").click()); + // Past what the limits allow, it says so under the field, and saves nothing. + expect(saves).toEqual([]); + expect(sheet?.textContent).toContain("Keep 0 to 20 warm"); + type(input("Warm"), "4"); + expect(sheet?.textContent).toContain("4 microVMs wait warm for new sessions, of 20 at most."); + await act(async () => button("Save").click()); + expect(saves).toEqual([{ id: "run_lambda", settings: settings({ warm: 4 }) }]); + }); + + 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."); + // With no settings yet, fctl's image comes first. + const radios = [...(sheet?.querySelectorAll('input[type="radio"]') ?? [])]; + expect(radios.map((r) => r.checked)).toEqual([true, false]); + await act(async () => button("Save").click()); + expect(saves).toEqual([]); + expect(sheet?.textContent).toContain("Where its host puts what Lambda builds it from"); + type(input("Where its host puts"), "s3://acme-fctl/microvms"); + type(input("The role Lambda builds it as"), "arn:aws:iam::123456789012:role/fctl-microvm-build"); + await act(async () => button("Save").click()); + expect(saves[0]?.settings.image).toEqual({ + kind: "managed", + artifacts: "s3://acme-fctl/microvms", + build_role_arn: "arn:aws:iam::123456789012:role/fctl-microvm-build", + }); + }); + + it("shows the policy its host needs, for its account, bucket and roles, at once when AWS refuses it", () => { + const managed = settings({ + image: { + kind: "managed", + artifacts: "s3://acme-fctl/microvms", + build_role_arn: "arn:aws:iam::123456789012:role/fctl-microvm-build", + }, + }); + // The policy's box: the one code that is JSON. + const box = (d?: HTMLElement) => + [...(d?.querySelectorAll("code") ?? [])].find((c) => c.textContent?.trim().startsWith("{")); + let sheet = open(microvms({ settings: managed })); + expect(sheet?.textContent).toContain("Its host's AWS policy"); + expect(box(sheet)).toBeUndefined(); + act(() => button("Show it").click()); + const policy = JSON.parse(box(sheet)?.textContent ?? "{}"); + const of = (sid: string) => policy.Statement.find((x: { Sid: string }) => x.Sid === sid)?.Resource; + expect(of("Images")).toBe("arn:aws:lambda:us-east-1:123456789012:microvm-image:*"); + expect(of("Roles")).toEqual(["arn:aws:iam::123456789012:role/fctl-microvm-build"]); + expect(of("Artifacts")).toBe("arn:aws:s3:::acme-fctl/microvms/*"); + for (const unmount of roots.splice(0)) unmount(); + document.body.innerHTML = ""; + + const problem = { kind: "access", message: "AWS refused running a microVM", since: now }; + sheet = open(microvms({ settings: managed, report: report({ problem }) })); + expect(box(sheet)).toBeDefined(); + expect(sheet?.querySelector(".text-amber")?.textContent).toContain("AWS refuses its host something"); + }); + + it("takes egress connectors a line each, as typed", async () => { + const sheet = open(microvms()); + act(() => button("Network, role, encryption and logs").click()); + const area = sheet?.querySelector("textarea"); + if (!area) throw new Error("no textarea"); + const typeArea = (value: string) => { + const set = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")?.set; + act(() => { + set?.call(area, value); + area.dispatchEvent(new Event("input", { bubbles: true })); + }); + }; + const first = "arn:aws:lambda:us-east-1:123456789012:network-connector:nc-1"; + const second = "arn:aws:lambda:us-east-1:123456789012:network-connector:nc-2"; + // The line break after the first stays, for the second to follow it. + typeArea(`${first}\n`); + expect(area.value).toBe(`${first}\n`); + typeArea(`${first}\n${second}`); + await act(async () => button("Save").click()); + expect(saves.at(-1)?.settings.egress_connectors).toEqual([first, second]); + }); + + it("has nothing left to save once saved, its connectors cleared", async () => { + const first = "arn:aws:lambda:us-east-1:123456789012:network-connector:nc-1"; + const sheet = open(microvms({ settings: settings({ egress_connectors: [first] }) })); + const area = sheet?.querySelector("textarea"); + if (!area) throw new Error("no textarea"); + const set = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")?.set; + act(() => { + set?.call(area, ""); + area.dispatchEvent(new Event("input", { bubbles: true })); + }); + expect(button("Save").disabled).toBe(false); + await act(async () => button("Save").click()); + expect(saves.at(-1)?.settings.egress_connectors).toBeUndefined(); + await act(() => new Promise((r) => setTimeout(r, 10))); + expect(button("Save").disabled).toBe(true); + }); + + it("shows members the settings in words, with no form", () => { + const sheet = open(microvms({ manage: false }), false); + expect(sheet?.querySelector("form")).toBeNull(); + expect(sheet?.textContent).toContain( + "It suspends once the session has waited 90 seconds with nothing running, and goes 1 hour later", + ); + }); +}); diff --git a/web/src/components/workspace/microvms.tsx b/web/src/components/workspace/microvms.tsx new file mode 100644 index 000000000..d2391dc1b --- /dev/null +++ b/web/src/components/workspace/microvms.tsx @@ -0,0 +1,1119 @@ +// A workspace's runners of AWS Lambda microVMs (docs/architecture.md#aws-lambda-microvms): on its +// Runners tab, what they do and how to set one up; each one's card, with how its microVMs are; and +// the sheet with every one of its microVMs and the settings its host runs them with. + +import { useMutation, useQuery } from "@tanstack/react-query"; +import { Link } from "@tanstack/react-router"; +import { ArrowDown, Box, CircleDashed, CloudCog, Moon, Play, Sparkles } from "lucide-react"; +import { type ReactNode, useEffect, useId, useMemo, useState } from "react"; +import { Step } from "@/components/claude/guide"; +import { + Banner, + Button, + CodeBox, + Field, + Input, + Meta, + Select, + Sheet, + Spinner, + Switch, + Textarea, + toast, +} from "@/components/ui"; +import { ManageRunner } from "@/components/workspace/runners"; +import type * as G from "@/gen"; +import { MICROVM_DEFAULTS, MICROVM_LIMITS, MICROVM_SIZES } from "@/gen/defaults"; +import { ApiFailure, api } from "@/lib/api"; +import { cn } from "@/lib/cn"; +import { ago, stamp } from "@/lib/format"; +import { siteUrl } from "@/lib/install"; +import { + countParts, + counts, + countWords, + defaultSettings, + hostPolicy, + imageName, + imageWords, + isMicrovmRunner, + lifeUsed, + peakWords, + SUSPEND_PRESETS, + settingsKey, + settingsProblem, + settingsWords, + sizeOf, + sizeWords, + span, + TERMINATE_PRESETS, + vmWords, + withValue, +} from "@/lib/microvms"; +import { keys, queryClient } from "@/lib/queries"; + +const GUIDE = () => `${siteUrl()}/docs/runners-in-your-cloud/#aws-lambda-microvms`; + +/** + * The Runners tab's section on microVMs: what they do for sessions, then the workspace's runners of + * them as cards, or, while it has none, how to set one up. + */ +export function MicrovmsSection({ + w, + admin, + runners, +}: { + w: G.Workspace; + admin: boolean; + runners: G.Runner[]; +}) { + const mine = runners.filter(isMicrovmRunner); + const [open, setOpen] = useState(); + const opened = mine.find((r) => r.id === open); + // What the cards and the drawing say, from the first runner's settings where they show. + const first = useQuery({ + queryKey: keys.runnerMicrovms(mine[0]?.id ?? ""), + queryFn: () => api.runnerMicrovms(mine[0]?.id ?? ""), + enabled: !!mine[0], + }); + const settings = first.data?.settings; + const suspend = settings?.suspend_after_secs ?? MICROVM_DEFAULTS.suspend_after_secs; + const terminate = (settings?.terminate_after_minutes ?? MICROVM_DEFAULTS.terminate_after_minutes) * 60; + return ( +
+
+
+

Sessions in AWS Lambda microVMs

+

+ A runner can run each of {w.name}'s sessions in a microVM of its own, in your AWS account. A + session's microVM suspends once it has waited {span(suspend)} with nothing running, and costs no + compute while it waits for CI or for you: a message resumes it as it was, in a second or two. + After {span(terminate)} suspended it goes, and the next message{" "} + {w.snapshots === false + ? `starts the session again in a new microVM, from its task and branch: ${w.name} keeps no snapshots.` + : "carries the session on in a new microVM, with its conversation and the work it hadn't pushed."} +

+ {mine.length > 0 && ( +
    + {mine.map((r) => ( + setOpen(r.id)} /> + ))} +
+ )} +
+ +
+ {mine.length === 0 && } + {opened && setOpen(undefined)} />} +
+ ); +} + +/** A drawing of a session's microVM over its life: at work, suspended, gone. `aria-hidden`. */ +export function Lifecycle({ + suspend, + terminate, + snapshots, +}: { + suspend: number; + terminate: number; + /** Whether the workspace keeps sessions' snapshots, which carry them on once it goes. */ + snapshots: boolean; +}) { + return ( +
+ } + title="At work" + facts="the session's agent, in a microVM of its own" + /> + + } + title="Suspended" + facts="memory and disk kept · no compute" + aside={ + + a message resumes it in a second or two + + } + /> + + } + title="Gone" + facts={ + snapshots + ? "its snapshot kept: a message carries the session on in a new one" + : "a message starts the session again in a new one" + } + dashed + /> +
+ ); +} + +function Stage({ + icon, + title, + facts, + aside, + dashed, +}: { + icon: ReactNode; + title: string; + facts: string; + aside?: ReactNode; + dashed?: boolean; +}) { + return ( +
+
+ {icon} + {title} +
+
{facts}
+ {aside} +
+ ); +} + +function Gap({ words }: { words: string }) { + return ( +
+ + {words} +
+ ); +} + +/** Colors of what microVMs do, as their bar and the legend say them. */ +const TONE = { + running: "bg-accent", + changing: "bg-accent/45 motion-safe:animate-pulse", + suspended: "bg-blue", + warm: "bg-ink-3/70", + free: "border border-line bg-sunken", +} as const; + +/** + * A runner's microVMs at a glance: a pip for each it may have, by what each does (running, + * changing, suspended with a session, warm), and the room left; a bar for a runner of many. + */ +export function FleetBar({ report, large }: { report?: G.MicrovmReport; large?: boolean }) { + const c = counts(report); + const parts: [keyof typeof TONE, number][] = [ + ["running", c.running], + ["changing", c.changing], + ["suspended", c.suspended], + ["warm", c.warm], + ["free", c.free], + ]; + const label = `${countWords(report)}${c.max ? `, ${c.free} free of ${c.max}` : ""}`; + if (c.max > 0 && c.max <= 40) + return ( +
+ {parts.flatMap(([kind, n]) => + Array.from({ length: n }, (_, i) => ( + + )), + )} +
+ ); + return ( +
+ {parts + .filter(([kind, n]) => n > 0 && kind !== "free") + .map(([kind, n]) => ( + + ))} +
+ ); +} + +/** What the bar's colors mean, with how many of each. */ +function Legend({ report }: { report?: G.MicrovmReport }) { + const c = counts(report); + const items: [keyof typeof TONE, string, number][] = [ + ["running", "running", c.running], + ["suspended", "suspended", c.suspended], + ["warm", "warm", c.warm], + ["changing", "changing", c.changing], + ["free", "free", c.free], + ]; + return ( +
+ {items + .filter(([kind, , n]) => n > 0 || kind === "running" || kind === "free") + .map(([kind, word, n]) => ( + + + {n} {word} + + ))} + {c.max > 0 && of {c.max} at most} +
+ ); +} + +/** A runner of microVMs on the Runners tab: its state, its microVMs, its image, what stops it. */ +function MicrovmCard({ + w, + runner: r, + admin, + onOpen, +}: { + w: G.Workspace; + runner: G.Runner; + admin: boolean; + onOpen: () => void; +}) { + const report = r.microvms; + const own = r.workspace?.id === w.id && !r.created_by; + const manage = (own && admin) || r.yours; + const unset = r.microvms_configured === false; + const image = report?.image && imageWords(report.image); + const online = r.status === "online"; + // Each fact whole on its line: on a phone, they wrap between them. + const whole = "whitespace-nowrap"; + const doing = countParts(report); + return ( +
  • +
    + + + +
    +
    + {r.name} + + {online && r.drain ? "draining" : r.status} +
    + + ({ + key: d, + node: {d}, + className: whole, + })), + report && + report.max > 0 && { + key: "max", + node: `${counts(report).free} free of ${report.max}`, + className: whole, + }, + ]} + /> + + {report?.problem && ( +

    + {report.problem.message} +

    + )} + {unset && ( +

    + Its microVMs have no settings yet: until they do, it runs no sessions. +

    + )} +
    +
    + + {manage && } +
    +
    +
  • + ); +} + +/** How to set up a runner of microVMs, while the workspace has none. */ +function MicrovmSetup({ w, admin }: { w: G.Workspace; admin: boolean }) { + return ( +
    +

    To run sessions in microVMs

    +

    + One host runs them all, on a machine that may manage your account's microVMs: an EC2 instance or an + ECS task with a role, or any machine with AWS keys. Nothing reaches it from outside. +

    +
      + +

      + It runs, suspends, resumes and lets go of microVMs, makes tokens to reach them, and reads their + image. For an image fctl builds and keeps up to date, it also puts what Lambda builds it from in a + bucket of yours, and passes the role Lambda builds it as: +

      + +
      + +

      Signed in, with the lambda driver. It shows here within seconds:

      + + +

      + From a boot script instead? Give it an{" "} + + enrollment token + {" "} + in FCTL_ENROLL_TOKEN. A role of another account?{" "} + [lambda] role_arn in its host.toml. +

      +
      + +

      + {admin + ? "Open it here: fctl builds the image in your account from the sandbox image, or you name one of yours. Then choose its microVMs' size, when they suspend and go, and how many wait warm." + : `Its admins choose them${w.primary ? ` (${w.primary.name} is its primary admin)` : ""}: the image, its microVMs' size, when they suspend and go, and how many wait warm.`}{" "} + + The guide + {" "} + has the roles, the bucket and a VPC of yours. +

      +
      +
    +
    + ); +} + +/** Every one of a runner's microVMs, and their settings, which those who manage it change here. */ +function MicrovmsSheet({ w, runner, onClose }: { w: G.Workspace; runner: G.Runner; onClose: () => void }) { + const q = useQuery({ + queryKey: keys.runnerMicrovms(runner.id), + queryFn: () => api.runnerMicrovms(runner.id), + // Live while it is open: its host says what changed within seconds. + refetchInterval: 3000, + }); + const m = q.data; + const report = m?.report; + const where = [ + report?.region && `AWS Lambda in ${report.region}`, + report?.account && `account ${report.account}`, + ] + .filter(Boolean) + .join(" · "); + return ( + + {/* As wide as the sheet's header: the sheet pads only that. */} + {!m ? ( +
    + Reading how its microVMs are +
    + ) : ( +
    +
    + + + {report?.problem && ( + + {report.problem.message} + + )} +
    + {report?.image && } + + {m.manage && } + {m.manage ? ( + + ) : m.settings ? ( +

    {settingsWords(m.settings)}

    + ) : ( +

    + Its owners choose its image and settings. +

    + )} +
    + )} +
    + ); +} + +/** The image its microVMs run from, and how it is. */ +function ImageLine({ image: i }: { image: G.MicrovmImageReport }) { + const words = imageWords(i); + return ( +
    + +
    +
    + {words.name} + {i.arch && · {i.arch === "x86_64" ? "x86_64" : "arm64"}} +
    + {i.size && ( +
    + {sizeWords(i.size)}, bursting to {peakWords(i.size)} · {i.size.disk_gb} GB of disk +
    + )} +
    + {words.tone === "busy" && } + {words.state} +
    +
    +
    + ); +} + +/** Each microVM: what it does, its session, and how much of its 8 hours it has had. */ +function VmList({ m }: { m: G.RunnerMicrovms }) { + const vms = m.report?.vms ?? []; + // Sessions first, those at work before those that wait; warm ones last. + const order: Record = { + running: 0, + resuming: 1, + starting: 2, + suspending: 3, + suspended: 4, + terminating: 5, + }; + const sorted = [...vms].sort( + (a, b) => Number(!a.session) - Number(!b.session) || order[a.state] - order[b.state] || b.since - a.since, + ); + const now = Date.now(); + return ( +
    +

    Its microVMs

    + {sorted.length === 0 ? ( +

    + None now. One runs as each session starts, and its warm ones as soon as it has settings and an + image. +

    + ) : ( +
      + {sorted.map((vm) => { + const session = m.sessions?.find((s) => s.id === vm.session); + const words = vmWords(vm, now); + const used = lifeUsed(vm, now); + return ( +
    • + +
      +
      + {session ? ( + + + {session.project_slug}#{session.number} + {" "} + {session.title} + + ) : vm.session ? ( + A session + ) : ( + Waiting for a session + )} +
      +
      + {words.text} ·{" "} + + {vm.id.slice(0, 12)} + +
      +
      +
      +
      0.85 ? "bg-amber" : "bg-ink-4")} + style={{ width: `${Math.round(used * 100)}%` }} + /> +
      +
    • + ); + })} +
    + )} +
    + ); +} + +function VmIcon({ vm }: { vm: G.MicrovmVm }) { + const box = "flex size-6 shrink-0 items-center justify-center rounded-full"; + if (!vm.session && vm.state === "suspended") + return ( + + + + ); + switch (vm.state) { + case "running": + return ( + + + + ); + case "suspended": + return ( + + + + ); + default: + return ( + + + + ); + } +} + +/** + * The policy the role of its host's machine needs, for its region, account, bucket and roles: + * shown at once while AWS refuses the host something. + */ +function HostPolicy({ m, refused }: { m: G.RunnerMicrovms; refused: boolean }) { + const [open, setOpen] = useState(refused); + useEffect(() => { + if (refused) setOpen(true); + }, [refused]); + const s = m.settings; + const managed = s?.image.kind === "managed" ? s.image : undefined; + const policy = hostPolicy({ + region: m.report?.region, + account: m.report?.account, + artifacts: managed?.artifacts || undefined, + roles: [managed?.build_role_arn, s?.execution_role_arn].filter((r): r is string => !!r), + }); + return ( +
    +

    Its host's AWS policy

    +

    + {refused + ? "AWS refuses its host something: the role of the machine it runs on needs this policy, for these settings." + : "What the role of the machine its host runs on needs, for these settings."} +

    + {open ? ( + + ) : ( + + )} +
    + ); +} + +/** The connectors' ARNs in what someone typed, a line or a space between them. */ +const connectors = (typed: string) => typed.split(/\s+/).filter(Boolean); + +const sameList = (a: string[], b: string[]) => a.length === b.length && a.every((x, i) => x === b[i]); + +/** Where a draft's problem goes, by its field: `image.arn` under the image's ARN. */ +function errorsOf( + problem?: { field: string; message: string }, + server?: { field?: string; message: string }, +) { + const field = (f: string) => + server?.field?.replace(/^settings\./, "") === f + ? server.message + : problem?.field === f + ? problem.message + : undefined; + return field; +} + +/** The settings its host runs microVMs with, for those who manage it. */ +function SettingsForm({ w, runner, m }: { w: G.Workspace; runner: G.Runner; m: G.RunnerMicrovms }) { + const saved = useMemo( + () => + m.settings ?? + defaultSettings({ kind: "managed", artifacts: "", build_role_arn: "" } satisfies G.MicrovmImage), + [m.settings], + ); + const [draft, setDraft] = useState(saved); + // The connectors as typed, a line or a space between them: the draft has them parsed. + const [egress, setEgress] = useState(() => (saved.egress_connectors ?? []).join("\n")); + const [shown, setShown] = useState(false); + const [more, setMore] = useState( + !!(saved.execution_role_arn || saved.egress_connectors?.length || saved.kms_key_arn || saved.log_group), + ); + // What another person saved meanwhile shows, unless this one changed something. + const changed = settingsKey(draft) !== settingsKey(saved); + useEffect(() => { + if (!changed) { + setDraft(saved); + const list = saved.egress_connectors ?? []; + setEgress((typed) => (sameList(connectors(typed), list) ? typed : list.join("\n"))); + } + }, [saved, changed]); + const save = useMutation({ + mutationFn: (s: G.MicrovmSettings) => api.putRunnerMicrovms(runner.id, s), + onSuccess: (x) => { + queryClient.setQueryData(keys.runnerMicrovms(runner.id), x); + void queryClient.invalidateQueries({ queryKey: keys.workspaceRunners(w.id) }); + setShown(false); + toast(`Saved: ${runner.name}'s host runs new microVMs with these`); + }, + }); + const problem = settingsProblem(draft); + const server = save.error instanceof ApiFailure ? save.error : null; + const error = errorsOf(shown ? problem : undefined, server ?? undefined); + const set = (patch: Partial) => setDraft((d) => ({ ...d, ...patch })); + const image = draft.image; + const managed = image.kind === "managed"; + const size = sizeOf(draft.memory_mb); + return ( +
    { + e.preventDefault(); + setShown(true); + if (!problem) save.mutate(draft); + }} + > +
    +

    Its settings

    +

    + {m.updated_at + ? `Saved ${ago(m.updated_at)}${m.updated_by ? ` by ${m.updated_by.name}` : ""}. Its host runs new microVMs with what you save here; those that run keep theirs until they go.` + : "Its host runs no session until it has these."} +

    +
    +
    + Image +
    + + !managed && + set({ + image: { + kind: "managed", + artifacts: saved.image.kind === "managed" ? saved.image.artifacts : "", + build_role_arn: saved.image.kind === "managed" ? saved.image.build_role_arn : "", + }, + }) + } + /> + + Built from fctl's template:{" "} + fctl host microvm-image. + + } + onClick={() => + managed && + set({ image: { kind: "own", arn: saved.image.kind === "own" ? saved.image.arn : "" } }) + } + /> +
    + {image.kind === "managed" ? ( + <> + + {(id) => ( + set({ image: { ...image, artifacts: e.target.value.trim() } })} + /> + )} + + + {(id) => ( + set({ image: { ...image, build_role_arn: e.target.value.trim() } })} + /> + )} + + + ) : ( +
    + + {(id) => ( + set({ image: { ...image, arn: e.target.value.trim() } })} + /> + )} + + + {(id) => ( + set({ image: { ...image, version: e.target.value.trim() || undefined } })} + /> + )} + +
    + )} +
    +
    + + {(id) => ( + set({ arch: v === "arm64" ? undefined : (v as G.MicrovmArch) })} + options={[ + { value: "arm64", label: "arm64", description: "Graviton: Lambda's default" }, + { value: "x86_64", label: "x86_64" }, + ]} + /> + )} + +
    +
    + + {(id) => ( + set({ terminate_after_minutes: Number(v) })} + options={withValue(TERMINATE_PRESETS, draft.terminate_after_minutes).map((minutes) => ({ + value: String(minutes), + label: span(minutes * 60), + description: + minutes === MICROVM_DEFAULTS.terminate_after_minutes + ? "The default: time for CI to report" + : undefined, + }))} + /> + )} + +
    +
    + + {(id) => ( + set({ warm: Number(e.target.value) })} + /> + )} + + + {(id) => ( + set({ max_microvms: Number(e.target.value) })} + /> + )} + +
    +
    + + Run sessions here first + + Sessions any of {w.name}'s runners could run start here before the others, while it has room. + + + set({ first: v || undefined })} + label="Run sessions here first" + /> +
    + {!more ? ( + + ) : ( +
    + + Network, role, encryption and logs + + + {(id) => ( +