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

View File

@@ -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(())
}
}

View File

@@ -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(())
}
}

View File

@@ -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<String, std::path::PathBuf>,
}
pub struct OptimizerEngine {

View File

@@ -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<dyn PlatformSal> = if args.mock {
Arc::new(MockSal::new())
let (sal_box, facts): (Box<dyn PlatformSal>, SystemFactSheet) = if args.mock {
(Box::new(MockSal::new()), SystemFactSheet::default())
} 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());
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,

View File

@@ -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<dyn PlatformSal>,
facts: SystemFactSheet,
workload: Box<dyn Workload>,
telemetry_tx: mpsc::Sender<TelemetryState>,
command_rx: mpsc::Receiver<UiCommand>,
@@ -39,6 +42,7 @@ pub struct BenchmarkOrchestrator {
impl BenchmarkOrchestrator {
pub fn new(
sal: Arc<dyn PlatformSal>,
facts: SystemFactSheet,
workload: Box<dyn Workload>,
telemetry_tx: mpsc::Sender<TelemetryState>,
command_rx: mpsc::Receiver<UiCommand>,
@@ -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(),
}
}

View File

@@ -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<PathBuf>,
@@ -23,72 +25,30 @@ pub struct DellXps9380Sal {
}
impl DellXps9380Sal {
pub fn init() -> Result<Self> {
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<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 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<f32> {
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)
}
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)
}
fn get_fan_rpms(&self) -> Result<Vec<u32>> {
@@ -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(())

View File

@@ -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,
}
}

View File

@@ -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<String, PathBuf>,
pub tools: HashMap<String, PathBuf>,
}
/// 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<PathBuf>,
pub fan_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(
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))

View File

@@ -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<Box<dyn PlatformSal>> {
pub fn detect_and_build() -> 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.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))
}
}

View File

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