44 lines
1.4 KiB
Rust
44 lines
1.4 KiB
Rust
//! Current native clock evidence, independent of agent/IPC timestamps.
|
|
use anyhow::{Result, ensure};
|
|
use chrono::{DateTime, Utc};
|
|
use rmm_agent_core::reconcile::SyncClock;
|
|
use std::time::Instant;
|
|
|
|
pub struct NativeClock {
|
|
wall: DateTime<Utc>,
|
|
monotonic: Instant,
|
|
}
|
|
impl NativeClock {
|
|
pub fn new() -> Result<Self> {
|
|
let value = Self {
|
|
wall: Utc::now(),
|
|
monotonic: Instant::now(),
|
|
};
|
|
value.now()?;
|
|
Ok(value)
|
|
}
|
|
}
|
|
impl SyncClock for NativeClock {
|
|
fn now(&self) -> Result<DateTime<Utc>> {
|
|
let mut timex = std::mem::MaybeUninit::<libc::timex>::zeroed();
|
|
// modes=0 is strictly a read-only kernel synchronization/error query.
|
|
let status = unsafe { libc::adjtimex(timex.as_mut_ptr()) };
|
|
let timex = unsafe { timex.assume_init() };
|
|
ensure!(
|
|
status >= 0
|
|
&& status != libc::TIME_ERROR
|
|
&& timex.status & libc::STA_UNSYNC == 0
|
|
&& timex.maxerror >= 0
|
|
&& timex.maxerror <= 5_000_000,
|
|
"UPDATE_CLOCK_UNTRUSTED"
|
|
);
|
|
let now = Utc::now();
|
|
let elapsed = i64::try_from(self.monotonic.elapsed().as_millis())?;
|
|
ensure!(
|
|
((now - self.wall).num_milliseconds() - elapsed).unsigned_abs() <= 5000,
|
|
"UPDATE_CLOCK_CHANGED"
|
|
);
|
|
Ok(now)
|
|
}
|
|
}
|