corelens 0.1.0

Linux TUI for CPU topology, local AI workloads, and GPU metrics
Documentation
use crate::model::gpu::{GpuDevice, GpuKind, GpuMetrics, GpuSnapshot, GpuVendor};
use anyhow::{Context, Result};
use std::{
    fs,
    path::{Path, PathBuf},
};

pub trait GpuDeviceDiscovery {
    fn discover(&self) -> Result<Vec<GpuDevice>>;
}

pub trait GpuMetricsCollector {
    fn collect(&mut self, devices: &[GpuDevice]) -> Result<Vec<GpuMetrics>>;
}

pub struct SysfsGpuDeviceDiscovery {
    root: PathBuf,
}

impl Default for SysfsGpuDeviceDiscovery {
    fn default() -> Self {
        Self::new("/sys/class/drm")
    }
}

impl SysfsGpuDeviceDiscovery {
    pub fn new(root: impl Into<PathBuf>) -> Self {
        Self { root: root.into() }
    }
}

impl GpuDeviceDiscovery for SysfsGpuDeviceDiscovery {
    fn discover(&self) -> Result<Vec<GpuDevice>> {
        let mut cards = fs::read_dir(&self.root)
            .with_context(|| format!("read DRM sysfs directory {}", self.root.display()))?
            .filter_map(Result::ok)
            .filter_map(|entry| {
                let name = entry.file_name().to_string_lossy().into_owned();
                name.strip_prefix("card")
                    .and_then(|suffix| suffix.parse::<u32>().ok())
                    .map(|number| (number, name, entry.path()))
            })
            .collect::<Vec<_>>();
        cards.sort_by_key(|(number, _, _)| *number);

        cards
            .into_iter()
            .filter_map(|(_, card_name, card_path)| {
                let device_path = card_path.join("device");
                device_path
                    .is_dir()
                    .then(|| discover_device(card_name, device_path))
            })
            .collect()
    }
}

fn discover_device(card_name: String, sysfs_path: PathBuf) -> Result<GpuDevice> {
    let vendor_id = read_hex(&sysfs_path.join("vendor"));
    let device_id = read_hex(&sysfs_path.join("device"));
    let vendor = vendor_id.map_or(GpuVendor::Unknown(0), GpuVendor::from_id);
    let uevent = read_key_values(&sysfs_path.join("uevent"));
    let driver = sysfs_path
        .join("driver")
        .canonicalize()
        .ok()
        .and_then(|path| {
            path.file_name()
                .map(|name| name.to_string_lossy().into_owned())
        })
        .or_else(|| uevent.get("DRIVER").cloned());
    let pci_address = uevent.get("PCI_SLOT_NAME").cloned();
    let name =
        read_first(&sysfs_path, &["product_name", "label", "name"]).unwrap_or_else(
            || match vendor {
                GpuVendor::Intel => "Intel Graphics".into(),
                GpuVendor::Nvidia => "NVIDIA Graphics".into(),
                GpuVendor::Amd => "AMD Graphics".into(),
                GpuVendor::Unknown(_) => format!("{vendor:?} {card_name}"),
            },
        );
    let kind = classify_kind(
        vendor,
        read_trimmed(&sysfs_path.join("boot_vga")).as_deref(),
    );
    Ok(GpuDevice {
        card_name,
        name,
        pci_address,
        driver,
        vendor,
        vendor_id,
        device_id,
        kind,
        sysfs_path,
    })
}

fn classify_kind(vendor: GpuVendor, boot_vga: Option<&str>) -> GpuKind {
    if boot_vga == Some("1") {
        return GpuKind::Integrated;
    }
    match vendor {
        GpuVendor::Intel => GpuKind::Integrated,
        GpuVendor::Nvidia => GpuKind::Discrete,
        GpuVendor::Amd | GpuVendor::Unknown(_) => GpuKind::Unknown,
    }
}

fn read_hex(path: &Path) -> Option<u16> {
    u16::from_str_radix(read_trimmed(path)?.trim_start_matches("0x"), 16).ok()
}

fn read_first(root: &Path, names: &[&str]) -> Option<String> {
    names.iter().find_map(|name| read_trimmed(&root.join(name)))
}

fn read_trimmed(path: &Path) -> Option<String> {
    fs::read_to_string(path)
        .ok()
        .map(|value| value.trim().into())
}

fn read_key_values(path: &Path) -> std::collections::BTreeMap<String, String> {
    read_trimmed(path)
        .unwrap_or_default()
        .lines()
        .filter_map(|line| {
            let (key, value) = line.split_once('=')?;
            Some((key.into(), value.into()))
        })
        .collect()
}

pub struct IntelDrmCollector;

impl GpuMetricsCollector for IntelDrmCollector {
    fn collect(&mut self, devices: &[GpuDevice]) -> Result<Vec<GpuMetrics>> {
        Ok(read_busy_metrics(devices, GpuVendor::Intel))
    }
}

pub struct AmdDrmCollector;

impl GpuMetricsCollector for AmdDrmCollector {
    fn collect(&mut self, devices: &[GpuDevice]) -> Result<Vec<GpuMetrics>> {
        Ok(read_busy_metrics(devices, GpuVendor::Amd))
    }
}

fn read_busy_metrics(devices: &[GpuDevice], vendor: GpuVendor) -> Vec<GpuMetrics> {
    devices
        .iter()
        .filter(|device| device.vendor == vendor)
        .filter_map(|device| {
            let utilization_percent = ["gpu_busy_percent", "gt_busy_percent"]
                .iter()
                .find_map(|name| read_trimmed(&device.sysfs_path.join(name)))
                .and_then(|value| value.parse().ok());
            utilization_percent.map(|utilization_percent| GpuMetrics {
                device_key: device.card_name.clone(),
                utilization_percent: Some(utilization_percent),
                ..GpuMetrics::default()
            })
        })
        .collect()
}

pub struct CompositeGpuCollector {
    discovery: SysfsGpuDeviceDiscovery,
    nvidia: crate::collector::nvidia::NvidiaNvmlCollector,
    intel: IntelDrmCollector,
    amd: AmdDrmCollector,
}

impl Default for CompositeGpuCollector {
    fn default() -> Self {
        Self::new()
    }
}

impl CompositeGpuCollector {
    pub fn new() -> Self {
        Self {
            discovery: SysfsGpuDeviceDiscovery::default(),
            nvidia: crate::collector::nvidia::NvidiaNvmlCollector::new(),
            intel: IntelDrmCollector,
            amd: AmdDrmCollector,
        }
    }

    pub fn collect(&mut self) -> Result<Vec<GpuSnapshot>> {
        let devices = self.discovery.discover()?;
        let mut metrics = self.nvidia.collect(&devices)?;
        metrics.extend(self.intel.collect(&devices)?);
        metrics.extend(self.amd.collect(&devices)?);
        let mut kind_indices = [0_u32; 3];
        Ok(devices
            .into_iter()
            .map(|device| {
                let kind_index = match device.kind {
                    GpuKind::Integrated => 0,
                    GpuKind::Discrete => 1,
                    GpuKind::Unknown => 2,
                };
                let index = kind_indices[kind_index];
                kind_indices[kind_index] += 1;
                let metric = metrics
                    .iter()
                    .find(|metric| metric.device_key == device.card_name);
                GpuSnapshot {
                    index,
                    name: metric
                        .and_then(|metric| metric.name.clone())
                        .unwrap_or_else(|| device.name.clone()),
                    device,
                    utilization_percent: metric.and_then(|metric| metric.utilization_percent),
                    used_memory_bytes: metric.and_then(|metric| metric.used_memory_bytes),
                    total_memory_bytes: metric.and_then(|metric| metric.total_memory_bytes),
                    temperature_celsius: metric.and_then(|metric| metric.temperature_celsius),
                    power_draw_milliwatts: metric.and_then(|metric| metric.power_draw_milliwatts),
                    power_limit_milliwatts: metric.and_then(|metric| metric.power_limit_milliwatts),
                    processes: metric
                        .map(|metric| metric.processes.clone())
                        .unwrap_or_default(),
                }
            })
            .collect())
    }
}

#[cfg(test)]
mod tests {
    use super::{GpuDeviceDiscovery, SysfsGpuDeviceDiscovery};
    use crate::model::gpu::{GpuKind, GpuVendor};

    #[test]
    fn discovers_fixture_drm_cards() {
        let cards = SysfsGpuDeviceDiscovery::new(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/tests/fixtures/drm"
        ))
        .discover()
        .unwrap();
        assert_eq!(cards.len(), 2);
        assert_eq!(cards[0].card_name, "card0");
        assert_eq!(cards[0].vendor, GpuVendor::Intel);
        assert_eq!(cards[0].kind, GpuKind::Integrated);
        assert_eq!(cards[0].driver.as_deref(), Some("i915"));
        assert_eq!(cards[0].pci_address.as_deref(), Some("0000:00:02.0"));
        assert_eq!(cards[0].vendor_id, Some(0x8086));
        assert_eq!(cards[0].device_id, Some(0x46a3));
        assert_eq!(cards[1].vendor, GpuVendor::Nvidia);
        assert_eq!(cards[1].kind, GpuKind::Discrete);
    }
}