1 //! The deploy-level checks of `doctor`.2 //!3 //! The bundle check reads the directories. This check reads the things that4 //! bind one bundle to this machine: the target profile against the probed5 //! hardware, the token that a TCP client must present, and the content store6 //! that the web will open. None of them changes state: a doctor that repaired a7 //! host would hide the problem that the operator asked about.8 9 use std::path::{Path, PathBuf};10 11 use inf3r_deploy::Deploy;12 use inf3r_host::{Host, Profile};13 14 use crate::http::CliError;15 16 /// The token file is 32 bytes, written as 64 hex characters and one newline.17 const TOKEN_CHARS: usize = 64;18 19 /// The result of the deploy-level checks.20 #[derive(Clone, PartialEq, Eq, Debug)]21 pub struct Check {22 /// True when every check passed. A deploy file that is absent has nothing23 /// to check, so it is not a failure.24 pub ok: bool,25 /// One line per check, in deploy order.26 pub lines: Vec<String>,27 }28 29 /// Checks the host, the profiles, the token, and the blob store.30 pub fn checks(deploy: &Path) -> Result<Check, CliError> {31 if !deploy.is_file() {32 return Ok(Check {33 ok: true,34 lines: Vec::new(),35 });36 }37 let deploy = Deploy::read(deploy).map_err(|why| CliError::Usage(why.to_string()))?;38 let node = &deploy.node;39 let host = Host::probe();40 let mut check = Check {41 ok: true,42 lines: vec![format!("host {}: ok", host.arch)],43 };44 45 if node46 .binds47 .iter()48 .any(|bind| bind.runtime == inf3r_deploy::Runtime::Container)49 {50 match inf3r_container::docker_reachable() {51 Ok(()) => check.lines.push("container bind Docker: ok".to_string()),52 Err(why) => {53 check.ok = false;54 check.lines.push(format!("container bind Docker: {why}"));55 }56 }57 }58 59 for bind in &node.binds {60 let Some(dir) = bundle_dir(node, &bind.bundle) else {61 check.ok = false;62 check63 .lines64 .push(format!("profile {}: no bundle directory", bind.bundle));65 continue;66 };67 let path = dir.join("target.toml");68 match Profile::read(&path) {69 Ok(profile) => match profile.check(&host, &bind.devices) {70 Ok(()) => check.lines.push(format!("profile {}: ok", bind.bundle)),71 Err(mismatch) => {72 check.ok = false;73 check.lines.push(format!(74 "profile {}: needs {} {}, host has {}",75 bind.bundle, mismatch.field, mismatch.required, mismatch.measured76 ));77 }78 },79 Err(why) => {80 check.ok = false;81 check.lines.push(format!("profile {}: {why}", bind.bundle));82 }83 }84 for weight in &bind.weights {85 if !weight.is_file() {86 check.ok = false;87 check.lines.push(format!(88 "weights {}: {} is not a file",89 bind.bundle,90 weight.display()91 ));92 }93 }94 }95 96 if let Some(cache) = &node.cache97 && cache.enabled98 {99 let mut total = 0u64;100 let mut devices = std::collections::BTreeMap::new();101 let blob_dir =102 std::fs::canonicalize(&node.blob_dir).unwrap_or_else(|_| node.blob_dir.clone());103 for (index, tier) in cache.tiers.iter().enumerate() {104 total = total.saturating_add(tier.bound.unwrap_or(0));105 match inf3r_cache::probe_tier(&tier.dir) {106 Ok(probe) => {107 let dir = std::fs::canonicalize(&tier.dir).unwrap_or_else(|_| tier.dir.clone());108 if let Some(previous) = devices.insert(probe.dev, index) {109 check.ok = false;110 check.lines.push(format!(111 "cache tier {}: same filesystem as {}",112 tier.name, cache.tiers[previous].name113 ));114 } else if dir == blob_dir115 || dir.starts_with(&blob_dir)116 || blob_dir.starts_with(&dir)117 {118 check.ok = false;119 check120 .lines121 .push(format!("cache tier {}: overlaps blob_dir", tier.name));122 } else if tier.bound.is_none() && tier.headroom == 0 {123 check.ok = false;124 check.lines.push(format!(125 "cache tier {}: unbounded tier needs positive headroom",126 tier.name127 ));128 } else if tier.bound.is_none() && probe.free <= tier.headroom {129 check.ok = false;130 check.lines.push(format!(131 "cache tier {}: {} bytes free is not above headroom {}",132 tier.name, probe.free, tier.headroom133 ));134 } else {135 check.lines.push(format!(136 "cache tier {}: ok {} headroom {} dev {}{}",137 tier.name,138 tier.dir.display(),139 tier.headroom,140 probe.dev,141 if probe.held { " (claimed)" } else { "" }142 ));143 }144 }145 Err(why) => {146 check.ok = false;147 check.lines.push(format!("cache tier {}: {why}", tier.name));148 }149 }150 }151 if cache.pin_bound != 0 && total != 0 && cache.pin_bound >= total {152 check.ok = false;153 check.lines.push(format!(154 "cache pin_bound {} must be below total bound {total}",155 cache.pin_bound156 ));157 }158 for class in &cache.classes {159 check160 .lines161 .push(format!("cache class {}: ttl {:?}", class.name, class.ttl));162 }163 }164 165 match token(&node.auth_file) {166 Ok(()) => check167 .lines168 .push(format!("token {}: ok", node.auth_file.display())),169 Err(why) => {170 check.ok = false;171 check172 .lines173 .push(format!("token {}: {why}", node.auth_file.display()));174 }175 }176 177 match store(&node.blob_dir, node.blob_bound) {178 Ok((count, bytes)) => check.lines.push(format!(179 "blobs {}: ok {count} blobs {bytes} bytes",180 node.blob_dir.display()181 )),182 Err(why) => {183 check.ok = false;184 check185 .lines186 .push(format!("blobs {}: {why}", node.blob_dir.display()));187 }188 }189 Ok(check)190 }191 192 /// The first bundle directory that holds a bundle id.193 fn bundle_dir(node: &inf3r_deploy::Node, bundle: &str) -> Option<PathBuf> {194 node.bundle_dirs195 .iter()196 .map(|root| root.join(bundle))197 .find(|dir| dir.is_dir())198 }199 200 /// Whether the token file is exactly 64 hex characters and one newline.201 fn token(path: &Path) -> Result<(), String> {202 let text = std::fs::read_to_string(path).map_err(|why| why.to_string())?;203 let token = text.strip_suffix('\n').unwrap_or(&text);204 if token.len() != TOKEN_CHARS {205 return Err(format!(206 "need {TOKEN_CHARS} hex characters, got {}",207 token.len()208 ));209 }210 if !token.bytes().all(|byte| byte.is_ascii_hexdigit()) {211 return Err("the token is not hex".to_string());212 }213 Ok(())214 }215 216 /// The blob count and bytes in a store. A name that is not an address is not a217 /// blob and is ignored, exactly as `Blobs::open` ignores it.218 fn store(dir: &Path, bound: Option<u64>) -> Result<(usize, u64), String> {219 let entries = std::fs::read_dir(dir).map_err(|why| why.to_string())?;220 let mut count = 0usize;221 let mut bytes = 0u64;222 for entry in entries {223 let entry = entry.map_err(|why| why.to_string())?;224 let name = entry.file_name();225 let Some(name) = name.to_str() else {226 continue;227 };228 if name.len() != 64229 || !name230 .bytes()231 .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))232 {233 continue;234 }235 let metadata = entry.metadata().map_err(|why| why.to_string())?;236 if !metadata.is_file() {237 continue;238 }239 count += 1;240 bytes = bytes.saturating_add(metadata.len());241 }242 if let Some(bound) = bound243 && bytes > bound244 {245 return Err(format!("{bytes} bytes exceed the bound of {bound}"));246 }247 Ok((count, bytes))248 }