1 //! Docker is the only engine runtime (D28).2 //!3 //! This crate owns the one place that builds a `docker run` command. The4 //! supervisor uses it to start an engine; the web uses it to run the probe and5 //! to ask a cold image for its catalogue. No engine name appears here: a6 //! container is an image, a command, devices, mounts, and a network policy.7 //!8 //! The control process holds the rootless Docker socket. An engine container9 //! never receives it, never receives the host cache directory, and only gets10 //! the one private socket directory that the supervisor creates for that11 //! instance.12 13 use std::fs;14 use std::io;15 use std::path::Path;16 use std::process::{Command, Output, Stdio};17 18 use inf3r_host::Host;19 20 /// The label that says a container belongs to an inf3r control.21 pub const MANAGED_LABEL: &str = "inf3r.managed=1";22 23 /// The label that names the bundle that a container serves.24 pub const PLUGIN_LABEL: &str = "inf3r.plugin";25 26 /// The label that names the control which owns a container. A sweep removes27 /// only containers with its own value, so two controls can share one daemon.28 pub const CONTROL_LABEL: &str = "inf3r.control";29 30 /// The control scope used when a caller does not name one.31 pub const DEFAULT_CONTROL: &str = "default";32 33 /// The variable in which a bundle image keeps its manifest and engine tree.34 pub const BUNDLE_DIR_ENV: &str = "INF3R_BUNDLE_DIR";35 36 /// The bundle root inside every self-contained bundle image.37 ///38 /// The image layout is part of the container contract: the bundle's own39 /// Dockerfile copies its manifest tree below `/opt/inf3r/plugins/<id>`, and the40 /// manifest points at engine files relative to that directory. Keeping the41 /// spelling here means the server, the gate, and the image cannot drift.42 pub fn bundle_dir(bundle: &str) -> String {43 format!("/opt/inf3r/plugins/{bundle}")44 }45 46 /// The label that records the bundle source digest in a final image.47 pub const SOURCE_LABEL: &str = "org.inf3r.source.sha256";48 49 /// One row of the image lock written by `ops/images.sh build`.50 #[derive(Clone, PartialEq, Eq, Debug)]51 pub struct LockedImage {52 /// The bundle id that the image serves.53 pub bundle: String,54 /// The content-addressed final image tag.55 pub final_tag: String,56 /// The final image's immutable image id.57 pub final_digest: String,58 /// The source digest carried by the image label.59 pub source_sha256: String,60 }61 62 /// Reads the image lock, ignoring its comment header and empty lines.63 pub fn read_image_lock(path: &Path) -> Result<Vec<LockedImage>, String> {64 let text =65 fs::read_to_string(path).map_err(|why| format!("image lock {}: {why}", path.display()))?;66 let mut rows = Vec::new();67 for (number, line) in text.lines().enumerate() {68 let line = line.trim();69 if line.is_empty() || line.starts_with('#') {70 continue;71 }72 let fields: Vec<&str> = line.split('\t').collect();73 if fields.len() != 4 {74 return Err(format!(75 "image lock {}: line {} has {} fields, not 4",76 path.display(),77 number + 1,78 fields.len()79 ));80 }81 rows.push(LockedImage {82 bundle: fields[0].to_string(),83 final_tag: fields[1].to_string(),84 final_digest: fields[2].to_string(),85 source_sha256: fields[3].to_string(),86 });87 }88 Ok(rows)89 }90 91 /// The image id and source label that Docker reports.92 fn image_identity(reference: &str) -> Result<(String, String), String> {93 let output = Command::new("docker")94 .args([95 "image",96 "inspect",97 "--format",98 "{{.Id}}\t{{index .Config.Labels \"org.inf3r.source.sha256\"}}",99 reference,100 ])101 .output()102 .map_err(|why| format!("docker image inspect {reference}: {why}"))?;103 if !output.status.success() {104 let stderr = String::from_utf8_lossy(&output.stderr);105 return Err(format!(106 "docker image inspect {reference}: {}",107 stderr.trim()108 ));109 }110 let text = String::from_utf8(output.stdout)111 .map_err(|_| format!("docker image inspect {reference}: output is not UTF-8"))?;112 let text = text.trim_end_matches('\n');113 let Some((id, label)) = text.split_once('\t') else {114 return Err(format!(115 "docker image inspect {reference}: output has no id and label"116 ));117 };118 let label = label.trim();119 let label = if label == "<no value>" { "" } else { label };120 Ok((id.to_string(), label.to_string()))121 }122 123 /// The repository tags that point at an image.124 fn image_tags(reference: &str) -> Result<Vec<String>, String> {125 let output = Command::new("docker")126 .args([127 "image",128 "inspect",129 "--format",130 "{{range .RepoTags}}{{println .}}{{end}}",131 reference,132 ])133 .output()134 .map_err(|why| format!("docker image inspect {reference}: {why}"))?;135 if !output.status.success() {136 let stderr = String::from_utf8_lossy(&output.stderr);137 return Err(format!(138 "docker image inspect {reference}: {}",139 stderr.trim()140 ));141 }142 let text = String::from_utf8(output.stdout)143 .map_err(|_| format!("docker image inspect {reference}: output is not UTF-8"))?;144 Ok(text145 .lines()146 .map(str::trim)147 .filter(|line| !line.is_empty())148 .map(str::to_string)149 .collect())150 }151 152 /// The bundle-derived local alias that the image pipeline also tags.153 fn local_alias(bundle: &str) -> String {154 format!("inf3r/{bundle}:local")155 }156 157 /// Finds the lock row for an image, accepting either the bind's bundle id or158 /// the bundle id encoded in the image reference. The second form is used by159 /// proofs that bind one image under another bundle id.160 fn locked_row<'a>(161 rows: &'a [LockedImage],162 reference: &str,163 bundle: &str,164 ) -> Option<&'a LockedImage> {165 let exact = rows.iter().find(|row| {166 row.bundle == bundle167 && (reference == row.final_tag168 || reference == local_alias(&row.bundle)169 || reference170 .rsplit_once('@')171 .is_some_and(|(_, digest)| digest == row.final_digest))172 });173 exact.or_else(|| {174 rows.iter().find(|row| {175 reference == row.final_tag176 || reference == local_alias(&row.bundle)177 || reference178 .rsplit_once('@')179 .is_some_and(|(_, digest)| digest == row.final_digest)180 })181 })182 }183 184 /// Checks an image against one lock row.185 fn check_locked(186 reference: &str,187 bundle: &str,188 id: &str,189 label: &str,190 row: &LockedImage,191 ) -> Result<(), String> {192 if id != row.final_digest {193 return Err(format!(194 "image {reference} has id {id}, not the locked {} for {}",195 row.final_digest, row.bundle196 ));197 }198 if label != row.source_sha256 {199 return Err(format!(200 "image {reference} carries source {label}, not the locked {} for {}",201 row.source_sha256, row.bundle202 ));203 }204 let digest_ref = reference.rsplit_once('@').is_some();205 if !digest_ref206 && reference != row.final_tag207 && reference != local_alias(&row.bundle)208 && reference != local_alias(bundle)209 {210 return Err(format!(211 "image {reference} is not the locked tag {} or the local alias",212 row.final_tag213 ));214 }215 Ok(())216 }217 218 /// Checks a reference with no lock: a content tag must agree with the source219 /// label, and a mutable local alias must still have a content tag on the same220 /// image. Nothing else is accepted without a lock.221 fn check_unlocked(reference: &str, label: &str, tags: &[String]) -> Result<(), String> {222 if label.is_empty() {223 return Err(format!("image {reference} carries no {SOURCE_LABEL} label"));224 }225 if reference.rsplit_once('@').is_some() {226 return Ok(());227 }228 let name = reference229 .rfind('/')230 .map_or(reference, |slash| &reference[slash + 1..]);231 let Some((_, tag)) = name.rsplit_once(':') else {232 return Err(format!("image {reference} has no tag or digest"));233 };234 if let Some(source) = tag.strip_prefix("sha-") {235 if source.is_empty() {236 return Err(format!("image {reference} has an empty content tag"));237 }238 if !label.starts_with(source) {239 return Err(format!(240 "image {reference} has source {label}, not the tagged {source}"241 ));242 }243 return Ok(());244 }245 if tag != "local" {246 return Err(format!(247 "image {reference} is a mutable tag and there is no image lock to check it"248 ));249 }250 let backed = tags.iter().any(|tag| {251 let name = tag252 .rfind('/')253 .map_or(tag.as_str(), |slash| &tag[slash + 1..]);254 name.rsplit_once(':')255 .and_then(|(_, suffix)| suffix.strip_prefix("sha-"))256 .is_some_and(|source| label.starts_with(source))257 });258 if !backed {259 return Err(format!(260 "image {reference} is a mutable alias with no content tag to check it"261 ));262 }263 Ok(())264 }265 266 /// Verifies that `reference` is a pinned image whose content agrees with the267 /// build record.268 ///269 /// With a lock, the image id and source label must match the row and the270 /// reference must name the recorded content tag (or its local alias). Without271 /// a lock, only a content tag whose `sha-` suffix is the label prefix, or an272 /// immutable digest, is accepted; a mutable alias is refused because there is273 /// nothing to compare it with.274 pub fn verify_image(reference: &str, bundle: &str, lock: Option<&Path>) -> Result<(), String> {275 inf3r_deploy::image_pinned(reference).map_err(|why| format!("image {reference} {why}"))?;276 let (id, label) = image_identity(reference)?;277 match lock {278 Some(path) => {279 let rows = read_image_lock(path)?;280 let row = locked_row(&rows, reference, bundle).ok_or_else(|| {281 format!(282 "image {reference} has no record in {} for bundle {}",283 path.display(),284 bundle285 )286 })?;287 check_locked(reference, bundle, &id, &label, row)288 }289 None => {290 let tags = image_tags(reference)?;291 check_unlocked(reference, &label, &tags)292 }293 }294 }295 296 /// Turns a deploy device name into the CDI reference that Docker receives.297 ///298 /// `cuda:<n>` is the operator-facing spelling. A reference that is already a299 /// CDI device is passed through, and a CPU device has no container reference.300 pub fn device_reference(device: &str) -> Option<String> {301 if let Some(index) = device.strip_prefix("cuda:") {302 return Some(format!("nvidia.com/gpu={index}"));303 }304 device305 .starts_with("nvidia.com/")306 .then(|| device.to_string())307 }308 309 /// The socket directory root that the control creates. An engine sees only its310 /// own instance directory below this path.311 pub const DEFAULT_SOCKET_DIR: &str = "/run/inf3r";312 313 /// A conservative process ceiling for one engine. A model server needs many314 /// threads, but an engine that forks without bound must not take the host.315 pub const DEFAULT_PIDS_LIMIT: u32 = 256;316 /// The default memory ceiling for one engine. GPU weights are outside it;317 /// this bounds the host process image, mapped CPU weights, and runtime state.318 pub const DEFAULT_MEMORY_BYTES: u64 = 16 * 1024 * 1024 * 1024;319 /// The default `/dev/shm` size. PyTorch and some media runtimes need more than320 /// Docker's 64 MiB default.321 pub const DEFAULT_SHM_BYTES: u64 = 512 * 1024 * 1024;322 /// One rotated Docker log file.323 pub const DEFAULT_LOG_MAX_BYTES: u64 = 10 * 1024 * 1024;324 /// The number of rotated Docker log files.325 pub const DEFAULT_LOG_MAX_FILES: u32 = 3;326 /// The open-file limit for an engine.327 pub const DEFAULT_NOFILE: u64 = 65_536;328 329 /// One read-only bind mount that an engine image needs.330 #[derive(Clone, PartialEq, Eq, Debug)]331 pub struct Mount {332 /// The host path.333 pub source: std::path::PathBuf,334 /// The path inside the container.335 pub target: std::path::PathBuf,336 /// A mount is read-only unless it is the private socket directory.337 pub read_only: bool,338 }339 340 /// What to run as a sibling container.341 #[derive(Clone, PartialEq, Eq, Debug)]342 pub struct ContainerSpec {343 /// The image reference, pinned by digest or a local tag for development.344 pub image: String,345 /// The entrypoint override and its arguments. Empty keeps the image's own346 /// entrypoint and command.347 pub command: Vec<String>,348 /// The Docker network. D28 uses `none`; the deploy parser refuses others.349 pub network: String,350 /// CDI device references such as `nvidia.com/gpu=0`.351 pub devices: Vec<String>,352 /// Read-only mounts that the image needs.353 pub mounts: Vec<Mount>,354 /// Environment entries that the image needs. A gate may put a trace file355 /// inside its private socket directory; an ordinary engine needs none.356 pub env: Vec<(String, String)>,357 /// The bundle id, used only as a label.358 pub label: String,359 /// The control that owns this container. A sweep is scoped to one value.360 pub control: String,361 /// The process limit for this container.362 pub pids_limit: u32,363 /// The host memory ceiling in bytes.364 pub memory_bytes: u64,365 /// The `/dev/shm` size in bytes.366 pub shm_bytes: u64,367 /// The size of one rotated Docker log file.368 pub log_max_bytes: u64,369 /// The number of rotated Docker log files.370 pub log_max_files: u32,371 /// Whether the container shares the host PID namespace. Only the probe372 /// helper needs this; an engine never does.373 pub host_pid: bool,374 }375 376 impl ContainerSpec {377 /// A CPU-only specification with the sandbox flags that D28 requires.378 pub fn new(image: impl Into<String>, label: impl Into<String>) -> ContainerSpec {379 ContainerSpec {380 image: image.into(),381 command: Vec::new(),382 network: "none".to_string(),383 devices: Vec::new(),384 mounts: Vec::new(),385 env: Vec::new(),386 label: label.into(),387 control: DEFAULT_CONTROL.to_string(),388 pids_limit: DEFAULT_PIDS_LIMIT,389 memory_bytes: DEFAULT_MEMORY_BYTES,390 shm_bytes: DEFAULT_SHM_BYTES,391 log_max_bytes: DEFAULT_LOG_MAX_BYTES,392 log_max_files: DEFAULT_LOG_MAX_FILES,393 host_pid: false,394 }395 }396 397 /// Names the control that owns this container.398 pub fn with_control(mut self, control: impl Into<String>) -> ContainerSpec {399 self.control = control.into();400 self401 }402 403 /// The arguments that follow `docker`.404 ///405 /// `name` is set for a running engine and absent for a one-shot probe or406 /// describe. `extra` is appended after the image command, which is how the407 /// supervisor adds `--socket <path>`.408 pub fn args(&self, name: Option<&str>, extra: &[String]) -> Vec<String> {409 let mut args = vec![410 "run".to_string(),411 "--rm".to_string(),412 "--pull=never".to_string(),413 ];414 if let Some(name) = name {415 args.push("--name".to_string());416 args.push(name.to_string());417 }418 args.push("--network".to_string());419 args.push(if self.network.is_empty() {420 "none".to_string()421 } else {422 self.network.clone()423 });424 args.push("--read-only".to_string());425 args.push("--tmpfs".to_string());426 args.push("/tmp".to_string());427 args.push("--cap-drop".to_string());428 args.push("ALL".to_string());429 args.push("--security-opt".to_string());430 args.push("no-new-privileges".to_string());431 args.push("--user".to_string());432 args.push("0:0".to_string());433 args.push("--pids-limit".to_string());434 args.push(self.pids_limit.max(1).to_string());435 args.push("--memory".to_string());436 args.push(self.memory_bytes.max(1).to_string());437 args.push("--shm-size".to_string());438 args.push(self.shm_bytes.max(1).to_string());439 args.push("--ulimit".to_string());440 args.push(format!("nofile={DEFAULT_NOFILE}:{DEFAULT_NOFILE}"));441 args.push("--log-driver".to_string());442 args.push("json-file".to_string());443 args.push("--log-opt".to_string());444 let log_mib = self.log_max_bytes.saturating_add((1 << 20) - 1) >> 20;445 args.push(format!("max-size={}m", log_mib.max(1)));446 args.push("--log-opt".to_string());447 args.push(format!("max-file={}", self.log_max_files.max(1)));448 args.push("--label".to_string());449 args.push(MANAGED_LABEL.to_string());450 args.push("--label".to_string());451 args.push(format!("{PLUGIN_LABEL}={}", self.label));452 args.push("--label".to_string());453 args.push(format!(454 "{CONTROL_LABEL}={}",455 if self.control.is_empty() {456 DEFAULT_CONTROL457 } else {458 self.control.as_str()459 }460 ));461 if self.host_pid {462 args.push("--pid=host".to_string());463 }464 for (key, value) in &self.env {465 args.push("--env".to_string());466 args.push(format!("{key}={value}"));467 }468 for mount in &self.mounts {469 let mut value = format!(470 "type=bind,source={},target={}",471 mount.source.display(),472 mount.target.display()473 );474 if mount.read_only {475 value.push_str(",readonly");476 }477 args.push("--mount".to_string());478 args.push(value);479 }480 for device in &self.devices {481 args.push("--device".to_string());482 args.push(device.clone());483 }484 let (entrypoint, command) = match self.command.split_first() {485 Some((first, rest)) => (Some(first), rest),486 None => (None, &[][..]),487 };488 if let Some(entrypoint) = entrypoint {489 args.push("--entrypoint".to_string());490 args.push(entrypoint.clone());491 }492 args.push(self.image.clone());493 args.extend(command.iter().cloned());494 args.extend(extra.iter().cloned());495 args496 }497 498 /// Starts the container and returns the Docker CLI process.499 ///500 /// The CLI process is the supervisor's handle: when it exits, the501 /// container has exited, and its status is the container's status. The502 /// engine's stdout and stderr are available through `docker logs`; keeping503 /// them off the control's pipes means a chatty engine cannot fill a pipe504 /// and stop making progress.505 pub fn spawn(&self, name: &str, extra: &[String]) -> io::Result<std::process::Child> {506 Command::new("docker")507 .args(self.args(Some(name), extra))508 .stdin(Stdio::null())509 .stdout(Stdio::null())510 .stderr(Stdio::null())511 .spawn()512 }513 514 /// Runs the container once and captures its output.515 pub fn capture(&self, extra: &[String]) -> io::Result<Output> {516 Command::new("docker").args(self.args(None, extra)).output()517 }518 519 /// Runs `--describe` in the image without a socket or a weight.520 pub fn describe(&self) -> io::Result<Output> {521 self.capture(&["--describe".to_string()])522 }523 }524 525 /// The host pid of a running container, as Docker reports it.526 ///527 /// The control is in its own PID namespace; this number is only meaningful on528 /// the host, and the probe helper is what dereferences it. It is never passed529 /// to an engine.530 pub fn host_pid(name: &str) -> Option<u32> {531 let output = Command::new("docker")532 .args(["inspect", "--format", "{{.State.Pid}}", name])533 .output()534 .ok()?;535 if !output.status.success() {536 return None;537 }538 let pid = String::from_utf8_lossy(&output.stdout)539 .trim()540 .parse::<u32>()541 .ok()?;542 (pid != 0).then_some(pid)543 }544 545 /// The last few lines of a container's logs, for a start failure.546 pub fn logs(name: &str) -> String {547 let output = Command::new("docker")548 .args(["logs", "--tail", "50", name])549 .output();550 match output {551 Ok(output) if output.status.success() => {552 String::from_utf8_lossy(&output.stdout).into_owned()553 }554 Ok(output) => String::from_utf8_lossy(&output.stderr).into_owned(),555 Err(why) => format!("docker logs: {why}"),556 }557 }558 559 /// Stops a container, then removes it if it is still present.560 ///561 /// `--rm` removes a container that exited on its own; the explicit removal is562 /// for the case where the stop timed out or the CLI process died first.563 pub fn stop(name: &str, grace: std::time::Duration) {564 let seconds = grace.as_secs().min(u64::from(u32::MAX)).to_string();565 // The peer usually sees the closed stream first and exits, so Docker may566 // already have removed the container by the time this runs. A missing567 // container is the desired end state, not an error to print on every568 // clean shutdown.569 let _ = Command::new("docker")570 .args(["stop", "--time", &seconds, name])571 .stdout(Stdio::null())572 .stderr(Stdio::null())573 .status();574 let _ = Command::new("docker")575 .args(["rm", "-f", name])576 .stdout(Stdio::null())577 .stderr(Stdio::null())578 .status();579 }580 581 /// Removes the containers that one previous control left behind.582 ///583 /// `--rm` covers a clean exit. A control that was killed leaves a running584 /// sibling, and the next start must not inherit it. The managed label and the585 /// control label are the only authority: another control on the same daemon is586 /// never touched.587 pub fn sweep(control: &str) {588 let control = if control.is_empty() {589 DEFAULT_CONTROL590 } else {591 control592 };593 let filter = format!("label={MANAGED_LABEL}");594 let scope = format!("label={CONTROL_LABEL}={control}");595 let Ok(output) = Command::new("docker")596 .args(["ps", "-aq", "--filter", &filter, "--filter", &scope])597 .output()598 else {599 return;600 };601 if !output.status.success() {602 return;603 }604 for id in String::from_utf8_lossy(&output.stdout)605 .lines()606 .filter(|line| !line.trim().is_empty())607 {608 let _ = Command::new("docker")609 .args(["rm", "-f", id.trim()])610 .stdout(Stdio::null())611 .stderr(Stdio::inherit())612 .status();613 }614 }615 616 /// Whether the Docker CLI can reach a daemon.617 ///618 /// A container bind needs this before it can inspect an image, start a619 /// sibling, or run the probe. The message names the rootless socket because a620 /// system service account often cannot reach the interactive user's socket.621 pub fn docker_reachable() -> Result<(), String> {622 let output = Command::new("docker")623 .args(["info", "--format", "{{.ServerVersion}}"])624 .output()625 .map_err(|why| format!("cannot run docker: {why}"))?;626 if output.status.success() {627 return Ok(());628 }629 let detail = String::from_utf8_lossy(&output.stderr);630 let detail = detail.trim();631 let detail = if detail.is_empty() {632 format!("docker info exited {}", output.status)633 } else {634 detail.to_string()635 };636 Err(format!(637 "Docker is unreachable ({detail}); set DOCKER_HOST or grant the service account access to the rootless daemon socket, or use the compose control"638 ))639 }640 641 /// Fails if the image does not exist locally. The control never pulls at642 /// request time.643 pub fn image_present(image: &str) -> bool {644 Command::new("docker")645 .args(["image", "inspect", image])646 .stdout(Stdio::null())647 .stderr(Stdio::inherit())648 .status()649 .is_ok_and(|status| status.success())650 }651 652 /// The stable scope that a control uses for its containers.653 ///654 /// The host-side runtime root is the same directory before and after a655 /// restart, so it identifies the control rather than one process instance. A656 /// control container names `socket_host_dir`; a host-mode control names657 /// `socket_dir`. The default is the supervisor's runtime root.658 pub fn control_scope(socket_dir: Option<&Path>, socket_host_dir: Option<&Path>) -> String {659 socket_host_dir660 .or(socket_dir)661 .unwrap_or_else(|| Path::new(DEFAULT_SOCKET_DIR))662 .to_string_lossy()663 .into_owned()664 }665 666 /// The probe helper image and the devices that it may see.667 ///668 /// The helper runs in a sibling container with `--pid=host` and the assigned669 /// CDI devices. It never gets the Docker socket, the cache, or an engine's670 /// private socket directory. Its stdout is the only channel back to the671 /// control.672 #[derive(Clone, Debug)]673 pub struct Probe {674 image: String,675 devices: Vec<String>,676 }677 678 impl Probe {679 /// A probe that uses `image` and can see `devices` (CDI references).680 pub fn new(image: impl Into<String>, devices: Vec<String>) -> Probe {681 Probe {682 image: image.into(),683 devices,684 }685 }686 687 fn spec(&self) -> ContainerSpec {688 let mut spec = ContainerSpec::new(self.image.clone(), "probe");689 spec.host_pid = true;690 spec.devices = self.devices.clone();691 spec.command = vec!["/usr/local/bin/inf3r-probe".to_string()];692 spec693 }694 695 fn run(&self, args: &[&str]) -> Result<String, String> {696 let extra = args.iter().map(|arg| arg.to_string()).collect::<Vec<_>>();697 let output = self698 .spec()699 .capture(&extra)700 .map_err(|why| format!("probe: {why}"))?;701 if !output.status.success() {702 let stderr = String::from_utf8_lossy(&output.stderr);703 return Err(format!("probe exited {}: {}", output.status, stderr.trim()));704 }705 String::from_utf8(output.stdout).map_err(|_| "the probe output is not UTF-8".to_string())706 }707 708 /// The host that the probe container sees.709 pub fn host(&self) -> Result<Host, String> {710 let text = self.run(&["--host"])?;711 Host::decode(&text).ok_or_else(|| "the probe returned a partial host".to_string())712 }713 714 /// Resident bytes of a host pid tree.715 pub fn rss(&self, pid: u32) -> Option<u64> {716 self.run(&["--rss", &pid.to_string()])717 .ok()718 .and_then(|text| text.trim().parse().ok())719 }720 721 /// Device bytes of a host pid tree.722 pub fn vram(&self, pid: u32, device: &str) -> Option<u64> {723 self.run(&["--vram", &pid.to_string(), device])724 .ok()725 .and_then(|text| text.trim().parse().ok())726 }727 728 /// Free bytes of one device.729 pub fn free(&self, device: &str) -> Option<u64> {730 self.run(&["--free", device])731 .ok()732 .and_then(|text| text.trim().parse().ok())733 }734 }735 736 #[cfg(test)]737 mod tests {738 use super::*;739 740 fn row() -> LockedImage {741 LockedImage {742 bundle: "mock/x64-cpu".to_string(),743 final_tag: "inf3r/mock/x64-cpu:sha-e1c24821a1f4".to_string(),744 final_digest: "sha256:final".to_string(),745 source_sha256: "e1c24821a1f4a1f656097ca760489ce51d1a9969db8a6e722f9c49568a4cd0ec"746 .to_string(),747 }748 }749 750 #[test]751 fn a_content_tag_matches_its_source_label() {752 let tags = vec!["inf3r/mock/x64-cpu:sha-e1c24821a1f4".to_string()];753 assert!(754 check_unlocked(755 "inf3r/mock/x64-cpu:sha-e1c24821a1f4",756 &row().source_sha256,757 &tags758 )759 .is_ok()760 );761 assert!(762 check_unlocked(763 "inf3r/mock/x64-cpu:sha-deadbeef0000",764 &row().source_sha256,765 &tags766 )767 .is_err()768 );769 assert!(check_unlocked("inf3r/mock/x64-cpu:local", &row().source_sha256, &tags).is_ok());770 assert!(check_unlocked("inf3r/mock/x64-cpu:local", &row().source_sha256, &[]).is_err());771 assert!(check_unlocked("inf3r/mock/x64-cpu:sha-", &row().source_sha256, &tags).is_err());772 }773 774 #[test]775 fn a_lock_row_accepts_the_content_tag_and_the_alias() {776 let row = row();777 for reference in [778 "inf3r/mock/x64-cpu:sha-e1c24821a1f4",779 "inf3r/mock/x64-cpu:local",780 ] {781 assert_eq!(782 locked_row(std::slice::from_ref(&row), reference, "mock/x64-cpu"),783 Some(&row)784 );785 assert!(786 check_locked(787 reference,788 "mock/x64-cpu",789 "sha256:final",790 &row.source_sha256,791 &row792 )793 .is_ok()794 );795 }796 assert!(797 check_locked(798 "inf3r/mock/x64-cpu:sha-deadbeef0000",799 "mock/x64-cpu",800 "sha256:final",801 &row.source_sha256,802 &row803 )804 .is_err()805 );806 }807 808 #[test]809 fn a_retagged_image_fails_the_id_or_label_check() {810 let row = row();811 assert!(812 check_locked(813 "inf3r/mock/x64-cpu:sha-e1c24821a1f4",814 "mock/x64-cpu",815 "sha256:other",816 &row.source_sha256,817 &row818 )819 .is_err()820 );821 assert!(822 check_locked(823 "inf3r/mock/x64-cpu:sha-e1c24821a1f4",824 "mock/x64-cpu",825 "sha256:final",826 "different",827 &row828 )829 .is_err()830 );831 }832 833 #[test]834 fn the_lock_parser_reads_a_comment_and_one_row() {835 let dir = std::env::temp_dir().join(format!("inf3r-lock-{}", std::process::id()));836 let _ = fs::remove_dir_all(&dir);837 fs::create_dir_all(&dir).expect("a directory");838 let path = dir.join("images.lock");839 fs::write(840 &path,841 format!(842 "# header\n{}\n",843 "mock/x64-cpu\tfinal\tsha256:final\tsource"844 ),845 )846 .expect("a lock");847 let rows = read_image_lock(&path).expect("a lock");848 assert_eq!(rows.len(), 1);849 assert_eq!(rows[0].bundle, "mock/x64-cpu");850 assert_eq!(rows[0].final_digest, "sha256:final");851 fs::remove_dir_all(&dir).expect("cleanup");852 }853 }854 855 #[cfg(test)]856 mod control_scope_tests {857 use super::*;858 859 #[test]860 fn a_control_choice_is_the_host_root() {861 assert_eq!(862 control_scope(863 Some(Path::new("/run/inf3r")),864 Some(Path::new("/run/user/1/inf3r"))865 ),866 "/run/user/1/inf3r"867 );868 assert_eq!(869 control_scope(Some(Path::new("/run/inf3r")), None),870 "/run/inf3r"871 );872 assert_eq!(control_scope(None, None), DEFAULT_SOCKET_DIR);873 }874 875 #[test]876 fn a_spec_labels_its_control() {877 let spec = ContainerSpec::new("image", "bundle").with_control("/run/control");878 let args = spec.args(None, &[]);879 assert!(880 args.windows(2)881 .any(|pair| pair == ["--label", "inf3r.control=/run/control"])882 );883 }884 }885 886 #[cfg(test)]887 mod resource_tests {888 use super::*;889 890 fn value(args: &[String], flag: &str) -> String {891 let index = args.iter().position(|arg| arg == flag).expect(flag);892 args[index + 1].clone()893 }894 895 #[test]896 fn a_spec_has_conservative_limits_and_accepts_overrides() {897 let spec = ContainerSpec::new("image", "bundle");898 let args = spec.args(None, &[]);899 assert_eq!(value(&args, "--pids-limit"), DEFAULT_PIDS_LIMIT.to_string());900 assert_eq!(value(&args, "--memory"), DEFAULT_MEMORY_BYTES.to_string());901 assert_eq!(value(&args, "--shm-size"), DEFAULT_SHM_BYTES.to_string());902 assert_eq!(903 value(&args, "--ulimit"),904 format!("nofile={DEFAULT_NOFILE}:{DEFAULT_NOFILE}")905 );906 assert_eq!(value(&args, "--log-driver"), "json-file");907 assert!(args.contains(&"max-size=10m".to_string()), "{args:?}");908 assert!(args.contains(&"max-file=3".to_string()), "{args:?}");909 910 let mut over = ContainerSpec::new("image", "bundle");911 over.pids_limit = 64;912 over.memory_bytes = 128 * 1024 * 1024;913 over.shm_bytes = 256 * 1024 * 1024;914 over.log_max_bytes = 4 * 1024 * 1024;915 over.log_max_files = 2;916 let args = over.args(None, &[]);917 assert_eq!(value(&args, "--pids-limit"), "64");918 assert_eq!(value(&args, "--memory"), "134217728");919 assert_eq!(value(&args, "--shm-size"), "268435456");920 assert!(args.contains(&"max-size=4m".to_string()), "{args:?}");921 assert!(args.contains(&"max-file=2".to_string()), "{args:?}");922 }923 }