use std::fmt;
use std::path::PathBuf;
use super::{Call, CliError, argv, said_any};
use crate::process::Captured;
const TOOL: &str = "docker";
mod config;
mod ps;
pub(crate) use config::{ConfigPort, images, namespace_hosts, pins_override, ports as config_ports};
pub(crate) use ps::Container;
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Failure {
NameInUse,
NetworkExists,
PortTaken(Option<(u16, crate::project::platform::Protocol)>),
PullRefused(String),
PullTransient(String),
EngineDown(String),
EngineDenied(String),
PoolOverlap(String),
Other(String),
}
fn taken_port(out: &Captured) -> Option<(u16, crate::project::platform::Protocol)> {
use crate::project::platform::Protocol;
let protocol_of = |word: &str| {
if word.to_ascii_lowercase().starts_with("udp") {
Protocol::Udp
} else {
Protocol::Tcp
}
};
let port_of = |address: &str| address.rsplit_once(':').and_then(|(_, port)| port.parse::<u16>().ok());
out.stdout.iter().chain(&out.stderr_tail).find_map(|line| {
if let Some((_, rest)) = line.split_once("Bind for ") {
let address = rest.split_whitespace().next()?;
return Some((port_of(address)?, Protocol::Tcp));
}
if let Some((_, rest)) = line.split_once("failed to bind host port ") {
let bound = rest.split_whitespace().next()?.trim_end_matches(':');
let (address, protocol) = bound.rsplit_once('/').map_or((bound, "tcp"), |(a, p)| (a, p));
return Some((port_of(address)?, protocol_of(protocol)));
}
let (_, rest) = line.split_once("listen ")?;
let mut words = rest.split_whitespace();
let protocol = words.next()?;
let address = words.next()?.trim_end_matches(':');
Some((port_of(address)?, protocol_of(protocol)))
})
}
const ENGINE_DOWN: &[&str] = &[
"cannot connect to the docker daemon",
"is the docker daemon running",
"error during connect",
"failed to connect to the docker api",
];
fn engine_denied(out: &Captured) -> bool {
out.stdout.iter().chain(&out.stderr_tail).any(|l| {
let l = l.to_lowercase();
let socket = l.contains("permission denied") && ["docker.sock", "docker api", "docker daemon"].iter().any(|w| l.contains(w));
let pipe = l.contains("access is denied") && l.contains("pipe");
socket || pipe
})
}
const PULL_TRANSIENT: &[&str] = &[
"connection reset by peer",
"tls handshake timeout",
"i/o timeout",
"unexpected eof",
"502 bad gateway",
"503 service unavailable",
"504 gateway timeout",
"request canceled while waiting for connection",
];
const PULL_REFUSED: &[&str] = &[
"pull access denied",
"manifest unknown",
"toomanyrequests",
"no matching manifest",
"unauthorized: authentication required",
"failed to resolve reference",
];
impl Failure {
pub(crate) fn of(out: &Captured) -> Failure {
if engine_denied(out) {
Failure::EngineDenied(out.reason())
} else if said_any(out, ENGINE_DOWN) {
Failure::EngineDown(out.reason())
} else if said_any(out, &["pool overlaps with other one on this address space"]) {
Failure::PoolOverlap(out.reason())
} else if said_any(out, &["is already in use by container"]) {
Failure::NameInUse
} else if said_any(out, &["has incorrect label", "network with name"]) {
Failure::NetworkExists
} else if said_any(out, &["port is already allocated", "address already in use"]) {
Failure::PortTaken(taken_port(out))
} else if said_any(out, PULL_REFUSED) {
Failure::PullRefused(out.reason())
} else if said_any(out, PULL_TRANSIENT) {
Failure::PullTransient(out.reason())
} else {
Failure::Other(out.reason())
}
}
}
impl fmt::Display for Failure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Failure::NameInUse => f.write_str("a container name is already in use"),
Failure::NetworkExists => f.write_str("a network of the project's name is already there"),
Failure::PortTaken(_) => f.write_str("a host port it publishes is taken"),
Failure::PullRefused(reason) => write!(f, "an image's pull was refused: {reason}"),
Failure::PullTransient(reason) => write!(f, "an image's pull was cut short: {reason}"),
Failure::EngineDown(reason) | Failure::EngineDenied(reason) | Failure::PoolOverlap(reason) | Failure::Other(reason) => f.write_str(reason),
}
}
}
pub(crate) struct Project<'a> {
pub(crate) name: &'a str,
pub(crate) files: &'a [PathBuf],
pub(crate) pins: Option<PathBuf>,
pub(crate) profiles: &'a [String],
}
impl Project<'_> {
fn args(&self, rest: impl IntoIterator<Item = String>) -> Vec<String> {
let mut args = argv(["compose", "-p", self.name]);
for file in self.files.iter().chain(&self.pins) {
args.extend(["-f".to_owned(), file.to_string_lossy().into_owned()]);
}
for profile in self.profiles {
args.extend(["--profile".to_owned(), profile.clone()]);
}
args.extend(rest);
args
}
}
#[derive(Debug, Clone, Default)]
pub(crate) struct Up<'a> {
pub(crate) services: &'a [String],
pub(crate) wait: bool,
pub(crate) remove_orphans: bool,
pub(crate) existing: Existing,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) enum Existing {
#[default]
Remade,
Rebuilt,
Kept,
}
pub(crate) async fn up(call: &Call<'_>, project: &Project<'_>, how: &Up<'_>) -> Result<(), CliError<Failure>> {
let mut rest = argv(["up", "--detach"]);
if how.wait {
rest.push("--wait".into());
}
if how.remove_orphans {
rest.push("--remove-orphans".into());
}
match how.existing {
Existing::Remade => {}
Existing::Rebuilt => rest.push("--build".into()),
Existing::Kept => rest.push("--no-recreate".into()),
}
rest.extend(how.services.iter().cloned());
call.ok(TOOL, project.args(rest), Failure::of).await.map(drop)
}
pub(crate) async fn pull(call: &Call<'_>, project: &Project<'_>, stall: std::time::Duration) -> Result<(), CliError<Failure>> {
let args = project.args(argv(["pull", "--ignore-buildable"]));
call.ok_watched(TOOL, args, stall, Failure::of).await.map(drop)
}
pub(crate) async fn down(call: &Call<'_>, project: &Project<'_>, volumes: bool, remove_orphans: bool) -> Result<(), CliError<Failure>> {
let mut rest = argv(["down"]);
if volumes {
rest.push("--volumes".into());
}
if remove_orphans {
rest.push("--remove-orphans".into());
}
call.ok(TOOL, project.args(rest), Failure::of).await.map(drop)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Verb {
Stop,
Pause,
Unpause,
}
pub(crate) async fn act(call: &Call<'_>, project: &Project<'_>, verb: Verb, services: &[String]) -> Result<(), CliError<Failure>> {
let word = match verb {
Verb::Stop => "stop",
Verb::Pause => "pause",
Verb::Unpause => "unpause",
};
let rest = std::iter::once(word.to_owned()).chain(services.iter().cloned());
call.ok(TOOL, project.args(rest), Failure::of).await.map(drop)
}
pub(crate) async fn ps(call: &Call<'_>, project: &Project<'_>) -> Result<Vec<Container>, CliError<Failure>> {
let out = call.ok(TOOL, project.args(argv(["ps", "--all", "--format", "json"])), Failure::of).await?;
ps::parse(&out.stdout.join("\n")).ok_or_else(|| CliError::Unexpected {
tool: TOOL,
what: "a `compose ps` listing that isn't JSON containers".into(),
})
}
pub(crate) async fn services(call: &Call<'_>, project: &Project<'_>) -> Result<Vec<String>, CliError<Failure>> {
let out = call.ok(TOOL, project.args(argv(["config", "--services"])), Failure::of).await?;
Ok(out.stdout.iter().map(|l| l.trim()).filter(|l| !l.is_empty()).map(str::to_owned).collect())
}
pub(crate) async fn engine_answers(call: &Call<'_>) -> bool {
call.ok(TOOL, argv(["version", "--format", "{{.Server.Version}}"]), Failure::of).await.is_ok()
}
pub(crate) const MIN_VERSION: &str = "2.17.0";
pub(crate) async fn version(call: &Call<'_>) -> Result<Option<crate::project::platform::Version>, CliError<Failure>> {
let out = call.ok(TOOL, argv(["compose", "version", "--short"]), Failure::of).await?;
super::version(TOOL, &out.stdout.join("\n"), Some(MIN_VERSION))
}
pub(crate) struct Exec<'a> {
pub(crate) service: &'a str,
pub(crate) user: Option<&'a str>,
pub(crate) argv: &'a [String],
pub(crate) tty: bool,
}
fn exec_args(project: &Project<'_>, what: &Exec<'_>) -> Vec<String> {
let mut rest = argv(["exec"]);
if !what.tty {
rest.push("-T".into());
}
if let Some(user) = what.user {
rest.extend(["--user".to_owned(), user.to_owned()]);
}
rest.push(what.service.to_owned());
rest.extend(what.argv.iter().cloned());
project.args(rest)
}
pub(crate) fn exec_spec(call: &Call<'_>, project: &Project<'_>, what: &Exec<'_>) -> crate::process::ProcessSpec {
call.spec(TOOL, exec_args(project, what))
}
pub(crate) async fn exec(call: &Call<'_>, project: &Project<'_>, what: &Exec<'_>) -> Result<Captured, CliError<Failure>> {
call.run(TOOL, exec_args(project, what)).await
}
pub(crate) async fn run_rm(call: &Call<'_>, project: &Project<'_>, service: &str, argv_: &[String]) -> Result<Captured, CliError<Failure>> {
let rest = argv(["run", "--rm", "-T", service]).into_iter().chain(argv_.iter().cloned());
call.run(TOOL, project.args(rest)).await
}
pub(crate) async fn rm_stop_force(call: &Call<'_>, project: &Project<'_>, services: &[String]) -> Result<(), CliError<Failure>> {
let rest = argv(["rm", "--stop", "--force", "--volumes"]).into_iter().chain(services.iter().cloned());
call.ok(TOOL, project.args(rest), Failure::of).await.map(drop)
}
#[cfg(test)]
mod tests;