ghostscope_ui/utils/
trace_formatting.rs

1//! Trace event formatting utilities
2
3use std::time::{SystemTime, UNIX_EPOCH};
4
5/// Format eBPF timestamp (nanoseconds since boot) to human-readable format
6pub fn format_timestamp_ns(ns_timestamp: u64) -> String {
7    // Get current system time and boot time
8    let now = SystemTime::now();
9    let uptime = get_system_uptime_ns();
10
11    if let (Ok(now_since_epoch), Some(boot_ns)) = (now.duration_since(UNIX_EPOCH), uptime) {
12        // Calculate when the system booted
13        let boot_time_ns = now_since_epoch.as_nanos() as u64 - boot_ns;
14
15        // Add eBPF timestamp to boot time to get actual time
16        let actual_time_ns = boot_time_ns + ns_timestamp;
17        let actual_time_secs = actual_time_ns / 1_000_000_000;
18        let actual_time_nanos = actual_time_ns % 1_000_000_000;
19
20        // Convert to chrono DateTime with local timezone
21        if let Some(utc_datetime) =
22            chrono::DateTime::from_timestamp(actual_time_secs as i64, actual_time_nanos as u32)
23        {
24            let local_datetime: chrono::DateTime<chrono::Local> = utc_datetime.into();
25            return format!(
26                "{}.{:03}",
27                local_datetime.format("%Y-%m-%d %H:%M:%S"),
28                actual_time_nanos / 1_000_000
29            );
30        }
31    }
32
33    // Fallback to boot time offset if conversion fails
34    let ms = ns_timestamp / 1_000_000;
35    let seconds = ms / 1000;
36    let ms_remainder = ms % 1000;
37    format!("boot+{seconds}.{ms_remainder:03}s")
38}
39
40/// Get system uptime in nanoseconds
41fn get_system_uptime_ns() -> Option<u64> {
42    std::fs::read_to_string("/proc/uptime")
43        .ok()
44        .and_then(|content| {
45            let uptime_secs: f64 = content.split_whitespace().next()?.parse().ok()?;
46            Some((uptime_secs * 1_000_000_000.0) as u64)
47        })
48}