mod backend;
mod plan;
mod report;
mod run;
mod usage;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
pub use backend::{Backend, DISK_IMAGES_ENV, Trim, TrimOutcome, allocated_bytes};
pub use plan::{LaneKind, LanePlan, VolumeScope};
pub use report::{document, render_human, render_json};
use run::Failure;
use usage::{DiskUsage, parse_reclaimed, parse_usage};
pub const SCHEMA_VERSION: u32 = 1;
pub const DEFAULT_MAX_AGE: Duration = Duration::from_secs(7 * 24 * 60 * 60);
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(15 * 60);
const QUERY_TIMEOUT: Duration = Duration::from_secs(60);
const DOCKER: &str = "docker";
#[derive(Debug, Clone)]
pub struct DockerPruneOptions {
pub dry_run: bool,
pub max_age: Duration,
pub volumes: Option<VolumeScope>,
pub trim: bool,
pub timeout: Duration,
}
impl Default for DockerPruneOptions {
fn default() -> Self {
Self {
dry_run: false,
max_age: DEFAULT_MAX_AGE,
volumes: None,
trim: true,
timeout: DEFAULT_TIMEOUT,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Skip {
pub reason: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LaneOutcome {
WouldReclaim,
Reclaimed {
bytes: Option<u64>,
},
Skipped {
reason: String,
},
Failed {
message: String,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Lane {
pub plan: LanePlan,
pub outcome: LaneOutcome,
}
impl Lane {
#[must_use]
pub fn bytes(&self) -> u64 {
match &self.outcome {
LaneOutcome::WouldReclaim => self.plan.estimated_bytes,
LaneOutcome::Reclaimed { bytes } => bytes.unwrap_or(0),
LaneOutcome::Skipped { .. } | LaneOutcome::Failed { .. } => 0,
}
}
}
#[derive(Debug)]
pub struct DockerPruneResult {
pub dry_run: bool,
pub max_age: Duration,
pub volumes: Option<VolumeScope>,
pub skipped: Option<Skip>,
pub endpoint: Option<String>,
pub backend: Option<String>,
pub lanes: Vec<Lane>,
pub trim: Option<Trim>,
pub elapsed: Duration,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Totals {
pub candidates: usize,
pub bytes: u64,
pub failed: usize,
pub host_bytes_returned: Option<u64>,
}
impl DockerPruneResult {
#[must_use]
pub fn totals(&self) -> Totals {
let mut totals = Totals::default();
for lane in &self.lanes {
match lane.outcome {
LaneOutcome::WouldReclaim | LaneOutcome::Reclaimed { .. } => {
totals.candidates += lane.plan.candidates;
totals.bytes += lane.bytes();
}
LaneOutcome::Failed { .. } => totals.failed += 1,
LaneOutcome::Skipped { .. } => {}
}
}
totals.host_bytes_returned = self.trim.as_ref().and_then(|trim| trim.outcome.returned());
totals
}
#[must_use]
pub fn has_news(&self) -> bool {
let totals = self.totals();
totals.candidates > 0
|| totals.failed > 0
|| self
.trim
.as_ref()
.is_some_and(|trim| !matches!(trim.outcome, TrimOutcome::Withheld { .. }))
}
}
#[must_use]
pub fn prune(options: &DockerPruneOptions) -> DockerPruneResult {
let started = Instant::now();
let mut result = DockerPruneResult {
dry_run: options.dry_run,
max_age: options.max_age,
volumes: options.volumes,
skipped: None,
endpoint: None,
backend: None,
lanes: Vec::new(),
trim: None,
elapsed: Duration::ZERO,
};
let (version, inventory, endpoint) = std::thread::scope(|scope| {
let version = scope.spawn(|| docker(&["version", "--format", "{{.Server.APIVersion}}"], QUERY_TIMEOUT));
let inventory = scope.spawn(|| docker(&["system", "df", "--verbose", "--format", "json"], QUERY_TIMEOUT));
let endpoint = scope.spawn(endpoint);
(joined(version), joined(inventory), endpoint.join().ok().flatten())
});
result.endpoint.clone_from(&endpoint);
let usage = version.and_then(|api| read_inventory(&inventory?).map(|usage| (api, usage)));
let (api_version, usage) = match usage {
Ok(found) => found,
Err(failure) => {
result.skipped = Some(Skip {
reason: failure.to_string(),
});
result.elapsed = started.elapsed();
return result;
}
};
let backend = backend::detect(endpoint.as_deref().unwrap_or_default());
result.backend = Some(backend.name());
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.ok()
.and_then(|elapsed| i64::try_from(elapsed.as_secs()).ok())
.unwrap_or(0);
let mut plans = vec![
plan::images(&usage, now, options.max_age),
plan::build_cache(&usage, now, options.max_age),
];
if let Some(scope) = options.volumes {
plans.push(plan::volumes(&usage, scope, api_version.trim()));
}
let trim_plan = options
.trim
.then(|| dirs::home_dir().and_then(|home| backend::trim_plan(&backend, &home)))
.flatten();
result.lanes = if options.dry_run {
plans.into_iter().map(withhold).collect()
} else {
run_lanes(plans, options.timeout)
};
result.trim = trim_plan.map(|plan| backend::trim(&backend, &plan, options.dry_run, options.timeout));
result.elapsed = started.elapsed();
result
}
fn docker(args: &[&str], timeout: Duration) -> Result<String, Failure> {
let args: Vec<String> = args.iter().map(|arg| (*arg).to_owned()).collect();
run::run(DOCKER, &args, timeout)
}
fn joined<T>(handle: std::thread::ScopedJoinHandle<'_, Result<T, Failure>>) -> Result<T, Failure> {
handle.join().unwrap_or_else(|_| {
Err(Failure::Failed {
message: "a docker query panicked".to_owned(),
})
})
}
fn read_inventory(json: &str) -> Result<DiskUsage, Failure> {
parse_usage(json).map_err(|error| Failure::Failed {
message: format!("unrecognised `docker system df` output: {error}"),
})
}
fn endpoint() -> Option<String> {
if let Some(host) = std::env::var("DOCKER_HOST").ok().filter(|host| !host.trim().is_empty()) {
return Some(host);
}
docker(
&["context", "inspect", "--format", "{{.Endpoints.docker.Host}}"],
QUERY_TIMEOUT,
)
.ok()
.map(|host| host.trim().to_owned())
.filter(|host| !host.is_empty())
}
fn withhold(plan: LanePlan) -> Lane {
let outcome = match &plan.skipped {
Some(reason) => LaneOutcome::Skipped { reason: reason.clone() },
None => LaneOutcome::WouldReclaim,
};
Lane { plan, outcome }
}
fn run_lanes(plans: Vec<LanePlan>, timeout: Duration) -> Vec<Lane> {
std::thread::scope(|scope| {
let handles: Vec<_> = plans
.into_iter()
.map(|plan| {
let named = plan.clone();
let handle = scope.spawn(move || {
let outcome = execute(&plan, timeout);
Lane { plan, outcome }
});
(handle, named)
})
.collect();
handles
.into_iter()
.map(|(handle, plan)| match handle.join() {
Ok(lane) => lane,
Err(_) => Lane {
plan,
outcome: LaneOutcome::Failed {
message: "the lane panicked".to_owned(),
},
},
})
.collect()
})
}
fn execute(plan: &LanePlan, timeout: Duration) -> LaneOutcome {
if let Some(reason) = &plan.skipped {
return LaneOutcome::Skipped { reason: reason.clone() };
}
let mut reclaimed = Vec::new();
for command in &plan.commands {
match run::run(DOCKER, command, timeout) {
Ok(output) => reclaimed.push(parse_reclaimed(&output)),
Err(failure) => {
return LaneOutcome::Failed {
message: failure.to_string(),
};
}
}
}
let bytes = reclaimed.into_iter().sum::<Option<u64>>();
LaneOutcome::Reclaimed { bytes }
}