synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-bench / src / host.rs
| 1 | //! Host, toolchain, filesystem, and Git configuration manifest collection. |
| 2 | //! |
| 3 | //! Every field is read from the running system. When a value cannot be read it is |
| 4 | //! recorded as `"unknown"` (never a guessed or invented fallback). |
| 5 | |
| 6 | use crate::gitcmd::run_git; |
| 7 | use serde::{Deserialize, Serialize}; |
| 8 | use std::path::Path; |
| 9 | use std::process::Command; |
| 10 | |
| 11 | pub const UNKNOWN: &str = "unknown"; |
| 12 | |
| 13 | /// Host and toolchain facts recorded in `manifest.json`. |
| 14 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 15 | pub struct HostInfo { |
| 16 | pub hostname: String, |
| 17 | pub kernel_release: String, |
| 18 | pub arch: String, |
| 19 | /// Distinct CPU model names as reported by the source below. |
| 20 | pub cpu_models: Vec<String>, |
| 21 | /// `lscpu`, `/proc/cpuinfo`, or `unknown`. |
| 22 | pub cpu_model_source: String, |
| 23 | pub logical_cpus: Option<usize>, |
| 24 | pub mem_total_kib: Option<u64>, |
| 25 | pub git_version: String, |
| 26 | pub rustc_version: String, |
| 27 | pub cargo_version: String, |
| 28 | pub work_dir: String, |
| 29 | pub work_dir_fs_type: String, |
| 30 | pub work_dir_source: String, |
| 31 | pub work_dir_free_bytes_at_start: Option<u64>, |
| 32 | } |
| 33 | |
| 34 | fn command_line(program: &str, args: &[&str]) -> Option<String> { |
| 35 | let out = Command::new(program).args(args).output().ok()?; |
| 36 | if !out.status.success() { |
| 37 | return None; |
| 38 | } |
| 39 | let text = String::from_utf8_lossy(&out.stdout).trim().to_string(); |
| 40 | if text.is_empty() { |
| 41 | None |
| 42 | } else { |
| 43 | Some(text) |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | fn read_trimmed(path: &str) -> Option<String> { |
| 48 | std::fs::read_to_string(path) |
| 49 | .ok() |
| 50 | .map(|s| s.trim().to_string()) |
| 51 | .filter(|s| !s.is_empty()) |
| 52 | } |
| 53 | |
| 54 | /// CPU model names from `lscpu` ("Model name:" lines), else `/proc/cpuinfo` |
| 55 | /// ("model name" lines), else `["unknown"]`. |
| 56 | pub fn cpu_models() -> (Vec<String>, String) { |
| 57 | let mut models: Vec<String> = Vec::new(); |
| 58 | if let Some(text) = command_line("lscpu", &[]) { |
| 59 | for line in text.lines() { |
| 60 | if let Some(rest) = line.trim().strip_prefix("Model name:") { |
| 61 | let name = rest.trim().to_string(); |
| 62 | if !name.is_empty() && !models.contains(&name) { |
| 63 | models.push(name); |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | if !models.is_empty() { |
| 68 | return (models, "lscpu".to_string()); |
| 69 | } |
| 70 | } |
| 71 | if let Some(text) = read_trimmed("/proc/cpuinfo") { |
| 72 | for line in text.lines() { |
| 73 | let lower = line.to_ascii_lowercase(); |
| 74 | if lower.starts_with("model name") { |
| 75 | if let Some((_, v)) = line.split_once(':') { |
| 76 | let name = v.trim().to_string(); |
| 77 | if !name.is_empty() && !models.contains(&name) { |
| 78 | models.push(name); |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | } |
| 83 | if !models.is_empty() { |
| 84 | return (models, "/proc/cpuinfo".to_string()); |
| 85 | } |
| 86 | } |
| 87 | (vec![UNKNOWN.to_string()], UNKNOWN.to_string()) |
| 88 | } |
| 89 | |
| 90 | fn mem_total_kib() -> Option<u64> { |
| 91 | let text = std::fs::read_to_string("/proc/meminfo").ok()?; |
| 92 | let line = text.lines().find(|l| l.starts_with("MemTotal:"))?; |
| 93 | line.split_whitespace().nth(1)?.parse().ok() |
| 94 | } |
| 95 | |
| 96 | /// Free bytes available to unprivileged users on the filesystem holding `dir`. |
| 97 | pub fn free_bytes(dir: &Path) -> Option<u64> { |
| 98 | let c_path = std::ffi::CString::new(dir.to_str()?).ok()?; |
| 99 | // SAFETY: `statvfs` is a plain C struct; an all-zero bit pattern is valid. |
| 100 | let mut st: libc::statvfs = unsafe { std::mem::zeroed() }; |
| 101 | // SAFETY: `c_path` is a valid NUL-terminated string and `st` is exclusively borrowed. |
| 102 | let rc = unsafe { libc::statvfs(c_path.as_ptr(), &mut st) }; |
| 103 | if rc != 0 { |
| 104 | return None; |
| 105 | } |
| 106 | Some((st.f_bavail as u64).saturating_mul(st.f_frsize as u64)) |
| 107 | } |
| 108 | |
| 109 | /// Collect host facts; `work_dir` must exist. |
| 110 | pub fn collect_host_info(work_dir: &Path) -> HostInfo { |
| 111 | let (cpu_models, cpu_model_source) = cpu_models(); |
| 112 | let dir_str = work_dir.to_string_lossy().to_string(); |
| 113 | let findmnt = command_line("findmnt", &["-n", "-o", "FSTYPE,SOURCE", "-T", &dir_str]); |
| 114 | let (fs_type, source) = match findmnt { |
| 115 | Some(line) => { |
| 116 | let mut parts = line.split_whitespace(); |
| 117 | ( |
| 118 | parts.next().unwrap_or(UNKNOWN).to_string(), |
| 119 | parts.next().unwrap_or(UNKNOWN).to_string(), |
| 120 | ) |
| 121 | } |
| 122 | None => (UNKNOWN.to_string(), UNKNOWN.to_string()), |
| 123 | }; |
| 124 | HostInfo { |
| 125 | hostname: read_trimmed("/proc/sys/kernel/hostname").unwrap_or_else(|| UNKNOWN.into()), |
| 126 | kernel_release: read_trimmed("/proc/sys/kernel/osrelease") |
| 127 | .unwrap_or_else(|| UNKNOWN.into()), |
| 128 | arch: std::env::consts::ARCH.to_string(), |
| 129 | cpu_models, |
| 130 | cpu_model_source, |
| 131 | logical_cpus: std::thread::available_parallelism().ok().map(|n| n.get()), |
| 132 | mem_total_kib: mem_total_kib(), |
| 133 | git_version: command_line("git", &["--version"]).unwrap_or_else(|| UNKNOWN.into()), |
| 134 | rustc_version: command_line("rustc", &["--version"]).unwrap_or_else(|| UNKNOWN.into()), |
| 135 | cargo_version: command_line("cargo", &["--version"]).unwrap_or_else(|| UNKNOWN.into()), |
| 136 | work_dir: dir_str, |
| 137 | work_dir_fs_type: fs_type, |
| 138 | work_dir_source: source, |
| 139 | work_dir_free_bytes_at_start: free_bytes(work_dir), |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | /// Effective value and origin of one Git config key as seen from `repo`. |
| 144 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 145 | pub struct GitConfigValue { |
| 146 | pub key: String, |
| 147 | /// `git config --show-origin --get-all` lines, or empty when unset. |
| 148 | pub values_with_origin: Vec<String>, |
| 149 | pub set: bool, |
| 150 | } |
| 151 | |
| 152 | /// Read `key` with `git config --show-origin --get-all` (exit 1 means unset). |
| 153 | pub fn git_config_value(repo: &Path, key: &str) -> Result<GitConfigValue, String> { |
| 154 | let run = run_git( |
| 155 | repo, |
| 156 | &[], |
| 157 | &[], |
| 158 | &["config", "--show-origin", "--get-all", key], |
| 159 | None, |
| 160 | )?; |
| 161 | match run.code { |
| 162 | Some(0) => Ok(GitConfigValue { |
| 163 | key: key.to_string(), |
| 164 | values_with_origin: String::from_utf8_lossy(&run.stdout) |
| 165 | .lines() |
| 166 | .map(|l| l.replace('\t', " ")) |
| 167 | .collect(), |
| 168 | set: true, |
| 169 | }), |
| 170 | Some(1) => Ok(GitConfigValue { |
| 171 | key: key.to_string(), |
| 172 | values_with_origin: Vec::new(), |
| 173 | set: false, |
| 174 | }), |
| 175 | other => Err(format!( |
| 176 | "git config --get-all {key} failed (exit {other:?}): {}", |
| 177 | run.stderr_tail() |
| 178 | )), |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | /// Full `git config --list --show-origin` for `repo`, excluding `credential.*` keys. |
| 183 | pub fn git_config_listing(repo: &Path) -> Result<Vec<String>, String> { |
| 184 | let out = crate::gitcmd::git_ok(repo, &[], &[], &["config", "--list", "--show-origin"], None)?; |
| 185 | Ok(String::from_utf8_lossy(&out) |
| 186 | .lines() |
| 187 | .filter(|l| !l.contains("credential.")) |
| 188 | .map(|l| l.replace('\t', " ")) |
| 189 | .collect()) |
| 190 | } |
| 191 | |
| 192 | /// Result of counting fsync-family syscalls issued by one small `git hash-object -w` |
| 193 | /// under `strace`, with and without `core.fsync=all` (verifies that the G3F arm |
| 194 | /// really hardens writes instead of trusting the documentation). |
| 195 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 196 | pub struct FsyncProbe { |
| 197 | pub tool: String, |
| 198 | pub default_config_fsync_calls: Option<u64>, |
| 199 | pub fsync_all_config_fsync_calls: Option<u64>, |
| 200 | pub note: String, |
| 201 | } |
| 202 | |
| 203 | fn strace_fsync_count(repo: &Path, config: &[&str]) -> Result<u64, String> { |
| 204 | let trace_file = repo.join(format!("strace-{}.txt", config.len())); |
| 205 | let mut cmd = Command::new("strace"); |
| 206 | cmd.arg("-f") |
| 207 | .arg("-c") |
| 208 | .arg("-o") |
| 209 | .arg(&trace_file) |
| 210 | .arg("-e") |
| 211 | .arg("trace=fsync,fdatasync,sync_file_range,syncfs") |
| 212 | .arg("git") |
| 213 | .arg("-C") |
| 214 | .arg(repo); |
| 215 | for c in config { |
| 216 | cmd.arg("-c").arg(c); |
| 217 | } |
| 218 | cmd.args(["hash-object", "-w", "--stdin"]); |
| 219 | cmd.stdin(std::process::Stdio::piped()) |
| 220 | .stdout(std::process::Stdio::piped()) |
| 221 | .stderr(std::process::Stdio::piped()); |
| 222 | let mut child = cmd.spawn().map_err(|e| format!("spawn strace: {e}"))?; |
| 223 | { |
| 224 | use std::io::Write; |
| 225 | let mut stdin = child.stdin.take().ok_or("strace stdin unavailable")?; |
| 226 | stdin |
| 227 | .write_all(format!("fsync probe {}\n", config.join(",")).as_bytes()) |
| 228 | .map_err(|e| format!("write strace stdin: {e}"))?; |
| 229 | } |
| 230 | let out = child |
| 231 | .wait_with_output() |
| 232 | .map_err(|e| format!("wait strace: {e}"))?; |
| 233 | if !out.status.success() { |
| 234 | return Err(format!( |
| 235 | "strace git hash-object failed: {}", |
| 236 | String::from_utf8_lossy(&out.stderr).trim() |
| 237 | )); |
| 238 | } |
| 239 | let text = std::fs::read_to_string(&trace_file) |
| 240 | .map_err(|e| format!("read {}: {e}", trace_file.display()))?; |
| 241 | let _ = std::fs::remove_file(&trace_file); |
| 242 | // `strace -c` table rows: "% time seconds usecs/call calls errors syscall". |
| 243 | let mut total = 0u64; |
| 244 | for line in text.lines() { |
| 245 | let cols: Vec<&str> = line.split_whitespace().collect(); |
| 246 | if let Some(name) = cols.last() { |
| 247 | if matches!(*name, "fsync" | "fdatasync" | "sync_file_range" | "syncfs") |
| 248 | && cols.len() >= 5 |
| 249 | { |
| 250 | if let Ok(calls) = cols[3].parse::<u64>() { |
| 251 | total += calls; |
| 252 | } |
| 253 | } |
| 254 | } |
| 255 | } |
| 256 | Ok(total) |
| 257 | } |
| 258 | |
| 259 | /// Probe fsync behaviour in a scratch repository under `scratch_dir`. |
| 260 | pub fn probe_git_fsync(scratch_dir: &Path) -> FsyncProbe { |
| 261 | let repo = scratch_dir.join("fsync-probe-repo"); |
| 262 | let _ = std::fs::remove_dir_all(&repo); |
| 263 | if let Err(e) = std::fs::create_dir_all(&repo) { |
| 264 | return FsyncProbe { |
| 265 | tool: "strace".into(), |
| 266 | default_config_fsync_calls: None, |
| 267 | fsync_all_config_fsync_calls: None, |
| 268 | note: format!("could not create probe repo: {e}"), |
| 269 | }; |
| 270 | } |
| 271 | let init = crate::gitcmd::git_ok(&repo, &[], &[], &["init", "-q"], None); |
| 272 | if let Err(e) = init { |
| 273 | return FsyncProbe { |
| 274 | tool: "strace".into(), |
| 275 | default_config_fsync_calls: None, |
| 276 | fsync_all_config_fsync_calls: None, |
| 277 | note: format!("git init failed: {e}"), |
| 278 | }; |
| 279 | } |
| 280 | let default_calls = strace_fsync_count(&repo, &[]); |
| 281 | let all_calls = strace_fsync_count(&repo, &["core.fsync=all", "core.fsyncMethod=fsync"]); |
| 282 | let _ = std::fs::remove_dir_all(&repo); |
| 283 | let note = match (&default_calls, &all_calls) { |
| 284 | (Ok(_), Ok(_)) => "counts of fsync, fdatasync, sync_file_range, and syncfs calls made by \ |
| 285 | one `git hash-object -w --stdin` (strace -f -c)" |
| 286 | .to_string(), |
| 287 | (d, a) => format!( |
| 288 | "probe incomplete: default={:?} all={:?}", |
| 289 | d.as_ref().err(), |
| 290 | a.as_ref().err() |
| 291 | ), |
| 292 | }; |
| 293 | FsyncProbe { |
| 294 | tool: "strace".into(), |
| 295 | default_config_fsync_calls: default_calls.ok(), |
| 296 | fsync_all_config_fsync_calls: all_calls.ok(), |
| 297 | note, |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | #[cfg(test)] |
| 302 | mod tests { |
| 303 | use super::*; |
| 304 | |
| 305 | #[test] |
| 306 | fn cpu_models_never_empty_and_free_bytes_readable() { |
| 307 | let (models, source) = cpu_models(); |
| 308 | assert!(!models.is_empty()); |
| 309 | assert!(!source.is_empty()); |
| 310 | assert!(free_bytes(&std::env::temp_dir()).is_some()); |
| 311 | } |
| 312 | } |