impemented mock testing

This commit is contained in:
2026-02-26 17:11:42 +01:00
parent f76acd6256
commit 667d94af7a
21 changed files with 480 additions and 110 deletions

View File

@@ -1,14 +1,14 @@
use super::traits::{PreflightAuditor, EnvironmentGuard, SensorBus, ActuatorBus, HardwareWatchdog, AuditError, AuditStep, SafetyStatus};
use super::traits::{PreflightAuditor, EnvironmentGuard, SensorBus, ActuatorBus, HardwareWatchdog, AuditError, AuditStep, SafetyStatus, EnvironmentCtx};
use anyhow::{Result, Context, anyhow};
use std::fs;
use std::path::{PathBuf};
use std::process::Command;
use std::time::{Duration, Instant};
use std::sync::Mutex;
use tracing::{debug};
use crate::sal::heuristic::discovery::SystemFactSheet;
pub struct DellXps9380Sal {
ctx: EnvironmentCtx,
fact_sheet: SystemFactSheet,
temp_path: PathBuf,
pwr_path: PathBuf,
@@ -25,15 +25,18 @@ pub struct DellXps9380Sal {
}
impl DellXps9380Sal {
pub fn init(facts: SystemFactSheet) -> Result<Self> {
pub fn init(ctx: EnvironmentCtx, facts: SystemFactSheet) -> Result<Self> {
let temp_path = facts.temp_path.clone().context("Dell SAL requires temperature sensor")?;
let pwr_base = facts.rapl_paths.first().cloned().context("Dell SAL requires RAPL interface")?;
let fan_paths = facts.fan_paths.clone();
let freq_path = PathBuf::from("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq");
let freq_path = ctx.sysfs_base.join("sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq");
let msr_path = ctx.sysfs_base.join("dev/cpu/0/msr");
let msr_file = fs::OpenOptions::new().read(true).write(true).open("/dev/cpu/0/msr")
.context("Failed to open /dev/cpu/0/msr. Is the 'msr' module loaded?")?;
let msr_file = fs::OpenOptions::new().read(true).write(true).open(&msr_path)
.with_context(|| format!("Failed to open {:?}. Is the 'msr' module loaded?", msr_path))?;
let initial_energy = fs::read_to_string(pwr_base.join("energy_uj")).unwrap_or_default().trim().parse().unwrap_or(0);
Ok(Self {
temp_path,
@@ -47,8 +50,9 @@ impl DellXps9380Sal {
last_fans: Mutex::new(Vec::new()),
suppressed_services: Mutex::new(Vec::new()),
msr_file: Mutex::new(msr_file),
last_energy: Mutex::new((0, Instant::now())),
last_energy: Mutex::new((initial_energy, Instant::now())),
fact_sheet: facts,
ctx,
})
}
@@ -78,16 +82,17 @@ impl PreflightAuditor for DellXps9380Sal {
let modules = ["dell_smm_hwmon", "msr", "intel_rapl_msr"];
for mod_name in modules {
let path = format!("/sys/module/{}", mod_name);
let path = self.ctx.sysfs_base.join(format!("sys/module/{}", mod_name));
steps.push(AuditStep {
description: format!("Kernel Module: {}", mod_name),
outcome: if PathBuf::from(path).exists() { Ok(()) } else {
outcome: if path.exists() { Ok(()) } else {
Err(AuditError::ToolMissing(format!("Module '{}' not loaded.", mod_name)))
}
});
}
let cmdline = fs::read_to_string("/proc/cmdline").unwrap_or_default();
let cmdline_path = self.ctx.sysfs_base.join("proc/cmdline");
let cmdline = fs::read_to_string(cmdline_path).unwrap_or_default();
let params = [
("dell_smm_hwmon.ignore_dmi=1", "dell_smm_hwmon.ignore_dmi=1"),
("dell_smm_hwmon.restricted=0", "dell_smm_hwmon.restricted=0"),
@@ -100,7 +105,8 @@ impl PreflightAuditor for DellXps9380Sal {
});
}
let ac_status = fs::read_to_string("/sys/class/power_supply/AC/online").unwrap_or_else(|_| "0".to_string());
let ac_status_path = self.ctx.sysfs_base.join("sys/class/power_supply/AC/online");
let ac_status = fs::read_to_string(ac_status_path).unwrap_or_else(|_| "0".to_string());
steps.push(AuditStep {
description: "AC Power Connection".to_string(),
outcome: if ac_status.trim() == "1" { Ok(()) } else {
@@ -123,9 +129,9 @@ impl EnvironmentGuard for DellXps9380Sal {
let services = ["tlp", "thermald", "i8kmon"];
let mut suppressed = self.suppressed_services.lock().unwrap();
for s in services {
if Command::new("systemctl").args(["is-active", "--quiet", s]).status()?.success() {
if self.ctx.runner.run("systemctl", &["is-active", "--quiet", s]).is_ok() {
debug!("Suppressing service: {}", s);
Command::new("systemctl").args(["stop", s]).status()?;
self.ctx.runner.run("systemctl", &["stop", s])?;
suppressed.push(s.to_string());
}
}
@@ -135,7 +141,7 @@ impl EnvironmentGuard for DellXps9380Sal {
fn restore(&self) -> Result<()> {
let mut suppressed = self.suppressed_services.lock().unwrap();
for s in suppressed.drain(..) {
let _ = Command::new("systemctl").args(["start", &s]).status();
let _ = self.ctx.runner.run("systemctl", &["start", &s]);
}
Ok(())
}
@@ -156,15 +162,20 @@ impl SensorBus for DellXps9380Sal {
}
fn get_power_w(&self) -> Result<f32> {
let mut last = self.last_energy.lock().unwrap();
let e2 = fs::read_to_string(&self.pwr_path)?.trim().parse::<u64>()?;
let t2 = Instant::now();
let (e1, t1) = *last;
let delta_e = e2.wrapping_sub(e1);
let delta_t = t2.duration_since(t1).as_secs_f32();
*last = (e2, t2);
if delta_t < 0.01 { return Ok(0.0); }
Ok((delta_e as f32 / 1_000_000.0) / delta_t)
if self.pwr_path.to_string_lossy().contains("energy_uj") {
let mut last = self.last_energy.lock().unwrap();
let e2 = fs::read_to_string(&self.pwr_path)?.trim().parse::<u64>()?;
let t2 = Instant::now();
let (e1, t1) = *last;
let delta_e = e2.wrapping_sub(e1);
let delta_t = t2.duration_since(t1).as_secs_f32();
*last = (e2, t2);
if delta_t < 0.01 { return Ok(0.0); }
Ok((delta_e as f32 / 1_000_000.0) / delta_t)
} else {
let s = fs::read_to_string(&self.pwr_path)?;
Ok(s.trim().parse::<f32>()? / 1000000.0)
}
}
fn get_fan_rpms(&self) -> Result<Vec<u32>> {
@@ -194,10 +205,11 @@ impl ActuatorBus for DellXps9380Sal {
fn set_fan_mode(&self, mode: &str) -> Result<()> {
let tool_path = self.fact_sheet.paths.tools.get("dell_fan_ctrl")
.ok_or_else(|| anyhow!("Dell fan control tool not found in PATH"))?;
let tool_str = tool_path.to_string_lossy();
match mode {
"max" | "Manual" => { Command::new(tool_path).arg("0").status()?; }
"auto" | "Auto" => { Command::new(tool_path).arg("1").status()?; }
"max" | "Manual" => { self.ctx.runner.run(&tool_str, &["0"])?; }
"auto" | "Auto" => { self.ctx.runner.run(&tool_str, &["1"])?; }
_ => { debug!("Unknown fan mode: {}", mode); }
}
Ok(())

View File

@@ -1,16 +1,16 @@
use anyhow::{Result, anyhow};
use std::path::Path;
use std::path::{Path};
use std::fs;
use std::time::{Duration, Instant};
use std::process::Command;
use tracing::{debug, warn};
use std::sync::Mutex;
use tracing::{debug};
use crate::sal::traits::{SensorBus, ActuatorBus, EnvironmentGuard, HardwareWatchdog, PreflightAuditor, AuditStep, AuditError, SafetyStatus};
use crate::sal::traits::{SensorBus, ActuatorBus, EnvironmentGuard, HardwareWatchdog, PreflightAuditor, AuditStep, AuditError, SafetyStatus, EnvironmentCtx};
use crate::sal::heuristic::discovery::SystemFactSheet;
use crate::sal::heuristic::schema::HardwareDb;
pub struct GenericLinuxSal {
ctx: EnvironmentCtx,
fact_sheet: SystemFactSheet,
db: HardwareDb,
suppressed_services: Mutex<Vec<String>>,
@@ -20,14 +20,21 @@ pub struct GenericLinuxSal {
}
impl GenericLinuxSal {
pub fn new(facts: SystemFactSheet, db: HardwareDb) -> Self {
pub fn new(ctx: EnvironmentCtx, facts: SystemFactSheet, db: HardwareDb) -> Self {
let initial_energy = if let Some(pwr_base) = facts.rapl_paths.first() {
fs::read_to_string(pwr_base.join("energy_uj")).unwrap_or_default().trim().parse().unwrap_or(0)
} else {
0
};
Self {
db,
suppressed_services: Mutex::new(Vec::new()),
last_valid_temp: Mutex::new((0.0, Instant::now())),
current_pl1: Mutex::new(15.0),
last_energy: Mutex::new((0, Instant::now())),
last_energy: Mutex::new((initial_energy, Instant::now())),
fact_sheet: facts,
ctx,
}
}
@@ -35,8 +42,6 @@ impl GenericLinuxSal {
self.fact_sheet.vendor.to_lowercase().contains("dell")
}
/// Read sysfs safely. We removed the thread-per-read timeout logic
/// as it was inefficient. sysfs reads are generally fast enough.
fn read_sysfs(&self, path: &Path) -> Result<String> {
fs::read_to_string(path).map(|s| s.trim().to_string()).map_err(|e| anyhow!(e))
}
@@ -46,11 +51,11 @@ impl PreflightAuditor for GenericLinuxSal {
fn audit(&self) -> Box<dyn Iterator<Item = AuditStep> + '_> {
let mut steps = Vec::new();
for check in &self.db.preflight_checks {
let status = Command::new("sh").arg("-c").arg(&check.check_cmd).status();
let status = self.ctx.runner.run("sh", &["-c", &check.check_cmd]);
steps.push(AuditStep {
description: check.name.clone(),
outcome: match status {
Ok(s) if s.success() => Ok(()),
Ok(_) => Ok(()),
_ => Err(AuditError::KernelIncompatible(check.fail_help.clone())),
}
});
@@ -106,11 +111,12 @@ impl SensorBus for GenericLinuxSal {
}
fn get_freq_mhz(&self) -> Result<f32> {
let path = Path::new("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq");
let path = self.ctx.sysfs_base.join("sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq");
if path.exists() {
Ok(self.read_sysfs(path)?.parse::<f32>()? / 1000.0)
Ok(self.read_sysfs(&path)?.parse::<f32>()? / 1000.0)
} else {
let cpuinfo = fs::read_to_string("/proc/cpuinfo")?;
let cpuinfo_path = self.ctx.sysfs_base.join("proc/cpuinfo");
let cpuinfo = fs::read_to_string(cpuinfo_path)?;
for line in cpuinfo.lines() {
if line.starts_with("cpu MHz") {
if let Some((_, mhz)) = line.split_once(':') {
@@ -133,7 +139,7 @@ impl ActuatorBus for GenericLinuxSal {
};
if let Some(cmd_str) = cmd {
let parts: Vec<&str> = cmd_str.split_whitespace().collect();
Command::new(parts[0]).args(&parts[1..]).status()?;
self.ctx.runner.run(parts[0], &parts[1..])?;
Ok(())
} else { Err(anyhow!("Dell fan command missing")) }
} else { Ok(()) }
@@ -159,7 +165,8 @@ impl EnvironmentGuard for GenericLinuxSal {
for conflict_id in &self.fact_sheet.active_conflicts {
if let Some(conflict) = self.db.conflicts.iter().find(|c| &c.id == conflict_id) {
for service in &conflict.services {
if Command::new("systemctl").arg("stop").arg(service).status()?.success() {
if self.ctx.runner.run("systemctl", &["is-active", "--quiet", service]).is_ok() {
self.ctx.runner.run("systemctl", &["stop", service])?;
suppressed.push(service.clone());
}
}
@@ -171,7 +178,7 @@ impl EnvironmentGuard for GenericLinuxSal {
fn restore(&self) -> Result<()> {
let mut suppressed = self.suppressed_services.lock().unwrap();
for service in suppressed.drain(..) {
let _ = Command::new("systemctl").arg("start").arg(service).status();
let _ = self.ctx.runner.run("systemctl", &["start", &service]);
}
if self.is_dell() { let _ = self.set_fan_mode("auto"); }
Ok(())

View File

@@ -5,7 +5,7 @@ use std::time::{Duration};
use std::thread;
use std::sync::mpsc;
use std::collections::HashMap;
use crate::sal::heuristic::schema::{SensorDiscovery, ActuatorDiscovery, Conflict, Discovery};
use crate::sal::heuristic::schema::{SensorDiscovery, ActuatorDiscovery, Conflict, Discovery, Benchmarking};
use tracing::{debug, warn};
/// Registry of dynamically discovered paths for configs and tools.
@@ -25,19 +25,22 @@ pub struct SystemFactSheet {
pub rapl_paths: Vec<PathBuf>,
pub active_conflicts: Vec<String>,
pub paths: PathRegistry,
pub bench_config: Option<Benchmarking>,
}
/// Probes the system for hardware sensors, actuators, service conflicts, and paths.
pub fn discover_facts(
base_path: &Path,
discovery: &Discovery,
conflicts: &[Conflict]
conflicts: &[Conflict],
bench_config: Benchmarking,
) -> SystemFactSheet {
let (vendor, model) = read_dmi_info();
let (vendor, model) = read_dmi_info(base_path);
debug!("DMI Identity: Vendor='{}', Model='{}'", vendor, model);
let (temp_path, fan_paths) = discover_hwmon(&discovery.sensors);
let rapl_paths = discover_rapl(&discovery.actuators);
let (temp_path, fan_paths) = discover_hwmon(base_path, &discovery.sensors);
let rapl_paths = discover_rapl(base_path, &discovery.actuators);
let mut active_conflicts = Vec::new();
for conflict in conflicts {
@@ -50,7 +53,7 @@ pub fn discover_facts(
}
}
let paths = discover_paths(discovery);
let paths = discover_paths(base_path, discovery);
SystemFactSheet {
vendor,
@@ -60,10 +63,11 @@ pub fn discover_facts(
rapl_paths,
active_conflicts,
paths,
bench_config: Some(bench_config),
}
}
fn discover_paths(discovery: &Discovery) -> PathRegistry {
fn discover_paths(base_path: &Path, discovery: &Discovery) -> PathRegistry {
let mut registry = PathRegistry::default();
// 1. Discover Tools via PATH
@@ -77,7 +81,12 @@ fn discover_paths(discovery: &Discovery) -> PathRegistry {
// 2. Discover Configs via existence check
for (id, candidates) in &discovery.configs {
for candidate in candidates {
let path = PathBuf::from(candidate);
let path = if candidate.starts_with('/') {
base_path.join(&candidate[1..])
} else {
base_path.join(candidate)
};
if path.exists() {
debug!("Discovered config: {} -> {:?}", id, path);
registry.configs.insert(id.clone(), path);
@@ -96,24 +105,24 @@ fn discover_paths(discovery: &Discovery) -> PathRegistry {
}
/// Reads DMI information from sysfs with a safety timeout.
fn read_dmi_info() -> (String, String) {
let vendor = read_sysfs_with_timeout(Path::new("/sys/class/dmi/id/sys_vendor"), Duration::from_millis(100))
fn read_dmi_info(base_path: &Path) -> (String, String) {
let vendor = read_sysfs_with_timeout(&base_path.join("sys/class/dmi/id/sys_vendor"), Duration::from_millis(100))
.unwrap_or_else(|| "Unknown".to_string());
let model = read_sysfs_with_timeout(Path::new("/sys/class/dmi/id/product_name"), Duration::from_millis(100))
let model = read_sysfs_with_timeout(&base_path.join("sys/class/dmi/id/product_name"), Duration::from_millis(100))
.unwrap_or_else(|| "Unknown".to_string());
(vendor, model)
}
/// Discovers hwmon sensors by matching labels and prioritizing drivers.
fn discover_hwmon(cfg: &SensorDiscovery) -> (Option<PathBuf>, Vec<PathBuf>) {
fn discover_hwmon(base_path: &Path, cfg: &SensorDiscovery) -> (Option<PathBuf>, Vec<PathBuf>) {
let mut temp_candidates = Vec::new();
let mut fan_candidates = Vec::new();
let hwmon_base = Path::new("/sys/class/hwmon");
let entries = match fs::read_dir(hwmon_base) {
let hwmon_base = base_path.join("sys/class/hwmon");
let entries = match fs::read_dir(&hwmon_base) {
Ok(e) => e,
Err(e) => {
warn!("Could not read /sys/class/hwmon: {}", e);
warn!("Could not read {:?}: {}", hwmon_base, e);
return (None, Vec::new());
}
};
@@ -170,11 +179,11 @@ fn discover_hwmon(cfg: &SensorDiscovery) -> (Option<PathBuf>, Vec<PathBuf>) {
}
/// Discovers RAPL powercap paths.
fn discover_rapl(cfg: &ActuatorDiscovery) -> Vec<PathBuf> {
fn discover_rapl(base_path: &Path, cfg: &ActuatorDiscovery) -> Vec<PathBuf> {
let mut paths = Vec::new();
let powercap_base = Path::new("/sys/class/powercap");
let powercap_base = base_path.join("sys/class/powercap");
let entries = match fs::read_dir(powercap_base) {
let entries = match fs::read_dir(&powercap_base) {
Ok(e) => e,
Err(_) => return Vec::new(),
};

View File

@@ -3,7 +3,7 @@ use std::fs;
use regex::Regex;
use tracing::{info, debug};
use crate::sal::traits::PlatformSal;
use crate::sal::traits::{PlatformSal, EnvironmentCtx};
use crate::sal::dell_xps_9380::DellXps9380Sal;
use crate::sal::generic_linux::GenericLinuxSal;
use crate::sal::heuristic::schema::HardwareDb;
@@ -13,7 +13,7 @@ pub struct HeuristicEngine;
impl HeuristicEngine {
/// Loads the hardware database, probes the system, and builds the appropriate SAL.
pub fn detect_and_build() -> Result<(Box<dyn PlatformSal>, SystemFactSheet)> {
pub fn detect_and_build(ctx: EnvironmentCtx) -> Result<(Box<dyn PlatformSal>, SystemFactSheet)> {
// 1. Load Hardware DB
let db_path = "assets/hardware_db.toml";
let db_content = fs::read_to_string(db_path)
@@ -24,7 +24,7 @@ impl HeuristicEngine {
.context("Failed to parse hardware_db.toml")?;
// 2. Discover Facts
let facts = discover_facts(&db.discovery, &db.conflicts);
let facts = discover_facts(&ctx.sysfs_base, &db.discovery, &db.conflicts, db.benchmarking.clone());
info!("System Identity: {} {}", facts.vendor, facts.model);
// 3. Routing Logic
@@ -32,7 +32,7 @@ impl HeuristicEngine {
// --- Special Case: Dell XPS 13 9380 ---
if is_match(&facts.vendor, "(?i)Dell.*") && is_match(&facts.model, "(?i)XPS.*13.*9380.*") {
info!("Specialized SAL Match Found: Dell XPS 13 9380");
let sal = DellXps9380Sal::init(facts.clone()).map_err(|e| miette::miette!(e))?;
let sal = DellXps9380Sal::init(ctx, facts.clone()).map_err(|e| miette::miette!(e))?;
return Ok((Box::new(sal), facts));
}
@@ -47,7 +47,7 @@ impl HeuristicEngine {
return Err(miette::miette!("No RAPL power interface discovered. Generic fallback impossible."));
}
Ok((Box::new(GenericLinuxSal::new(facts.clone(), db)), facts))
Ok((Box::new(GenericLinuxSal::new(ctx, facts.clone(), db)), facts))
}
}

View File

@@ -8,6 +8,7 @@ pub struct HardwareDb {
pub ecosystems: HashMap<String, Ecosystem>,
pub quirks: Vec<Quirk>,
pub discovery: Discovery,
pub benchmarking: Benchmarking,
pub preflight_checks: Vec<PreflightCheck>,
}
@@ -72,6 +73,15 @@ pub struct Discovery {
pub tools: HashMap<String, String>,
}
#[derive(Debug, Deserialize, Clone)]
pub struct Benchmarking {
pub idle_duration_s: u64,
pub stress_duration_min_s: u64,
pub stress_duration_max_s: u64,
pub cool_down_s: u64,
pub power_steps_watts: Vec<f32>,
}
#[derive(Debug, Deserialize, Clone)]
pub struct SensorDiscovery {
pub temp_labels: Vec<String>,

View File

@@ -1,11 +1,15 @@
use super::traits::{PreflightAuditor, EnvironmentGuard, SensorBus, ActuatorBus, HardwareWatchdog, AuditStep, PlatformSal, SafetyStatus};
use super::traits::{PreflightAuditor, EnvironmentGuard, SensorBus, ActuatorBus, HardwareWatchdog, AuditStep, SafetyStatus};
use anyhow::Result;
pub struct MockSal;
pub struct MockSal {
pub temperature_sequence: std::sync::atomic::AtomicUsize,
}
impl MockSal {
pub fn new() -> Self {
Self
Self {
temperature_sequence: std::sync::atomic::AtomicUsize::new(0),
}
}
}
@@ -36,7 +40,9 @@ impl EnvironmentGuard for MockSal {
impl SensorBus for MockSal {
fn get_temp(&self) -> Result<f32> {
Ok(42.0)
// Support dynamic sequence for Step 5
let seq = self.temperature_sequence.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
Ok(40.0 + (seq as f32 * 0.5).min(50.0)) // Heats up from 40 to 90
}
fn get_power_w(&self) -> Result<f32> {
Ok(15.0)

View File

@@ -2,6 +2,24 @@ use anyhow::Result;
use thiserror::Error;
use miette::Diagnostic;
use std::sync::Arc;
use std::path::PathBuf;
use crate::sys::SyscallRunner;
/// Context holding OS abstractions (filesystem base and syscall runner).
#[derive(Clone)]
pub struct EnvironmentCtx {
pub sysfs_base: PathBuf,
pub runner: Arc<dyn SyscallRunner>,
}
impl EnvironmentCtx {
pub fn production() -> Self {
Self {
sysfs_base: PathBuf::from("/"),
runner: Arc::new(crate::sys::RealSyscallRunner),
}
}
}
#[derive(Error, Diagnostic, Debug, Clone)]
pub enum AuditError {