corelens 0.1.0

Linux TUI for CPU topology, local AI workloads, and GPU metrics
Documentation
use crate::error::CorelensError;
use crate::model::cpu::{
    CoreKind, CoreKindDetection, CpuTopology, DetectionSource, LogicalCpu, PhysicalCore,
    TopologyDiagnostics,
};
use anyhow::{Context, Result};
use std::{
    collections::{BTreeMap, BTreeSet},
    fs,
    path::{Path, PathBuf},
};

#[derive(Debug, Clone, Default)]
pub struct LogicalCpuMetadata {
    pub logical_id: u32,
    pub core_id: Option<u32>,
    pub die_id: Option<u32>,
    pub package_id: Option<u32>,
    pub siblings: Vec<u32>,
    pub kernel_core_type: Option<u32>,
    pub capacity: Option<u64>,
    pub current_frequency_khz: Option<u64>,
    pub max_frequency_khz: Option<u64>,
}

pub trait CoreKindDetector: Send + Sync {
    fn detect(&self, cpu: &LogicalCpuMetadata) -> CoreKindDetection;
}

#[derive(Debug, Clone)]
pub struct DefaultCoreKindDetector {
    max_capacity: Option<u64>,
    max_frequency: Option<u64>,
    distinct_capacities: usize,
    distinct_frequencies: usize,
}

impl DefaultCoreKindDetector {
    pub fn new(metadata: &[LogicalCpuMetadata]) -> Self {
        let capacities: BTreeSet<u64> = metadata.iter().filter_map(|c| c.capacity).collect();
        let frequencies: BTreeSet<u64> = metadata
            .iter()
            .filter_map(|c| c.max_frequency_khz)
            .collect();
        Self {
            max_capacity: capacities.iter().next_back().copied(),
            max_frequency: frequencies.iter().next_back().copied(),
            distinct_capacities: capacities.len(),
            distinct_frequencies: frequencies.len(),
        }
    }
}

impl CoreKindDetector for DefaultCoreKindDetector {
    fn detect(&self, cpu: &LogicalCpuMetadata) -> CoreKindDetection {
        if let Some(kind) = cpu.kernel_core_type.and_then(|value| match value {
            1 => Some(CoreKind::Performance),
            2 => Some(CoreKind::Efficiency),
            3 => Some(CoreKind::LowPowerEfficiency),
            _ => None,
        }) {
            return CoreKindDetection {
                kind,
                source: DetectionSource::KernelMetadata,
                confidence_percent: 100,
            };
        }
        if self.distinct_capacities > 1 {
            if cpu.capacity == self.max_capacity {
                return CoreKindDetection {
                    kind: CoreKind::Performance,
                    source: DetectionSource::Capacity,
                    confidence_percent: 75,
                };
            }
            return CoreKindDetection {
                kind: CoreKind::Efficiency,
                source: DetectionSource::Capacity,
                confidence_percent: 75,
            };
        }
        if self.distinct_frequencies > 1 {
            if cpu.max_frequency_khz == self.max_frequency {
                return CoreKindDetection {
                    kind: CoreKind::Performance,
                    source: DetectionSource::FrequencyHeuristic,
                    confidence_percent: 55,
                };
            }
            return CoreKindDetection {
                kind: CoreKind::Efficiency,
                source: DetectionSource::FrequencyHeuristic,
                confidence_percent: 55,
            };
        }
        let kind = if self.distinct_capacities == 1 || self.distinct_frequencies == 1 {
            CoreKind::Homogeneous
        } else {
            CoreKind::Unknown
        };
        CoreKindDetection {
            kind,
            source: if kind == CoreKind::Unknown {
                DetectionSource::Unsupported
            } else {
                DetectionSource::FrequencyHeuristic
            },
            confidence_percent: if kind == CoreKind::Unknown { 0 } else { 100 },
        }
    }
}

pub fn parse_cpu_list(input: &str) -> Result<Vec<u32>, CorelensError> {
    let mut cpus = Vec::new();
    for part in input.trim().split(',').filter(|part| !part.is_empty()) {
        let mut bounds = part.split('-');
        let start: u32 = bounds
            .next()
            .ok_or_else(|| CorelensError::InvalidCpuList(part.into()))?
            .parse()
            .map_err(|_| CorelensError::InvalidCpuList(part.into()))?;
        let end = bounds
            .next()
            .map(|value| value.parse::<u32>())
            .transpose()
            .map_err(|_| CorelensError::InvalidCpuList(part.into()))?
            .unwrap_or(start);
        if start > end || bounds.next().is_some() {
            return Err(CorelensError::InvalidCpuList(part.into()));
        }
        cpus.extend(start..=end);
    }
    cpus.sort_unstable();
    cpus.dedup();
    Ok(cpus)
}

pub fn parse_siblings(input: &str) -> Result<Vec<u32>, CorelensError> {
    parse_cpu_list(input)
}

#[derive(Debug, Clone)]
pub struct SysfsTopologyCollector {
    root: PathBuf,
    pub last: Option<CpuTopology>,
}

impl Default for SysfsTopologyCollector {
    fn default() -> Self {
        Self::new("/sys/devices/system/cpu")
    }
}

impl SysfsTopologyCollector {
    pub fn new(root: impl Into<PathBuf>) -> Self {
        Self {
            root: root.into(),
            last: None,
        }
    }

    pub fn collect(&mut self) -> Result<CpuTopology> {
        let online = read_to_string(self.root.join("online"))
            .and_then(|text| parse_cpu_list(&text).map_err(anyhow::Error::from))
            .unwrap_or_else(|_| discover_cpu_dirs(&self.root));
        if online.is_empty() {
            anyhow::bail!("no online CPUs found in {}", self.root.display());
        }
        let metadata: Vec<_> = online
            .iter()
            .map(|&id| {
                self.read_metadata(id)
                    .unwrap_or_else(|_| LogicalCpuMetadata {
                        logical_id: id,
                        ..LogicalCpuMetadata::default()
                    })
            })
            .collect();
        if metadata.is_empty() {
            anyhow::bail!("online CPU metadata unavailable");
        }
        let detector = DefaultCoreKindDetector::new(&metadata);
        let cpus = metadata
            .iter()
            .map(|metadata| {
                let detection = detector.detect(metadata);
                LogicalCpu {
                    logical_id: metadata.logical_id,
                    core_id: metadata.core_id,
                    die_id: metadata.die_id,
                    package_id: metadata.package_id,
                    siblings: metadata.siblings.clone(),
                    core_kind: detection.kind,
                    detection,
                    utilization: None,
                    current_frequency_khz: metadata.current_frequency_khz,
                    max_frequency_khz: metadata.max_frequency_khz,
                    temperature_celsius: None,
                }
            })
            .collect::<Vec<_>>();
        let (cores, mut diagnostics) = group_topology_with_diagnostics(&cpus, &online);
        diagnostics.physical_core_count = cores.len();
        for core in &cores {
            let kind = core
                .logical_cpus
                .iter()
                .find_map(|id| {
                    cpus.iter()
                        .find(|cpu| cpu.logical_id == *id)
                        .map(|cpu| cpu.core_kind)
                })
                .unwrap_or(CoreKind::Unknown);
            match kind {
                CoreKind::Performance => diagnostics.performance_core_count += 1,
                CoreKind::Efficiency | CoreKind::LowPowerEfficiency => {
                    diagnostics.efficiency_core_count += 1
                }
                _ => diagnostics.unknown_core_count += 1,
            }
        }
        let result = CpuTopology {
            cpus,
            cores,
            diagnostics,
        };
        self.last = Some(result.clone());
        Ok(result)
    }

    fn read_metadata(&self, id: u32) -> Result<LogicalCpuMetadata> {
        let cpu = self.root.join(format!("cpu{id}"));
        let topology = cpu.join("topology");
        let read_optional = |name: &str| {
            read_to_string(topology.join(name))
                .ok()
                .and_then(|v| v.trim().parse().ok())
        };
        Ok(LogicalCpuMetadata {
            logical_id: id,
            core_id: read_optional("core_id"),
            die_id: read_optional("die_id"),
            package_id: read_optional("physical_package_id"),
            siblings: read_to_string(topology.join("thread_siblings_list"))
                .ok()
                .and_then(|v| parse_siblings(&v).ok())
                .unwrap_or_else(|| vec![id]),
            kernel_core_type: read_optional("core_type"),
            capacity: read_optional_from(&cpu, "cpu_capacity")
                .or_else(|| read_optional_from(&cpu, "capacity")),
            current_frequency_khz: read_optional_from(&cpu.join("cpufreq"), "scaling_cur_freq"),
            max_frequency_khz: read_optional_from(&cpu.join("cpufreq"), "cpuinfo_max_freq"),
        })
    }
}

pub fn group_topology(cpus: &[LogicalCpu]) -> Vec<PhysicalCore> {
    group_topology_with_diagnostics(
        cpus,
        &cpus.iter().map(|cpu| cpu.logical_id).collect::<Vec<_>>(),
    )
    .0
}

type PhysicalCoreKey = (Option<u32>, Option<u32>, Option<u32>, Option<u32>);

pub fn group_topology_with_diagnostics(
    cpus: &[LogicalCpu],
    online: &[u32],
) -> (Vec<PhysicalCore>, TopologyDiagnostics) {
    let mut input_counts = BTreeMap::new();
    for cpu in cpus {
        *input_counts.entry(cpu.logical_id).or_insert(0_usize) += 1;
    }
    let mut groups: BTreeMap<PhysicalCoreKey, BTreeSet<u32>> = BTreeMap::new();
    for cpu in cpus {
        let fallback = cpu.core_id.is_none().then_some(cpu.logical_id);
        groups
            .entry((cpu.package_id, cpu.die_id, cpu.core_id, fallback))
            .or_default()
            .insert(cpu.logical_id);
    }
    for logical_id in online {
        if !input_counts.contains_key(logical_id) {
            groups
                .entry((None, None, None, Some(*logical_id)))
                .or_default()
                .insert(*logical_id);
        }
    }
    let cores = groups
        .into_iter()
        .map(|((package_id, die_id, core_id, _), logical)| PhysicalCore {
            package_id,
            die_id,
            core_id,
            logical_cpus: logical.into_iter().collect(),
        })
        .collect::<Vec<_>>();
    let assigned = input_counts.keys().filter(|id| online.contains(id)).count();
    let duplicates = input_counts
        .values()
        .filter(|count| **count > 1)
        .map(|count| count - 1)
        .sum();
    let missing = online
        .iter()
        .filter(|id| !input_counts.contains_key(id))
        .count();
    let diagnostics = TopologyDiagnostics {
        online_logical_cpus: online.len(),
        assigned_logical_cpus: assigned,
        duplicate_assignments: duplicates,
        missing_assignments: missing,
        ..TopologyDiagnostics::default()
    };
    (cores, diagnostics)
}

fn discover_cpu_dirs(root: &Path) -> Vec<u32> {
    fs::read_dir(root)
        .ok()
        .into_iter()
        .flatten()
        .filter_map(|entry| entry.ok())
        .filter_map(|entry| {
            entry
                .file_name()
                .to_str()
                .and_then(|name| name.strip_prefix("cpu"))
                .and_then(|id| id.parse().ok())
        })
        .collect()
}

fn read_to_string(path: impl AsRef<Path>) -> Result<String> {
    fs::read_to_string(path.as_ref()).with_context(|| format!("read {}", path.as_ref().display()))
}

fn read_optional_from(root: &Path, name: &str) -> Option<u64> {
    read_to_string(root.join(name))
        .ok()
        .and_then(|v| v.trim().parse().ok())
}