container details: limits, sandbox flags and a live stats sample

Container details now carry the image id and the HostConfig resource limits
(CPU cores and shares, memory and swap bytes, pids, device requests) plus sandbox flags
(privileged, read-only rootfs, network mode, restart policy), with null meaning unlimited. A new
GET /api/v1/docker/containers/{name}/stats returns one live sample: CPU percent
of one core, memory working set, processes, block IO and network bytes. Peers
proxy the new route.

Env, labels, command lines and mounts are deliberately excluded from the payload.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
HermenixandClaude Sonnet 5.5 committed 2026-11-05 03:02:33 +00:00
1 parent 72fccc34f8
commit 0ff3520563
16 files changed
+947 -19

No files matched your search

+160 -1
View File
@@ -14,6 +14,7 @@ use bollard::errors::Error as BollardError;
use bollard::models::{ContainerInspectResponse, ContainerStateStatusEnum};
use bollard::query_parameters::{
InspectContainerOptions, ListContainersOptionsBuilder, LogsOptions, LogsOptionsBuilder,
StatsOptionsBuilder,
};
use bollard::{Docker, API_DEFAULT_VERSION};
use futures::stream::{self, StreamExt};
@@ -22,7 +23,8 @@ use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use super::{
clamp_count, ContainerStatus, ContainerSummary, DockerSource, LogLine, LogOptions, LogStream,
clamp_count, ContainerDevice, ContainerResources, ContainerStats, ContainerStatus,
ContainerSummary, DockerSource, LogLine, LogOptions, LogStream,
};
use crate::config::Config;
use crate::error::AppError;
@@ -215,6 +217,28 @@ impl DockerSource for BollardDocker {
});
Ok(rx)
}
async fn stats(&self, name: &str) -> Result<ContainerStats, AppError> {
let name = normalize_name(name)?;
let docker = self.client()?;
let socket = self.socket_name();
// One shot: the daemon samples once, answers and closes the stream.
let opts = StatsOptionsBuilder::new()
.stream(false)
.one_shot(true)
.build();
let mut s = Box::pin(docker.stats(&name, Some(opts)));
let sample = match s.next().await {
Some(Ok(sample)) => sample,
Some(Err(e)) => return Err(map_container_error(&e, &socket, &name)),
None => {
return Err(AppError::Internal(format!(
"docker returned no stats for '{name}'"
)))
}
};
Ok(stats_from_response(&sample, Timestamp::now()))
}
}
/// Strip the leading `/` and reject names that could alter the request path.
@@ -379,9 +403,144 @@ fn status_from_inspect(i: &ContainerInspectResponse, now: Timestamp) -> Containe
exit_code: state.and_then(|s| s.exit_code),
oom_killed: state.and_then(|s| s.oom_killed),
health_output,
image_id: i.image.clone().filter(|s| !s.is_empty()),
resources: i.host_config.as_ref().map(resources_from_host_config),
}
}
/// Copy only limits and sandbox flags. `Env`, `Labels`, `Cmd`, `Args` and mounts
/// stay on the daemon, so no credential can travel through this API.
fn resources_from_host_config(h: &bollard::models::HostConfig) -> ContainerResources {
ContainerResources {
cpu_cores: cpu_cores_from(h.nano_cpus, h.cpu_quota, h.cpu_period),
cpu_shares: h.cpu_shares,
memory_bytes: h.memory.filter(|v| *v > 0),
memory_swap_bytes: h.memory_swap.filter(|v| *v > 0),
pids_limit: h.pids_limit.filter(|v| *v > 0),
privileged: h.privileged,
read_only_rootfs: h.readonly_rootfs,
network_mode: h.network_mode.clone().filter(|s| !s.is_empty()),
restart_policy: h
.restart_policy
.as_ref()
.and_then(|p| p.name)
.map(|n| n.to_string())
.filter(|s| !s.is_empty()),
devices: h
.device_requests
.as_deref()
.unwrap_or_default()
.iter()
.map(device_from_request)
.collect(),
}
}
/// `nano_cpus` wins; a quota/period pair is the older way to say the same thing.
/// Non-positive values mean "unlimited" in both spellings.
fn cpu_cores_from(nano_cpus: Option<i64>, quota: Option<i64>, period: Option<i64>) -> Option<f64> {
if let Some(n) = nano_cpus.filter(|n| *n > 0) {
return Some(n as f64 / 1_000_000_000.0);
}
let (q, p) = (quota.filter(|q| *q > 0)?, period.filter(|p| *p > 0)?);
Some(q as f64 / p as f64)
}
fn device_from_request(r: &bollard::models::DeviceRequest) -> ContainerDevice {
ContainerDevice {
driver: r.driver.clone().filter(|s| !s.is_empty()),
count: r.count,
ids: r.device_ids.clone().unwrap_or_default(),
capabilities: r
.capabilities
.clone()
.unwrap_or_default()
.into_iter()
.flatten()
.collect(),
}
}
fn stats_from_response(
s: &bollard::models::ContainerStatsResponse,
now: Timestamp,
) -> ContainerStats {
let mem = s.memory_stats.as_ref();
let page_cache = mem
.and_then(|m| m.stats.as_ref())
.and_then(|st| st.get("inactive_file").or_else(|| st.get("cache")))
.copied();
let used = mem
.and_then(|m| m.usage)
.map(|u| u.saturating_sub(page_cache.unwrap_or(0)));
let limit = mem.and_then(|m| m.limit).filter(|l| *l > 0);
ContainerStats {
sampled_at: now,
cpu_percent: cpu_percent_from(s),
memory_used_bytes: used,
memory_limit_bytes: limit,
memory_percent: match (used, limit) {
(Some(u), Some(l)) => Some(u as f64 / l as f64 * 100.0),
_ => None,
},
pids: s.pids_stats.as_ref().and_then(|p| p.current),
block_read_bytes: blkio_bytes(s, "read"),
block_write_bytes: blkio_bytes(s, "write"),
network_rx_bytes: network_bytes(s, true),
network_tx_bytes: network_bytes(s, false),
}
}
/// Percent of one core; 400 means four cores saturated. Needs the previous
/// sample the daemon sends alongside, so a zero delta answers `None`.
fn cpu_percent_from(s: &bollard::models::ContainerStatsResponse) -> Option<f64> {
let cpu = s.cpu_stats.as_ref()?;
let pre = s.precpu_stats.as_ref()?;
let total = cpu.cpu_usage.as_ref()?.total_usage?;
let pre_total = pre.cpu_usage.as_ref()?.total_usage?;
let system = cpu.system_cpu_usage?;
let pre_system = pre.system_cpu_usage?;
let cpu_delta = total.checked_sub(pre_total)? as f64;
let system_delta = system.checked_sub(pre_system)? as f64;
if system_delta <= 0.0 {
return None;
}
let cores = cpu
.online_cpus
.filter(|n| *n > 0)
.map(f64::from)
.or_else(|| {
cpu.cpu_usage
.as_ref()
.and_then(|u| u.percpu_usage.as_ref())
.map(|v| v.len() as f64)
})
.unwrap_or(1.0);
Some(cpu_delta / system_delta * cores * 100.0)
}
fn blkio_bytes(s: &bollard::models::ContainerStatsResponse, op: &str) -> Option<u64> {
let entries = s
.blkio_stats
.as_ref()
.and_then(|b| b.io_service_bytes_recursive.as_ref())?;
let total: u64 = entries
.iter()
.filter(|e| e.op.as_deref().is_some_and(|o| o.eq_ignore_ascii_case(op)))
.filter_map(|e| e.value)
.sum();
Some(total)
}
fn network_bytes(s: &bollard::models::ContainerStatsResponse, rx: bool) -> Option<u64> {
let nets = s.networks.as_ref()?;
Some(
nets.values()
.filter_map(|n| if rx { n.rx_bytes } else { n.tx_bytes })
.sum(),
)
}
fn state_str(s: ContainerStateStatusEnum) -> &'static str {
use ContainerStateStatusEnum as S;
match s {