mod actions;
mod config;
mod pins;
mod ps;
mod pull;
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::time::Duration;
use isoloom_manifest::{Action, ComposeIdentity, Machine, Native, Port, Protocol, Step, access, contract};
use super::{Driver, GuestUse, Observed};
use crate::Result;
use crate::console::ShellCommand;
use crate::error::Error;
use crate::executor::{Cx, Echo, call_ok};
use crate::process::ProcessSpec;
use crate::state::Op;
pub(crate) use ps::UNREADABLE as UNREADABLE_PS;
pub(crate) use pull::before_step as pull_before_step;
pub(crate) const COMPOSE_SERVICE_LABEL: &str = "com.docker.compose.service";
const PROJECT_LABEL: &str = "com.docker.compose.project";
const ONE_OFF_LABEL: &str = "com.docker.compose.oneoff=True";
pub(crate) fn read_ps(manifest: &isoloom_manifest::Manifest, out: &str) -> Option<(Vec<crate::status::MachineStatus>, BTreeMap<crate::vars::PortKey, u16>)> {
Some(ps::machines(manifest, &ps::parse_ps(out)?))
}
const NO_PINS: &str = "services: {}\n";
const CALL_LIMIT: Duration = Duration::from_secs(120);
const ATTACH_LIMIT: Duration = Duration::from_secs(900);
#[derive(Debug, Clone)]
pub(crate) struct Compose {
identity: ComposeIdentity,
}
impl Compose {
pub(crate) fn new(identity: ComposeIdentity) -> Compose {
Compose { identity }
}
fn project(&self, cx: &Cx<'_>) -> Result<String> {
cx.vars.render(&self.identity.project, "identity.compose.project")
}
fn pins(&self, cx: &Cx<'_>) -> Result<Option<PathBuf>> {
let Some(file) = &self.identity.pinned_ports_file else {
return Ok(None);
};
let path = cx.vars.render(file.template(), "identity.compose.pinned_ports_file")?;
Ok(Some(cx.run.dir().join(path)))
}
fn compose_args(&self, cx: &Cx<'_>, rest: &[&str]) -> Result<Vec<String>> {
let mut args = vec!["compose".to_owned(), "--project-name".into(), self.project(cx)?];
for file in &self.identity.files {
args.push("--file".into());
args.push(cx.vars.render(file.template(), "identity.compose.files")?);
}
args.extend(rest.iter().map(|s| (*s).to_owned()));
Ok(args)
}
async fn compose(&self, cx: &Cx<'_>, step: &Step, rest: &[&str], env: &[(String, String)]) -> Result<String> {
let args = self.compose_args(cx, rest)?;
docker(cx, step, args, env).await
}
}
pub(super) async fn docker(cx: &Cx<'_>, step: &Step, args: Vec<String>, env: &[(String, String)]) -> Result<String> {
let spec = docker_spec(cx, args, env.to_vec());
call_ok(cx, step.id.as_str(), &spec, CALL_LIMIT, Echo::Quiet).await
}
fn protocol(said: &str) -> Option<Protocol> {
match said {
"tcp" | "" => Some(Protocol::Tcp),
"udp" => Some(Protocol::Udp),
_ => None,
}
}
fn machine_port(m: &Machine, port: u16, protocol: Protocol) -> Option<&Port> {
m.ports.iter().find(|q| q.port.get() == port && q.kind.transport() == protocol)
}
impl Driver for Compose {
fn preflight(&self, _cx: &Cx<'_>) -> impl Future<Output = Result<()>> {
std::future::ready(Ok(()))
}
fn env(&self, _cx: &Cx<'_>) -> Result<Vec<(String, String)>> {
Ok(Vec::new())
}
fn prepare(&self, cx: &Cx<'_>) -> Result<()> {
if let Some(pins) = self.pins(cx)?
&& !pins.exists()
{
crate::store::write(&pins, NO_PINS.as_bytes())?;
}
Ok(())
}
async fn action(&self, cx: &Cx<'_>, list: &str, step: &Step, action: Action) -> Result<()> {
match action {
Action::ComposePinPorts => actions::pin_ports(self, cx, list, step).await,
Action::ComposeCheckPortsFree => actions::check_ports_free(self, cx, list, step).await,
Action::ComposeRemoveStaleNetworks => actions::remove_stale_networks(self, cx, list, step).await,
Action::ComposeRemoveContainers => actions::remove_containers(self, cx, list, step).await,
Action::ComposeRemoveNetworks => actions::remove_networks(self, cx, step).await,
other => Err(super::foreign_action(isoloom_manifest::Driver::Compose, step, other)),
}
}
async fn observe(&self, cx: &Cx<'_>) -> Result<Observed> {
let out = super::status_report(cx).await?;
let (machines, published) = read_ps(cx.run.manifest(), &out).ok_or_else(|| ps::unreadable(super::STATUS))?;
let publishing = cx
.run
.manifest()
.machines
.iter()
.filter(|m| published.keys().any(|(name, _)| m.name.as_str() == name));
let mut hosts = BTreeMap::new();
for m in publishing {
hosts.insert(m.name.to_string(), super::publish_host(cx, m)?);
}
Ok(Observed {
machines,
published,
hosts,
..Observed::default()
})
}
fn after_down(&self, cx: &Cx<'_>) -> Result<()> {
if let Some(pins) = self.pins(cx)? {
crate::store::write(&pins, NO_PINS.as_bytes())?;
}
Ok(())
}
fn restart(&self, _cx: &Cx<'_>, _machine: &Machine, _id: &str) -> impl Future<Output = Result<()>> {
std::future::ready(Ok(()))
}
async fn attach(&self, cx: &Cx<'_>, machine: &Machine, image: Option<&str>, network: Option<&str>) -> Result<()> {
self.attach_profile(cx, service_of(machine, "hot-adding")?, image, network).await
}
async fn retire(&self, cx: &Cx<'_>, machine: &Machine) -> Result<()> {
let profile = machine.on_demand.then_some(access::PROFILE);
self.remove(cx, cx.events.call_id(), profile, service_of(machine, "taking out")?).await
}
fn console_command(&self, cx: &Cx<'_>, machine: &Machine, user: Option<&str>) -> Result<ShellCommand> {
let service = service_of(machine, "a console into")?;
let args = match user {
None => self.compose_args(cx, &["exec", service, "sh", "-c", super::shells::CONTAINER_SHELL])?,
Some(user) => self.compose_args(cx, &["exec", "--user", user, service, "sh", "-c", &super::shells::container_shell_as()])?,
};
Ok(super::console_in_run(cx, ProcessSpec::new("docker", args)))
}
fn in_guest(&self, _cx: &Cx<'_>, vm: &Machine, _script: &str, _use: GuestUse) -> Result<ProcessSpec> {
Err(Error::Unsupported {
what: format!("running a script in `{}`: a Compose run has no VM its containers run in", vm.name),
})
}
}
fn service_of<'m>(machine: &'m Machine, what: &str) -> Result<&'m str> {
match &machine.native {
Some(Native::Compose { service }) => Ok(service.as_str()),
_ => Err(Error::Unsupported {
what: format!("{what} `{}`, which isn't a Compose service", machine.name),
}),
}
}
impl Compose {
async fn attach_profile(&self, cx: &Cx<'_>, native: &str, image: Option<&str>, network: Option<&str>) -> Result<()> {
let mut env = Vec::new();
if let Some(image) = image {
env.push((contract::ACCESS_IMAGE.to_owned(), image.to_owned()));
}
let services = self.with_namespace(cx, Op::Attach.as_str(), Some(access::PROFILE), native).await?;
let mut rest = vec!["--profile", access::PROFILE, "up", "-d", "--wait", "--no-deps"];
rest.extend(services.iter().map(String::as_str));
let args = self.compose_args(cx, &rest)?;
let up = docker_spec(cx, args, env);
pull::before_call(cx, Op::Attach.as_str(), &up).await?;
call_ok(cx, Op::Attach.as_str(), &up, ATTACH_LIMIT, Echo::Shown).await?;
if let Some(network) = network {
self.connect_network(cx, native, network).await?;
}
Ok(())
}
async fn remove(&self, cx: &Cx<'_>, id: &str, profile: Option<&str>, native: &str) -> Result<()> {
let services = self.with_namespace(cx, id, profile, native).await?;
let mut rest = profiled(profile);
rest.extend(["rm", "-sf"]);
rest.extend(services.iter().map(String::as_str));
let args = self.compose_args(cx, &rest)?;
call_ok(cx, id, &docker_spec(cx, args, Vec::new()), CALL_LIMIT, Echo::Shown).await?;
Ok(())
}
async fn with_namespace(&self, cx: &Cx<'_>, id: &str, profile: Option<&str>, native: &str) -> Result<Vec<String>> {
let mut rest = profiled(profile);
rest.extend(["config", "--format", "json"]);
let args = self.compose_args(cx, &rest)?;
let config = call_ok(cx, id, &docker_spec(cx, args, Vec::new()), CALL_LIMIT, Echo::Quiet).await?;
let sidecars = config::sharing_namespace(&config, native).map_err(|why| config::unreadable(id, "the services in the machine's namespace are", &why))?;
let mut services = vec![native.to_owned()];
services.extend(sidecars);
Ok(services)
}
async fn connect_network(&self, cx: &Cx<'_>, native: &str, network: &str) -> Result<()> {
let step = Op::Attach.as_str();
let id_args = self.compose_args(cx, &["ps", "-q", native])?;
let out = call_ok(cx, step, &docker_spec(cx, id_args, Vec::new()), CALL_LIMIT, Echo::Quiet).await?;
let container = out.lines().map(str::trim).find(|s| !s.is_empty()).ok_or_else(|| Error::ToolFailed {
step: step.to_owned(),
reason: format!("`{native}` has no container to join to network `{network}`"),
})?;
let connect = ["network", "connect", network, container].map(String::from).to_vec();
match call_ok(cx, step, &docker_spec(cx, connect, Vec::new()), CALL_LIMIT, Echo::Quiet).await {
Err(Error::ToolFailed { reason, .. }) if reason.contains(ALREADY_CONNECTED) => Ok(()),
done => done.map(drop),
}
}
}
const ALREADY_CONNECTED: &str = "already exists in network";
fn profiled(profile: Option<&str>) -> Vec<&str> {
profile.map(|p| vec!["--profile", p]).unwrap_or_default()
}
fn docker_spec(cx: &Cx<'_>, args: Vec<String>, env: Vec<(String, String)>) -> ProcessSpec {
ProcessSpec {
program: "docker".into(),
args,
cwd: Some(cx.run.dir().to_path_buf()),
env,
stdin: None,
tools: None,
}
}