From 07ccf7ccc7bf540bcd77d9972f0cf3f76acf9cd1 Mon Sep 17 00:00:00 2001 From: Nils Pukropp Date: Thu, 26 Feb 2026 16:04:34 +0100 Subject: [PATCH] added dynamic discovery of configurations --- Cargo.lock | 24 +++++++ Cargo.toml | 1 + assets/hardware_db.toml | 12 +++- src/engine/formatters/i8kmon.rs | 9 +++ src/engine/formatters/throttled.rs | 28 +++----- src/engine/mod.rs | 1 + src/main.rs | 19 +++-- src/orchestrator/mod.rs | 38 +++++----- src/sal/dell_xps_9380.rs | 107 ++++++++++------------------- src/sal/generic_linux.rs | 4 +- src/sal/heuristic/discovery.rs | 61 +++++++++++++--- src/sal/heuristic/engine.rs | 12 ++-- src/sal/heuristic/schema.rs | 2 + 13 files changed, 188 insertions(+), 130 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index aca5993..dbce524 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -535,6 +535,7 @@ dependencies = [ "tracing", "tracing-appender", "tracing-subscriber", + "which", ] [[package]] @@ -543,6 +544,12 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" +[[package]] +name = "env_home" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7f84e12ccf0a7ddc17a6c41c93326024c42920d7ee630d04950e6926645c0fe" + [[package]] name = "equivalent" version = "1.0.2" @@ -2254,6 +2261,17 @@ dependencies = [ "wezterm-dynamic", ] +[[package]] +name = "which" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fabb953106c3c8eea8306e4393700d7657561cb43122571b172bbfb7c7ba1d" +dependencies = [ + "env_home", + "rustix", + "winsafe", +] + [[package]] name = "winapi" version = "0.3.9" @@ -2548,6 +2566,12 @@ version = "0.7.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a5364e9d77fcdeeaa6062ced926ee3381faa2ee02d3eb83a5c27a8825540829" +[[package]] +name = "winsafe" +version = "0.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904" + [[package]] name = "wit-bindgen" version = "0.51.0" diff --git a/Cargo.toml b/Cargo.toml index 40147dc..91ab9f7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,3 +30,4 @@ libc = "0.2" num_cpus = "1.17" toml = "1.0.3" regex = "1.12.3" +which = "8.0.0" diff --git a/assets/hardware_db.toml b/assets/hardware_db.toml index 4eeedef..f6219e2 100644 --- a/assets/hardware_db.toml +++ b/assets/hardware_db.toml @@ -1,5 +1,5 @@ [metadata] -version = "1.1.0" +version = "1.2.0" updated = "2026-02-26" description = "Hardware and Conflict Database for ember-tune Thermal Engine" @@ -129,6 +129,16 @@ rapl_paths = ["intel-rapl:0", "package-0", "intel-rapl:1"] amd_energy_paths = ["zenpower/energy1_input", "k10temp/energy1_input"] governor_files = ["energy_performance_preference", "energy_performance_hint", "scaling_governor"] +[discovery.configs] +throttled = ["/etc/throttled.conf", "/usr/local/etc/throttled.conf", "/etc/lenovo_fix.conf"] +i8kmon = ["/etc/i8kmon.conf", "/etc/default/i8kmon"] +tlp = ["/etc/tlp.conf", "/etc/default/tlp"] + +[discovery.tools] +dell_fan_ctrl = "dell-bios-fan-control" +ectool = "ectool" +ryzenadj = "ryzenadj" + # env health verification [[preflight_checks]] diff --git a/src/engine/formatters/i8kmon.rs b/src/engine/formatters/i8kmon.rs index d1b1129..bf12297 100644 --- a/src/engine/formatters/i8kmon.rs +++ b/src/engine/formatters/i8kmon.rs @@ -1,3 +1,6 @@ +use std::path::Path; +use anyhow::Result; + pub struct I8kmonConfig { pub t_ambient: f32, pub t_max_fan: f32, @@ -38,4 +41,10 @@ set config(speed_high) 4500 t_high_off = t_high_off ) } + + pub fn save(path: &Path, config: &I8kmonConfig) -> Result<()> { + let content = Self::generate_conf(config); + std::fs::write(path, content)?; + Ok(()) + } } diff --git a/src/engine/formatters/throttled.rs b/src/engine/formatters/throttled.rs index 3e4c771..9febe7e 100644 --- a/src/engine/formatters/throttled.rs +++ b/src/engine/formatters/throttled.rs @@ -1,4 +1,6 @@ use std::collections::HashSet; +use std::path::Path; +use anyhow::{Result}; pub struct ThrottledConfig { pub pl1_limit: f32, @@ -38,13 +40,11 @@ Trip_Temp_C: {trip:.0} } /// Merges benchmarked values into an existing throttled.conf content. - /// Preserves all other sections (like [UnderVOLT]), comments, and formatting. pub fn merge_conf(existing_content: &str, config: &ThrottledConfig) -> String { let mut sections = Vec::new(); let mut current_section_name = String::new(); let mut current_section_lines = Vec::new(); - // 1. Parse into sections to ensure we only update keys in [BATTERY] and [AC] for line in existing_content.lines() { let trimmed = line.trim(); if trimmed.starts_with('[') && trimmed.ends_with(']') { @@ -68,17 +68,14 @@ Trip_Temp_C: {trip:.0} let mut result_lines = Vec::new(); let mut handled_sections = HashSet::new(); - // 2. Process sections for (name, mut lines) in sections { if name == "BATTERY" || name == "AC" { handled_sections.insert(name.clone()); let mut updated_keys = HashSet::new(); - let mut new_lines = Vec::new(); for line in lines { let mut updated = false; let trimmed = line.trim(); - if !trimmed.starts_with('#') && !trimmed.is_empty() { if let Some((key, _)) = trimmed.split_once(':') { let key = key.trim(); @@ -87,11 +84,7 @@ Trip_Temp_C: {trip:.0} if let Some(colon_idx) = line.find(':') { let prefix = &line[..colon_idx + 1]; let rest = &line[colon_idx + 1..]; - let comment = if let Some(hash_idx) = rest.find('#') { - &rest[hash_idx..] - } else { - "" - }; + let comment = if let Some(hash_idx) = rest.find('#') { &rest[hash_idx..] } else { "" }; new_lines.push(format!("{} {}{}", prefix, new_value, comment)); updated_keys.insert(*target_key); updated = true; @@ -101,12 +94,8 @@ Trip_Temp_C: {trip:.0} } } } - - if !updated { - new_lines.push(line); - } + if !updated { new_lines.push(line); } } - for (target_key, new_value) in &target_keys { if !updated_keys.contains(*target_key) { new_lines.push(format!("{}: {}", target_key, new_value)); @@ -117,7 +106,6 @@ Trip_Temp_C: {trip:.0} result_lines.extend(lines); } - // 3. Add missing sections if they didn't exist at all for section_name in &["BATTERY", "AC"] { if !handled_sections.contains(*section_name) { result_lines.push(String::new()); @@ -127,7 +115,13 @@ Trip_Temp_C: {trip:.0} } } } - result_lines.join("\n") } + + pub fn save(path: &Path, config: &ThrottledConfig) -> Result<()> { + let existing = if path.exists() { std::fs::read_to_string(path)? } else { String::new() }; + let content = if existing.is_empty() { Self::generate_conf(config) } else { Self::merge_conf(&existing, config) }; + std::fs::write(path, content)?; + Ok(()) + } } diff --git a/src/engine/mod.rs b/src/engine/mod.rs index 24878bc..7ae4681 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -26,6 +26,7 @@ pub struct OptimizationResult { pub recommended_pl2: f32, pub max_temp_c: f32, pub is_partial: bool, + pub config_paths: std::collections::HashMap, } pub struct OptimizerEngine { diff --git a/src/main.rs b/src/main.rs index 9c62c32..3f14c3a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -30,7 +30,8 @@ use mediator::{TelemetryState, UiCommand, BenchmarkPhase}; use sal::traits::{AuditError, PlatformSal}; use sal::mock::MockSal; use sal::heuristic::engine::HeuristicEngine; -use load::{StressNg, Workload}; +use sal::heuristic::discovery::SystemFactSheet; +use load::{StressNg}; use orchestrator::BenchmarkOrchestrator; use ui::dashboard::{draw_dashboard, DashboardState}; use engine::OptimizationResult; @@ -67,9 +68,10 @@ fn print_summary_report(result: &OptimizationResult) { println!("│ Burst (PL2): {:>5.1} W │", result.recommended_pl2); println!("│ │"); - println!("│ {} │", "Apply to /etc/throttled.conf:".bold().magenta()); - println!("│ PL1_Tdp_W: {:<5.1} │", result.recommended_pl1); - println!("│ PL2_Tdp_W: {:<5.1} │", result.recommended_pl2); + println!("│ {} │", "Apply these to your system:".bold().magenta()); + for (id, path) in &result.config_paths { + println!("│ {:<10}: {:<34} │", id, path.display()); + } println!("╰──────────────────────────────────────────────────╯"); println!(); } @@ -108,11 +110,12 @@ fn main() -> Result<()> { info!("ember-tune starting with args: {:?}", args); // 2. Platform Detection & Audit - let sal: Arc = if args.mock { - Arc::new(MockSal::new()) + let (sal_box, facts): (Box, SystemFactSheet) = if args.mock { + (Box::new(MockSal::new()), SystemFactSheet::default()) } else { - HeuristicEngine::detect_and_build()?.into() + HeuristicEngine::detect_and_build()? }; + let sal: Arc = sal_box.into(); println!("{}", console::style("─── Pre-flight System Audit ───").bold().cyan()); let mut audit_failures = Vec::new(); @@ -163,10 +166,12 @@ fn main() -> Result<()> { // 5. Spawn Backend Orchestrator let sal_backend = sal.clone(); + let facts_backend = facts.clone(); let backend_handle = thread::spawn(move || { let workload = Box::new(StressNg::new()); let mut orchestrator = BenchmarkOrchestrator::new( sal_backend, + facts_backend, workload, telemetry_tx, command_rx, diff --git a/src/orchestrator/mod.rs b/src/orchestrator/mod.rs index 83b5101..8674175 100644 --- a/src/orchestrator/mod.rs +++ b/src/orchestrator/mod.rs @@ -7,14 +7,17 @@ use sysinfo::System; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Mutex; +use std::path::PathBuf; use crate::sal::traits::{PlatformSal, AuditStep, SafetyStatus}; +use crate::sal::heuristic::discovery::SystemFactSheet; use crate::load::Workload; use crate::mediator::{TelemetryState, UiCommand, BenchmarkPhase}; use crate::engine::{OptimizerEngine, ThermalProfile, ThermalPoint, OptimizationResult}; pub struct BenchmarkOrchestrator { sal: Arc, + facts: SystemFactSheet, workload: Box, telemetry_tx: mpsc::Sender, command_rx: mpsc::Receiver, @@ -39,6 +42,7 @@ pub struct BenchmarkOrchestrator { impl BenchmarkOrchestrator { pub fn new( sal: Arc, + facts: SystemFactSheet, workload: Box, telemetry_tx: mpsc::Sender, command_rx: mpsc::Receiver, @@ -53,6 +57,7 @@ impl BenchmarkOrchestrator { Self { sal, + facts, workload, telemetry_tx, command_rx, @@ -168,7 +173,7 @@ impl BenchmarkOrchestrator { self.phase = BenchmarkPhase::PhysicalModeling; self.log("Phase 3: Calculating Silicon Physical Sweet Spot...")?; - let res = self.generate_result(false); + let mut res = self.generate_result(false); self.log(&format!("✓ Thermal Resistance (Rθ): {:.3} K/W", res.thermal_resistance_kw))?; self.log(&format!("✓ Silicon Knee Found: {:.1} W", res.silicon_knee_watts))?; @@ -186,24 +191,22 @@ impl BenchmarkOrchestrator { }; // 1. Throttled (Merged if exists) - let throttled_path = "throttled.conf"; - let existing_throttled = std::fs::read_to_string(throttled_path).unwrap_or_default(); - let throttled_content = if existing_throttled.is_empty() { - crate::engine::formatters::throttled::ThrottledTranslator::generate_conf(&config) - } else { - crate::engine::formatters::throttled::ThrottledTranslator::merge_conf(&existing_throttled, &config) - }; - std::fs::write(throttled_path, throttled_content)?; - self.log("✓ Saved 'throttled.conf' (merged).")?; + if let Some(throttled_path) = self.facts.paths.configs.get("throttled") { + crate::engine::formatters::throttled::ThrottledTranslator::save(throttled_path, &config)?; + self.log(&format!("✓ Saved '{}' (merged).", throttled_path.display()))?; + res.config_paths.insert("throttled".to_string(), throttled_path.clone()); + } // 2. i8kmon - let i8k_config = crate::engine::formatters::i8kmon::I8kmonConfig { - t_ambient: self.profile.ambient_temp, - t_max_fan: res.max_temp_c - 5.0, // Aim to hit max fan before max temp - }; - let i8k_content = crate::engine::formatters::i8kmon::I8kmonTranslator::generate_conf(&i8k_config); - std::fs::write("i8kmon.conf", i8k_content)?; - self.log("✓ Saved 'i8kmon.conf'.")?; + if let Some(i8k_path) = self.facts.paths.configs.get("i8kmon") { + let i8k_config = crate::engine::formatters::i8kmon::I8kmonConfig { + t_ambient: self.profile.ambient_temp, + t_max_fan: res.max_temp_c - 5.0, + }; + crate::engine::formatters::i8kmon::I8kmonTranslator::save(i8k_path, &i8k_config)?; + self.log(&format!("✓ Saved '{}'.", i8k_path.display()))?; + res.config_paths.insert("i8kmon".to_string(), i8k_path.clone()); + } self.sal.restore()?; self.log("✓ Environment restored.")?; @@ -253,6 +256,7 @@ impl BenchmarkOrchestrator { recommended_pl2: knee * 1.25, max_temp_c: max_t, is_partial, + config_paths: std::collections::HashMap::new(), } } diff --git a/src/sal/dell_xps_9380.rs b/src/sal/dell_xps_9380.rs index b59c197..61eaf21 100644 --- a/src/sal/dell_xps_9380.rs +++ b/src/sal/dell_xps_9380.rs @@ -1,13 +1,15 @@ use super::traits::{PreflightAuditor, EnvironmentGuard, SensorBus, ActuatorBus, HardwareWatchdog, AuditError, AuditStep, SafetyStatus}; -use anyhow::{Result, Context}; +use anyhow::{Result, Context, anyhow}; use std::fs; -use std::path::PathBuf; +use std::path::{PathBuf}; use std::process::Command; use std::time::{Duration, Instant}; use std::sync::Mutex; -use tracing::{debug, warn}; +use tracing::{debug}; +use crate::sal::heuristic::discovery::SystemFactSheet; pub struct DellXps9380Sal { + fact_sheet: SystemFactSheet, temp_path: PathBuf, pwr_path: PathBuf, fan_paths: Vec, @@ -23,72 +25,30 @@ pub struct DellXps9380Sal { } impl DellXps9380Sal { - pub fn init() -> Result { - let mut temp_path = None; - let mut pwr_path = None; - let mut fan_paths = Vec::new(); - let mut rapl_base_path = None; - - // Dynamic hwmon discovery - if let Ok(entries) = fs::read_dir("/sys/class/hwmon") { - for entry in entries.flatten() { - let p = entry.path(); - let name = fs::read_to_string(p.join("name")).unwrap_or_default().trim().to_string(); - - if name == "dell_smm" { - temp_path = Some(p.join("temp1_input")); - if let Ok(fan_entries) = fs::read_dir(&p) { - for fan_entry in fan_entries.flatten() { - let fan_p = fan_entry.path(); - if fan_p.file_name().unwrap_or_default().to_string_lossy().starts_with("fan") && - fan_p.file_name().unwrap_or_default().to_string_lossy().ends_with("_input") { - fan_paths.push(fan_p); - } - } - } - fan_paths.sort(); - } - - if name == "intel_rapl" || name == "rapl" { - pwr_path = Some(p.join("power1_average")); - } - } - } - - if let Ok(entries) = fs::read_dir("/sys/class/powercap") { - for entry in entries.flatten() { - let p = entry.path(); - if let Ok(name) = fs::read_to_string(p.join("name")) { - if name.trim() == "package-0" { - rapl_base_path = Some(p.clone()); - if pwr_path.is_none() { - pwr_path = Some(p.join("energy_uj")); - } - break; - } - } - } - } - - let rapl_base = rapl_base_path.context("Could not find RAPL package-0 path in powercap")?; + pub fn init(facts: SystemFactSheet) -> Result { + 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 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?")?; Ok(Self { - temp_path: temp_path.context("Could not find dell_smm temperature path")?, - pwr_path: pwr_path.context("Could not find RAPL power path")?, + temp_path, + pwr_path: pwr_base.join("power1_average"), fan_paths, freq_path, - pl1_path: rapl_base.join("constraint_0_power_limit_uw"), - pl2_path: rapl_base.join("constraint_1_power_limit_uw"), + pl1_path: pwr_base.join("constraint_0_power_limit_uw"), + pl2_path: pwr_base.join("constraint_1_power_limit_uw"), last_poll: Mutex::new(Instant::now() - Duration::from_secs(2)), last_temp: Mutex::new(0.0), 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())), + fact_sheet: facts, }) } @@ -148,6 +108,13 @@ impl PreflightAuditor for DellXps9380Sal { } }); + // Tool availability check + let tool_check = self.fact_sheet.paths.tools.contains_key("dell_fan_ctrl"); + steps.push(AuditStep { + description: "Dell Fan Control Tool".to_string(), + outcome: if tool_check { Ok(()) } else { Err(AuditError::ToolMissing("dell-bios-fan-control not found in PATH".to_string())) } + }); + Box::new(steps.into_iter()) } } @@ -189,20 +156,15 @@ impl SensorBus for DellXps9380Sal { } fn get_power_w(&self) -> Result { - 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::()?; - 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::()? / 1000000.0) - } + let mut last = self.last_energy.lock().unwrap(); + let e2 = fs::read_to_string(&self.pwr_path)?.trim().parse::()?; + 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) } fn get_fan_rpms(&self) -> Result> { @@ -230,9 +192,12 @@ impl SensorBus for DellXps9380Sal { 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"))?; + match mode { - "max" | "Manual" => { Command::new("dell-bios-fan-control").arg("0").status()?; } - "auto" | "Auto" => { Command::new("dell-bios-fan-control").arg("1").status()?; } + "max" | "Manual" => { Command::new(tool_path).arg("0").status()?; } + "auto" | "Auto" => { Command::new(tool_path).arg("1").status()?; } _ => { debug!("Unknown fan mode: {}", mode); } } Ok(()) diff --git a/src/sal/generic_linux.rs b/src/sal/generic_linux.rs index 13fde32..cecefe1 100644 --- a/src/sal/generic_linux.rs +++ b/src/sal/generic_linux.rs @@ -20,14 +20,14 @@ pub struct GenericLinuxSal { } impl GenericLinuxSal { - pub fn new(fact_sheet: SystemFactSheet, db: HardwareDb) -> Self { + pub fn new(facts: SystemFactSheet, db: HardwareDb) -> Self { Self { - fact_sheet, 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())), + fact_sheet: facts, } } diff --git a/src/sal/heuristic/discovery.rs b/src/sal/heuristic/discovery.rs index a4f894a..7495326 100644 --- a/src/sal/heuristic/discovery.rs +++ b/src/sal/heuristic/discovery.rs @@ -1,12 +1,20 @@ use std::fs; use std::path::{Path, PathBuf}; use std::process::Command; -use std::time::Duration; +use std::time::{Duration}; use std::thread; use std::sync::mpsc; -use crate::sal::heuristic::schema::{SensorDiscovery, ActuatorDiscovery, Conflict}; +use std::collections::HashMap; +use crate::sal::heuristic::schema::{SensorDiscovery, ActuatorDiscovery, Conflict, Discovery}; use tracing::{debug, warn}; +/// Registry of dynamically discovered paths for configs and tools. +#[derive(Debug, Clone, Default)] +pub struct PathRegistry { + pub configs: HashMap, + pub tools: HashMap, +} + /// Strongly-typed findings about the current system. #[derive(Debug, Clone, Default)] pub struct SystemFactSheet { @@ -15,21 +23,21 @@ pub struct SystemFactSheet { pub temp_path: Option, pub fan_paths: Vec, pub rapl_paths: Vec, - pub active_conflicts: Vec, // List of conflict IDs found active + pub active_conflicts: Vec, + pub paths: PathRegistry, } -/// Probes the system for hardware sensors, actuators, and service conflicts. +/// Probes the system for hardware sensors, actuators, service conflicts, and paths. pub fn discover_facts( - sensors: &SensorDiscovery, - actuators: &ActuatorDiscovery, + discovery: &Discovery, conflicts: &[Conflict] ) -> SystemFactSheet { let (vendor, model) = read_dmi_info(); debug!("DMI Identity: Vendor='{}', Model='{}'", vendor, model); - let (temp_path, fan_paths) = discover_hwmon(sensors); - let rapl_paths = discover_rapl(actuators); + let (temp_path, fan_paths) = discover_hwmon(&discovery.sensors); + let rapl_paths = discover_rapl(&discovery.actuators); let mut active_conflicts = Vec::new(); for conflict in conflicts { @@ -37,11 +45,13 @@ pub fn discover_facts( if is_service_active(service) { debug!("Detected active conflict: {} (Service: {})", conflict.id, service); active_conflicts.push(conflict.id.clone()); - break; // Found one service in this conflict, move to next conflict + break; } } } + let paths = discover_paths(discovery); + SystemFactSheet { vendor, model, @@ -49,9 +59,42 @@ pub fn discover_facts( fan_paths, rapl_paths, active_conflicts, + paths, } } +fn discover_paths(discovery: &Discovery) -> PathRegistry { + let mut registry = PathRegistry::default(); + + // 1. Discover Tools via PATH + for (id, binary_name) in &discovery.tools { + if let Ok(path) = which::which(binary_name) { + debug!("Discovered tool: {} -> {:?}", id, path); + registry.tools.insert(id.clone(), path); + } + } + + // 2. Discover Configs via existence check + for (id, candidates) in &discovery.configs { + for candidate in candidates { + let path = PathBuf::from(candidate); + if path.exists() { + debug!("Discovered config: {} -> {:?}", id, path); + registry.configs.insert(id.clone(), path); + break; + } + } + // If not found, use the first one as default if any exist + if !registry.configs.contains_key(id) { + if let Some(first) = candidates.first() { + registry.configs.insert(id.clone(), PathBuf::from(first)); + } + } + } + + registry +} + /// 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)) diff --git a/src/sal/heuristic/engine.rs b/src/sal/heuristic/engine.rs index fce728c..d5e5662 100644 --- a/src/sal/heuristic/engine.rs +++ b/src/sal/heuristic/engine.rs @@ -7,13 +7,13 @@ use crate::sal::traits::PlatformSal; use crate::sal::dell_xps_9380::DellXps9380Sal; use crate::sal::generic_linux::GenericLinuxSal; use crate::sal::heuristic::schema::HardwareDb; -use crate::sal::heuristic::discovery::{discover_facts}; +use crate::sal::heuristic::discovery::{discover_facts, SystemFactSheet}; pub struct HeuristicEngine; impl HeuristicEngine { /// Loads the hardware database, probes the system, and builds the appropriate SAL. - pub fn detect_and_build() -> Result> { + pub fn detect_and_build() -> Result<(Box, 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.sensors, &db.discovery.actuators, &db.conflicts); + let facts = discover_facts(&db.discovery, &db.conflicts); info!("System Identity: {} {}", facts.vendor, facts.model); // 3. Routing Logic @@ -32,8 +32,8 @@ 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().map_err(|e| miette::miette!(e))?; - return Ok(Box::new(sal)); + let sal = DellXps9380Sal::init(facts.clone()).map_err(|e| miette::miette!(e))?; + return Ok((Box::new(sal), facts)); } // --- Fallback: Generic Linux SAL --- @@ -47,7 +47,7 @@ impl HeuristicEngine { return Err(miette::miette!("No RAPL power interface discovered. Generic fallback impossible.")); } - Ok(Box::new(GenericLinuxSal::new(facts, db))) + Ok((Box::new(GenericLinuxSal::new(facts.clone(), db)), facts)) } } diff --git a/src/sal/heuristic/schema.rs b/src/sal/heuristic/schema.rs index a64ff9e..aeaf839 100644 --- a/src/sal/heuristic/schema.rs +++ b/src/sal/heuristic/schema.rs @@ -68,6 +68,8 @@ pub struct Quirk { pub struct Discovery { pub sensors: SensorDiscovery, pub actuators: ActuatorDiscovery, + pub configs: HashMap>, + pub tools: HashMap, } #[derive(Debug, Deserialize, Clone)]