added dynamic discovery of configurations

This commit is contained in:
2026-02-26 16:04:34 +01:00
parent 073414a25e
commit 07ccf7ccc7
13 changed files with 188 additions and 130 deletions

24
Cargo.lock generated
View File

@@ -535,6 +535,7 @@ dependencies = [
"tracing", "tracing",
"tracing-appender", "tracing-appender",
"tracing-subscriber", "tracing-subscriber",
"which",
] ]
[[package]] [[package]]
@@ -543,6 +544,12 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0"
[[package]]
name = "env_home"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c7f84e12ccf0a7ddc17a6c41c93326024c42920d7ee630d04950e6926645c0fe"
[[package]] [[package]]
name = "equivalent" name = "equivalent"
version = "1.0.2" version = "1.0.2"
@@ -2254,6 +2261,17 @@ dependencies = [
"wezterm-dynamic", "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]] [[package]]
name = "winapi" name = "winapi"
version = "0.3.9" version = "0.3.9"
@@ -2548,6 +2566,12 @@ version = "0.7.14"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a5364e9d77fcdeeaa6062ced926ee3381faa2ee02d3eb83a5c27a8825540829" checksum = "5a5364e9d77fcdeeaa6062ced926ee3381faa2ee02d3eb83a5c27a8825540829"
[[package]]
name = "winsafe"
version = "0.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904"
[[package]] [[package]]
name = "wit-bindgen" name = "wit-bindgen"
version = "0.51.0" version = "0.51.0"

View File

@@ -30,3 +30,4 @@ libc = "0.2"
num_cpus = "1.17" num_cpus = "1.17"
toml = "1.0.3" toml = "1.0.3"
regex = "1.12.3" regex = "1.12.3"
which = "8.0.0"

View File

@@ -1,5 +1,5 @@
[metadata] [metadata]
version = "1.1.0" version = "1.2.0"
updated = "2026-02-26" updated = "2026-02-26"
description = "Hardware and Conflict Database for ember-tune Thermal Engine" 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"] amd_energy_paths = ["zenpower/energy1_input", "k10temp/energy1_input"]
governor_files = ["energy_performance_preference", "energy_performance_hint", "scaling_governor"] 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 # env health verification
[[preflight_checks]] [[preflight_checks]]

View File

@@ -1,3 +1,6 @@
use std::path::Path;
use anyhow::Result;
pub struct I8kmonConfig { pub struct I8kmonConfig {
pub t_ambient: f32, pub t_ambient: f32,
pub t_max_fan: f32, pub t_max_fan: f32,
@@ -38,4 +41,10 @@ set config(speed_high) 4500
t_high_off = t_high_off 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(())
}
} }

View File

@@ -1,4 +1,6 @@
use std::collections::HashSet; use std::collections::HashSet;
use std::path::Path;
use anyhow::{Result};
pub struct ThrottledConfig { pub struct ThrottledConfig {
pub pl1_limit: f32, pub pl1_limit: f32,
@@ -38,13 +40,11 @@ Trip_Temp_C: {trip:.0}
} }
/// Merges benchmarked values into an existing throttled.conf content. /// 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 { pub fn merge_conf(existing_content: &str, config: &ThrottledConfig) -> String {
let mut sections = Vec::new(); let mut sections = Vec::new();
let mut current_section_name = String::new(); let mut current_section_name = String::new();
let mut current_section_lines = Vec::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() { for line in existing_content.lines() {
let trimmed = line.trim(); let trimmed = line.trim();
if trimmed.starts_with('[') && trimmed.ends_with(']') { if trimmed.starts_with('[') && trimmed.ends_with(']') {
@@ -68,17 +68,14 @@ Trip_Temp_C: {trip:.0}
let mut result_lines = Vec::new(); let mut result_lines = Vec::new();
let mut handled_sections = HashSet::new(); let mut handled_sections = HashSet::new();
// 2. Process sections
for (name, mut lines) in sections { for (name, mut lines) in sections {
if name == "BATTERY" || name == "AC" { if name == "BATTERY" || name == "AC" {
handled_sections.insert(name.clone()); handled_sections.insert(name.clone());
let mut updated_keys = HashSet::new(); let mut updated_keys = HashSet::new();
let mut new_lines = Vec::new(); let mut new_lines = Vec::new();
for line in lines { for line in lines {
let mut updated = false; let mut updated = false;
let trimmed = line.trim(); let trimmed = line.trim();
if !trimmed.starts_with('#') && !trimmed.is_empty() { if !trimmed.starts_with('#') && !trimmed.is_empty() {
if let Some((key, _)) = trimmed.split_once(':') { if let Some((key, _)) = trimmed.split_once(':') {
let key = key.trim(); let key = key.trim();
@@ -87,11 +84,7 @@ Trip_Temp_C: {trip:.0}
if let Some(colon_idx) = line.find(':') { if let Some(colon_idx) = line.find(':') {
let prefix = &line[..colon_idx + 1]; let prefix = &line[..colon_idx + 1];
let rest = &line[colon_idx + 1..]; let rest = &line[colon_idx + 1..];
let comment = if let Some(hash_idx) = rest.find('#') { let comment = if let Some(hash_idx) = rest.find('#') { &rest[hash_idx..] } else { "" };
&rest[hash_idx..]
} else {
""
};
new_lines.push(format!("{} {}{}", prefix, new_value, comment)); new_lines.push(format!("{} {}{}", prefix, new_value, comment));
updated_keys.insert(*target_key); updated_keys.insert(*target_key);
updated = true; 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 { for (target_key, new_value) in &target_keys {
if !updated_keys.contains(*target_key) { if !updated_keys.contains(*target_key) {
new_lines.push(format!("{}: {}", target_key, new_value)); new_lines.push(format!("{}: {}", target_key, new_value));
@@ -117,7 +106,6 @@ Trip_Temp_C: {trip:.0}
result_lines.extend(lines); result_lines.extend(lines);
} }
// 3. Add missing sections if they didn't exist at all
for section_name in &["BATTERY", "AC"] { for section_name in &["BATTERY", "AC"] {
if !handled_sections.contains(*section_name) { if !handled_sections.contains(*section_name) {
result_lines.push(String::new()); result_lines.push(String::new());
@@ -127,7 +115,13 @@ Trip_Temp_C: {trip:.0}
} }
} }
} }
result_lines.join("\n") 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(())
}
} }

View File

@@ -26,6 +26,7 @@ pub struct OptimizationResult {
pub recommended_pl2: f32, pub recommended_pl2: f32,
pub max_temp_c: f32, pub max_temp_c: f32,
pub is_partial: bool, pub is_partial: bool,
pub config_paths: std::collections::HashMap<String, std::path::PathBuf>,
} }
pub struct OptimizerEngine { pub struct OptimizerEngine {

View File

@@ -30,7 +30,8 @@ use mediator::{TelemetryState, UiCommand, BenchmarkPhase};
use sal::traits::{AuditError, PlatformSal}; use sal::traits::{AuditError, PlatformSal};
use sal::mock::MockSal; use sal::mock::MockSal;
use sal::heuristic::engine::HeuristicEngine; use sal::heuristic::engine::HeuristicEngine;
use load::{StressNg, Workload}; use sal::heuristic::discovery::SystemFactSheet;
use load::{StressNg};
use orchestrator::BenchmarkOrchestrator; use orchestrator::BenchmarkOrchestrator;
use ui::dashboard::{draw_dashboard, DashboardState}; use ui::dashboard::{draw_dashboard, DashboardState};
use engine::OptimizationResult; use engine::OptimizationResult;
@@ -67,9 +68,10 @@ fn print_summary_report(result: &OptimizationResult) {
println!("│ Burst (PL2): {:>5.1} W │", result.recommended_pl2); println!("│ Burst (PL2): {:>5.1} W │", result.recommended_pl2);
println!("│ │"); println!("│ │");
println!("{}", "Apply to /etc/throttled.conf:".bold().magenta()); println!("{}", "Apply these to your system:".bold().magenta());
println!("│ PL1_Tdp_W: {:<5.1}", result.recommended_pl1); for (id, path) in &result.config_paths {
println!("PL2_Tdp_W: {:<5.1}", result.recommended_pl2); println!("{:<10}: {:<34}", id, path.display());
}
println!("╰──────────────────────────────────────────────────╯"); println!("╰──────────────────────────────────────────────────╯");
println!(); println!();
} }
@@ -108,11 +110,12 @@ fn main() -> Result<()> {
info!("ember-tune starting with args: {:?}", args); info!("ember-tune starting with args: {:?}", args);
// 2. Platform Detection & Audit // 2. Platform Detection & Audit
let sal: Arc<dyn PlatformSal> = if args.mock { let (sal_box, facts): (Box<dyn PlatformSal>, SystemFactSheet) = if args.mock {
Arc::new(MockSal::new()) (Box::new(MockSal::new()), SystemFactSheet::default())
} else { } else {
HeuristicEngine::detect_and_build()?.into() HeuristicEngine::detect_and_build()?
}; };
let sal: Arc<dyn PlatformSal> = sal_box.into();
println!("{}", console::style("─── Pre-flight System Audit ───").bold().cyan()); println!("{}", console::style("─── Pre-flight System Audit ───").bold().cyan());
let mut audit_failures = Vec::new(); let mut audit_failures = Vec::new();
@@ -163,10 +166,12 @@ fn main() -> Result<()> {
// 5. Spawn Backend Orchestrator // 5. Spawn Backend Orchestrator
let sal_backend = sal.clone(); let sal_backend = sal.clone();
let facts_backend = facts.clone();
let backend_handle = thread::spawn(move || { let backend_handle = thread::spawn(move || {
let workload = Box::new(StressNg::new()); let workload = Box::new(StressNg::new());
let mut orchestrator = BenchmarkOrchestrator::new( let mut orchestrator = BenchmarkOrchestrator::new(
sal_backend, sal_backend,
facts_backend,
workload, workload,
telemetry_tx, telemetry_tx,
command_rx, command_rx,

View File

@@ -7,14 +7,17 @@ use sysinfo::System;
use std::sync::Arc; use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex; use std::sync::Mutex;
use std::path::PathBuf;
use crate::sal::traits::{PlatformSal, AuditStep, SafetyStatus}; use crate::sal::traits::{PlatformSal, AuditStep, SafetyStatus};
use crate::sal::heuristic::discovery::SystemFactSheet;
use crate::load::Workload; use crate::load::Workload;
use crate::mediator::{TelemetryState, UiCommand, BenchmarkPhase}; use crate::mediator::{TelemetryState, UiCommand, BenchmarkPhase};
use crate::engine::{OptimizerEngine, ThermalProfile, ThermalPoint, OptimizationResult}; use crate::engine::{OptimizerEngine, ThermalProfile, ThermalPoint, OptimizationResult};
pub struct BenchmarkOrchestrator { pub struct BenchmarkOrchestrator {
sal: Arc<dyn PlatformSal>, sal: Arc<dyn PlatformSal>,
facts: SystemFactSheet,
workload: Box<dyn Workload>, workload: Box<dyn Workload>,
telemetry_tx: mpsc::Sender<TelemetryState>, telemetry_tx: mpsc::Sender<TelemetryState>,
command_rx: mpsc::Receiver<UiCommand>, command_rx: mpsc::Receiver<UiCommand>,
@@ -39,6 +42,7 @@ pub struct BenchmarkOrchestrator {
impl BenchmarkOrchestrator { impl BenchmarkOrchestrator {
pub fn new( pub fn new(
sal: Arc<dyn PlatformSal>, sal: Arc<dyn PlatformSal>,
facts: SystemFactSheet,
workload: Box<dyn Workload>, workload: Box<dyn Workload>,
telemetry_tx: mpsc::Sender<TelemetryState>, telemetry_tx: mpsc::Sender<TelemetryState>,
command_rx: mpsc::Receiver<UiCommand>, command_rx: mpsc::Receiver<UiCommand>,
@@ -53,6 +57,7 @@ impl BenchmarkOrchestrator {
Self { Self {
sal, sal,
facts,
workload, workload,
telemetry_tx, telemetry_tx,
command_rx, command_rx,
@@ -168,7 +173,7 @@ impl BenchmarkOrchestrator {
self.phase = BenchmarkPhase::PhysicalModeling; self.phase = BenchmarkPhase::PhysicalModeling;
self.log("Phase 3: Calculating Silicon Physical Sweet Spot...")?; 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!("✓ Thermal Resistance (Rθ): {:.3} K/W", res.thermal_resistance_kw))?;
self.log(&format!("✓ Silicon Knee Found: {:.1} W", res.silicon_knee_watts))?; self.log(&format!("✓ Silicon Knee Found: {:.1} W", res.silicon_knee_watts))?;
@@ -186,24 +191,22 @@ impl BenchmarkOrchestrator {
}; };
// 1. Throttled (Merged if exists) // 1. Throttled (Merged if exists)
let throttled_path = "throttled.conf"; if let Some(throttled_path) = self.facts.paths.configs.get("throttled") {
let existing_throttled = std::fs::read_to_string(throttled_path).unwrap_or_default(); crate::engine::formatters::throttled::ThrottledTranslator::save(throttled_path, &config)?;
let throttled_content = if existing_throttled.is_empty() { self.log(&format!("✓ Saved '{}' (merged).", throttled_path.display()))?;
crate::engine::formatters::throttled::ThrottledTranslator::generate_conf(&config) res.config_paths.insert("throttled".to_string(), throttled_path.clone());
} else { }
crate::engine::formatters::throttled::ThrottledTranslator::merge_conf(&existing_throttled, &config)
};
std::fs::write(throttled_path, throttled_content)?;
self.log("✓ Saved 'throttled.conf' (merged).")?;
// 2. i8kmon // 2. i8kmon
let i8k_config = crate::engine::formatters::i8kmon::I8kmonConfig { if let Some(i8k_path) = self.facts.paths.configs.get("i8kmon") {
t_ambient: self.profile.ambient_temp, let i8k_config = crate::engine::formatters::i8kmon::I8kmonConfig {
t_max_fan: res.max_temp_c - 5.0, // Aim to hit max fan before max temp t_ambient: self.profile.ambient_temp,
}; t_max_fan: res.max_temp_c - 5.0,
let i8k_content = crate::engine::formatters::i8kmon::I8kmonTranslator::generate_conf(&i8k_config); };
std::fs::write("i8kmon.conf", i8k_content)?; crate::engine::formatters::i8kmon::I8kmonTranslator::save(i8k_path, &i8k_config)?;
self.log("✓ Saved 'i8kmon.conf'.")?; self.log(&format!("✓ Saved '{}'.", i8k_path.display()))?;
res.config_paths.insert("i8kmon".to_string(), i8k_path.clone());
}
self.sal.restore()?; self.sal.restore()?;
self.log("✓ Environment restored.")?; self.log("✓ Environment restored.")?;
@@ -253,6 +256,7 @@ impl BenchmarkOrchestrator {
recommended_pl2: knee * 1.25, recommended_pl2: knee * 1.25,
max_temp_c: max_t, max_temp_c: max_t,
is_partial, is_partial,
config_paths: std::collections::HashMap::new(),
} }
} }

View File

@@ -1,13 +1,15 @@
use super::traits::{PreflightAuditor, EnvironmentGuard, SensorBus, ActuatorBus, HardwareWatchdog, AuditError, AuditStep, SafetyStatus}; 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::fs;
use std::path::PathBuf; use std::path::{PathBuf};
use std::process::Command; use std::process::Command;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use std::sync::Mutex; use std::sync::Mutex;
use tracing::{debug, warn}; use tracing::{debug};
use crate::sal::heuristic::discovery::SystemFactSheet;
pub struct DellXps9380Sal { pub struct DellXps9380Sal {
fact_sheet: SystemFactSheet,
temp_path: PathBuf, temp_path: PathBuf,
pwr_path: PathBuf, pwr_path: PathBuf,
fan_paths: Vec<PathBuf>, fan_paths: Vec<PathBuf>,
@@ -23,72 +25,30 @@ pub struct DellXps9380Sal {
} }
impl DellXps9380Sal { impl DellXps9380Sal {
pub fn init() -> Result<Self> { pub fn init(facts: SystemFactSheet) -> Result<Self> {
let mut temp_path = None; let temp_path = facts.temp_path.clone().context("Dell SAL requires temperature sensor")?;
let mut pwr_path = None; let pwr_base = facts.rapl_paths.first().cloned().context("Dell SAL requires RAPL interface")?;
let mut fan_paths = Vec::new(); let fan_paths = facts.fan_paths.clone();
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")?;
let freq_path = PathBuf::from("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq"); 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") 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?")?; .context("Failed to open /dev/cpu/0/msr. Is the 'msr' module loaded?")?;
Ok(Self { Ok(Self {
temp_path: temp_path.context("Could not find dell_smm temperature path")?, temp_path,
pwr_path: pwr_path.context("Could not find RAPL power path")?, pwr_path: pwr_base.join("power1_average"),
fan_paths, fan_paths,
freq_path, freq_path,
pl1_path: rapl_base.join("constraint_0_power_limit_uw"), pl1_path: pwr_base.join("constraint_0_power_limit_uw"),
pl2_path: rapl_base.join("constraint_1_power_limit_uw"), pl2_path: pwr_base.join("constraint_1_power_limit_uw"),
last_poll: Mutex::new(Instant::now() - Duration::from_secs(2)), last_poll: Mutex::new(Instant::now() - Duration::from_secs(2)),
last_temp: Mutex::new(0.0), last_temp: Mutex::new(0.0),
last_fans: Mutex::new(Vec::new()), last_fans: Mutex::new(Vec::new()),
suppressed_services: Mutex::new(Vec::new()), suppressed_services: Mutex::new(Vec::new()),
msr_file: Mutex::new(msr_file), msr_file: Mutex::new(msr_file),
last_energy: Mutex::new((0, Instant::now())), 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()) Box::new(steps.into_iter())
} }
} }
@@ -189,20 +156,15 @@ impl SensorBus for DellXps9380Sal {
} }
fn get_power_w(&self) -> Result<f32> { fn get_power_w(&self) -> Result<f32> {
if self.pwr_path.to_string_lossy().contains("energy_uj") { let mut last = self.last_energy.lock().unwrap();
let mut last = self.last_energy.lock().unwrap(); let e2 = fs::read_to_string(&self.pwr_path)?.trim().parse::<u64>()?;
let e2 = fs::read_to_string(&self.pwr_path)?.trim().parse::<u64>()?; let t2 = Instant::now();
let t2 = Instant::now(); let (e1, t1) = *last;
let (e1, t1) = *last; let delta_e = e2.wrapping_sub(e1);
let delta_e = e2.wrapping_sub(e1); let delta_t = t2.duration_since(t1).as_secs_f32();
let delta_t = t2.duration_since(t1).as_secs_f32(); *last = (e2, t2);
*last = (e2, t2); if delta_t < 0.01 { return Ok(0.0); }
if delta_t < 0.01 { return Ok(0.0); } Ok((delta_e as f32 / 1_000_000.0) / delta_t)
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>> { fn get_fan_rpms(&self) -> Result<Vec<u32>> {
@@ -230,9 +192,12 @@ impl SensorBus for DellXps9380Sal {
impl ActuatorBus for DellXps9380Sal { impl ActuatorBus for DellXps9380Sal {
fn set_fan_mode(&self, mode: &str) -> Result<()> { 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 { match mode {
"max" | "Manual" => { Command::new("dell-bios-fan-control").arg("0").status()?; } "max" | "Manual" => { Command::new(tool_path).arg("0").status()?; }
"auto" | "Auto" => { Command::new("dell-bios-fan-control").arg("1").status()?; } "auto" | "Auto" => { Command::new(tool_path).arg("1").status()?; }
_ => { debug!("Unknown fan mode: {}", mode); } _ => { debug!("Unknown fan mode: {}", mode); }
} }
Ok(()) Ok(())

View File

@@ -20,14 +20,14 @@ pub struct GenericLinuxSal {
} }
impl GenericLinuxSal { impl GenericLinuxSal {
pub fn new(fact_sheet: SystemFactSheet, db: HardwareDb) -> Self { pub fn new(facts: SystemFactSheet, db: HardwareDb) -> Self {
Self { Self {
fact_sheet,
db, db,
suppressed_services: Mutex::new(Vec::new()), suppressed_services: Mutex::new(Vec::new()),
last_valid_temp: Mutex::new((0.0, Instant::now())), last_valid_temp: Mutex::new((0.0, Instant::now())),
current_pl1: Mutex::new(15.0), current_pl1: Mutex::new(15.0),
last_energy: Mutex::new((0, Instant::now())), last_energy: Mutex::new((0, Instant::now())),
fact_sheet: facts,
} }
} }

View File

@@ -1,12 +1,20 @@
use std::fs; use std::fs;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::process::Command; use std::process::Command;
use std::time::Duration; use std::time::{Duration};
use std::thread; use std::thread;
use std::sync::mpsc; 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}; use tracing::{debug, warn};
/// Registry of dynamically discovered paths for configs and tools.
#[derive(Debug, Clone, Default)]
pub struct PathRegistry {
pub configs: HashMap<String, PathBuf>,
pub tools: HashMap<String, PathBuf>,
}
/// Strongly-typed findings about the current system. /// Strongly-typed findings about the current system.
#[derive(Debug, Clone, Default)] #[derive(Debug, Clone, Default)]
pub struct SystemFactSheet { pub struct SystemFactSheet {
@@ -15,21 +23,21 @@ pub struct SystemFactSheet {
pub temp_path: Option<PathBuf>, pub temp_path: Option<PathBuf>,
pub fan_paths: Vec<PathBuf>, pub fan_paths: Vec<PathBuf>,
pub rapl_paths: Vec<PathBuf>, pub rapl_paths: Vec<PathBuf>,
pub active_conflicts: Vec<String>, // List of conflict IDs found active pub active_conflicts: Vec<String>,
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( pub fn discover_facts(
sensors: &SensorDiscovery, discovery: &Discovery,
actuators: &ActuatorDiscovery,
conflicts: &[Conflict] conflicts: &[Conflict]
) -> SystemFactSheet { ) -> SystemFactSheet {
let (vendor, model) = read_dmi_info(); let (vendor, model) = read_dmi_info();
debug!("DMI Identity: Vendor='{}', Model='{}'", vendor, model); debug!("DMI Identity: Vendor='{}', Model='{}'", vendor, model);
let (temp_path, fan_paths) = discover_hwmon(sensors); let (temp_path, fan_paths) = discover_hwmon(&discovery.sensors);
let rapl_paths = discover_rapl(actuators); let rapl_paths = discover_rapl(&discovery.actuators);
let mut active_conflicts = Vec::new(); let mut active_conflicts = Vec::new();
for conflict in conflicts { for conflict in conflicts {
@@ -37,11 +45,13 @@ pub fn discover_facts(
if is_service_active(service) { if is_service_active(service) {
debug!("Detected active conflict: {} (Service: {})", conflict.id, service); debug!("Detected active conflict: {} (Service: {})", conflict.id, service);
active_conflicts.push(conflict.id.clone()); active_conflicts.push(conflict.id.clone());
break; // Found one service in this conflict, move to next conflict break;
} }
} }
} }
let paths = discover_paths(discovery);
SystemFactSheet { SystemFactSheet {
vendor, vendor,
model, model,
@@ -49,9 +59,42 @@ pub fn discover_facts(
fan_paths, fan_paths,
rapl_paths, rapl_paths,
active_conflicts, 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. /// Reads DMI information from sysfs with a safety timeout.
fn read_dmi_info() -> (String, String) { fn read_dmi_info() -> (String, String) {
let vendor = read_sysfs_with_timeout(Path::new("/sys/class/dmi/id/sys_vendor"), Duration::from_millis(100)) let vendor = read_sysfs_with_timeout(Path::new("/sys/class/dmi/id/sys_vendor"), Duration::from_millis(100))

View File

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

View File

@@ -68,6 +68,8 @@ pub struct Quirk {
pub struct Discovery { pub struct Discovery {
pub sensors: SensorDiscovery, pub sensors: SensorDiscovery,
pub actuators: ActuatorDiscovery, pub actuators: ActuatorDiscovery,
pub configs: HashMap<String, Vec<String>>,
pub tools: HashMap<String, String>,
} }
#[derive(Debug, Deserialize, Clone)] #[derive(Debug, Deserialize, Clone)]