use std::fs::File;
use std::io;
use std::path::PathBuf;
use super::chrony::ChronyPoll;
use super::clockbound;
use super::clocksource::{CLOCKSOURCE, Clocksource, ClocksourceName};
use super::kernel::KernelSync;
use super::probe::{TimeSyncProbe, clockbound_at, coarse_now, sequence};
use super::sync::{
Bound, BoundSource, ChronyAnswer, ClockBoundAnswer, Observed, SyncVerdict, TimeSync, Why,
bound, bound_warns, judge, leap_pending, unsettled,
};
use crate::finding::Finding;
use crate::host::{Host, ReadError};
use crate::platform::Arch;
use crate::quota::read_from_start;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ClockSample {
pub kernel: Option<KernelSync>,
pub chrony: ChronyAnswer,
pub clockbound: ClockBoundAnswer,
pub clocksource: Result<ClocksourceName, io::ErrorKind>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Key {
why: Why,
chrony_ref: Option<u32>,
bound: Option<(BoundSource, bool)>,
unsettled: bool,
leap: Option<&'static str>,
}
#[derive(Debug)]
pub struct ClockWatch {
probe: TimeSyncProbe,
live_linux: bool,
observed: Observed,
last: ClockSample,
key: Key,
verdict: SyncVerdict,
bound: Option<Bound>,
chrony: Option<ChronyPoll>,
clockbound: Option<PathBuf>,
clocksource: Result<File, io::ErrorKind>,
arch: Arch,
invariant_tsc: Option<bool>,
}
impl ClockWatch {
#[must_use]
pub fn open(host: &Host, probe: &TimeSyncProbe) -> (Self, Vec<Finding>) {
let observed = probe.observe(host);
let mut findings = TimeSync::from_observed(observed.clone()).findings(&probe.limits);
let source = Clocksource::read(host);
findings.push(source.finding());
let live_linux = host.is_live() && observed.linux;
let chrony = if observed.linux {
probe
.chrony
.and_then(|addr| ChronyPoll::open(addr, sequence()).ok())
} else {
None
};
let clockbound =
(probe.clockbound && observed.linux).then(|| host.path(clockbound::DEFAULT_PATH));
let clocksource = host.open(CLOCKSOURCE).map_err(|e| match e {
ReadError::Io { kind, .. } => kind,
_ => io::ErrorKind::Unsupported,
});
let mut watch = Self {
probe: probe.clone(),
live_linux,
last: ClockSample {
kernel: observed.kernel,
chrony: observed.chrony,
clockbound: observed.clockbound,
clocksource: Err(io::ErrorKind::Unsupported),
},
observed,
key: Key {
why: Why::NotLinux,
chrony_ref: None,
bound: None,
unsettled: false,
leap: None,
},
verdict: SyncVerdict::Unknown,
bound: None,
chrony,
clockbound,
clocksource,
arch: source.arch,
invariant_tsc: source.invariant_tsc,
};
watch.last.clocksource = watch.read_clocksource();
watch.key = watch.judge();
(watch, findings)
}
pub fn sample(&mut self) -> ClockSample {
let kernel = if self.live_linux {
KernelSync::read_live().ok()
} else {
None
};
let chrony = match &mut self.chrony {
Some(poll) => poll.poll(self.last.chrony),
None => self.last.chrony,
};
let clockbound = match &self.clockbound {
Some(path) => {
let now = self
.probe
.clockbound_now_ns
.or_else(|| self.live_linux.then(coarse_now).flatten());
clockbound_at(path, now)
}
None => self.last.clockbound,
};
ClockSample {
kernel,
chrony,
clockbound,
clocksource: self.read_clocksource(),
}
}
pub fn update(&mut self, sample: ClockSample) -> Vec<Finding> {
let before = self.last.clocksource;
self.observed.kernel = sample.kernel;
self.observed.chrony = sample.chrony;
self.observed.clockbound = sample.clockbound;
self.last = sample;
let key = self.judge();
let t11 = key != self.key;
let t12 = sample.clocksource != before;
self.key = key;
if !t11 && !t12 {
return Vec::new();
}
let mut out = Vec::new();
if t11 {
out.extend(TimeSync::from_observed(self.observed.clone()).findings(&self.probe.limits));
}
if t12 {
out.push(self.clocksource_finding(before, sample.clocksource));
}
out
}
pub fn check(&mut self) -> Vec<Finding> {
let sample = self.sample();
self.update(sample)
}
#[must_use]
pub const fn verdict(&self) -> SyncVerdict {
self.verdict
}
#[must_use]
pub const fn bound(&self) -> Option<Bound> {
self.bound
}
#[must_use]
pub const fn leap_pending(&self) -> bool {
self.key.leap.is_some()
}
#[must_use]
pub const fn observed(&self) -> &Observed {
&self.observed
}
#[must_use]
pub const fn last(&self) -> ClockSample {
self.last
}
fn judge(&mut self) -> Key {
let o = &self.observed;
let why = judge(o);
self.verdict = why.verdict();
self.bound = bound(o, self.verdict);
let limit = self.probe.limits.warn_over_ns;
Key {
why,
chrony_ref: match &o.chrony {
ChronyAnswer::Tracking(t) => Some(t.ref_id),
_ => None,
},
bound: self
.bound
.map(|b| (b.source, bound_warns(self.verdict, b, limit))),
unsettled: unsettled(o, limit).is_some(),
leap: leap_pending(o),
}
}
fn read_clocksource(&self) -> Result<ClocksourceName, io::ErrorKind> {
let file = self.clocksource.as_ref().map_err(|kind| *kind)?;
let mut buf = [0_u8; 64];
let n = read_from_start(file, &mut buf).map_err(|e| e.kind())?;
let text = std::str::from_utf8(buf.get(..n).unwrap_or_default())
.map_err(|_| io::ErrorKind::InvalidData)?;
ClocksourceName::new(text).ok_or(io::ErrorKind::InvalidData)
}
fn clocksource_finding(
&self,
before: Result<ClocksourceName, io::ErrorKind>,
now: Result<ClocksourceName, io::ErrorKind>,
) -> Finding {
let source = Clocksource {
name: now
.map(|n| n.as_str().to_owned())
.map_err(|kind| ReadError::Io {
path: CLOCKSOURCE.to_owned(),
kind,
}),
arch: self.arch,
invariant_tsc: self.invariant_tsc,
};
let mut f = source.finding();
if let (Ok(before), Ok(now)) = (before, now) {
f.message = format!("changed from {before} to {now}: {}", f.message);
}
f
}
}