diff --git a/AGENTS.md b/AGENTS.md index c9b7af20..91d54576 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -100,9 +100,11 @@ fake-claude's behaviors are listed in [docs/development.md](docs/development.md) default sandbox image, `ghcr.io/hyperstructure/sandbox`, published for every release. Hosts pull it, and `fctl host image build` builds its `main`. The host relies on its layout (the `agent` user, the PATH, - `/opt/fctl/bin`) and on `Dockerfile` and `provision.sh` at its root: - change those there, together with `docs/sandbox-images.md` here. Its Rust - is the one in `rust-toolchain.toml`; bump the two together. + `/opt/fctl/bin`), on `Dockerfile` and `provision.sh` at its root, and on + the `org.opencontainers.image.revision` label that only its Image + workflow sets (hosts pull again over, and remove, only images that have + it): change those there, together with `docs/sandbox-images.md` here. + Its Rust is the one in `rust-toolchain.toml`; bump the two together. design and fctl-site are private for now: `npm ci` reaches the design package over git, so it needs GitHub access (CI uses a read-only deploy diff --git a/crates/fctl-host/src/build.rs b/crates/fctl-host/src/build.rs index 76a873e5..51ea1cb2 100644 --- a/crates/fctl-host/src/build.rs +++ b/crates/fctl-host/src/build.rs @@ -1092,7 +1092,7 @@ mod tests { use crate::driver::Driver; use crate::driver::container::Flavor; - use crate::driver::container::fake::FakeCli; + use crate::driver::fake::FakeCli; use crate::session::HostCtx; use std::sync::{Arc, Mutex, PoisonError}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; diff --git a/crates/fctl-host/src/daemon.rs b/crates/fctl-host/src/daemon.rs index cb5b7d88..ad14f9bd 100644 --- a/crates/fctl-host/src/daemon.rs +++ b/crates/fctl-host/src/daemon.rs @@ -13,6 +13,7 @@ use crate::config::HostConfig; use crate::driver::{Driver, SandboxInfo, sandbox_name, session_of, timed_out}; use crate::expiry; use crate::login::{self, LoginCmd}; +use crate::refresh; use crate::session::{self, HostCtx, SessionCmd, SessionEvent, SessionHandle, Start}; use crate::sysinfo; use anyhow::Result; @@ -116,34 +117,23 @@ impl Daemon { }) } - /// Pulls the host's sandbox image in the background when it isn't here - /// yet, so that the first session after an upgrade doesn't wait for it. - /// When it can't be pulled, as before a release's image is published, - /// it pulls the image sessions start from instead. - fn prefetch_image(&self) { + /// Pulls the host's sandbox image in the background, now and every + /// [`refresh::REFRESH_EVERY`]: when it isn't here yet, so that the first + /// session after an upgrade doesn't wait for it, and on the default + /// image again, so that new sessions start from its newest build. Then + /// it removes the images sessions no longer start from. + fn refresh_image(&self) { if !self.ctx.driver.uses_images() { return; } let ctx = self.ctx.clone(); tokio::spawn(async move { - let image = ctx.cfg.image(); - if ctx.driver.has_image(&image).await { - return; - } - // Never over a fallback that is here: sessions start from it. - let fallback = match ctx.cfg.fallback_image() { - Some(f) if !ctx.driver.has_image(&f).await => Some(f), - _ => None, - }; - tracing::info!("pulling {image}"); - let log = |line: String| tracing::info!("{line}"); - match ctx - .driver - .pull_or_fallback(&image, fallback.as_deref(), false, &log) - .await - { - Ok(pulled) => tracing::info!("pulled {pulled}"), - Err(e) => tracing::warn!("pulling {image}: {e:#} (sessions try again)"), + let mut every = tokio::time::interval(refresh::REFRESH_EVERY); + every.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + loop { + every.tick().await; + refresh::refresh(&ctx.driver, &ctx.cfg).await; + clean_up_images(&ctx).await; } }); } @@ -253,7 +243,12 @@ impl Daemon { } self.release(&name); } - Chore::Swept => self.sweeping = false, + Chore::Swept => { + self.sweeping = false; + // Images that only the removed sandboxes used can go too. + let ctx = self.ctx.clone(); + tokio::spawn(async move { clean_up_images(&ctx).await }); + } Chore::Stopped { name, ended } => { self.outbox.push_back(ended); self.release(&name); @@ -360,7 +355,7 @@ impl Daemon { wait = (wait * 2).min(Duration::from_secs(60)); } // Once the runtime answers. - self.prefetch_image(); + self.refresh_image(); self.start_sweep(); refresh_facts_every(self.ctx.clone(), FACTS_EVERY); let url = format!( @@ -658,6 +653,15 @@ impl Daemon { } } +/// Removes the sandbox images that sessions no longer start from, saying +/// which in the log. +async fn clean_up_images(ctx: &HostCtx) { + for name in refresh::clean_up(&ctx.driver, &ctx.cfg).await { + let what = refresh::describe(&name); + tracing::info!("removed {what}: sessions no longer start from it"); + } +} + /// Probes the drivers and measures what sandboxes run on every `period`, in /// the background. fn refresh_facts_every(ctx: Arc, period: Duration) { diff --git a/crates/fctl-host/src/driver/container.rs b/crates/fctl-host/src/driver/container.rs index c43fe9a4..bf60c8f7 100644 --- a/crates/fctl-host/src/driver/container.rs +++ b/crates/fctl-host/src/driver/container.rs @@ -14,7 +14,7 @@ use super::{ use anyhow::{Context, Result}; use fctl_proto::runner::{DriverInfo, SandboxSize}; use serde_json::Value; -use std::collections::VecDeque; +use std::collections::{BTreeMap, VecDeque}; use std::path::Path; use std::process::Stdio; use tokio::io::{AsyncBufReadExt, AsyncRead, BufReader}; @@ -30,6 +30,17 @@ pub struct ContainerDriver { bin: String, } +/// An image on this host, as its runtime describes it. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ImageInfo { + /// Docker's image ID, or with Apple's `container` the digest of the + /// image's index: a pull that brings a newer build changes it. Empty + /// when the runtime's description can't be read. + pub id: String, + /// Its labels (with Apple's `container`, those of each platform). + pub labels: BTreeMap, +} + /// Why a sandbox wasn't created. enum Create { /// Its image isn't on this host and pulling it failed. @@ -52,6 +63,12 @@ impl ContainerDriver { } } + /// A driver whose CLI is `bin`, a stand-in. + #[cfg(test)] + pub(crate) fn with_bin(flavor: Flavor, bin: String) -> Self { + Self { flavor, bin } + } + pub fn flavor_name(&self) -> &'static str { match self.flavor { Flavor::Apple => "apple", @@ -373,15 +390,6 @@ impl ContainerDriver { } } - /// Removes an image; fails while a sandbox uses it. - pub async fn remove_image(&self, image: &str) -> Result<()> { - let args: &[&str] = match self.flavor { - Flavor::Apple => &["image", "delete", image], - Flavor::Docker => &["image", "rm", image], - }; - self.run(args).await.map(drop) - } - pub async fn has_image(&self, image: &str) -> bool { let inspect: &[&str] = match self.flavor { Flavor::Apple => &["image", "inspect", image], @@ -444,6 +452,47 @@ impl ContainerDriver { } } + /// What the runtime says about `image`: `None` when it isn't here, and + /// an empty [`ImageInfo`] when its description can't be read. An error + /// only when the runtime doesn't answer. + pub async fn image(&self, image: &str) -> Result> { + match self.run(&["image", "inspect", image]).await { + Ok(out) => Ok(Some(image_info(&out).unwrap_or_default())), + Err(e) if e.is::() => Err(e), + Err(_) => Ok(None), + } + } + + /// Gives `image` another name, `name`. + pub async fn tag_image(&self, image: &str, name: &str) -> Result<()> { + self.run(&["image", "tag", image, name]).await.map(drop) + } + + /// Removes the name `image`, and the image once no other name refers to + /// it, without force: Docker refuses while a container uses it, stopped + /// ones included. Apple's `container` doesn't check, but each of its + /// containers has a copy of the image's filesystem, so it still starts. + pub async fn remove_image(&self, image: &str) -> Result<()> { + let args: &[&str] = match self.flavor { + Flavor::Apple => &["image", "delete", image], + Flavor::Docker => &["image", "rm", image], + }; + self.run(args).await.map(drop) + } + + /// The names (`repository:tag`) of `repository`'s images on this host. + pub async fn images(&self, repository: &str) -> Result> { + let out = match self.flavor { + Flavor::Apple => self.run(&["image", "list", "--quiet"]).await?, + Flavor::Docker => { + let format = "{{.Repository}}:{{.Tag}}"; + self.run(&["image", "ls", "--format", format, repository]) + .await? + } + }; + Ok(names_in(&out, repository)) + } + pub async fn install_agent(&self, sb: &Sandbox, binary: &Path) -> Result<()> { let src = binary.display().to_string(); let dest = format!("{}:{AGENT_PATH}", sb.name); @@ -625,6 +674,48 @@ fn linux_arch(arch: &str) -> &str { } } +/// An image's ID and labels from `image inspect`: Docker's, or Apple's, +/// whose `index` became `configuration.descriptor` in its 1.0. +fn image_info(out: &str) -> Option { + let v: Value = serde_json::from_str(out).ok()?; + let image = v.get(0)?; + let id = image + .get("Id") + .or_else(|| image.pointer("/configuration/descriptor/digest")) + .or_else(|| image.pointer("/index/digest")) + .and_then(Value::as_str)?; + let variants = image.get("variants").and_then(Value::as_array); + let configs = image.pointer("/Config/Labels").into_iter().chain( + variants + .into_iter() + .flatten() + .filter_map(|v| v.pointer("/config/config/Labels")), + ); + let mut labels = BTreeMap::new(); + for (k, v) in configs.filter_map(Value::as_object).flatten() { + if let Some(v) = v.as_str() { + labels.insert(k.clone(), v.to_owned()); + } + } + Some(ImageInfo { + id: id.to_owned(), + labels, + }) +} + +/// The tagged names of `repository` in a list of image names, one per line. +fn names_in(out: &str, repository: &str) -> Vec { + out.lines() + .map(str::trim) + .filter(|name| { + name.strip_prefix(repository) + .and_then(|rest| rest.strip_prefix(':')) + .is_some_and(|tag| !tag.is_empty() && tag != "") + }) + .map(str::to_owned) + .collect() +} + /// `docker info --format '{{.NCPU}} {{.MemTotal}}'`: CPUs, and memory in bytes. fn docker_resources(out: &str) -> Option { let mut words = out.split_whitespace(); @@ -643,124 +734,11 @@ fn installed(bin: &str) -> bool { } } -#[cfg(test)] -pub(crate) mod fake { - use super::*; - use anyhow::Result; - use std::sync::{Mutex, PoisonError}; - - /// A stand-in for the `docker` or `container` CLI with no sandboxes yet: - /// `have` are the images on the host, `registry` those it can pull. It - /// writes each call to `calls`; with `fail_run` every `run` fails, and with - /// `fail_build` every `build`. A build lists its context in `context` and - /// copies its Dockerfile to `dockerfile`; `size` holds the size images - /// have (1000 bytes without it). - pub struct FakeCli { - pub dir: tempfile::TempDir, - } - - impl FakeCli { - pub fn new(have: &[&str], registry: &[&str]) -> Result { - use std::os::unix::fs::PermissionsExt; - let dir = tempfile::tempdir()?; - let root = dir.path(); - for (sub, images) in [("have", have), ("registry", registry)] { - std::fs::create_dir(root.join(sub))?; - for image in images { - std::fs::write(root.join(sub).join(image.replace(['/', ':'], "_")), "")?; - } - } - let script = format!( - r##"#!/bin/sh -d='{}' -echo "$*" >> "$d/calls" -key() {{ printf '%s' "$1" | tr '/:' '__'; }} -for last in "$@"; do :; done -pull() {{ - [ -e "$d/registry/$(key "$last")" ] || {{ echo "$last: manifest unknown" >&2; exit 1; }} - touch "$d/have/$(key "$last")" -}} -case "$1 $2" in - "image inspect") - [ -e "$d/have/$(key "$last")" ] || exit 1 - [ "$4" != '{{{{.Size}}}}' ] || cat "$d/size" 2>/dev/null || echo 1000 ;; - "image rm" | "image delete") rm "$d/have/$(key "$last")" ;; - "build "*) - [ ! -e "$d/fail_build" ] || {{ echo "#3 ERROR: process did not complete successfully: exit code: 1" >&2; exit 1; }} - echo "#1 [internal] load build definition from Dockerfile" - echo "#5 [1/2] FROM debian" >&2 - echo "#5 0.1 noise" - (cd "$last" && find . | sort) > "$d/context" - cat "$5" > "$d/dockerfile" - touch "$d/have/$(key "$3")" ;; - "image pull" | "pull "*) pull ;; - "inspect "*) exit 1 ;; - "run "*) - [ ! -e "$d/fail_run" ] || {{ echo "no room for it" >&2; exit 1; }} - while [ $# -gt 0 ] && [ "$1" != tail ]; do shift; done - [ -e "$d/have/$(key "$2")" ] || {{ echo "Unable to find image '$2' locally" >&2; exit 125; }} ;; - *) echo "unexpected: $*" >&2; exit 2 ;; -esac -"##, - root.display() - ); - let bin = root.join("cli"); - std::fs::write(&bin, script)?; - std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755))?; - Ok(Self { dir }) - } - - pub fn driver(&self, flavor: Flavor) -> ContainerDriver { - ContainerDriver { - flavor, - bin: self.dir.path().join("cli").display().to_string(), - } - } - - pub fn calls(&self) -> Vec { - std::fs::read_to_string(self.dir.path().join("calls")) - .unwrap_or_default() - .lines() - .map(str::to_owned) - .collect() - } - - /// Creates the sandbox: the image it started from, and the log. - pub async fn ensure( - &self, - flavor: Flavor, - spec: &SandboxSpec, - ) -> Result<(String, Vec)> { - let lines = Mutex::new(Vec::new()); - let log = |line: String| { - lines - .lock() - .unwrap_or_else(PoisonError::into_inner) - .push(line) - }; - self.driver(flavor).ensure(spec, &log).await?; - let run = self - .calls() - .into_iter() - .rev() - .find(|c| c.starts_with("run ")); - let image = run - .as_deref() - .and_then(|c| c.split(" tail ").nth(1)?.split(' ').next()) - .unwrap_or_default() - .to_owned(); - Ok(( - image, - lines.into_inner().unwrap_or_else(PoisonError::into_inner), - )) - } - } -} - #[cfg(test)] mod tests { - use super::fake::FakeCli; use super::*; + use crate::driver::fake::FakeCli; + use std::sync::{Mutex, PoisonError}; #[test] fn build_logs_show_the_steps() { @@ -815,7 +793,92 @@ mod tests { } } - use std::sync::{Mutex, PoisonError}; + #[test] + fn reads_an_images_id_and_labels() { + let labels = BTreeMap::from([ + ( + "org.opencontainers.image.revision".to_owned(), + "12685ad".to_owned(), + ), + ( + "sh.fctl.claude-code.version".to_owned(), + "2.1.302".to_owned(), + ), + ]); + let published = |id: &str| ImageInfo { + id: id.into(), + labels: labels.clone(), + }; + let docker = r#"[{ + "Id": "sha256:4f1c", + "RepoTags": ["ghcr.io/hyperstructure/sandbox:0.5.0"], + "Config": {"User": "agent", "Labels": { + "org.opencontainers.image.revision": "12685ad", + "sh.fctl.claude-code.version": "2.1.302" + }} + }]"#; + assert_eq!(image_info(docker), Some(published("sha256:4f1c"))); + let built = r#"[{"Id": "sha256:77aa", "Config": {"User": "agent", "Labels": null}}]"#; + assert_eq!( + image_info(built), + Some(ImageInfo { + id: "sha256:77aa".into(), + labels: BTreeMap::new(), + }) + ); + // Apple's `container` from 1.0: an attestation has no image config. + let apple = r#"[{ + "id": "9a8b", + "configuration": { + "name": "ghcr.io/hyperstructure/sandbox:0.5.0", + "descriptor": {"digest": "sha256:9a8b", "size": 1609} + }, + "variants": [ + {"platform": {"os": "linux", "architecture": "arm64"}, "digest": "sha256:01", "size": 1, + "config": {"os": "linux", "architecture": "arm64", "config": {"User": "agent", "Labels": { + "org.opencontainers.image.revision": "12685ad", + "sh.fctl.claude-code.version": "2.1.302" + }}}}, + {"platform": {"os": "unknown", "architecture": "unknown"}, "digest": "sha256:02", "size": 1, + "config": {"os": "unknown", "architecture": "unknown"}} + ] + }]"#; + assert_eq!(image_info(apple), Some(published("sha256:9a8b"))); + // …and before it. + let apple_0 = r#"[{ + "name": "ghcr.io/hyperstructure/sandbox:0.5.0", + "index": {"digest": "sha256:9a8b", "size": 1609}, + "variants": [{"platform": {"os": "linux", "architecture": "arm64"}, "size": 1, + "config": {"os": "linux", "architecture": "arm64", "config": {"Labels": { + "org.opencontainers.image.revision": "12685ad", + "sh.fctl.claude-code.version": "2.1.302" + }}}}] + }]"#; + assert_eq!(image_info(apple_0), Some(published("sha256:9a8b"))); + for unreadable in ["", "[]", "{}", "[{\"Config\": {}}]", "Error: no such image"] { + assert_eq!(image_info(unreadable), None, "{unreadable}"); + } + } + + #[test] + fn lists_the_tagged_names_of_a_repository() { + let repository = "ghcr.io/hyperstructure/sandbox"; + // `docker image ls` lists a build without a tag as ``, and + // Apple's `container image list --quiet` lists every image. + let out = "ghcr.io/hyperstructure/sandbox:0.5.0\n\ + ghcr.io/hyperstructure/sandbox:\n\ + ghcr.io/hyperstructure/sandbox-dev:1\n\ + ghcr.io/hyperstructure/sandbox@sha256:9a8b\n\ + docker.io/library/debian:bookworm-slim\n\ + ghcr.io/hyperstructure/sandbox:latest\n"; + assert_eq!( + names_in(out, repository), + [ + "ghcr.io/hyperstructure/sandbox:0.5.0", + "ghcr.io/hyperstructure/sandbox:latest" + ] + ); + } const VERSION_IMAGE: &str = "ghcr.io/hyperstructure/sandbox:0.3.0"; const LATEST_IMAGE: &str = "ghcr.io/hyperstructure/sandbox:latest"; @@ -993,7 +1056,7 @@ mod tests { #[tokio::test] async fn other_failures_are_not_about_the_image() -> Result<()> { let cli = FakeCli::new(&[VERSION_IMAGE], &[LATEST_IMAGE])?; - std::fs::write(cli.dir.path().join("fail_run"), "")?; + cli.fail_runs()?; let default = spec(VERSION_IMAGE, Some(LATEST_IMAGE)); let error = error_of(cli.ensure(Flavor::Docker, &default).await); assert!(error.starts_with("starting fctl-ses-1: "), "{error}"); diff --git a/crates/fctl-host/src/driver/fake.rs b/crates/fctl-host/src/driver/fake.rs new file mode 100644 index 00000000..db8a98c1 --- /dev/null +++ b/crates/fctl-host/src/driver/fake.rs @@ -0,0 +1,240 @@ +//! A stand-in for the `docker` and `container` CLIs, for tests of the +//! drivers and of what the host does with its images. + +use super::container::{ContainerDriver, Flavor}; +use super::{Driver, SandboxSpec}; +use anyhow::Result; +use sha2::{Digest, Sha256}; +use std::sync::{Mutex, PoisonError}; + +/// The CLI. Each image name on the host is a file in `have`, and each one +/// it can pull a file in `registry`, holding the build's ID, its revision +/// label and Claude Code version (`-` for a build without labels) and the +/// name. `containers` holds the ID of the build each container was made +/// from. Like Docker, `image rm` refuses to remove an image's last name +/// while a container uses it; Apple's `image delete` doesn't check. A +/// `build` lists its context in `context`, copies its Dockerfile to +/// `dockerfile` and makes a build without labels, and with `fail_build` it +/// fails; `size` holds the size images have (1000 bytes without it). +const SCRIPT: &str = r##"#!/bin/sh +d=$(dirname "$0") +echo "$*" >> "$d/calls" +key() { printf '%s' "$1" | tr '/:' '__'; } +for last in "$@"; do :; done +file() { printf '%s/have/%s' "$d" "$(key "$1")"; } +here() { [ -e "$(file "$1")" ] || { echo "Error: No such image: $1" >&2; exit 1; }; } +id_of() { cut -d' ' -f1 "$(file "$1")"; } +labels() { + if [ "$1" = - ]; then echo null; else + printf '{"org.opencontainers.image.revision": "%s", "sh.fctl.claude-code.version": "%s"}' "$1" "$2" + fi +} +size() { cat "$d/size" 2>/dev/null || echo 1000; } +inspect() { + set -- $(cat "$(file "$1")") + printf '[{"Id": "%s", "RepoTags": ["%s"], "Config": {"Labels": %s},' "$1" "$4" "$(labels "$2" "$3")" + printf ' "variants": [{"platform": {"os": "linux", "architecture": "amd64"}, "size": %s}]}]\n' "$(size)" +} +pull() { + [ -e "$d/registry/$(key "$last")" ] || { echo "$last: manifest unknown" >&2; exit 1; } + cp "$d/registry/$(key "$last")" "$(file "$last")" +} +names() { for f in "$d"/have/*; do [ -e "$f" ] && cut -d' ' -f4 "$f"; done; } +count() { + n=0 + for f in "$d"/have/*; do [ -e "$f" ] && [ "$(cut -d' ' -f1 "$f")" = "$1" ] && n=$((n + 1)); done + echo "$n" +} +used() { + for c in "$d"/containers/*; do [ -e "$c" ] && [ "$(cat "$c")" = "$1" ] && return 0; done + return 1 +} +case "$1 $2" in + "image inspect") + here "$last" + case "$3 $4" in + "--format {{.Size}}") size ;; + --format*) id_of "$last" ;; + *) inspect "$last" ;; + esac ;; + "image pull" | "pull "*) pull ;; + "image tag") + here "$3" + set -- $(cat "$(file "$3")") "$4" + echo "$1 $2 $3 $5" > "$(file "$5")" ;; + "image rm" | "image delete") + here "$3" + id=$(id_of "$3") + if [ "$2" = rm ] && [ "$(count "$id")" = 1 ] && used "$id"; then + echo "Error response from daemon: conflict: unable to remove repository reference \"$3\" (must force) - container is using its referenced image $id" >&2 + exit 1 + fi + rm "$(file "$3")" + echo "Untagged: $3" ;; + "image ls") names | while read -r n; do case "$n" in "$last":*) echo "$n" ;; esac; done ;; + "image list") names ;; + "build "*) + [ ! -e "$d/fail_build" ] || { echo "#3 ERROR: process did not complete successfully: exit code: 1" >&2; exit 1; } + echo "#1 [internal] load build definition from Dockerfile" + echo "#5 [1/2] FROM debian" >&2 + echo "#5 0.1 noise" + (cd "$last" && find . | sort) > "$d/context" + cat "$5" > "$d/dockerfile" + echo "x" >> "$d/builds" + echo "sha256:build$(wc -l < "$d/builds" | tr -d ' ') - - $3" > "$(file "$3")" ;; + "inspect "*) exit 1 ;; + "run "*) + [ ! -e "$d/fail_run" ] || { echo "no room for it" >&2; exit 1; } + while [ $# -gt 0 ] && [ "$1" != tail ]; do + [ "$1" != --name ] || name=$2 + shift + done + [ -e "$(file "$2")" ] || { echo "Unable to find image '$2' locally" >&2; exit 125; } + id_of "$2" > "$d/containers/$name" ;; + *) echo "unexpected: $*" >&2; exit 2 ;; +esac +"##; + +/// The revision label of the stand-in's published builds. +const REVISION: &str = "688d0dd"; + +/// A stand-in for the `docker` or `container` CLI, with no sandboxes yet. +pub struct FakeCli { + pub dir: tempfile::TempDir, +} + +impl FakeCli { + /// A host that has the published images `have` and can pull those in + /// `registry`, each a build of its own. + pub fn new(have: &[&str], registry: &[&str]) -> Result { + let cli = Self::empty()?; + for name in have { + cli.have(name, &id(&format!("have {name}")), Some("2.1.302"))?; + } + for name in registry { + cli.publish(name, &id(&format!("registry {name}")), "2.1.302")?; + } + Ok(cli) + } + + /// A host with no images, and nothing it can pull. + pub fn empty() -> Result { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir()?; + for sub in ["have", "registry", "containers"] { + std::fs::create_dir(dir.path().join(sub))?; + } + let bin = dir.path().join("cli"); + std::fs::write(&bin, SCRIPT)?; + std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755))?; + Ok(Self { dir }) + } + + /// Puts `name` on the host as the build `id`: published, with that + /// Claude Code, or built here (`None`). + pub fn have(&self, name: &str, id: &str, claude_code: Option<&str>) -> Result<()> { + let labels = match claude_code { + Some(version) => format!("{REVISION} {version}"), + None => "- -".into(), + }; + let file = self.dir.path().join("have").join(key(name)); + std::fs::write(file, format!("{id} {labels} {name}\n"))?; + Ok(()) + } + + /// Publishes the build `id`, with that Claude Code, as `name`. + pub fn publish(&self, name: &str, id: &str, claude_code: &str) -> Result<()> { + let file = self.dir.path().join("registry").join(key(name)); + std::fs::write(file, format!("{id} {REVISION} {claude_code} {name}\n"))?; + Ok(()) + } + + /// Makes a container, `name`, from the build `id`. + pub fn uses(&self, name: &str, id: &str) -> Result<()> { + std::fs::write(self.dir.path().join("containers").join(name), id)?; + Ok(()) + } + + /// Removes the container `name`. + pub fn drop_container(&self, name: &str) -> Result<()> { + std::fs::remove_file(self.dir.path().join("containers").join(name))?; + Ok(()) + } + + /// Makes every `run` fail as if for some other reason than the image. + pub fn fail_runs(&self) -> Result<()> { + std::fs::write(self.dir.path().join("fail_run"), "")?; + Ok(()) + } + + /// The images on the host: each name with its build's ID, by name. + pub fn images(&self) -> Result> { + let mut images = Vec::new(); + for entry in std::fs::read_dir(self.dir.path().join("have"))? { + let text = std::fs::read_to_string(entry?.path())?; + let fields: Vec<&str> = text.split_whitespace().collect(); + if let [id, _, _, name] = fields[..] { + images.push((name.to_owned(), id.to_owned())); + } + } + images.sort(); + Ok(images) + } + + pub fn driver(&self, flavor: Flavor) -> ContainerDriver { + let bin = self.dir.path().join("cli").display().to_string(); + ContainerDriver::with_bin(flavor, bin) + } + + pub fn host_driver(&self, flavor: Flavor) -> Driver { + Driver::Container(self.driver(flavor)) + } + + /// The commands run so far, one per line. + pub fn calls(&self) -> Vec { + std::fs::read_to_string(self.dir.path().join("calls")) + .unwrap_or_default() + .lines() + .map(str::to_owned) + .collect() + } + + /// Creates the sandbox: the image it started from, and the log. + pub async fn ensure( + &self, + flavor: Flavor, + spec: &SandboxSpec, + ) -> Result<(String, Vec)> { + let lines = Mutex::new(Vec::new()); + let log = |line: String| { + lines + .lock() + .unwrap_or_else(PoisonError::into_inner) + .push(line) + }; + self.driver(flavor).ensure(spec, &log).await?; + let run = self + .calls() + .into_iter() + .rev() + .find(|c| c.starts_with("run ")); + let image = run + .as_deref() + .and_then(|c| c.split(" tail ").nth(1)?.split(' ').next()) + .unwrap_or_default() + .to_owned(); + Ok(( + image, + lines.into_inner().unwrap_or_else(PoisonError::into_inner), + )) + } +} + +/// A made-up image ID. +pub fn id(seed: &str) -> String { + format!("sha256:{}", hex::encode(Sha256::digest(seed.as_bytes()))) +} + +fn key(name: &str) -> String { + name.replace(['/', ':'], "_") +} diff --git a/crates/fctl-host/src/driver/mod.rs b/crates/fctl-host/src/driver/mod.rs index c636bf55..a7b6a85f 100644 --- a/crates/fctl-host/src/driver/mod.rs +++ b/crates/fctl-host/src/driver/mod.rs @@ -9,9 +9,13 @@ //! | `process` | none | development and trusted hosts | pub mod container; +#[cfg(test)] +pub(crate) mod fake; pub mod lima; pub mod process; +pub use container::ImageInfo; + use anyhow::Result; use fctl_proto::runner::{DriverInfo, SandboxSize}; use std::path::{Path, PathBuf}; @@ -202,6 +206,30 @@ impl Driver { } } + /// What the runtime says about `image`; `None` when it isn't here. + pub async fn image(&self, image: &str) -> Result> { + match self { + Self::Container(d) => d.image(image).await, + _ => Ok(None), + } + } + + /// Gives `image` another name, `name`. + pub async fn tag_image(&self, image: &str, name: &str) -> Result<()> { + match self { + Self::Container(d) => d.tag_image(image, name).await, + _ => anyhow::bail!("the {} driver does not use images", self.name()), + } + } + + /// The names (`repository:tag`) of `repository`'s images on this host. + pub async fn images(&self, repository: &str) -> Result> { + match self { + Self::Container(d) => d.images(repository).await, + _ => Ok(Vec::new()), + } + } + /// Builds an image, saying in `log` what the build does. pub async fn build( &self, @@ -222,7 +250,8 @@ impl Driver { } } - /// Removes an image; fails while a sandbox uses it. + /// Removes the name `image`, and the image once no other name refers to + /// it, without force: it fails while a sandbox uses the image (Docker). pub async fn remove_image(&self, image: &str) -> Result<()> { match self { Self::Container(d) => d.remove_image(image).await, diff --git a/crates/fctl-host/src/image.rs b/crates/fctl-host/src/image.rs index 50698f94..72dd38b4 100644 --- a/crates/fctl-host/src/image.rs +++ b/crates/fctl-host/src/image.rs @@ -61,44 +61,43 @@ async fn build_from(driver: &Driver, tag: &str, download_base: &str, dir: &Path) // published (a development build). let version = format!("FCTL_VERSION={}", crate::agentbin::VERSION); let download = format!("FCTL_DOWNLOAD={download_base}"); - match driver.name() { - "apple" => { - run_inherit( - "container", - &[ - "build", - "--tag", - tag, - "--build-arg", - &version, - "--build-arg", - &download, - "--file", - &format!("{ctx}/Dockerfile"), - &ctx, - ], - ) - .await - } - "docker" => { - run_inherit( - "docker", - &[ - "build", - "--tag", - tag, - "--build-arg", - &version, - "--build-arg", - &download, - &ctx, - ], - ) - .await - } - "lima" => build_lima_base(dir, &[&version, &download]).await, + let file = format!("{ctx}/Dockerfile"); + let (program, args): (&str, Vec<&str>) = match driver.name() { + "apple" => ( + "container", + vec![ + "build", + "--tag", + tag, + "--build-arg", + &version, + "--build-arg", + &download, + "--file", + &file, + &ctx, + ], + ), + "docker" => ( + "docker", + vec![ + "build", + "--tag", + tag, + "--build-arg", + &version, + "--build-arg", + &download, + &ctx, + ], + ), + "lima" => return build_lima_base(dir, &[&version, &download]).await, other => bail!("the {other} driver has no image to build"), - } + }; + // A published image that the build replaces goes once no sandbox uses it. + crate::refresh::replacing(driver, tag, run_inherit(program, &args)) + .await + .map(drop) } /// Downloads [`SOURCE`] into `dir`; returns the directory with its files. diff --git a/crates/fctl-host/src/lib.rs b/crates/fctl-host/src/lib.rs index 620fa504..14117b03 100644 --- a/crates/fctl-host/src/lib.rs +++ b/crates/fctl-host/src/lib.rs @@ -13,6 +13,7 @@ pub mod files; pub mod image; pub mod liveness; pub mod login; +pub mod refresh; pub mod service; pub mod session; pub mod sysinfo; diff --git a/crates/fctl-host/src/refresh.rs b/crates/fctl-host/src/refresh.rs new file mode 100644 index 00000000..e52da713 --- /dev/null +++ b/crates/fctl-host/src/refresh.rs @@ -0,0 +1,583 @@ +//! Keeping the default sandbox image current on a host, and removing the +//! builds and versions of it that sessions no longer start from. +//! +//! hyperstructure/sandbox's Image workflow rebuilds the newest release's +//! image under the same tag when Claude Code has a newer release, since fctl +//! turns off Claude Code's auto-updater. A host on the default image pulls +//! its tag again when it starts and every [`REFRESH_EVERY`], so that new +//! sessions start from the newer build, but never over a build of the +//! host's own: only the workflow sets [`REVISION_LABEL`]. +//! +//! A published build that a newer one replaces keeps a name of its own, +//! `…:0.5.0-replaced-`. [`clean_up`] removes those, the images of +//! other versions, and `latest` once the version's image is here. It +//! removes them without force, so Docker keeps the ones a sandbox uses +//! until the sweep removes the sandbox. + +use crate::config::{HostConfig, IMAGE_REPOSITORY}; +use crate::driver::{Driver, ImageInfo}; +use anyhow::Result; +use std::future::Future; +use std::time::Duration; + +/// How often a host on the default image pulls it again. Its tag changes at +/// most about once a day, and a pull of an unchanged tag fetches only its +/// manifest. +pub const REFRESH_EVERY: Duration = Duration::from_secs(6 * 60 * 60); + +/// The commit of hyperstructure/sandbox an image was built from. Only its +/// Image workflow sets it: an image without it was built on the host. +pub const REVISION_LABEL: &str = "org.opencontainers.image.revision"; + +/// The version of Claude Code in a published image. +pub const CLAUDE_CODE_LABEL: &str = "sh.fctl.claude-code.version"; + +/// What the name of a build that a newer one replaced has after its tag. +const REPLACED: &str = "-replaced-"; + +/// Whether the Image workflow built `image`, rather than the host (`fctl +/// host image build`) or someone on it. An image whose description can't +/// be read counts as built here, so the host leaves it alone. +pub fn published(image: &ImageInfo) -> bool { + !image.id.is_empty() + && image + .labels + .get(REVISION_LABEL) + .is_some_and(|r| !r.is_empty()) +} + +/// ` (Claude Code 2.1.302)` for a published image, or nothing. +pub fn claude_code(image: &ImageInfo) -> String { + image + .labels + .get(CLAUDE_CODE_LABEL) + .map(|version| format!(" (Claude Code {version})")) + .unwrap_or_default() +} + +/// The host's own pull, when it starts and every [`REFRESH_EVERY`]. It pulls +/// an image that isn't here yet, so that the first session after an upgrade +/// doesn't wait for it, or the fallback while the image can't be pulled: +/// sessions start from it then. On the default image it pulls the tag +/// again, so that new sessions start from its newest build, unless the +/// build here is the host's own. What it does goes to the log. +pub async fn refresh(driver: &Driver, cfg: &HostConfig) { + let image = cfg.image(); + match driver.image(&image).await { + Err(e) => tracing::warn!("looking for {image}: {e:#}"), + Ok(None) => { + // Never over a fallback that is here: sessions start from it. + let fallback = match cfg.fallback_image() { + Some(f) if !driver.has_image(&f).await => Some(f), + _ => None, + }; + tracing::info!("pulling {image}"); + let log = |line: String| tracing::info!("{line}"); + match driver + .pull_or_fallback(&image, fallback.as_deref(), false, &log) + .await + { + Ok(pulled) => tracing::info!("pulled {pulled}"), + Err(e) => tracing::warn!("pulling {image}: {e:#} (sessions try again)"), + } + } + Ok(Some(here)) if cfg.image.is_none() && published(&here) => { + match replacing(driver, &image, driver.pull(&image, false)).await { + Ok(Replaced { + newer: Some(newer), .. + }) => tracing::info!("pulled a newer build of {image}{}", claude_code(&newer)), + Ok(_) => tracing::debug!("{image} is up to date"), + Err(e) => tracing::warn!( + "pulling {image} again: {e:#} (sessions start from the build here)" + ), + } + } + // Built here, or another image: the host leaves it as it is. + Ok(Some(_)) => tracing::debug!("{image} is not the published image; not pulling it"), + } +} + +/// What `fctl host image pull` pulled. +#[derive(Debug)] +pub struct Pulled { + /// The host's image, or the fallback while that can't be pulled. + pub image: String, + /// The build it brought, when it replaced one that was here. + pub newer: Option, + /// The name the published build it replaced keeps until [`clean_up`] + /// removes it. + pub replaced: Option, +} + +/// `fctl host image pull`: pulls the host's image again, over a build of +/// the host's own too, or the fallback while the image can't be pulled and +/// isn't here. `progress` shows the runtime's own output. +pub async fn pull( + driver: &Driver, + cfg: &HostConfig, + progress: bool, + log: &(dyn Fn(String) + Send + Sync), +) -> Result { + let image = cfg.image(); + if cfg.image.is_none() && driver.has_image(&image).await { + let replaced = replacing(driver, &image, driver.pull(&image, progress)).await?; + return Ok(Pulled { + image, + newer: replaced.newer, + replaced: replaced.name, + }); + } + // Another image, or one that isn't here yet. + let fallback = cfg.fallback_image(); + let pulled = driver + .pull_or_fallback(&image, fallback.as_deref(), progress, log) + .await?; + Ok(Pulled { + image: pulled, + newer: None, + replaced: None, + }) +} + +/// What [`replacing`] did. +#[derive(Debug)] +pub struct Replaced { + /// The image's build now, when it is a newer one. + pub newer: Option, + /// The name the published build it replaced keeps until [`clean_up`] + /// removes it. + pub name: Option, +} + +/// Runs `replace`, a pull or a build that may give `image` a newer build. +/// A published build of the default image that it replaces keeps a name +/// ([`replaced_name`]), so that [`clean_up`] can remove it once no sandbox +/// uses it: Docker would keep it without a name, and Apple's `container` +/// as content no image refers to. +pub async fn replacing( + driver: &Driver, + image: &str, + replace: impl Future>, +) -> Result { + let before = driver.image(image).await?; + let name = before + .as_ref() + .filter(|b| published(b) && tag_of(image).is_some()) + .map(|b| replaced_name(image, &b.id)); + if let Some(name) = &name { + driver.tag_image(image, name).await?; + } + let result = replace.await; + let after = driver.image(image).await.ok().flatten(); + let newer = after.filter(|a| before.as_ref().is_none_or(|b| b.id != a.id)); + // Without a newer build, the name is a second one for the build here. + if newer.is_none() + && let Some(name) = &name + && let Err(e) = driver.remove_image(name).await + { + tracing::debug!("removing {name}: {e:#}"); + } + result?; + let name = name.filter(|_| newer.is_some()); + Ok(Replaced { newer, name }) +} + +/// The name a build of `image` keeps once a newer one replaced it, after +/// the start of its ID: `…:0.5.0-replaced-4f1c0ab2d3e5`. +pub fn replaced_name(image: &str, id: &str) -> String { + let id = id.split_once(':').map_or(id, |(_, hex)| hex); + let short: String = id + .chars() + .filter(char::is_ascii_alphanumeric) + .take(12) + .collect(); + format!("{image}{REPLACED}{short}") +} + +/// Removes the default image's names that sessions no longer start from +/// ([`removable`]), without force: Docker keeps an image that a sandbox +/// uses, stopped ones too, until the sweep removes the sandbox. A host on +/// another image leaves them alone. Returns the names it removed. +pub async fn clean_up(driver: &Driver, cfg: &HostConfig) -> Vec { + if cfg.image.is_some() || !driver.uses_images() { + return Vec::new(); + } + let names = match driver.images(IMAGE_REPOSITORY).await { + Ok(names) => names, + Err(e) => { + tracing::warn!("listing the images of {IMAGE_REPOSITORY}: {e:#}"); + return Vec::new(); + } + }; + let mut here = Vec::new(); + for name in names { + if let Ok(Some(info)) = driver.image(&name).await { + here.push((name, info)); + } + } + let mut removed = Vec::new(); + for name in removable(&cfg.image(), cfg.fallback_image().as_deref(), &here) { + match driver.remove_image(&name).await { + Ok(()) => removed.push(name), + // A sandbox still uses it. + Err(e) => tracing::debug!("keeping {name}: {e:#}"), + } + } + removed +} + +/// Which of `here`, the default image's names on this host with what each +/// holds, [`clean_up`] removes on a host whose sessions start from `image`, +/// or from `fallback` while `image` isn't here: the images of other +/// versions, builds that a newer one replaced, and `fallback` once `image` +/// is here. Builds without the [`REVISION_LABEL`] stay, and so do tags +/// that hosts don't pull, like `0.5`, which projects may use. +pub fn removable(image: &str, fallback: Option<&str>, here: &[(String, ImageInfo)]) -> Vec { + let id_of = |name: &str| { + here.iter() + .find(|(n, _)| n == name) + .map(|(_, info)| info.id.as_str()) + }; + let has_image = id_of(image).is_some(); + // A name for the build sessions start from isn't a replaced build's + // yet: a pull is under way, or one stopped before it removed the name. + let current = id_of(image).or_else(|| fallback.and_then(id_of)); + here.iter() + .filter(|(name, info)| { + let Some(tag) = tag_of(name) else { + return false; + }; + if name == image || !published(info) { + false + } else if Some(name.as_str()) == fallback { + has_image + } else if tag.contains(REPLACED) { + current != Some(info.id.as_str()) + } else { + is_version(tag) + } + }) + .map(|(name, _)| name.clone()) + .collect() +} + +/// A name that [`clean_up`] removed, as people know it: a replaced build +/// by the name it had. +pub fn describe(name: &str) -> String { + match name.split_once(REPLACED) { + Some((image, _)) => format!("a build of {image} that a newer one replaced"), + None => name.to_owned(), + } +} + +/// The tag of one of the default image's names: `0.5.0` for +/// `ghcr.io/hyperstructure/sandbox:0.5.0`. +fn tag_of(name: &str) -> Option<&str> { + name.strip_prefix(IMAGE_REPOSITORY)?.strip_prefix(':') +} + +/// Whether `tag` is a release's version, like `0.5.0` or `0.6.0-rc.1`: +/// the tags hosts pull. +fn is_version(tag: &str) -> bool { + let release = tag.split_once('-').map_or(tag, |(release, _)| release); + let numbers: Vec<&str> = release.split('.').collect(); + numbers.len() == 3 + && numbers + .iter() + .all(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::driver::container::Flavor; + use crate::driver::fake::{FakeCli, id}; + use std::collections::BTreeMap; + + const LATEST: &str = "ghcr.io/hyperstructure/sandbox:latest"; + + fn name(tag: &str) -> String { + format!("{IMAGE_REPOSITORY}:{tag}") + } + + fn info(id: &str, published: bool) -> ImageInfo { + let labels = if published { + BTreeMap::from([(REVISION_LABEL.to_owned(), "12685ad".to_owned())]) + } else { + BTreeMap::new() + }; + ImageInfo { + id: id.into(), + labels, + } + } + + #[test] + fn removes_what_sessions_no_longer_start_from() { + let image = name("0.5.0"); + let here = [ + (image.clone(), info("sha256:aa", true)), + (name("latest"), info("sha256:bb", true)), + (name("0.4.0"), info("sha256:cc", true)), + (name("0.6.0-rc.1"), info("sha256:dd", true)), + (name("0.3.0"), info("sha256:ee", false)), + (name("0.5"), info("sha256:aa", true)), + (name("dev"), info("sha256:ff", true)), + (name("0.5.0-replaced-0011"), info("sha256:0011", true)), + (name("0.5.0-replaced-aa"), info("sha256:aa", true)), + ("ghcr.io/acme/agent:0.4.0".into(), info("sha256:99", true)), + ]; + assert_eq!( + removable(&image, Some(LATEST), &here), + [ + name("latest"), + name("0.4.0"), + name("0.6.0-rc.1"), + name("0.5.0-replaced-0011"), + ] + ); + // A build without the label stays, even as `latest`. + let here = [ + (image.clone(), info("sha256:aa", true)), + (name("latest"), info("sha256:bb", false)), + ]; + assert!(removable(&image, Some(LATEST), &here).is_empty()); + } + + #[test] + fn keeps_latest_while_the_versions_image_is_not_here() { + let image = name("0.5.0"); + let mut here = vec![ + (name("latest"), info("sha256:bb", true)), + (name("0.4.0"), info("sha256:cc", true)), + // A pull of `latest` under way. + (name("latest-replaced-bb"), info("sha256:bb", true)), + ]; + assert_eq!(removable(&image, Some(LATEST), &here), [name("0.4.0")]); + here.push((image.clone(), info("sha256:aa", true))); + assert_eq!( + removable(&image, Some(LATEST), &here), + [name("latest"), name("0.4.0"), name("latest-replaced-bb")] + ); + } + + #[test] + fn knows_a_version_when_it_sees_one() { + for tag in ["0.5.0", "10.20.30", "0.6.0-rc.1"] { + assert!(is_version(tag), "{tag}"); + } + for tag in [ + "0.5", "latest", "1.2.3.4", "v0.5.0", "0.5.x", "", "..", "0.5.0.", + ] { + assert!(!is_version(tag), "{tag}"); + } + } + + #[test] + fn names_a_replaced_build_after_its_id() { + let image = name("0.5.0"); + let id = "sha256:4f1c0ab2d3e5f60718293a4b5c6d7e8f"; + assert_eq!( + replaced_name(&image, id), + format!("{image}-replaced-4f1c0ab2d3e5") + ); + // Podman's IDs have no algorithm. + assert_eq!( + replaced_name(&image, "4f1c0ab2d3e5f607"), + format!("{image}-replaced-4f1c0ab2d3e5") + ); + assert_eq!( + describe(&format!("{image}-replaced-4f1c0ab2d3e5")), + format!("a build of {image} that a newer one replaced") + ); + assert_eq!(describe(&name("0.4.0")), name("0.4.0")); + } + + /// The host's image, a stand-in CLI without images, and its driver. + fn setup(flavor: Flavor) -> Result<(String, FakeCli, Driver)> { + let cli = FakeCli::empty()?; + let driver = cli.host_driver(flavor); + Ok((crate::config::default_image(), cli, driver)) + } + + #[tokio::test] + async fn the_host_pulls_a_newer_build_and_removes_the_old_one_once_unused() -> Result<()> { + let cfg = HostConfig::default(); + let (image, cli, driver) = setup(Flavor::Docker)?; + let (old, new) = (id("old"), id("new")); + cli.have(&image, &old, Some("2.1.302"))?; + cli.publish(&image, &new, "2.1.310")?; + cli.uses("fctl-ses-1", &old)?; + refresh(&driver, &cfg).await; + let kept = replaced_name(&image, &old); + assert_eq!( + cli.images()?, + [(image.clone(), new.clone()), (kept.clone(), old.clone())] + ); + // A stopped sandbox keeps the build it was made from. + assert!(clean_up(&driver, &cfg).await.is_empty()); + assert_eq!(cli.images()?.len(), 2); + // Once the sweep removed it, the build goes. + cli.drop_container("fctl-ses-1")?; + assert_eq!(clean_up(&driver, &cfg).await, [kept]); + assert_eq!(cli.images()?, [(image.clone(), new.clone())]); + Ok(()) + } + + #[tokio::test] + async fn the_host_leaves_a_current_build_as_it_is() -> Result<()> { + let cfg = HostConfig::default(); + let (image, cli, driver) = setup(Flavor::Docker)?; + let build = id("build"); + cli.have(&image, &build, Some("2.1.302"))?; + cli.publish(&image, &build, "2.1.302")?; + refresh(&driver, &cfg).await; + assert_eq!(cli.images()?, [(image.clone(), build.clone())]); + let kept = replaced_name(&image, &build); + assert_eq!( + cli.calls(), + [ + format!("image inspect {image}"), + format!("image inspect {image}"), + format!("image tag {image} {kept}"), + format!("pull {image}"), + format!("image inspect {image}"), + format!("image rm {kept}"), + ] + ); + Ok(()) + } + + #[tokio::test] + async fn only_a_person_pulls_over_a_build_of_the_hosts_own() -> Result<()> { + let cfg = HostConfig::default(); + let (image, cli, driver) = setup(Flavor::Docker)?; + let (built, published) = (id("built"), id("published")); + cli.have(&image, &built, None)?; + cli.publish(&image, &published, "2.1.310")?; + refresh(&driver, &cfg).await; + assert_eq!(cli.images()?, [(image.clone(), built.clone())]); + assert!(!cli.calls().iter().any(|c| c.contains("pull"))); + assert!(clean_up(&driver, &cfg).await.is_empty()); + + let log = |_: String| {}; + let pulled = pull(&driver, &cfg, false, &log).await?; + assert_eq!(pulled.image, image); + let newer = pulled.newer.map(|n| n.id); + assert_eq!(newer.as_deref(), Some(published.as_str())); + // The build it replaced is the person's: it has no name to remove it by. + assert_eq!(pulled.replaced, None); + assert_eq!(cli.images()?, [(image, published)]); + Ok(()) + } + + #[tokio::test] + async fn a_build_over_the_published_image_leaves_it_to_the_clean_up() -> Result<()> { + let cfg = HostConfig::default(); + let (image, cli, driver) = setup(Flavor::Docker)?; + let published = id("published"); + cli.have(&image, &published, Some("2.1.302"))?; + let failed = async { Err::<(), _>(anyhow::anyhow!("the build failed")) }; + assert!(replacing(&driver, &image, failed).await.is_err()); + assert_eq!(cli.images()?, [(image.clone(), published.clone())]); + + // What `fctl host image build` does to the image's name. + let build = async { cli.have(&image, &id("built"), None) }; + let replaced = replacing(&driver, &image, build).await?; + let kept = replaced_name(&image, &published); + assert_eq!(replaced.name.as_deref(), Some(kept.as_str())); + assert_eq!(clean_up(&driver, &cfg).await, [kept.as_str()]); + assert_eq!(cli.images()?, [(image, id("built"))]); + Ok(()) + } + + #[tokio::test] + async fn latest_goes_once_the_versions_image_is_here() -> Result<()> { + let cfg = HostConfig::default(); + let (image, cli, driver) = setup(Flavor::Docker)?; + // A release's image is published within the hour after the release. + cli.publish(LATEST, &id("previous release"), "2.1.302")?; + refresh(&driver, &cfg).await; + assert_eq!(cli.images()?, [(LATEST.to_owned(), id("previous release"))]); + assert!(clean_up(&driver, &cfg).await.is_empty()); + + cli.publish(&image, &id("release"), "2.1.310")?; + refresh(&driver, &cfg).await; + assert_eq!(clean_up(&driver, &cfg).await, [LATEST]); + assert_eq!(cli.images()?, [(image, id("release"))]); + Ok(()) + } + + #[tokio::test] + async fn after_an_upgrade_the_versions_before_go() -> Result<()> { + let cfg = HostConfig::default(); + let (image, cli, driver) = setup(Flavor::Docker)?; + cli.have(&image, &id("current"), Some("2.1.310"))?; + cli.publish(&image, &id("current"), "2.1.310")?; + cli.have(&name("0.0.1"), &id("0.0.1"), Some("2.1.200"))?; + cli.have(&name("0.0.2"), &id("0.0.2"), Some("2.1.250"))?; + cli.have(&name("0.0.3"), &id("0.0.3"), None)?; + cli.have(&name("0.0"), &id("0.0.2"), Some("2.1.250"))?; + cli.uses("fctl-ses-1", &id("0.0.1"))?; + refresh(&driver, &cfg).await; + // `0.0` names the build of 0.0.2 too, so removing `0.0.2` untags it. + assert_eq!(clean_up(&driver, &cfg).await, [name("0.0.2")]); + assert_eq!( + cli.images()?, + [ + (name("0.0"), id("0.0.2")), + (name("0.0.1"), id("0.0.1")), + (name("0.0.3"), id("0.0.3")), + (image, id("current")), + ] + ); + Ok(()) + } + + #[tokio::test] + async fn apple_removes_a_replaced_build_that_a_sandbox_was_made_from() -> Result<()> { + // Each container has a copy of the image's filesystem. + let cfg = HostConfig::default(); + let (image, cli, driver) = setup(Flavor::Apple)?; + let (old, new) = (id("old"), id("new")); + cli.have(&image, &old, Some("2.1.302"))?; + cli.publish(&image, &new, "2.1.310")?; + cli.uses("fctl-ses-1", &old)?; + let log = |_: String| {}; + let pulled = pull(&driver, &cfg, false, &log).await?; + let kept = replaced_name(&image, &old); + assert_eq!(pulled.replaced.as_deref(), Some(kept.as_str())); + assert_eq!(clean_up(&driver, &cfg).await, [kept.as_str()]); + assert_eq!(cli.images()?, [(image.clone(), new)]); + let calls = cli.calls(); + for call in [ + format!("image tag {image} {kept}"), + "image list --quiet".to_owned(), + format!("image delete {kept}"), + ] { + assert!(calls.contains(&call), "{call} in {calls:?}"); + } + let pulled = + |c: &String| c.starts_with("image pull --platform linux/") && c.ends_with(&image); + assert!(calls.iter().any(pulled), "{calls:?}"); + Ok(()) + } + + #[tokio::test] + async fn hosts_on_another_image_leave_the_default_ones_alone() -> Result<()> { + let cfg = HostConfig { + image: Some("ghcr.io/acme/agent:1".into()), + ..HostConfig::default() + }; + let (image, cli, driver) = setup(Flavor::Docker)?; + cli.have("ghcr.io/acme/agent:1", &id("acme"), Some("2.1.302"))?; + cli.publish("ghcr.io/acme/agent:1", &id("acme 2"), "2.1.310")?; + cli.have(&image, &id("default"), Some("2.1.302"))?; + cli.have(&name("0.0.1"), &id("0.0.1"), Some("2.1.200"))?; + refresh(&driver, &cfg).await; + assert!(clean_up(&driver, &cfg).await.is_empty()); + assert_eq!(cli.images()?.len(), 3); + assert!(!cli.calls().iter().any(|c| c.contains("pull"))); + Ok(()) + } +} diff --git a/crates/fctl/src/cmd/host.rs b/crates/fctl/src/cmd/host.rs index f71fc798..48b48f69 100644 --- a/crates/fctl/src/cmd/host.rs +++ b/crates/fctl/src/cmd/host.rs @@ -8,7 +8,7 @@ use clap::Subcommand; use fctl_domain::{image, size}; use fctl_host::config::means_default_image; use fctl_host::driver::Driver; -use fctl_host::{HostConfig, service}; +use fctl_host::{HostConfig, refresh, service}; use fctl_proto::api::{RunnerDetail, RunnerStatus}; use std::io::IsTerminal; @@ -387,16 +387,22 @@ pub async fn run(server: Option<&str>, cmd: HostCmd, json: bool) -> Result<()> { } }; // The default image falls back to `latest` until its version's is published. - let pulled = d - .pull_or_fallback(&image, cfg.fallback_image().as_deref(), !json, ¬e) - .await?; - let instead_of = (pulled != image).then_some(&image); + let pulled = refresh::pull(&d, &cfg, !json, ¬e).await?; + let removed = refresh::clean_up(&d, &cfg).await; + let instead_of = (pulled.image != image).then_some(&image); if json { - return style::print_json( - &serde_json::json!({ "image": pulled, "instead_of": instead_of }), - ); + return style::print_json(&serde_json::json!({ + "image": pulled.image, + "instead_of": instead_of, + "newer": pulled.newer.is_some(), + "removed": removed, + })); } - println!("{} Pulled {pulled}", style::accent("✓")); + let newer = match &pulled.newer { + Some(build) => format!(", a newer build{}", refresh::claude_code(build)), + None => String::new(), + }; + println!("{} Pulled {}{newer}", style::accent("✓"), pulled.image); if instead_of.is_some() { println!( " {}", @@ -405,6 +411,20 @@ pub async fn run(server: Option<&str>, cmd: HostCmd, json: bool) -> Result<()> { )) ); } + for name in &removed { + let what = refresh::describe(name); + println!(" {}", style::dim(&format!("Removed {what}"))); + } + if let Some(name) = &pulled.replaced + && !removed.contains(name) + { + println!( + " {}", + style::dim( + "The build it replaced stays until no sandbox uses it; the host removes it then." + ) + ); + } Ok(()) } HostCmd::Image(ImageCmd::Build { @@ -780,8 +800,15 @@ async fn doctor() -> Result<()> { && d.probe().await.available { let image = cfg.image(); - if d.has_image(&image).await { - check(true, &format!("sandbox image {image}"), ""); + if let Ok(Some(here)) = d.image(&image).await { + let detail = if refresh::published(&here) { + refresh::claude_code(&here) + } else if cfg.image.is_none() { + " (built here: the host doesn't pull over it)".into() + } else { + String::new() + }; + check(true, &format!("sandbox image {image}{detail}"), ""); } else { let meanwhile = match cfg.fallback_image() { Some(f) if d.has_image(&f).await => { diff --git a/docs/architecture.md b/docs/architecture.md index d018faaa..b6875fc4 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -559,11 +559,16 @@ sets another, the default image of the host's own version, workflow publishes it for arm64 and amd64 within the hour after every release, and rebuilds the latest release's when Claude Code has a newer release, since fctl turns off Claude Code's auto-updater. The host pulls the -image when it starts and when a sandbox needs one it doesn't have, never -over one it has, and falls back to `latest` when its version's can't be -pulled ([Sandbox images](sandbox-images.md)). `fctl host image build` -builds it on the host instead, from that repository's `main`, which it -downloads; the Lima driver's base VM gets the image's `provision.sh`. +image when it starts and when a sandbox needs one it doesn't have, and falls +back to `latest` when its version's can't be pulled. On the default image, +it pulls its tag again when it starts and every 6 hours, unless the image +there was built on the host: only the Image workflow sets the +`org.opencontainers.image.revision` label. It also removes the default +images that sessions no longer start from, without force, so that Docker +keeps those a sandbox uses (`crates/fctl-host/src/refresh.rs`, +[Sandbox images](sandbox-images.md)). `fctl host image build` builds it on +the host instead, from that repository's `main`, which it downloads; the +Lima driver's base VM gets the image's `provision.sh`. A project names an image (`ProjectSettings.image`) or a file in its repository to build one from (`image_build`: a Dockerfile and its context, diff --git a/docs/cli.md b/docs/cli.md index e3218c57..1b7f0e4b 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -182,7 +182,7 @@ fctl host run # run in the foreground (what the service runs) fctl host status # with the runner's sessions, and whether it drains fctl host doctor # check the driver, image, agent binary, connection fctl host logs -n 200 -fctl host image pull # pull the sandbox image again, for a newer build +fctl host image pull # pull the sandbox image again now (the host does every 6 hours) fctl host image build # build it here instead (with Lima: the base VM) fctl host image build --source ~/src/sandbox # from a checkout of hyperstructure/sandbox fctl host restart # sessions keep running diff --git a/docs/sandbox-images.md b/docs/sandbox-images.md index 0187c8b3..c53f6ddd 100644 --- a/docs/sandbox-images.md +++ b/docs/sandbox-images.md @@ -36,7 +36,7 @@ Its labels say what is inside: |---|---| | `org.opencontainers.image.version`, `sh.fctl.version` | fctl's version | | `sh.fctl.claude-code.version` | Claude Code's version | -| `org.opencontainers.image.revision` | the commit of hyperstructure/sandbox it was built from | +| `org.opencontainers.image.revision` | the commit of hyperstructure/sandbox it was built from; images built elsewhere have none | | `org.opencontainers.image.created` | when it was built | ```sh @@ -55,28 +55,41 @@ before its image is published, the host pulls `latest` instead, and sessions start from it and say so in their log. The first session after the version's image is published pulls it. -The host pulls a tag once. To get a newer build of it, with a newer Claude -Code, run `fctl host image pull`. While the version's image can't be -pulled, it pulls `latest` instead, and says so. +The host pulls its tag again when it starts and every 6 hours, so new +sessions start from the newest build of it, with the newest Claude Code. +Sessions don't wait for that: they start from the build that is there, and +a tag that hasn't changed costs one request to ghcr.io. `fctl host image +pull` pulls it now. While the version's image can't be pulled, it pulls +`latest` instead, and says so. - **Another image.** `image` in `host.toml` (or `fctl host install --image …`) sets the image for sessions whose project sets none, and a project can choose one for its own sessions ([Your own image](#your-own-image)). `fctl-agent:latest`, the name the default - image had when hosts built it themselves, means the default. + image had when hosts built it themselves, means the default. On another + image, the host pulls it when it isn't there, only `fctl host image pull` + pulls it again, and the host leaves the default image's tags alone. - **Building it.** `fctl host image build` builds the default image on the host with its driver, from the `main` branch of hyperstructure/sandbox, under the same name, so sessions use the build: for a host that can't reach ghcr.io, for instance. `--source DIR` builds from a checkout of the repository instead, to try changes to the image with fctl. The host never - replaces a build with the published image; `fctl host image pull` does. + replaces a build with the published image, which it tells apart by its + `org.opencontainers.image.revision` label; `fctl host image pull` does. - **Lima** sessions clone the `fctl-base` VM instead, which `fctl host image build` prepares with the image's provisioning script. The process driver uses no image. -- **Disk.** The images of earlier versions stay on the host until you - remove them: `docker image rm ghcr.io/hyperstructure/sandbox:0.4.0` - (with Apple container, `container image delete`) removes one that no - sandbox uses. +- **Disk.** The host removes the default images that sessions no longer + start from: builds that a newer one replaced, other versions' images, and + `latest` once the version's image is there. It does that when it starts, + after each pull and after the sweep removes stopped sandboxes, and leaves + images built on the host and tags it doesn't pull, like `0.4`, alone. It + removes them without force: with Docker, an image that a sandbox uses, + stopped ones too, stays until the sweep removes the sandbox + (`keep_stopped_hours`), and a build that a newer one replaced keeps the + name `-replaced-` until then. Apple's + `container` gives each sandbox its own copy of the image's filesystem, + so the host removes them right away, and stopped sandboxes still start. ## Its layout