mod failures;
mod fetched;
mod namespaces;
mod pins;
mod progress;
mod pull;
mod reading;
mod unpaused;
mod usage;
use std::time::Duration;
use self::failures::{checked, engine_error, up_error};
use self::reading::{object_word, one_service, ran, run_state};
use super::{Change, FormatDriver, Found, Ran, Seen, SeenMachine, SeenPort, ToolCx, tool_error};
use crate::Result;
use crate::cli::CliError;
use crate::cli::compose::{self, Exec, Existing, Failure, Project, Up, Verb};
use crate::cli::docker::{self, Object};
use crate::console::ShellCommand;
use crate::console::shells;
use crate::error::Error;
use crate::events::Stream;
use crate::state::{Park, RunState};
use crate::status::MachineState;
use crate::store::{Lifetime, ResourceKind};
pub(crate) const PROJECT_LABEL: &str = "com.docker.compose.project";
const UP_LIMIT: Duration = Duration::from_secs(1800);
const CALL_LIMIT: Duration = Duration::from_secs(600);
const READ_LIMIT: Duration = Duration::from_secs(30);
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct Compose;
impl Compose {
fn project<'a>(cx: &'a ToolCx<'_>) -> Project<'a> {
Project {
name: cx.run.as_str(),
files: &cx.project.files,
pins: pins::file(cx),
profiles: &[],
}
}
fn label(cx: &ToolCx<'_>) -> String {
format!("{PROJECT_LABEL}={}", cx.run.as_str())
}
async fn start(&self, cx: &ToolCx<'_>) -> Result<()> {
fetched::recording(cx, &[], async {
self.prepare(cx, false).await?;
self.launch(cx).await
})
.await
}
async fn prepare(&self, cx: &ToolCx<'_>, first: bool) -> Result<()> {
pins::pin(cx, first).await?;
self.pull(cx).await
}
async fn launch(&self, cx: &ToolCx<'_>) -> Result<()> {
let how = Up {
wait: true,
remove_orphans: true,
existing: Existing::Rebuilt,
..Up::default()
};
self.up_recovering(cx, "up", &how).await
}
async fn up_recovering(&self, cx: &ToolCx<'_>, step: &str, how: &Up<'_>) -> Result<()> {
let watch = progress::Watch::new(&cx.steps);
let sink = |stream: Stream, line: &str| {
watch.see(line);
(cx.sink)(stream, line);
};
let mut call = cx.call(UP_LIMIT);
call.sink = &sink;
self.up_watched(cx, &call, step, how).await?;
cx.steps.end(true);
Ok(())
}
async fn up_watched(&self, cx: &ToolCx<'_>, call: &crate::cli::Call<'_>, step: &str, how: &Up<'_>) -> Result<()> {
let first = compose::up(call, &Self::project(cx), how).await;
let retry = match first {
Ok(()) => return Ok(()),
Err(CliError::Failed {
failure: Failure::NameInUse | Failure::NetworkExists,
..
}) => true,
Err(e) => return checked(cx, Err(e), |e| up_error(step, e)).await,
};
if retry {
tracing::info!(run = %cx.run, "a name of the project is taken by what an earlier start left: removing it, then starting again");
self.remove_labelled(cx).await?;
}
checked(cx, compose::up(call, &Self::project(cx), how).await, |e| up_error(step, e)).await
}
async fn remove_labelled(&self, cx: &ToolCx<'_>) -> Result<()> {
let call = cx.call(CALL_LIMIT);
for kind in [Object::Container, Object::Network, Object::Volume] {
let ids = docker::labelled(&call, kind, &Self::label(cx)).await.map_err(|e| tool_error("leftovers", e))?;
let removed = match docker::remove(&call, kind, &ids).await {
Err(CliError::Failed {
failure: docker::Failure::InUse(_),
..
}) if kind == Object::Volume => Self::remove_held(&call, &ids).await,
other => other,
};
removed.map_err(|e| tool_error("leftovers", e))?;
}
Ok(())
}
async fn remove_held(call: &crate::cli::Call<'_>, volumes: &[String]) -> std::result::Result<(), CliError<docker::Failure>> {
for volume in volumes {
let holders = docker::holding(call, volume).await?;
tracing::info!(volume = %volume, containers = ?holders, "removing the containers that still hold a leftover volume");
docker::remove(call, Object::Container, &holders).await?;
}
docker::remove(call, Object::Volume, volumes).await
}
async fn gone(&self, cx: &ToolCx<'_>, containers: &[compose::Container]) -> Vec<String> {
let declared = match compose::services(&cx.read(READ_LIMIT), &Self::project(cx)).await {
Ok(services) => services,
Err(e) => {
tracing::warn!(run = %cx.run, error = %e, "the project's services couldn't be read; the status is the containers'");
return Vec::new();
}
};
declared.into_iter().filter(|s| !containers.iter().any(|c| c.service() == s)).collect()
}
async fn retire_unstarted(&self, cx: &ToolCx<'_>) -> Result<()> {
let started = checked(cx, compose::services(&cx.read(READ_LIMIT), &Self::project(cx)).await, |e| {
engine_error("services", e)
})
.await?;
let attached = pins::attached(cx)?;
let mut stale: Vec<String> = Vec::new();
for c in self.containers(cx).await? {
let service = c.service();
if !started.iter().any(|s| s == service) && !attached.iter().any(|s| s == service) && !stale.iter().any(|s| s == service) {
stale.push(service.to_owned());
}
}
if stale.is_empty() {
return Ok(());
}
tracing::info!(run = %cx.run, services = ?stale, "removing the containers of services the files no longer start");
checked(cx, compose::rm_stop_force(&cx.call(CALL_LIMIT), &Self::project(cx), &stale).await, |e| {
engine_error("update", e)
})
.await
}
async fn containers(&self, cx: &ToolCx<'_>) -> Result<Vec<compose::Container>> {
let all = checked(cx, compose::ps(&cx.read(READ_LIMIT), &Self::project(cx)).await, |e| engine_error("status", e)).await?;
Ok(all.into_iter().filter(|c| !c.one_off()).collect())
}
}
impl FormatDriver for Compose {
async fn probe(&self, cx: &ToolCx<'_>) -> Result<()> {
let found = compose::version(&cx.read(READ_LIMIT)).await.map_err(|e| engine_error("tools", e))?;
super::unknown_version(cx, found.as_ref(), "docker compose", compose::MIN_VERSION);
Ok(())
}
async fn up(&self, cx: &ToolCx<'_>) -> Result<()> {
let first = (cx.made)()?.is_empty();
let started = fetched::recording(cx, &[], async {
self.prepare(cx, first).await?;
Ok::<_, crate::Error>(self.launch(cx).await)
})
.await?;
if let Err(e) = &started
&& first
&& e.code() == crate::ErrorCode::PortInUse
{
tracing::info!(run = %cx.run, "the start was refused for a taken host port: removing what it made");
if let Err(undo) = self.down(cx).await {
let said = format!("what the refused start made wasn't all removed (the next start clears it): {undo}");
(cx.warn)(crate::events::WarningCode::CleanupFailed, &said);
}
}
started
}
async fn down(&self, cx: &ToolCx<'_>) -> Result<()> {
checked(cx, compose::down(&cx.call(CALL_LIMIT), &Self::project(cx), true, true).await, |e| {
engine_error("down", e)
})
.await?;
self.remove_labelled(cx).await?;
pins::forget(cx)
}
async fn park(&self, cx: &ToolCx<'_>, mode: Park) -> Result<()> {
let verb = match mode {
Park::Pause => Verb::Pause,
Park::Shutdown => Verb::Stop,
};
checked(cx, compose::act(&cx.call(CALL_LIMIT), &Self::project(cx), verb, &[]).await, |e| {
engine_error("park", e)
})
.await
}
async fn resume(&self, cx: &ToolCx<'_>) -> Result<()> {
let containers = self.containers(cx).await?;
let gone = self.gone(cx, &containers).await;
if !gone.is_empty() && !containers.is_empty() {
return Err(Error::PartlyGone {
run: cx.run.to_string(),
machines: gone,
});
}
let paused: Vec<String> = containers.iter().filter(|c| c.is_paused()).map(|c| c.service().to_owned()).collect();
if !paused.is_empty() {
checked(cx, compose::act(&cx.call(CALL_LIMIT), &Self::project(cx), Verb::Unpause, &paused).await, |e| {
engine_error("resume", e)
})
.await?;
unpaused::health_back(cx, &Self::project(cx), &paused).await?;
}
let stranded = namespaces::stranded(cx, &Self::project(cx), &containers).await;
if !stranded.is_empty() {
tracing::info!(run = %cx.run, services = ?stranded, "stopping the services left in the network namespace of one that stopped, so the start joins them to its new one");
checked(cx, compose::act(&cx.call(CALL_LIMIT), &Self::project(cx), Verb::Stop, &stranded).await, |e| {
engine_error("resume", e)
})
.await?;
}
let how = Up {
wait: true,
existing: Existing::Kept,
..Up::default()
};
self.up_recovering(cx, "resume", &how).await?;
let attached = pins::attached(cx)?;
if attached.is_empty() {
return Ok(());
}
let theirs = Up { services: &attached, ..how };
self.up_recovering(cx, "resume", &theirs).await
}
async fn update(&self, cx: &ToolCx<'_>) -> Result<()> {
self.start(cx).await?;
self.retire_unstarted(cx).await
}
async fn machines(&self, cx: &ToolCx<'_>) -> Result<Vec<String>> {
checked(cx, compose::services(&cx.read(READ_LIMIT), &Self::project(cx)).await, |e| {
engine_error("services", e)
})
.await
}
async fn reapply(&self, cx: &ToolCx<'_>, _change: &Change) -> Result<()> {
self.start(cx).await
}
#[expect(
clippy::unused_async_trait_impl,
reason = "the trait's operations are async; Compose refuses this one before calling anything"
)]
async fn provision(&self, _cx: &ToolCx<'_>, _machine: Option<&str>, _with: Option<&str>) -> Result<()> {
Err(Error::Declined {
what: "provisioning a Compose project again (its services set themselves up when they start: update it instead)".to_owned(),
})
}
async fn attach(&self, cx: &ToolCx<'_>, machine: &str) -> Result<()> {
let services = one_service(machine);
let how = Up {
services: &services,
wait: true,
existing: Existing::Rebuilt,
..Up::default()
};
pins::attach(cx, machine).await?;
fetched::recording(cx, &services, self.up_recovering(cx, "attach", &how)).await
}
async fn retire(&self, cx: &ToolCx<'_>, machine: &str) -> Result<()> {
checked(
cx,
compose::rm_stop_force(&cx.call(CALL_LIMIT), &Self::project(cx), &one_service(machine)).await,
|e| engine_error("retire", e),
)
.await?;
pins::retire(cx, machine)
}
async fn exec(&self, cx: &ToolCx<'_>, machine: &str, argv: &[String]) -> Result<Ran> {
let call = cx.call(super::CHECK_LIMIT);
let running = self.containers(cx).await?.iter().any(|c| c.service() == machine && c.machine_state().runs());
let out = if running {
let what = Exec {
service: machine,
user: None,
argv,
tty: false,
};
compose::exec(&call, &Self::project(cx), &what).await
} else {
compose::run_rm(&call, &Self::project(cx), machine, argv).await
};
Ok(ran(&checked(cx, out, |e| engine_error("exec", e)).await?))
}
fn console(&self, cx: &ToolCx<'_>, machine: &str, user: Option<&str>) -> impl Future<Output = Result<ShellCommand>> {
let shell = user.map_or_else(|| shells::CONTAINER_SHELL.to_owned(), |_| shells::container_shell_as());
let argv = vec!["sh".to_owned(), "-c".to_owned(), shell];
let what = Exec {
service: machine,
user,
argv: &argv,
tty: true,
};
let spec = compose::exec_spec(&cx.call(READ_LIMIT), &Self::project(cx), &what);
std::future::ready(Ok(ShellCommand::of_spec(spec, &cx.project.dir)))
}
async fn observe(&self, cx: &ToolCx<'_>) -> Result<(Seen, RunState)> {
let containers = self.containers(cx).await?;
let gone = self.gone(cx, &containers).await;
let mut machines: Vec<SeenMachine> = containers
.iter()
.filter(|c| !c.one_off())
.map(|c| SeenMachine {
name: c.service().to_owned(),
state: c.machine_state(),
published: c
.published()
.into_iter()
.map(|p| SeenPort {
guest: p.guest,
host: p.host,
protocol: p.protocol,
})
.collect(),
kind: None,
address: None,
windows: false,
})
.collect();
machines.extend(gone.into_iter().map(|name| SeenMachine {
name,
state: MachineState::Absent,
published: Vec::new(),
kind: None,
address: None,
windows: false,
}));
let state = run_state(&machines);
Ok((Seen { machines, ..Seen::default() }, state))
}
async fn usage(&self, cx: &ToolCx<'_>) -> Result<Vec<crate::MachineUsage>> {
let running: Vec<compose::Container> = self.containers(cx).await?.into_iter().filter(compose::Container::runs).collect();
usage::of(cx, &running).await
}
async fn found(&self, cx: &ToolCx<'_>) -> Result<Vec<Found>> {
let call = cx.read(READ_LIMIT);
let mut found = Vec::new();
for (object, kind, lifetime) in [
(Object::Container, ResourceKind::Container, Lifetime::Machines),
(Object::Network, ResourceKind::Network, Lifetime::Run),
(Object::Volume, ResourceKind::Volume, Lifetime::Run),
] {
for id in docker::labelled(&call, object, &Self::label(cx))
.await
.map_err(|e| tool_error("resources", e))?
{
found.push(Found {
key: format!("{}:{id}", object_word(object)),
kind,
native_id: id,
lifetime,
});
}
}
Ok(found)
}
async fn destroy_by_id(&self, cx: &ToolCx<'_>, _key: &str, kind: ResourceKind, native_id: &str) -> Result<()> {
let object = match kind {
ResourceKind::Container => Object::Container,
ResourceKind::Network => Object::Network,
ResourceKind::Volume => Object::Volume,
other => {
return Err(Error::Unsupported {
what: format!("removing a {other:?} resource through Compose"),
});
}
};
docker::remove(&cx.call(CALL_LIMIT), object, &[native_id.to_owned()])
.await
.map_err(|e| tool_error("remove", e))
}
}
#[cfg(test)]
mod tests;