tracexec_core/
timestamp.rs1use std::{borrow::Cow, sync::LazyLock};
2
3use chrono::{DateTime, Local};
4use nutype::nutype;
5
6#[nutype(
7 validate(with = validate_strftime, error = Cow<'static,str>),
8 derive(Debug, Clone, Serialize, Deserialize, Deref, FromStr)
9)]
10pub struct TimestampFormat(String);
11
12fn validate_strftime(fmt: &str) -> Result<(), Cow<'static, str>> {
13 if fmt.contains("\n") {
14 return Err("inline timestamp format string should not contain newline(s)".into());
15 }
16 Ok(())
17}
18
19pub type Timestamp = DateTime<Local>;
20
21pub fn ts_from_boot_ns(boot_ns: u64) -> Timestamp {
22 DateTime::from_timestamp_nanos((*BOOT_TIME + boot_ns) as i64).into()
23}
24
25static BOOT_TIME: LazyLock<u64> = LazyLock::new(|| {
26 let content = std::fs::read_to_string("/proc/stat").expect("Failed to read /proc/stat");
27 for line in content.lines() {
28 if line.starts_with("btime") {
29 return line
30 .split(' ')
31 .nth(1)
32 .unwrap()
33 .parse::<u64>()
34 .expect("Failed to parse btime in /proc/stat")
35 * 1_000_000_000;
36 }
37 }
38 panic!("btime is not available in /proc/stat. Am I running on Linux?")
39});