diff --git a/CHANGELOG.md b/CHANGELOG.md index 28fcab1d..b9533209 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed + +- **`rm` and `kill` remove a workspace's compose volumes when its containers are gone.** + A workspace whose containers were already gone (`NotFound` in `dl --ls`) left its + `_bazel-output` and every other compose volume behind. `kill` now finds a compose + workspace's running containers by devpod's uid instead of by the workspace id. See + [Every other volume only the workspace used](docs/cleanup.md#every-other-volume-only-the-workspace-used) + for which volumes go. + ## [0.64.2] - 2026-10-31 ### Fixed diff --git a/docs/cleanup.md b/docs/cleanup.md index aef9bc49..49d1e180 100644 --- a/docs/cleanup.md +++ b/docs/cleanup.md @@ -68,8 +68,24 @@ hold: - **No container that is left uses it.** dl asks Docker after the workspace's own containers are gone, so a volume another workspace still mounts stays. - **It is the workspace's own.** Compose made it for the workspace's project under - compose's default name, `_`, or its name holds the workspace id or - devpod's uid as a whole part, as `-pixi` does. + compose's default name, `_`, or its name holds one of devpod's uids + for the workspace as a whole part, as `dind-var-lib-docker-` does. A name that + holds the workspace id as a whole part, as `-pixi` does, counts only when a + container of devpod's current uid mounts it and dl read devpod's create result for + that uid: only that result says which names the config spells literally. + +A compose volume is also found by its label, not only by what mounts it. A volume compose +made for one of the workspace's projects under the default name `_` is +the workspace's own even when no container is left to mount it, as when `dl --ls` shows +the workspace `NotFound`. The workspace's projects are devpod's current uid for it, every +older uid dl kept from an earlier `up` (devpod makes a record again under a new uid, and +the old project's volumes keep the old one), and the project of each leftover container +the delete removes that devpod made for this workspace. dl keeps the older uids by +workspace id alone, so when two devpod contexts hold the same id, dl reads none of them: +an older uid may be the other context's workspace. A leftover project somebody +started by hand in the clone is named after its folder, and `_` is shared +by every folder of that name, so its volumes stay. A volume of the workspace's own that stays because another container +still uses it is named on stderr, with the command that finds that container. Two kinds of volume are shared on purpose and always stay: a name the devcontainer config spells literally, with no `${...}` in it (`team-tracker-pixi`), and a volume compose made @@ -86,7 +102,8 @@ Keeping a volume can be undone; deleting a shared one cannot. A volume created b compose ran, and not marked external, has no compose label: it stays only when its name holds neither the workspace id nor devpod's uid. Each volume removed is named on stderr. A volume Docker will not remove is a line, never a failed delete. A delete that the guard refuses, that devpod -refuses, or a `kill` whose `devpod delete` times out, removes no volume. `stop`, `up`, `recreate` and `--refresh-stale` never +refuses, or a `kill` whose `devpod delete` times out, removes no volume, except the +compose volumes of leftover containers the delete itself removed. `stop`, `up`, `recreate` and `--refresh-stale` never run this, so the caches a recreate keeps stay. ### The volumes of a workspace devpod has already forgotten diff --git a/rust/devlaunch-core/public-api.api.txt b/rust/devlaunch-core/public-api.api.txt index 437a6e13..3cd04532 100644 --- a/rust/devlaunch-core/public-api.api.txt +++ b/rust/devlaunch-core/public-api.api.txt @@ -208,6 +208,9 @@ pub devlaunch_core::api::LifecycleNotice::VolumesNotRemoved pub devlaunch_core::api::LifecycleNotice::VolumesNotRemoved::occasion: devlaunch_core::flows::lifecycle::SweepOccasion pub devlaunch_core::api::LifecycleNotice::VolumesNotRemoved::refusal: devlaunch_core::flows::lifecycle::VolumeRefusal pub devlaunch_core::api::LifecycleNotice::VolumesNotRemoved::workspace_id: alloc::string::String +pub devlaunch_core::api::LifecycleNotice::WorkspaceVolumeInUse +pub devlaunch_core::api::LifecycleNotice::WorkspaceVolumeInUse::name: alloc::string::String +pub devlaunch_core::api::LifecycleNotice::WorkspaceVolumeInUse::workspace_id: alloc::string::String pub devlaunch_core::api::LifecycleNotice::WorkspaceVolumeNotRemoved pub devlaunch_core::api::LifecycleNotice::WorkspaceVolumeNotRemoved::name: alloc::string::String pub devlaunch_core::api::LifecycleNotice::WorkspaceVolumeNotRemoved::reason: alloc::string::String @@ -900,6 +903,9 @@ pub devlaunch_core::flows::lifecycle::LifecycleNotice::VolumesNotRemoved pub devlaunch_core::flows::lifecycle::LifecycleNotice::VolumesNotRemoved::occasion: devlaunch_core::flows::lifecycle::SweepOccasion pub devlaunch_core::flows::lifecycle::LifecycleNotice::VolumesNotRemoved::refusal: devlaunch_core::flows::lifecycle::VolumeRefusal pub devlaunch_core::flows::lifecycle::LifecycleNotice::VolumesNotRemoved::workspace_id: alloc::string::String +pub devlaunch_core::flows::lifecycle::LifecycleNotice::WorkspaceVolumeInUse +pub devlaunch_core::flows::lifecycle::LifecycleNotice::WorkspaceVolumeInUse::name: alloc::string::String +pub devlaunch_core::flows::lifecycle::LifecycleNotice::WorkspaceVolumeInUse::workspace_id: alloc::string::String pub devlaunch_core::flows::lifecycle::LifecycleNotice::WorkspaceVolumeNotRemoved pub devlaunch_core::flows::lifecycle::LifecycleNotice::WorkspaceVolumeNotRemoved::name: alloc::string::String pub devlaunch_core::flows::lifecycle::LifecycleNotice::WorkspaceVolumeNotRemoved::reason: alloc::string::String diff --git a/rust/devlaunch-core/src/clients/docker.rs b/rust/devlaunch-core/src/clients/docker.rs index c3573775..b8f4848a 100644 --- a/rust/devlaunch-core/src/clients/docker.rs +++ b/rust/devlaunch-core/src/clients/docker.rs @@ -204,6 +204,9 @@ pub(crate) struct ComposeContainer { pub(crate) working_dir: Option, /// `com.docker.compose.project.config_files`, split on its commas. pub(crate) config_files: Vec, + /// `com.docker.compose.project`: the project compose made it for, which names + /// the compose volumes the project made (`_`). + pub(crate) project: Option, } impl ComposeContainer { @@ -229,7 +232,8 @@ pub(crate) enum Unlisted { /// line per container. const COMPOSE_FORMAT: &str = "{{.ID}}\t{{.Names}}\t\ {{.Label \"com.docker.compose.project.working_dir\"}}\t\ -{{.Label \"com.docker.compose.project.config_files\"}}"; +{{.Label \"com.docker.compose.project.config_files\"}}\t\ +{{.Label \"com.docker.compose.project\"}}"; /// Every container on this machine that a compose project made, running or not. pub(crate) fn compose_containers(runner: &dyn Runner) -> Result, Unlisted> { @@ -547,11 +551,17 @@ fn compose_container(line: &str) -> Option { .filter(|file| !file.is_empty()) .map(PathBuf::from) .collect(); + let project = fields + .next() + .map(str::trim) + .filter(|project| !project.is_empty()) + .map(str::to_owned); Some(ComposeContainer { id: id.to_owned(), name: name.to_owned(), working_dir, config_files, + project, }) } diff --git a/rust/devlaunch-core/src/flows/kept_copies.rs b/rust/devlaunch-core/src/flows/kept_copies.rs index e2a86a04..06060921 100644 --- a/rust/devlaunch-core/src/flows/kept_copies.rs +++ b/rust/devlaunch-core/src/flows/kept_copies.rs @@ -63,6 +63,9 @@ use crate::domain::workspace_state::NonEmpty; /// conditions, and a reader of either can see at a glance which it is holding. const COPIES_DIR: &str = "workspace-copies"; +/// The docker-in-docker feature's volume name, before the uid devpod substitutes. +const DIND_PREFIX: &str = "dind-var-lib-docker-"; + /// Where devlaunch keeps its copies of what devpod substituted. /// /// A path parameter rather than a read of the process environment, for @@ -122,13 +125,24 @@ impl KeptCopies { let Ok(bytes) = std::fs::read(&result) else { return; }; - let recorded = parse_result(&bytes); + let mut recorded = parse_result(&bytes); if recorded.is_empty() { // Nothing devpod substituted and no image it named: a document this // could not read is a document it copies nothing out of, which leaves - // the workspace exactly where it was before the copy existed. + // the workspace exactly where it was before the copy existed. Asked + // before the kept uids join it, so they cannot make it look worth + // writing over the copy that is there. return; } + // The uids of every earlier record go first: devpod forgets them when it + // makes a record again, and their compose volumes still carry them. + let mut uids = self.uids(workspace_id); + for uid in recorded.uids.drain(..) { + if !uids.contains(&uid) { + uids.push(uid); + } + } + recorded.uids = uids; let Ok(text) = serde_json::to_string(&recorded) else { return; }; @@ -147,6 +161,31 @@ impl KeptCopies { NonEmpty::of(read_copy(&self.copy_path(workspace_id))?.volumes) } + /// Every uid devpod gave this workspace, oldest first, or nothing where there + /// is no copy to read. + /// + /// devpod names the compose project after the uid, so each one names the + /// compose volumes a record of this workspace made. A copy written before uids + /// were kept still names its last one, inside the dind volume name devpod + /// substituted it into — a value devpod wrote down, not a guess. + pub(crate) fn uids(&self, workspace_id: &str) -> Vec { + let Some(copy) = read_copy(&self.copy_path(workspace_id)) else { + return Vec::new(); + }; + let mut uids = copy.uids; + for uid in copy + .volumes + .iter() + .filter_map(|name| name.strip_prefix(DIND_PREFIX)) + .filter(|uid| !uid.is_empty()) + { + if !uids.iter().any(|known| known == uid) { + uids.push(uid.to_owned()); + } + } + uids + } + /// Every workspace this cache holds a copy for, sorted. /// /// The reclaim's domain, and it is deliberately not a walk of the clone @@ -213,12 +252,21 @@ struct Copy { /// stays distinguishable from one devpod derived; a devcontainer built from a /// Dockerfile declares none. declared_image: Option, + /// Every `SubstitutionContext.DevContainerID` a completed `up` recorded, oldest + /// first. devpod names the compose project after it, so it is what names the + /// compose volumes of a record devpod has since made again or forgotten. + /// `default` so a copy written before this field still reads. + #[serde(default)] + uids: Vec, } impl Copy { /// Whether this copy would say nothing at all, in which case none is written. fn is_empty(&self) -> bool { - self.volumes.is_empty() && self.image.is_none() && self.declared_image.is_none() + self.volumes.is_empty() + && self.image.is_none() + && self.declared_image.is_none() + && self.uids.is_empty() } } @@ -237,8 +285,10 @@ fn parse_result(bytes: &[u8]) -> Copy { let Ok(document) = serde_json::from_slice::(bytes) else { return Copy::default(); }; + let substitutions = substitutions_in(&document); Copy { - volumes: substitutions_in(&document).volume_names(), + volumes: substitutions.volume_names(), + uids: substitutions.devcontainer_id.clone().into_iter().collect(), image: non_empty_string(&document["ContainerDetails"]["Config"]["Image"]), declared_image: non_empty_string(&document["MergedConfig"]["image"]), } @@ -451,6 +501,76 @@ mod tests { assert_eq!(copies.copied(), Vec::::new()); } + /// devpod's uid for the workspace is kept too: it is the compose project + /// name, so it names every compose volume the workspace made. + #[test] + fn a_completed_up_keeps_the_workspaces_uid() { + let (_dir, copies) = a_cache(); + let home = a_completed_up("myws", "/repos/o/r/repo-main-ab12", "default-my-aaaaa"); + + copies.keep("myws", Some(&home)); + + assert_eq!(copies.uids("myws"), ["default-my-aaaaa"]); + } + + /// A record devpod made again gets a new uid, and the old project's volumes + /// still carry the old one. The copy keeps both, oldest first, so a later + /// delete can still name the old project's volumes. + #[test] + fn a_new_uid_does_not_drop_the_old_one() { + let (_dir, copies) = a_cache(); + let old = a_completed_up("myws", "/repos/o/r/repo-main-ab12", "default-my-aaaaa"); + copies.keep("myws", Some(&old)); + let new = a_completed_up("myws", "/repos/o/r/repo-main-ab12", "default-my-bbbbb"); + copies.keep("myws", Some(&new)); + copies.keep("myws", Some(&new)); + + assert_eq!( + copies.uids("myws"), + ["default-my-aaaaa", "default-my-bbbbb"] + ); + assert_eq!( + names(&copies, "myws"), + [ + "repo-main-ab12-pixi", + "dind-var-lib-docker-default-my-bbbbb" + ] + ); + } + + /// A later result that names nothing devpod substituted leaves the copy as + /// it was. Before, the kept uids alone made it look like a copy worth + /// writing, and it replaced the volume names with nothing. + #[test] + fn a_result_that_names_nothing_leaves_the_copy_with_uids_alone() { + let (_dir, copies) = a_cache(); + let up = a_completed_up("myws", "/repos/o/r/repo-main-ab12", "default-my-aaaaa"); + copies.keep("myws", Some(&up)); + let before = (copies.uids("myws"), names(&copies, "myws")); + let unreadable = a_result("myws", serde_json::json!({})); + copies.keep("myws", Some(&unreadable)); + + assert_eq!((copies.uids("myws"), names(&copies, "myws")), before); + assert!(!before.1.is_empty()); + } + + /// A copy written before uids were kept still names its uid, in the dind + /// volume name devpod substituted it into. + #[test] + fn a_copy_from_before_uids_were_kept_names_its_uid_through_the_dind_volume() { + let (dir, copies) = a_cache(); + let store = dir.path().join(COPIES_DIR); + std::fs::create_dir_all(&store).expect("a store"); + std::fs::write( + store.join("legacy.json"), + r#"{"volumes":["repo-pixi","dind-var-lib-docker-default-re-ccccc"],"image":null,"declared_image":null}"#, + ) + .expect("a legacy copy"); + + assert_eq!(copies.uids("legacy"), ["default-re-ccccc"]); + assert_eq!(copies.uids("never-written"), Vec::::new()); + } + /// The image reference rides on the same copy, read from the same document at /// the same moment (devlaunch#450), and the two references stay apart: what the /// container ran, and what the devcontainer named. diff --git a/rust/devlaunch-core/src/flows/kill.rs b/rust/devlaunch-core/src/flows/kill.rs index 77d4bae3..485a94ce 100644 --- a/rust/devlaunch-core/src/flows/kill.rs +++ b/rust/devlaunch-core/src/flows/kill.rs @@ -45,6 +45,7 @@ use crate::clients::devpod_home::{self as devpod_home, DevpodHome}; use crate::clients::docker; use crate::clients::kill::{self as signals, Sent, Signal}; use crate::clients::ps; +use crate::flows::workspace_volumes; pub use crate::clients::ps::HostProcess; use crate::domain::workspace_state::NonEmpty; @@ -759,7 +760,14 @@ pub fn workspace_kill( Killed::Swept(Sweep { signalled, marker: sweep_marker(devpod_home, workspace_id, &holding), - containers: kill_containers(runner, workspace_id, &holding), + containers: kill_containers( + runner, + // devpod names the compose project after its uid, not the id. With + // no uid on record, the id is the only name left to try. + &workspace_volumes::workspace_uid(devpod_home, workspace_id) + .unwrap_or_else(|| workspace_id.to_owned()), + &holding, + ), holding, }) } @@ -903,11 +911,11 @@ fn sweep_holders( /// /// The listing comes first because a project with nothing running is the common /// case and a `docker kill` with no arguments is an error rather than a no-op. -fn kill_containers(runner: &dyn Runner, workspace_id: &str, holding: &Holding) -> Containers { +fn kill_containers(runner: &dyn Runner, project: &str, holding: &Holding) -> Containers { if holding.any_attended() { return Containers::LeftForALiveBuild; } - let ids = match docker::running_for_project(runner, workspace_id) { + let ids = match docker::running_for_project(runner, project) { docker::Running::These(ids) => ids, docker::Running::NotInstalled => return Containers::NoDocker, docker::Running::Refused { exit, stderr } => { @@ -1809,6 +1817,33 @@ mod tests { ); } + /// devpod names the compose project after its uid for the workspace, not + /// after the workspace id. So the containers are found by the uid: a filter + /// on the id matched no compose container devpod ever made. + #[test] + fn the_containers_are_found_by_the_compose_project_devpod_named() { + let home = home_for("my-ws"); + std::fs::write( + home.record("default", "my-ws"), + serde_json::json!({ "id": "my-ws", "uid": "default-my-65da1" }).to_string(), + ) + .expect("a record"); + let fake = host_showing(NOTHING); + fake.script(["docker", "ps"], Response::stdout("abc123\n")); + + let sweep = swept(workspace_kill(&fake, Some(&home), "my-ws", &mut |_| {})); + + assert_eq!( + sweep.containers, + Containers::Killed(vec!["abc123".to_owned()]) + ); + let ps = &fake.args_to("docker")[0]; + assert!( + ps.contains(&"label=com.docker.compose.project=default-my-65da1".to_owned()), + "{ps:?}" + ); + } + /// The issue's own case: the container had exited 137 a minute before the /// restart, so a `docker kill` would have found nothing to kill. Nothing to /// kill is a finding, and it points at the process rather than the container. diff --git a/rust/devlaunch-core/src/flows/launch.rs b/rust/devlaunch-core/src/flows/launch.rs index 4dec0293..e93b6ed8 100644 --- a/rust/devlaunch-core/src/flows/launch.rs +++ b/rust/devlaunch-core/src/flows/launch.rs @@ -1341,17 +1341,19 @@ fn sweep_leftovers( workspace_id, clone, ) { - OrphanSweep::Removed(names) => notices.say(LaunchNotice::LeftoverContainersRemoved { - workspace_id: workspace_id.to_owned(), - names, - }), + OrphanSweep::Removed { names, .. } => { + notices.say(LaunchNotice::LeftoverContainersRemoved { + workspace_id: workspace_id.to_owned(), + names, + }) + } OrphanSweep::NotListed { reason } => { notices.say(LaunchNotice::LeftoverContainersNotListed { workspace_id: workspace_id.to_owned(), reason, }) } - OrphanSweep::NotRemoved { names, reason } => { + OrphanSweep::NotRemoved { names, reason, .. } => { notices.say(LaunchNotice::LeftoverContainersNotRemoved { workspace_id: workspace_id.to_owned(), names, diff --git a/rust/devlaunch-core/src/flows/lifecycle/delete.rs b/rust/devlaunch-core/src/flows/lifecycle/delete.rs index 39edf3ae..1da9ccc4 100644 --- a/rust/devlaunch-core/src/flows/lifecycle/delete.rs +++ b/rust/devlaunch-core/src/flows/lifecycle/delete.rs @@ -283,7 +283,12 @@ pub(crate) fn workspace_delete( // Read while the containers are still there: what they mount is the only // record of the volumes beyond the two above, and `devpod delete` takes the // containers away. Removed only once devpod has let go, below. - let mounted = workspace_volumes::record(context.runner(), devpod_home, workspace_id); + let mounted = workspace_volumes::record( + context.runner(), + devpod_home, + &copies.uids(workspace_id), + workspace_id, + ); // The lock line is answered the way a launch answers it (devlaunch#602): said, // and then *cleared*, by the same sweep `up` runs. It used to be said and // nothing more, with advice to run `kill` in another terminal, which left an @@ -322,13 +327,16 @@ pub(crate) fn workspace_delete( // `NotRun` here used to mean devpod was missing or would not exec. Err(NotRun::TimedOut) => { context.forget_workspaces(); - sweep_leftovers( + let leftover_projects = sweep_leftovers( context.runner(), devpod_home, workspace_id, clone_path.as_deref(), notices, ); + // The leftovers' containers are gone by this delete's hand whatever + // devpod did, so their volumes go with them here too. + sweep_leftover_volumes(context.runner(), workspace_id, &leftover_projects, notices); refresh.ask(context.runner(), RefreshReason::Forced); return Err(NotRun::TimedOut); } @@ -342,7 +350,7 @@ pub(crate) fn workspace_delete( // a delete devpod refused, which leaves the record, keeps its containers; a // `--force` delete that gave up on `compose down` and dropped the record // anyway does not leave them running. - sweep_leftovers( + let leftover_projects = sweep_leftovers( context.runner(), devpod_home, workspace_id, @@ -350,6 +358,7 @@ pub(crate) fn workspace_delete( notices, ); if !exit.is_success() { + sweep_leftover_volumes(context.runner(), workspace_id, &leftover_projects, notices); refresh.ask(context.runner(), RefreshReason::Forced); return Ok(RemoveOutcome::DevpodRefused { exit }); } @@ -386,7 +395,16 @@ pub(crate) fn workspace_delete( Err(error) } }; - let tried = sweep_mounted(context.runner(), workspace_id, mounted, notices); + let mut tried = sweep_mounted(context.runner(), workspace_id, mounted, notices); + // The leftovers swept above were made for compose projects of their own, an + // older uid of this workspace that may be in no copy. Their compose volumes + // are read now that the containers are gone, and go the same way. + tried.extend(sweep_leftover_volumes( + context.runner(), + workspace_id, + &leftover_projects, + notices, + )); let named = named.and_then(|names| { NonEmpty::of(names.iter().filter(|name| !tried.contains(*name)).cloned()) }); @@ -430,34 +448,61 @@ fn managed_clone( crate::domain::xdg::is_clone_of(clones.repos_dir(), &path, workspace_id).then_some(path) } -/// Remove the containers a deleted workspace left behind, and say so. +/// Remove the containers a deleted workspace left behind, and say so. Returns the +/// compose projects of the containers it removed, whose volumes are then the +/// delete's to sweep. fn sweep_leftovers( runner: &dyn Runner, devpod_home: Option<&DevpodHome>, workspace_id: &str, clone: Option<&Path>, notices: &mut dyn Notices, -) { +) -> BTreeSet { match orphan_containers::sweep(runner, devpod_home, workspace_id, clone) { - OrphanSweep::Removed(names) => notices.say(LifecycleNotice::LeftoverContainersRemoved { - workspace_id: workspace_id.to_owned(), - names, - }), + OrphanSweep::Removed { names, projects } => { + notices.say(LifecycleNotice::LeftoverContainersRemoved { + workspace_id: workspace_id.to_owned(), + names, + }); + return projects; + } OrphanSweep::NotListed { reason } => { notices.say(LifecycleNotice::LeftoverContainersNotListed { workspace_id: workspace_id.to_owned(), reason, }) } - OrphanSweep::NotRemoved { names, reason } => { + OrphanSweep::NotRemoved { + names, + reason, + projects, + } => { notices.say(LifecycleNotice::LeftoverContainersNotRemoved { workspace_id: workspace_id.to_owned(), names, reason, }); + return projects; } OrphanSweep::Nothing | OrphanSweep::NoDocker => {} } + BTreeSet::new() +} + +/// Remove the compose volumes of the leftover projects [`sweep_leftovers`] +/// removed the containers of, read now that those containers are gone. +fn sweep_leftover_volumes( + runner: &dyn Runner, + workspace_id: &str, + projects: &BTreeSet, + notices: &mut dyn Notices, +) -> BTreeSet { + sweep_mounted( + runner, + workspace_id, + workspace_volumes::record_projects(runner, workspace_id, projects), + notices, + ) } /// Remove the volumes only this workspace's containers used, and say what @@ -495,9 +540,15 @@ fn sweep_mounted( reason, }); } - // Something left uses it, so it is not this workspace's alone; and - // one already gone has nothing to say. - Swept::InUse(_) | Swept::Gone(_) => {} + // Something left uses it, so it is not this workspace's alone. It + // stays, and the line says so: a silent keep reads as nothing to + // remove, and the disk is not given back. + Swept::InUse(name) => notices.say(LifecycleNotice::WorkspaceVolumeInUse { + workspace_id: workspace_id.to_owned(), + name, + }), + // One already gone has nothing to say. + Swept::Gone(_) => {} } } if let Some(names) = NonEmpty::of(removed) { diff --git a/rust/devlaunch-core/src/flows/lifecycle/notices.rs b/rust/devlaunch-core/src/flows/lifecycle/notices.rs index 125c91f5..af5afd29 100644 --- a/rust/devlaunch-core/src/flows/lifecycle/notices.rs +++ b/rust/devlaunch-core/src/flows/lifecycle/notices.rs @@ -79,6 +79,10 @@ pub enum LifecycleNotice { name: String, reason: String, }, + /// One of this workspace's own volumes stays because a container that is + /// not the workspace's still uses it. Said so the volume is not left in + /// silence: the user can find the container and remove both. + WorkspaceVolumeInUse { workspace_id: String, name: String }, /// docker would not say what this workspace's containers mounted, or a /// compose file they were started from could not be read for its external /// volumes, so none of its own volumes beyond the two devlaunch names was diff --git a/rust/devlaunch-core/src/flows/lifecycle/tests.rs b/rust/devlaunch-core/src/flows/lifecycle/tests.rs index 16272846..177f343a 100644 --- a/rust/devlaunch-core/src/flows/lifecycle/tests.rs +++ b/rust/devlaunch-core/src/flows/lifecycle/tests.rs @@ -2745,7 +2745,7 @@ fn a_delete_removes_both_volumes_the_workspaces_devcontainer_created() { let (outcome, notices) = deleting.delete(); assert_eq!( - deleting.world.devpod.docker_argvs()[2..], + deleting.world.devpod.docker_argvs()[3..], [[ "volume", "rm", @@ -2796,9 +2796,22 @@ fn the_volumes_are_removed_after_devpod_has_let_go_of_the_workspace() { argvs, [ // What the containers mount, read while they are there; nothing - // mounts anything in this world, so nothing more is asked. + // mounts anything in this world, so only the compose volume labels + // are asked, for a volume of the project no container is left to + // mount. ps_filtered("label=dev.containers.id=dc9a8b7c"), ps_filtered("label=com.docker.compose.project=dc9a8b7c"), + [ + "docker", + "volume", + "ls", + "--filter", + "label=com.docker.compose.project", + "--format", + "{{.Name}}\t{{.Label \"com.docker.compose.project\"}}\t{{.Label \"com.docker.compose.volume\"}}", + ] + .map(str::to_owned) + .to_vec(), ["devpod", "delete", "r-main-aa"] .map(str::to_owned) .to_vec(), @@ -3050,6 +3063,190 @@ fn a_volume_something_else_still_uses_is_kept() { ); } +/// A volume of the workspace's own that something else still uses stays, and the +/// delete says so. It used to stay in silence, which read as "nothing to remove". +#[test] +fn a_volume_something_else_still_uses_is_named() { + let mut deleting = a_world_ready_to_delete().with_containers_mounting_a_cache(); + deleting.world.devpod.fake.script( + ps_filtered("volume=r-main-aa-cache"), + Response::stdout("other\n"), + ); + + let (_, notices) = deleting.delete(); + + assert!( + notices.contains(&LifecycleNotice::WorkspaceVolumeInUse { + workspace_id: "r-main-aa".to_owned(), + name: "r-main-aa-cache".to_owned(), + }), + "{notices:?}" + ); +} + +/// `volume ls` rows for project `project`: its own `bazel-output`, a volume +/// compose named on purpose, and another project's `bazel-output`. +fn bazel_output_rows(project: &str) -> String { + format!( + "{project}_bazel-output\t{project}\tbazel-output\n\ + named-cache\t{project}\tcache\n\ + someone-else_bazel-output\tsomeone-else\tbazel-output\n" + ) +} + +/// The leak from the field: the workspace's containers are gone (dl shows it +/// `NotFound`), so nothing mounts its compose volume. The volume still carries +/// compose's label for the workspace's project, and goes with the delete. +#[test] +fn a_delete_removes_the_compose_volume_of_a_workspace_with_no_container_left() { + let mut deleting = a_world_ready_to_delete(); + deleting.world.devpod.fake.script( + ["docker", "volume", "ls"], + Response::stdout(bazel_output_rows("dc9a8b7c")), + ); + + let (_, notices) = deleting.delete(); + + assert!( + notices.contains(&LifecycleNotice::WorkspaceVolumesRemoved { + workspace_id: "r-main-aa".to_owned(), + names: NonEmpty::one("dc9a8b7c_bazel-output".to_owned()), + }), + "{notices:?}" + ); + let docker = deleting.world.devpod.docker_argvs(); + assert!( + docker.contains(&vec![ + "volume".to_owned(), + "rm".to_owned(), + "dc9a8b7c_bazel-output".to_owned() + ]), + "{docker:?}" + ); + assert!( + !docker.iter().any(|argv| argv + .iter() + .any(|a| a == "named-cache" || a.starts_with("someone-else"))), + "{docker:?}" + ); +} + +/// devpod made the record again under a new uid. The uid an earlier `up` kept +/// still names the old project's volume, and the delete removes it too. +#[test] +fn a_delete_removes_the_compose_volume_of_a_uid_the_workspace_had_before() { + let mut deleting = a_world_ready_to_delete(); + let before = devpod_home_recording("r-main-aa", "/host/clones/opened-as", "dc0ld000"); + deleting.world.copies().keep("r-main-aa", Some(&before)); + deleting.world.devpod.fake.script( + ["docker", "volume", "ls"], + Response::stdout(bazel_output_rows("dc0ld000")), + ); + + let (_, notices) = deleting.delete(); + + assert!( + notices.contains(&LifecycleNotice::WorkspaceVolumesRemoved { + workspace_id: "r-main-aa".to_owned(), + names: NonEmpty::one("dc0ld000_bazel-output".to_owned()), + }), + "{notices:?}" + ); +} + +/// The delete removed a leftover container of another compose project (a uid +/// devlaunch kept no copy of). That project's compose volume goes with it. +#[test] +fn a_delete_removes_the_compose_volumes_of_the_leftovers_it_swept() { + let (outcome, notices) = delete_over_a_leftover(None); + + assert!( + matches!(outcome, Ok(RemoveOutcome::Deleted { .. })), + "{outcome:?}" + ); + assert_leftover_and_its_volume_removed(¬ices); +} + +/// `devpod delete` failed after the leftover sweep removed the containers. The +/// containers are gone by dl's hand all the same, so their volumes go too. +#[test] +fn a_delete_devpod_refused_still_removes_the_volumes_of_the_leftovers_it_swept() { + let (outcome, notices) = delete_over_a_leftover(Some(Response::exited(1))); + + assert!( + matches!(outcome, Ok(RemoveOutcome::DevpodRefused { .. })), + "{outcome:?}" + ); + assert_leftover_and_its_volume_removed(¬ices); +} + +fn assert_leftover_and_its_volume_removed(notices: &[LifecycleNotice]) { + assert!( + notices.contains(&LifecycleNotice::LeftoverContainersRemoved { + workspace_id: "myws".to_owned(), + names: NonEmpty::one("myws_dev".to_owned()), + }), + "{notices:?}" + ); + assert!( + notices.contains(&LifecycleNotice::WorkspaceVolumesRemoved { + workspace_id: "myws".to_owned(), + names: NonEmpty::one("dc0ld000_bazel-output".to_owned()), + }), + "{notices:?}" + ); +} + +/// Delete `myws`, which devpod holds no record of, over a leftover container of +/// project `dc0ld000` whose compose volume nothing else uses. `devpod_delete` +/// is how `devpod delete` answers, when not the fake's default. +fn delete_over_a_leftover( + devpod_delete: Option, +) -> (Result, Vec) { + let world = a_stopping_world(); + let home = devpod_home_with(&[]); + let override_file = agent_compose_file(&home, "default", "myws"); + if let Some(response) = devpod_delete { + world.devpod.fake.script(["devpod", "delete"], response); + } + world.devpod.fake.script( + ps_filtered("volume=dc0ld000_bazel-output"), + Response::stdout(""), + ); + world.devpod.fake.script( + ["docker", "ps"], + Response::stdout(format!( + "aaa\tmyws_dev\t/elsewhere\t{}\tdc0ld000\n", + override_file.display() + )), + ); + world.devpod.fake.script( + ["docker", "volume", "ls"], + Response::stdout(bazel_output_rows("dc0ld000")), + ); + let mut world_cache = World::empty(); + let clones = clones_for(&world_cache.repos_dir, &world_cache.devpod); + let mut context = CommandContext::new(&world.devpod); + let mut refresh = Refresh::new(&world.updater, &world.cache_path); + let mut notices = Vec::new(); + + let copies = world_cache.copies(); + let outcome = workspace_delete( + &mut context, + &mut refresh, + &clones, + &mut world_cache.storage, + Some(&home), + &copies, + "myws", + Insistence::Insisted, + Persistence::Ordinary, + &mut unblocked(), + &mut notices, + ); + (outcome, notices) +} + /// docker will not list the workspace's containers, so what they mount is /// unknown: the delete goes on, says so, and removes none of their volumes. #[test] diff --git a/rust/devlaunch-core/src/flows/orphan_containers.rs b/rust/devlaunch-core/src/flows/orphan_containers.rs index fe7d9bd1..8651125b 100644 --- a/rust/devlaunch-core/src/flows/orphan_containers.rs +++ b/rust/devlaunch-core/src/flows/orphan_containers.rs @@ -42,6 +42,7 @@ //! Nothing is matched on a container *name*: names are the devcontainer's to //! choose, and a pattern over them would reach other people's containers. +use std::collections::BTreeSet; use std::path::Path; use crate::clients::devpod_home::{DevpodHome, RecordPresence}; @@ -60,14 +61,22 @@ pub(crate) enum OrphanSweep { Nothing, /// No docker on this machine, so nothing was made to be left. NoDocker, - /// These containers were removed, by name. - Removed(NonEmpty), + /// These containers were removed, by name, with the compose projects they + /// were made for: a project names the compose volumes it made, which the + /// containers' removal leaves behind. + Removed { + names: NonEmpty, + projects: BTreeSet, + }, /// docker would not list the containers, in its own words. NotListed { reason: String }, - /// docker would not remove these containers, in its own words. + /// docker would not remove these containers, in its own words. `projects` + /// are the projects of the ones it did remove, none of whose containers is + /// left, as in [`Self::Removed`]. NotRemoved { names: NonEmpty, reason: String, + projects: BTreeSet, }, } @@ -106,16 +115,20 @@ pub(crate) fn sweep( }; let names = left.map(|c| c.name.clone()); let ids = left.map(|c| c.id.clone()); + let projects = devpod_projects(&left, home, workspace_id); match docker::remove_containers(runner, &ids) { - docker::Answer::Ran { exit, .. } if exit.is_success() => OrphanSweep::Removed(names), + docker::Answer::Ran { exit, .. } if exit.is_success() => { + OrphanSweep::Removed { names, projects } + } docker::Answer::Ran { exit, stderr } => { let reason = format!("docker rm failed ({exit:?}): {}", stderr.trim()); - still_there(runner, &left, names, reason) + still_there(runner, &left, names, projects, home, workspace_id, reason) } docker::Answer::NotInstalled => OrphanSweep::NoDocker, docker::Answer::NotStarted(failure) => OrphanSweep::NotRemoved { names, reason: format!("docker rm did not finish ({:?})", failure.kind), + projects: BTreeSet::new(), }, } } @@ -126,26 +139,73 @@ pub(crate) fn sweep( /// gone, and still removes the rest. So the sweep lists them again and names only /// those still there; when none is, every one of them is gone. When the second /// listing fails too, all of them are named, as the first answer said. +/// +/// The projects handed on are those none of whose containers is still there: a +/// volume of a project with a container left is that container's to keep. fn still_there( runner: &dyn crate::runner::Runner, left: &NonEmpty<&ComposeContainer>, names: NonEmpty, + projects: BTreeSet, + home: &DevpodHome, + workspace_id: &str, reason: String, ) -> OrphanSweep { let ids = left.map(|c| c.id.clone()); let Ok(present) = docker::present_containers(runner, &ids) else { - return OrphanSweep::NotRemoved { names, reason }; + return OrphanSweep::NotRemoved { + names, + reason, + projects: BTreeSet::new(), + }; }; - match NonEmpty::of( - left.iter() - .filter(|c| present.contains(&c.id)) - .map(|c| c.name.clone()), - ) { - Some(names) => OrphanSweep::NotRemoved { names, reason }, - None => OrphanSweep::Removed(names), + let (stayed, went): (Vec<&ComposeContainer>, Vec<&ComposeContainer>) = + left.iter().copied().partition(|c| present.contains(&c.id)); + match NonEmpty::of(stayed.iter().map(|c| c.name.clone())) { + Some(names) => { + let still_used: BTreeSet<&String> = + stayed.iter().filter_map(|c| c.project.as_ref()).collect(); + let projects = NonEmpty::of(went) + .map(|went| devpod_projects(&went, home, workspace_id)) + .unwrap_or_default() + .into_iter() + .filter(|project| !still_used.contains(project)) + .collect(); + OrphanSweep::NotRemoved { + names, + reason, + projects, + } + } + None => OrphanSweep::Removed { names, projects }, } } +/// The compose projects devpod made for this workspace, among `left`. +/// +/// Only a container whose labels name this id's devpod directory counts: devpod +/// wrote its override there, so its project is a uid devpod chose for this +/// workspace. A container matched by the clone alone may be a project somebody +/// started by hand in the clone, and compose names that one after the folder +/// (`docker`, `kinisi_ros`). Volumes go by `_`, so the same name +/// belongs to every folder of that name on the machine, and removing them would +/// reach a project that is not this workspace's. +fn devpod_projects( + left: &NonEmpty<&ComposeContainer>, + home: &DevpodHome, + workspace_id: &str, +) -> BTreeSet { + left.iter() + .filter(|c| { + c.paths().any(|path| { + home.agent_dir_owner(path) + .is_some_and(|owner| owner == workspace_id) + }) + }) + .filter_map(|c| c.project.clone()) + .collect() +} + /// Whether one container's compose labels name this workspace, and nothing /// else that could own it. /// @@ -233,6 +293,20 @@ mod tests { ) } + /// [`row`], for a container compose made for `project`. + fn row_of( + project: &str, + id: &str, + name: &str, + working_dir: &Path, + config_files: &[&Path], + ) -> String { + format!( + "{}\t{project}\n", + row(id, name, working_dir, config_files).trim_end() + ) + } + fn clone_dir() -> PathBuf { PathBuf::from("/cache/devlaunch/repos/org/repo").join(WS) } @@ -251,12 +325,14 @@ mod tests { fake.script( ["docker", "ps"], Response::stdout( - row( + row_of( + "default-ki-0ld11", "aaa", &format!("kinisi_jazzy_{WS}"), &devcontainer, &[&compose, &override_file], - ) + &row( + ) + &row_of( + "default-ki-0ld11", "bbb", &format!("kinisi_unreal_runtime_1.6.1_{WS}"), &devcontainer, @@ -274,10 +350,13 @@ mod tests { assert_eq!( swept, - OrphanSweep::Removed(names([ - format!("kinisi_jazzy_{WS}"), - format!("kinisi_unreal_runtime_1.6.1_{WS}"), - ])) + OrphanSweep::Removed { + names: names([ + format!("kinisi_jazzy_{WS}"), + format!("kinisi_unreal_runtime_1.6.1_{WS}"), + ]), + projects: ["default-ki-0ld11".to_owned()].into_iter().collect(), + } ); assert_eq!( fake.args_to("docker").last().expect("a removal"), @@ -400,7 +479,50 @@ mod tests { assert_eq!( sweep(&fake, Some(&home), "project", None), - OrphanSweep::Removed(names(["project_dev".to_owned()])) + OrphanSweep::Removed { + names: names(["project_dev".to_owned()]), + projects: BTreeSet::new(), + } + ); + } + + /// A project somebody started by hand in the clone is a leftover too, but + /// compose named it after its folder, and `_` volumes belong to + /// every folder of that name. Only the project devpod made for this id is + /// handed on for its volumes. + #[test] + fn only_the_project_devpod_made_names_volumes_to_remove() { + let home = devpod_home_with(&[]); + let override_file = agent_compose_file(&home, "default", WS); + let clone = clone_dir(); + let devcontainer = clone.join(".devcontainer"); + let tools = clone.join("tools"); + let fake = FakeRunner::new(); + fake.script( + ["docker", "ps"], + Response::stdout( + row_of( + "default-ki-0ld11", + "aaa", + "dev", + &devcontainer, + &[&devcontainer.join("compose.yml"), &override_file], + ) + &row_of( + "tools", + "bbb", + "tools_db_1", + &tools, + &[&tools.join("compose.yml")], + ), + ), + ); + + assert_eq!( + sweep(&fake, Some(&home), WS, Some(&clone)), + OrphanSweep::Removed { + names: names(["dev".to_owned(), "tools_db_1".to_owned()]), + projects: ["default-ki-0ld11".to_owned()].into_iter().collect(), + } ); } @@ -426,7 +548,10 @@ mod tests { assert_eq!( sweep(&fake, Some(&home), WS, None), - OrphanSweep::Removed(names(["dev".to_owned()])) + OrphanSweep::Removed { + names: names(["dev".to_owned()]), + projects: BTreeSet::new(), + } ); assert_eq!( fake.args_to("docker").last().expect("a removal"), @@ -541,7 +666,10 @@ mod tests { assert_eq!( sweep(&fake, Some(&home), WS, Some(&clone)), - OrphanSweep::Removed(names(["ours".to_owned()])) + OrphanSweep::Removed { + names: names(["ours".to_owned()]), + projects: BTreeSet::new(), + } ); } @@ -608,6 +736,46 @@ mod tests { reason: "docker rm failed (Code(1)): \ Error response from daemon: No such container: aaa" .to_owned(), + projects: BTreeSet::new(), + } + ); + } + + /// The containers that did go take their projects with them: the delete + /// still reads those projects' volumes. A project with a container still + /// there is not handed on. + #[test] + fn a_partly_failed_removal_keeps_the_projects_of_what_went() { + let home = devpod_home_with(&[]); + let override_file = agent_compose_file(&home, "default", WS); + let fake = FakeRunner::new(); + fake.script(["docker", "ps", "--quiet"], Response::stdout("bbb\n")); + fake.script( + ["docker", "ps"], + Response::stdout( + row_of( + "default-ki-0ld11", + "aaa", + "dev", + Path::new("/x"), + &[&override_file], + ) + &row_of( + "default-ki-0ld22", + "bbb", + "side", + Path::new("/x"), + &[&override_file], + ), + ), + ); + fake.script(["docker", "rm"], Response::failed(1, "busy\n")); + + assert_eq!( + sweep(&fake, Some(&home), WS, None), + OrphanSweep::NotRemoved { + names: names(["side".to_owned()]), + reason: "docker rm failed (Code(1)): busy".to_owned(), + projects: ["default-ki-0ld11".to_owned()].into_iter().collect(), } ); } @@ -631,7 +799,10 @@ mod tests { assert_eq!( sweep(&fake, Some(&home), WS, None), - OrphanSweep::Removed(names(["dev".to_owned()])) + OrphanSweep::Removed { + names: names(["dev".to_owned()]), + projects: BTreeSet::new(), + } ); } @@ -651,6 +822,7 @@ mod tests { OrphanSweep::NotRemoved { names: names(["dev".to_owned()]), reason: "docker rm failed (Code(1)): daemon said no".to_owned(), + projects: BTreeSet::new(), } ); } diff --git a/rust/devlaunch-core/src/flows/workspace_volumes.rs b/rust/devlaunch-core/src/flows/workspace_volumes.rs index 167b1068..41e307ff 100644 --- a/rust/devlaunch-core/src/flows/workspace_volumes.rs +++ b/rust/devlaunch-core/src/flows/workspace_volumes.rs @@ -14,13 +14,23 @@ //! A volume one of the workspace's containers mounted, that **both** //! //! - **belongs to the workspace**: compose made it for the workspace's project -//! under compose's default name `_`, or its name holds the -//! workspace id (or devpod's uid for it) as a whole `-`/`_`/`.`-separated -//! part — what `${localWorkspaceFolderBasename}` and `${devcontainerId}` -//! expand to; +//! under compose's default name `_`, or its name holds one +//! of devpod's uids for it as a whole `-`/`_`/`.`-separated part — what +//! `${devcontainerId}` expands to — or it holds the workspace id that way — +//! what `${localWorkspaceFolderBasename}` expands to — and a container of the +//! current uid mounts it, started from the config dl read (see +//! [`Mounted::config_read`]); //! - and **no container that is left uses** — asked of docker after the //! workspace's own containers are gone. //! +//! A compose volume of one of the workspace's projects is found by compose's +//! own label as well as by its mounts, so it goes even when no container is left +//! to mount it. The projects are devpod's uids for the workspace: the current +//! one, the ones devlaunch kept from earlier `up`s +//! ([`super::kept_copies::KeptCopies::uids`]), and the projects of the leftover +//! containers a delete removed ([`record_projects`]). Each uid is a value devpod +//! wrote down, so this is not a pattern over `docker volume ls`. +//! //! A name the devcontainer config spells literally, with no substitution in it //! (`team-tracker-pixi`), is shared by every checkout of that repository by //! design and is never one workspace's, whatever the id. A compose volume with an @@ -45,7 +55,9 @@ use std::collections::{BTreeMap, BTreeSet}; use std::path::Path; use crate::clients::compose_files::ComposeFiles; -use crate::clients::devpod_home::{DevpodHome, sole_workspace_record, sole_workspace_result}; +use crate::clients::devpod_home::{ + DevpodHome, RecordPresence, sole_workspace_record, sole_workspace_result, +}; use crate::clients::docker::{self, Unlisted, VolumeRemoval}; use crate::domain::workspace_state::NonEmpty; use crate::runner::Runner; @@ -55,11 +67,17 @@ use crate::runner::Runner; pub(crate) struct Mounted { /// The workspace id dl addresses it by. pub(crate) workspace_id: String, - /// devpod's uid for the workspace — `${devcontainerId}`, and the compose - /// project devpod names after it. - pub(crate) devcontainer_id: Option, + /// devpod's uids for the workspace — `${devcontainerId}`, and the compose + /// projects devpod names after them: the current one and every older one. + pub(crate) uids: BTreeSet, /// Every named volume any of the workspace's containers mounted. pub(crate) volumes: BTreeSet, + /// The volumes the containers of the current uid mount, when devpod's create + /// result for it was read. Only for these does [`Self::literal`] say which + /// names the config spells literally, so only these can be claimed by the + /// workspace id in their name. A volume only an older uid's containers mount + /// came from an older config, which nothing on the machine still holds. + pub(crate) config_read: BTreeSet, /// The volumes compose made for one of the workspace's projects under /// compose's own default name. pub(crate) compose_made: BTreeSet, @@ -102,11 +120,8 @@ pub(crate) fn belongs(mounted: &Mounted, name: &str) -> bool { if mounted.compose_made.contains(name) { return true; } - has_part(name, &mounted.workspace_id) - || mounted - .devcontainer_id - .as_deref() - .is_some_and(|uid| has_part(name, uid)) + mounted.uids.iter().any(|uid| has_part(name, uid)) + || (mounted.config_read.contains(name) && has_part(name, &mounted.workspace_id)) } /// The volumes a delete should try to remove, in name order. @@ -138,30 +153,92 @@ fn has_part(name: &str, part: &str) -> bool { /// carries it as `dev.containers.id`, and devpod names the compose project after /// it, so every compose sidecar carries it as `com.docker.compose.project`. /// Stopped containers count: their volumes are as much the workspace's. +/// +/// `former_uids` are the uids devlaunch kept from earlier `up`s of the same +/// workspace ([`super::kept_copies::KeptCopies::uids`]). devpod makes a record +/// again under a new uid, and the old project's containers and volumes still +/// carry the old one, so each is read as the workspace's too. +/// +/// A compose volume of one of these projects, under compose's default name, is +/// the workspace's own **whether or not a container is left to mount it**: a +/// workspace whose containers are gone (dl shows it `NotFound`) still has its +/// `_bazel-output`, and before this the read found no container and stopped +/// there. +/// +/// The kept uids are keyed by the workspace id alone, so they are read only when +/// one devpod context at most holds that id: with two, a kept uid may be the +/// other context's workspace, which is not being deleted. pub(crate) fn record( runner: &dyn Runner, devpod_home: Option<&DevpodHome>, + former_uids: &[String], workspace_id: &str, ) -> Recording { let result = sole_workspace_result(devpod_home, workspace_id).and_then(|path| read_json(&path)); - let uid = sole_workspace_record(devpod_home, workspace_id) - .and_then(|path| read_json(&path)) - .and_then(|record| non_empty(&record["uid"])) - .or_else(|| { - result - .as_ref() - .and_then(|r| non_empty(&r["SubstitutionContext"]["DevContainerID"])) - }); - let Some(uid) = uid else { + let uid = uid_in(devpod_home, workspace_id, result.as_ref()); + let one_owner = devpod_home.is_some_and(|home| { + sole_workspace_record(Some(home), workspace_id).is_some() + || home.record_presence(workspace_id) == RecordPresence::Absent + }); + let former_uids: &[String] = if one_owner { former_uids } else { &[] }; + let uids: BTreeSet = uid + .iter() + .chain(former_uids) + .filter(|uid| !uid.is_empty()) + .cloned() + .collect(); + if uids.is_empty() { return Recording::Nothing; + } + let config = Config { + current: uid.filter(|_| result.is_some()), }; - let mut mounted = Mounted { + let mounted = Mounted { workspace_id: workspace_id.to_owned(), - devcontainer_id: Some(uid.clone()), + uids: uids.clone(), literal: result.as_ref().map(literal_volumes).unwrap_or_default(), ..Mounted::default() }; - match read_mounts(runner, &uid, &mut mounted) { + read(runner, &uids, &config, mounted) +} + +/// Which uid's containers were started from the config dl read. +#[derive(Default)] +struct Config { + /// The current uid, when its create result was read; nothing otherwise. + current: Option, +} + +/// The compose volumes of `projects`, the compose projects of containers a delete +/// removed as this workspace's leftovers ([`super::orphan_containers`]). +/// +/// Read after those containers are gone, so only compose's volume labels are left +/// to read: a volume of one of these projects under compose's default name. A +/// leftover's project is an older uid of the workspace that devlaunch may hold no +/// copy of, so without this its volumes outlived the containers that were removed. +pub(crate) fn record_projects( + runner: &dyn Runner, + workspace_id: &str, + projects: &BTreeSet, +) -> Recording { + if projects.is_empty() { + return Recording::Nothing; + } + let mounted = Mounted { + workspace_id: workspace_id.to_owned(), + uids: projects.clone(), + ..Mounted::default() + }; + read(runner, projects, &Config::default(), mounted) +} + +fn read( + runner: &dyn Runner, + uids: &BTreeSet, + config: &Config, + mut mounted: Mounted, +) -> Recording { + match read_mounts(runner, uids, config, &mut mounted) { Ok(()) => Recording::Read(mounted), Err(NotRead::Docker(Unlisted::NotInstalled)) => Recording::Nothing, Err(NotRead::Docker(Unlisted::Failed(reason)) | NotRead::ComposeFile(reason)) => { @@ -170,6 +247,28 @@ pub(crate) fn record( } } +/// devpod's uid for the workspace: the compose project devpod names after it, and +/// the `dev.containers.id` its dev container carries. From devpod's record, or +/// from its create result where the record has none. +pub(crate) fn workspace_uid( + devpod_home: Option<&DevpodHome>, + workspace_id: &str, +) -> Option { + let result = sole_workspace_result(devpod_home, workspace_id).and_then(|path| read_json(&path)); + uid_in(devpod_home, workspace_id, result.as_ref()) +} + +fn uid_in( + devpod_home: Option<&DevpodHome>, + workspace_id: &str, + result: Option<&serde_json::Value>, +) -> Option { + sole_workspace_record(devpod_home, workspace_id) + .and_then(|path| read_json(&path)) + .and_then(|record| non_empty(&record["uid"])) + .or_else(|| result.and_then(|r| non_empty(&r["SubstitutionContext"]["DevContainerID"]))) +} + /// Why [`read_mounts`] could not say which volumes are the workspace's. enum NotRead { /// docker is not there, or did not answer. @@ -186,50 +285,62 @@ impl From for NotRead { } /// The docker half of [`record`]. -fn read_mounts(runner: &dyn Runner, uid: &str, mounted: &mut Mounted) -> Result<(), NotRead> { - let mut ids: BTreeSet = BTreeSet::new(); - ids.extend(docker::containers_labelled( - runner, - &format!("dev.containers.id={uid}"), - )?); - ids.extend(docker::containers_labelled( - runner, - &format!("com.docker.compose.project={uid}"), - )?); - let Some(ids) = NonEmpty::of(ids) else { - return Ok(()); - }; - let mut project_files: BTreeMap = BTreeMap::new(); - let mut projectless_files: Vec = Vec::new(); - for container in docker::container_mounts(runner, &ids)? { - match container.project { - Some(project) => project_files - .entry(project) - .or_default() - .merge(container.compose), - // docker sets each compose label on its own, so a container can name - // compose files with no project. Its files are read as a group of - // their own: dropping them would find fewer external volumes. - None if !container.compose.files.is_empty() => { - projectless_files.push(container.compose); - } - None => {} - } - mounted.volumes.extend(container.volumes); +fn read_mounts( + runner: &dyn Runner, + uids: &BTreeSet, + config: &Config, + mounted: &mut Mounted, +) -> Result<(), NotRead> { + let mut current: BTreeSet = BTreeSet::new(); + let mut former: BTreeSet = BTreeSet::new(); + for uid in uids { + let ids = if config.current.as_ref() == Some(uid) { + &mut current + } else { + &mut former + }; + ids.extend(docker::containers_labelled( + runner, + &format!("dev.containers.id={uid}"), + )?); + ids.extend(docker::containers_labelled( + runner, + &format!("com.docker.compose.project={uid}"), + )?); } - if mounted.volumes.is_empty() { - return Ok(()); + former.retain(|id| !current.contains(id)); + let mut groups = ComposeGroups::default(); + if let Some(ids) = NonEmpty::of(current) { + let volumes = read_containers(runner, &ids, &mut groups)?; + mounted.config_read.extend(volumes.iter().cloned()); + mounted.volumes.extend(volumes); } - for group in project_files.values().chain(&projectless_files) { + if let Some(ids) = NonEmpty::of(former) { mounted - .literal - .extend(group.external_volumes().map_err(NotRead::ComposeFile)?); + .volumes + .extend(read_containers(runner, &ids, &mut groups)?); + } + if !mounted.volumes.is_empty() { + for group in groups.by_project.values().chain(&groups.projectless) { + mounted + .literal + .extend(group.external_volumes().map_err(NotRead::ComposeFile)?); + } } + let project_files = groups.by_project; for volume in docker::compose_volumes(runner)? { + let default_name = volume.name == format!("{}_{}", volume.project, volume.key); + if default_name && uids.contains(&volume.project) { + // Compose made it for one of the workspace's own projects. Its label + // says so whether or not a container is left to mount it. + mounted.volumes.insert(volume.name.clone()); + mounted.compose_made.insert(volume.name); + continue; + } if !mounted.volumes.contains(&volume.name) { continue; } - if volume.name != format!("{}_{}", volume.project, volume.key) { + if !default_name { mounted.literal.insert(volume.name); } else if project_files.contains_key(&volume.project) { mounted.compose_made.insert(volume.name); @@ -238,6 +349,42 @@ fn read_mounts(runner: &dyn Runner, uid: &str, mounted: &mut Mounted) -> Result< Ok(()) } +/// The compose files the workspace's containers were started from, read for the +/// external volumes they declare. +#[derive(Default)] +struct ComposeGroups { + by_project: BTreeMap, + /// docker sets each compose label on its own, so a container can name + /// compose files with no project. Its files are read as a group of their + /// own: dropping them would find fewer external volumes. + projectless: Vec, +} + +/// The container half of [`read_mounts`]: what `ids` mount, with the compose +/// files they were started from added to `groups`. +fn read_containers( + runner: &dyn Runner, + ids: &NonEmpty, + groups: &mut ComposeGroups, +) -> Result, NotRead> { + let mut volumes = BTreeSet::new(); + for container in docker::container_mounts(runner, ids)? { + match container.project { + Some(project) => groups + .by_project + .entry(project) + .or_default() + .merge(container.compose), + None if !container.compose.files.is_empty() => { + groups.projectless.push(container.compose); + } + None => {} + } + volumes.extend(container.volumes); + } + Ok(volumes) +} + /// Remove each owned volume nothing left uses, after the workspace's own /// containers are gone. One volume at a time, so one refusal does not stop the /// rest and each line names its own volume. @@ -320,8 +467,9 @@ mod tests { fn mounted(volumes: &[&str]) -> Mounted { Mounted { workspace_id: WS.to_owned(), - devcontainer_id: Some(UID.to_owned()), + uids: [UID.to_owned()].into_iter().collect(), volumes: volumes.iter().map(|v| (*v).to_owned()).collect(), + config_read: volumes.iter().map(|v| (*v).to_owned()).collect(), ..Mounted::default() } } @@ -408,9 +556,29 @@ mod tests { home } + /// [`home_with_uid`], with the create result devpod writes at the end of an + /// `up`: the config read, with no literal volume in it. + fn home_with_result() -> crate::clients::devpod_home::ScratchHome { + let home = home_with_uid(); + write_result(&home, "default", WS); + home + } + + fn write_result(home: &DevpodHome, context: &str, workspace_id: &str) { + std::fs::write( + home.result(context, workspace_id), + serde_json::json!({ + "DevContainerConfigWithPath": { "config": { "mounts": [] } }, + "SubstitutionContext": { "DevContainerID": UID }, + }) + .to_string(), + ) + .expect("a result"); + } + #[test] fn the_mounts_of_the_dev_container_and_its_sidecars_are_read() { - let home = home_with_uid(); + let home = home_with_result(); let fake = FakeRunner::new(); fake.script( container_ps(&format!("label=dev.containers.id={UID}")), @@ -438,7 +606,7 @@ mod tests { )), ); - let Recording::Read(m) = record(&fake, Some(&home), WS) else { + let Recording::Read(m) = record(&fake, Some(&home), &[], WS) else { panic!("read"); }; @@ -470,6 +638,97 @@ mod tests { ); } + /// The volume ls rows for the case from the field: the workspace's own + /// `bazel-output`, a volume compose named on purpose for the same project, + /// and another project's `bazel-output`. + fn bazel_output_rows(project: &str) -> String { + format!( + "{project}_bazel-output\t{project}\tbazel-output\n\ + named-cache\t{project}\tcache\n\ + default-ki-0ther_bazel-output\tdefault-ki-0ther\tbazel-output\n" + ) + } + + /// dl shows the workspace NotFound: its containers are gone, so nothing + /// mounts its compose volume. The volume still carries compose's project + /// label, and the project is the workspace's uid, so it is still the + /// workspace's own. Before this, the read found no container and stopped, + /// and every such delete left `_bazel-output` behind. + #[test] + fn a_compose_volume_is_the_workspaces_own_when_no_container_is_left() { + let home = home_with_uid(); + let fake = FakeRunner::new(); + fake.script( + ["docker", "volume", "ls"], + Response::stdout(bazel_output_rows(UID)), + ); + + let Recording::Read(m) = record(&fake, Some(&home), &[], WS) else { + panic!("read"); + }; + + assert_eq!(owned(&m), [format!("{UID}_bazel-output")]); + assert!( + !fake.argvs().iter().any(|argv| argv[1] == "inspect"), + "no container, so nothing to inspect: {:?}", + fake.argvs() + ); + } + + /// devpod made the record again under a new uid, and the old project's + /// volume carries the old one. A uid devlaunch kept from an earlier `up` + /// still names it. + #[test] + fn a_compose_volume_of_a_former_uid_is_the_workspaces_own() { + let home = home_with_uid(); + let fake = FakeRunner::new(); + let former = "default-ki-0ld11"; + fake.script( + ["docker", "volume", "ls"], + Response::stdout(bazel_output_rows(UID) + &bazel_output_rows(former)), + ); + + let Recording::Read(m) = record(&fake, Some(&home), &[former.to_owned()], WS) else { + panic!("read"); + }; + + assert_eq!( + owned(&m), + [ + format!("{former}_bazel-output"), + format!("{UID}_bazel-output") + ] + ); + // The former uid's containers are looked for as well. + assert!( + fake.argvs().contains(&container_ps(&format!( + "label=com.docker.compose.project={former}" + ))), + "{:?}", + fake.argvs() + ); + } + + /// The containers a delete swept as leftovers were another project's. Their + /// compose volumes are read by that project alone, with no uid on record. + #[test] + fn the_compose_volumes_of_swept_projects_are_read_by_project() { + let fake = FakeRunner::new(); + let swept = "default-ki-0ld11"; + fake.script( + ["docker", "volume", "ls"], + Response::stdout(bazel_output_rows(swept)), + ); + + let Recording::Read(m) = + record_projects(&fake, WS, &[swept.to_owned()].into_iter().collect()) + else { + panic!("read"); + }; + + assert_eq!(owned(&m), [format!("{swept}_bazel-output")]); + } + /// Read the mounts of a workspace opened as the bare id `kinisi`, whose /// dev container mounts `kinisi-bazel-cache` and `{UID}_bazel-output`, with /// docker's compose labels for its volumes as `volume_ls` gives them. @@ -480,6 +739,7 @@ mod tests { serde_json::json!({ "id": "kinisi", "uid": UID }).to_string(), ) .expect("a record"); + write_result(&home, "default", "kinisi"); let fake = FakeRunner::new(); fake.script( container_ps(&format!("label=dev.containers.id={UID}")), @@ -498,7 +758,7 @@ mod tests { )])), ); fake.script(["docker", "volume", "ls"], Response::stdout(volume_ls)); - let Recording::Read(m) = record(&fake, Some(&home), "kinisi") else { + let Recording::Read(m) = record(&fake, Some(&home), &[], "kinisi") else { panic!("read"); }; m @@ -550,6 +810,7 @@ mod tests { serde_json::json!({ "id": "app", "uid": UID }).to_string(), ) .expect("a record"); + write_result(&home, "default", "app"); let fake = FakeRunner::new(); fake.script( container_ps(&format!("label=dev.containers.id={UID}")), @@ -571,7 +832,7 @@ mod tests { )])), ); fake.script(["docker", "volume", "ls"], Response::stdout("")); - record(&fake, Some(&home), "app") + record(&fake, Some(&home), &[], "app") } #[test] @@ -697,6 +958,7 @@ mod tests { serde_json::json!({ "id": "app", "uid": UID }).to_string(), ) .expect("a record"); + write_result(&home, "default", "app"); let fake = FakeRunner::new(); fake.script( container_ps(&format!("label=dev.containers.id={UID}")), @@ -729,7 +991,7 @@ mod tests { ); fake.script(["docker", "volume", "ls"], Response::stdout("")); - let Recording::Read(m) = record(&fake, Some(&home), "app") else { + let Recording::Read(m) = record(&fake, Some(&home), &[], "app") else { panic!("read"); }; @@ -779,7 +1041,7 @@ mod tests { let home = devpod_home_with(&[]); let fake = FakeRunner::new(); - assert_eq!(record(&fake, Some(&home), WS), Recording::Nothing); + assert_eq!(record(&fake, Some(&home), &[], WS), Recording::Nothing); assert!(fake.argvs().is_empty()); } @@ -789,7 +1051,7 @@ mod tests { let fake = FakeRunner::new(); fake.script_missing("docker"); - assert_eq!(record(&fake, Some(&home), WS), Recording::Nothing); + assert_eq!(record(&fake, Some(&home), &[], WS), Recording::Nothing); } #[test] @@ -799,7 +1061,7 @@ mod tests { fake.script(["docker", "ps"], Response::failed(1, "daemon down\n")); assert!(matches!( - record(&fake, Some(&home), WS), + record(&fake, Some(&home), &[], WS), Recording::Unread { .. } )); } @@ -823,7 +1085,7 @@ mod tests { .expect("a result"); let fake = FakeRunner::new(); - let Recording::Read(m) = record(&fake, Some(&home), WS) else { + let Recording::Read(m) = record(&fake, Some(&home), &[], WS) else { panic!("read"); }; assert_eq!( @@ -971,6 +1233,119 @@ mod tests { assert_eq!(swept[1], Swept::Removed(format!("{WS}-b"))); } + const FORMER: &str = "default-ki-0ld11"; + + /// A workspace whose record carries UID and whose current config was read, + /// and one container of the FORMER uid's project that mounts `volumes`. + fn record_former_container(volumes: &[&str], home: &DevpodHome) -> Mounted { + let fake = FakeRunner::new(); + fake.script( + container_ps(&format!("label=dev.containers.id={FORMER}")), + Response::stdout("fff\n"), + ); + fake.script( + ["docker", "inspect"], + Response::stdout(docker::inspect_output(&[inspected( + FORMER, + ComposeFiles::default(), + volumes, + )])), + ); + let Recording::Read(m) = record(&fake, Some(home), &[FORMER.to_owned()], WS) else { + panic!("read"); + }; + m + } + + /// A container of an older uid mounts a volume its own, older config spelled + /// literally. The current config no longer names it, so the current config + /// cannot say it is literal, and the id inside its name proves nothing: + /// it stays. + #[test] + fn a_volume_only_a_former_uid_mounts_is_not_claimed_by_the_id() { + let home = home_with_result(); + let shared = format!("{WS}-shared"); + + let m = record_former_container(&[&shared], &home); + + assert!(m.volumes.contains(&shared), "{m:?}"); + assert_eq!(owned(&m), Vec::::new()); + } + + /// The docker-in-docker volume of an older uid holds that uid, a value devpod + /// made for this workspace alone, so it goes with the workspace. + #[test] + fn a_volume_named_after_a_former_uid_is_the_workspaces_own() { + let home = home_with_result(); + // The docker-in-docker volume of FORMER. + let dind = "dind-var-lib-docker-default-ki-0ld11"; + + let m = record_former_container(&[dind], &home); + + assert_eq!(owned(&m), [dind.to_owned()]); + } + + /// With no create result, dl cannot read which names the config spells + /// literally, so a name that holds the id may be a shared one: it stays. + /// A name that holds devpod's uid is still the workspace's. + #[test] + fn with_no_config_to_read_the_id_claims_nothing() { + let home = home_with_uid(); + let fake = FakeRunner::new(); + fake.script( + container_ps(&format!("label=dev.containers.id={UID}")), + Response::stdout("aaa\n"), + ); + fake.script( + ["docker", "inspect"], + Response::stdout(docker::inspect_output(&[inspected( + UID, + ComposeFiles::default(), + &[&format!("{WS}-pixi"), DIND], + )])), + ); + + let Recording::Read(m) = record(&fake, Some(&home), &[], WS) else { + panic!("read"); + }; + + assert_eq!(owned(&m), [DIND.to_owned()]); + } + + /// The same id in two devpod contexts: the uids devlaunch kept may be the + /// other context's workspace, so they are not read at all. + #[test] + fn kept_uids_are_not_read_when_two_contexts_hold_the_id() { + let home = devpod_home_with(&[("default", WS, None), ("other", WS, None)]); + let fake = FakeRunner::new(); + fake.script( + ["docker", "volume", "ls"], + Response::stdout(bazel_output_rows(FORMER)), + ); + + let recording = record(&fake, Some(&home), &[FORMER.to_owned()], WS); + + assert_eq!(recording, Recording::Nothing); + assert!(fake.argvs().is_empty(), "{:?}", fake.argvs()); + } + + /// With no record in any context, the kept uids are the workspace's alone. + #[test] + fn kept_uids_are_read_when_no_context_holds_the_id() { + let home = devpod_home_with(&[]); + let fake = FakeRunner::new(); + fake.script( + ["docker", "volume", "ls"], + Response::stdout(bazel_output_rows(FORMER)), + ); + + let Recording::Read(m) = record(&fake, Some(&home), &[FORMER.to_owned()], WS) else { + panic!("read"); + }; + + assert_eq!(owned(&m), [format!("{FORMER}_bazel-output")]); + } + #[test] fn a_name_is_a_part_only_between_separators() { assert!(has_part("ws-pixi", "ws")); diff --git a/rust/dl/src/render.rs b/rust/dl/src/render.rs index 212e8751..9078a85f 100644 --- a/rust/dl/src/render.rs +++ b/rust/dl/src/render.rs @@ -1276,6 +1276,10 @@ fn lifecycle_notice(notice: &LifecycleNotice) -> Option { "Could not remove Docker volume {name} of {workspace_id} ({reason}). Remove it \ with: docker volume rm {name}" ), + LifecycleNotice::WorkspaceVolumeInUse { workspace_id, name } => format!( + "Kept Docker volume {name} of {workspace_id}: another container still uses it. \ + Find it with: docker ps -a --filter volume={name}" + ), LifecycleNotice::WorkspaceVolumesNotRead { workspace_id, reason, @@ -6320,6 +6324,17 @@ mod tests { Remove it with: docker volume rm ws-pixi" ) ); + let volume_in_use = lifecycle_notice(&LifecycleNotice::WorkspaceVolumeInUse { + workspace_id: "ws".to_owned(), + name: "dc_bazel-output".to_owned(), + }); + assert_eq!( + volume_in_use.as_deref(), + Some( + "Kept Docker volume dc_bazel-output of ws: another container still uses it. \ + Find it with: docker ps -a --filter volume=dc_bazel-output" + ) + ); let volumes_unread = lifecycle_notice(&LifecycleNotice::WorkspaceVolumesNotRead { workspace_id: "ws".to_owned(), reason: "docker ps failed (Code(1)): daemon down".to_owned(), diff --git a/rust/dl/tests/lifecycle.rs b/rust/dl/tests/lifecycle.rs index a1f02071..166a477b 100644 --- a/rust/dl/tests/lifecycle.rs +++ b/rust/dl/tests/lifecycle.rs @@ -427,6 +427,9 @@ impl World { "ps --all --quiet --no-trunc --filter label=com.docker.compose.project=", ) && !call.starts_with("inspect --type container --format ") + // The compose volume labels, read with the mounts: a volume + // of the workspace's project no container is left to mount. + && !call.starts_with("volume ls --filter label=com.docker.compose.project ") }) .collect() } @@ -1473,7 +1476,8 @@ fn a_delete_with_nothing_recorded_to_name_removes_nothing() { /// The leftover-container listing, as the fake docker logs its argv. const LEFTOVER_LISTING: &str = "ps --all --no-trunc --filter label=com.docker.compose.project \ --format {{.ID}}\t{{.Names}}\t{{.Label \"com.docker.compose.project.working_dir\"}}\t\ - {{.Label \"com.docker.compose.project.config_files\"}}"; + {{.Label \"com.docker.compose.project.config_files\"}}\t\ + {{.Label \"com.docker.compose.project\"}}"; /// devpod's delete finds a workspace's containers by the uid of the record it is /// deleting, so containers an older record left (or a forced delete gave up on)