use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fmt;
pub mod active;
pub mod apply;
pub mod bench;
pub mod cache;
pub mod cpu;
pub mod deviation;
pub mod diff;
pub mod display;
pub mod edid;
pub mod explain;
pub mod gpu;
pub mod memory;
#[cfg(windows)]
pub mod nvidia_drs;
pub mod nvme;
pub mod nvme_features;
pub mod spd_xmp;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub enum Subsystem {
Gpu,
Cpu,
Nvme,
Display,
Memory,
}
impl Subsystem {
pub const ALL: &'static [Subsystem] = &[
Subsystem::Gpu,
Subsystem::Cpu,
Subsystem::Nvme,
Subsystem::Display,
Subsystem::Memory,
];
pub fn as_str(self) -> &'static str {
match self {
Subsystem::Gpu => "gpu",
Subsystem::Cpu => "cpu",
Subsystem::Nvme => "nvme",
Subsystem::Display => "display",
Subsystem::Memory => "memory",
}
}
pub fn parse(s: &str) -> Option<Self> {
match s.to_ascii_lowercase().as_str() {
"gpu" => Some(Subsystem::Gpu),
"cpu" => Some(Subsystem::Cpu),
"nvme" | "storage" => Some(Subsystem::Nvme),
"display" => Some(Subsystem::Display),
"memory" | "dimm" | "ram" => Some(Subsystem::Memory),
_ => None,
}
}
}
impl fmt::Display for Subsystem {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SettingRisk {
Informational,
Safe,
Moderate,
Dangerous,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", content = "value", rename_all = "snake_case")]
pub enum SettingValue {
Bool(bool),
Int(i64),
Uint(u64),
Float(f64),
Text(String),
Hex(String),
Unreadable(String),
}
impl fmt::Display for SettingValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
SettingValue::Bool(b) => write!(f, "{}", b),
SettingValue::Int(i) => write!(f, "{}", i),
SettingValue::Uint(u) => write!(f, "{} (0x{:x})", u, u),
SettingValue::Float(x) => write!(f, "{}", x),
SettingValue::Text(s) => write!(f, "{}", s),
SettingValue::Hex(h) => write!(f, "{}", h),
SettingValue::Unreadable(reason) => write!(f, "<unreadable: {}>", reason),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Setting {
pub id: String,
pub display_name: String,
pub value: SettingValue,
pub unit: Option<String>,
pub default: Option<SettingValue>,
pub choices: Option<Vec<(String, SettingValue)>>,
pub range: Option<(SettingValue, SettingValue)>,
pub description: Option<String>,
pub risk: SettingRisk,
pub source: String,
#[serde(default)]
pub writable: bool,
}
impl Setting {
pub fn info(id: impl Into<String>, name: impl Into<String>, value: SettingValue) -> Self {
Self {
id: id.into(),
display_name: name.into(),
value,
unit: None,
default: None,
choices: None,
range: None,
description: None,
risk: SettingRisk::Informational,
source: String::new(),
writable: false,
}
}
pub fn with_writable(mut self, writable: bool) -> Self {
self.writable = writable;
self
}
pub fn with_unit(mut self, unit: impl Into<String>) -> Self {
self.unit = Some(unit.into());
self
}
pub fn with_source(mut self, src: impl Into<String>) -> Self {
self.source = src.into();
self
}
pub fn with_description(mut self, desc: impl Into<String>) -> Self {
self.description = Some(desc.into());
self
}
pub fn with_risk(mut self, risk: SettingRisk) -> Self {
self.risk = risk;
self
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileGroup {
pub subsystem: Subsystem,
pub device: String,
pub display_name: String,
pub source: String,
pub settings: Vec<Setting>,
pub notes: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key: Option<String>,
}
impl ProfileGroup {
pub fn new(
subsystem: Subsystem,
device: impl Into<String>,
display_name: impl Into<String>,
source: impl Into<String>,
) -> Self {
Self {
subsystem,
device: device.into(),
display_name: display_name.into(),
source: source.into(),
settings: Vec::new(),
notes: Vec::new(),
key: None,
}
}
pub fn with_key(mut self, key: impl Into<String>) -> Self {
self.key = Some(key.into());
self
}
pub fn push(&mut self, setting: Setting) {
self.settings.push(setting);
}
pub fn note(&mut self, msg: impl Into<String>) {
self.notes.push(msg.into());
}
}
#[derive(Debug, Default)]
pub struct ScanOutcome {
pub groups: Vec<ProfileGroup>,
pub unread: Vec<String>,
}
pub(crate) fn split_scan(scan: Result<ScanOutcome, String>) -> (Vec<ProfileGroup>, Vec<String>) {
match scan {
Ok(outcome) => (outcome.groups, outcome.unread),
Err(reason) => (Vec::new(), vec![reason]),
}
}
pub(crate) fn not_read_groups(
subsystem: Subsystem,
scanner: &str,
reasons: &[String],
) -> Vec<ProfileGroup> {
if reasons.is_empty() {
return Vec::new();
}
let mut group = ProfileGroup::new(subsystem, format!("{scanner} (not read)"), scanner, scanner);
for reason in reasons {
group.note(format!("{scanner} not read: {reason}"));
}
vec![group]
}
pub trait ProfileProvider: Send {
fn subsystem(&self) -> Subsystem;
fn snapshot(&mut self) -> Result<Vec<ProfileGroup>, String>;
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileSnapshot {
pub timestamp: u64,
pub providers: BTreeMap<Subsystem, Vec<ProfileGroup>>,
pub errors: BTreeMap<Subsystem, String>,
}
impl ProfileSnapshot {
pub fn total_settings(&self) -> usize {
self.providers
.values()
.flat_map(|groups| groups.iter())
.map(|g| g.settings.len())
.sum()
}
pub fn total_groups(&self) -> usize {
self.providers.values().map(|g| g.len()).sum()
}
pub fn search(&self, needle: &str) -> Vec<(Subsystem, &ProfileGroup, &Setting)> {
let needle = needle.to_ascii_lowercase();
let mut out = Vec::new();
for (sub, groups) in &self.providers {
for group in groups {
for setting in &group.settings {
let hay = format!(
"{} {} {} {}",
setting.id,
setting.display_name,
setting.description.as_deref().unwrap_or(""),
setting.value,
)
.to_ascii_lowercase();
if hay.contains(&needle) {
out.push((*sub, group, setting));
}
}
}
}
out
}
}
pub struct ProfileInspector {
providers: Vec<Box<dyn ProfileProvider>>,
}
impl ProfileInspector {
pub fn new() -> Self {
let providers: Vec<Box<dyn ProfileProvider>> = vec![
Box::new(gpu::GpuProfileProvider::new()),
Box::new(cpu::CpuProfileProvider::new()),
Box::new(nvme::NvmeProfileProvider::new()),
Box::new(display::DisplayProfileProvider::new()),
Box::new(memory::MemoryProfileProvider::new()),
];
Self { providers }
}
pub fn with_providers(providers: Vec<Box<dyn ProfileProvider>>) -> Self {
Self { providers }
}
pub fn snapshot_all(&mut self) -> ProfileSnapshot {
let mut providers = BTreeMap::new();
let mut errors = BTreeMap::new();
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
for p in self.providers.iter_mut() {
let sub = p.subsystem();
match p.snapshot() {
Ok(groups) => providers.entry(sub).or_insert_with(Vec::new).extend(groups),
Err(reason) => {
errors.entry(sub).or_insert(reason);
}
}
}
ProfileSnapshot {
timestamp,
providers,
errors,
}
}
pub fn snapshot(&mut self, subsystem: Subsystem) -> Result<Vec<ProfileGroup>, String> {
let mut out = Vec::new();
for p in self.providers.iter_mut() {
if p.subsystem() == subsystem {
out.extend(p.snapshot()?);
}
}
Ok(out)
}
}
impl Default for ProfileInspector {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn subsystem_roundtrip() {
for s in Subsystem::ALL {
assert_eq!(Subsystem::parse(s.as_str()), Some(*s));
}
assert_eq!(Subsystem::parse("RAM"), Some(Subsystem::Memory));
assert_eq!(Subsystem::parse("storage"), Some(Subsystem::Nvme));
assert_eq!(Subsystem::parse("nonsense"), None);
}
#[test]
fn snapshot_total_counts() {
let mut snap = ProfileSnapshot {
timestamp: 0,
providers: BTreeMap::new(),
errors: BTreeMap::new(),
};
let mut g = ProfileGroup::new(Subsystem::Gpu, "GPU0", "Global", "test");
g.push(Setting::info("k1", "Key 1", SettingValue::Bool(true)));
g.push(Setting::info("k2", "Key 2", SettingValue::Uint(42)));
snap.providers.insert(Subsystem::Gpu, vec![g]);
assert_eq!(snap.total_groups(), 1);
assert_eq!(snap.total_settings(), 2);
assert_eq!(snap.search("key 2").len(), 1);
assert_eq!(snap.search("Key").len(), 2);
}
#[test]
fn setting_value_display() {
assert_eq!(SettingValue::Bool(true).to_string(), "true");
assert_eq!(SettingValue::Uint(255).to_string(), "255 (0xff)");
assert_eq!(SettingValue::Text("perf".into()).to_string(), "perf");
assert!(SettingValue::Unreadable("perm".into())
.to_string()
.contains("perm"));
}
#[test]
fn inspector_default_runs() {
let mut inspector = ProfileInspector::new();
let _snap = inspector.snapshot_all();
}
struct FakeProvider {
sub: Subsystem,
result: Result<Vec<ProfileGroup>, String>,
}
impl ProfileProvider for FakeProvider {
fn subsystem(&self) -> Subsystem {
self.sub
}
fn snapshot(&mut self) -> Result<Vec<ProfileGroup>, String> {
self.result.clone()
}
}
#[test]
fn snapshot_all_records_failing_provider_in_errors() {
let ok_group = ProfileGroup::new(Subsystem::Cpu, "cpu0", "Default", "fake");
let mut inspector = ProfileInspector::with_providers(vec![
Box::new(FakeProvider {
sub: Subsystem::Cpu,
result: Ok(vec![ok_group]),
}),
Box::new(FakeProvider {
sub: Subsystem::Gpu,
result: Err("NVML init failed".to_string()),
}),
]);
let snap = inspector.snapshot_all();
assert_eq!(
snap.errors.get(&Subsystem::Gpu).map(String::as_str),
Some("NVML init failed")
);
assert!(!snap.providers.contains_key(&Subsystem::Gpu));
assert_eq!(snap.providers.get(&Subsystem::Cpu).map(Vec::len), Some(1));
assert!(!snap.errors.contains_key(&Subsystem::Cpu));
}
#[test]
fn failing_provider_is_not_the_same_as_empty_provider() {
let mut inspector = ProfileInspector::with_providers(vec![
Box::new(FakeProvider {
sub: Subsystem::Nvme,
result: Ok(Vec::new()),
}),
Box::new(FakeProvider {
sub: Subsystem::Memory,
result: Err("SMBIOS unreadable".to_string()),
}),
]);
let snap = inspector.snapshot_all();
assert_eq!(snap.providers.get(&Subsystem::Nvme).map(Vec::len), Some(0));
assert!(!snap.errors.contains_key(&Subsystem::Nvme));
assert!(!snap.providers.contains_key(&Subsystem::Memory));
assert!(snap.errors.contains_key(&Subsystem::Memory));
}
#[test]
fn single_subsystem_snapshot_surfaces_failure() {
let mut inspector = ProfileInspector::with_providers(vec![Box::new(FakeProvider {
sub: Subsystem::Display,
result: Err("no display stack".to_string()),
})]);
assert_eq!(
inspector.snapshot(Subsystem::Display).unwrap_err(),
"no display stack"
);
assert_eq!(inspector.snapshot(Subsystem::Gpu).map(|v| v.len()), Ok(0));
}
#[test]
fn a_read_scan_with_nothing_unread_adds_no_row() {
let outcome = ScanOutcome::default();
let (groups, unread) = split_scan(Ok(outcome));
assert!(groups.is_empty());
assert!(unread.is_empty());
assert!(not_read_groups(Subsystem::Display, "EDID", &unread).is_empty());
}
#[test]
fn a_failed_scan_is_one_unread_reason_not_zero_groups() {
let (groups, unread) = split_scan(Err("cannot list /sys/class/drm".to_string()));
assert!(groups.is_empty());
assert_eq!(unread, vec!["cannot list /sys/class/drm".to_string()]);
let rows = not_read_groups(Subsystem::Display, "EDID", &unread);
assert_eq!(rows.len(), 1);
assert_eq!(
rows[0].notes,
vec!["EDID not read: cannot list /sys/class/drm"]
);
}
#[test]
fn partial_scan_keeps_its_groups_and_names_each_unread_item() {
let mut found = ProfileGroup::new(Subsystem::Memory, "DIMM A0", "x", "x");
found.push(Setting::info("ecc", "ECC", SettingValue::Bool(true)));
let outcome = ScanOutcome {
groups: vec![found],
unread: vec!["a/eeprom: permission denied".into(), "b/eeprom: EIO".into()],
};
let (groups, unread) = split_scan(Ok(outcome));
assert_eq!(groups.len(), 1);
assert_eq!(unread.len(), 2);
let rows = not_read_groups(Subsystem::Memory, "SPD/XMP", &unread);
assert_eq!(rows[0].notes.len(), 2);
assert_eq!(rows[0].notes[1], "SPD/XMP not read: b/eeprom: EIO");
}
}