Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

feat(guest): proactively synchronize the native guest clock (#2751)

Vitus54a157a868fa
diff --git a/Cargo.lock b/Cargo.lock
index cf71f7bff..939ea579f 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -784,7 +784,10 @@ dependencies = [
"libc",
"serde_json",
"signal-hook",
+ "tempfile",
"tokio",
+ "tokio-stream",
+ "tonic",
"tracing",
"tracing-appender",
"tracing-subscriber",
diff --git a/src/boxlite/src/portal/interfaces/guest.rs b/src/boxlite/src/portal/interfaces/guest.rs
index 7d541bc9e..3263ea6cc 100644
--- a/src/boxlite/src/portal/interfaces/guest.rs
+++ b/src/boxlite/src/portal/interfaces/guest.rs
@@ -2,8 +2,8 @@
use boxlite_shared::{
BlockDeviceSource, BoxliteError, BoxliteResult, Filesystem, GuestClient, GuestInitRequest,
- NetworkInit, PingRequest, QuiesceRequest, ShutdownRequest, ThawRequest, VirtiofsSource, Volume,
- guest_init_response,
+ NetworkInit, PingRequest, QuiesceRequest, ShutdownRequest, SyncClockRequest, ThawRequest,
+ VirtiofsSource, Volume, guest_init_response,
};
use tonic::transport::Channel;
@@ -114,6 +114,24 @@ impl GuestInterface {
let response = self.client.thaw(ThawRequest {}).await?.into_inner();
Ok(response.thawed_count)
}
+
+ /// Correct CLOCK_REALTIME from UTC sampled by the host just before sending.
+ ///
+ /// The Linux/native shim pushes initially and checks every 2s, pushing on
+ /// a >=6s check gap, >=60s since success, no success, or host clock rollback.
+ /// It survives detached creator exit and needs no D-Bus. This host-only
+ /// operation leaves the RTC and monotonic clock unchanged.
+ /// Success means absolute drift <=100ms (no adjustment) or an accepted
+ /// clock setting in either direction; 100ms is not a precision guarantee.
+ /// Invalid timestamps, clock-read/set failures, and an agent without this
+ /// method surface as errors.
+ pub async fn sync_clock(&mut self, unix_sec: i64, nanos: i32) -> BoxliteResult<()> {
+ let _response = self
+ .client
+ .sync_clock(SyncClockRequest { unix_sec, nanos })
+ .await?;
+ Ok(())
+ }
}
/// A guest agent version as `(major, minor, patch)`.
diff --git a/src/guest/README.md b/src/guest/README.md
index 0ae46a25c..3063265fe 100644
--- a/src/guest/README.md
+++ b/src/guest/README.md
@@ -4,6 +4,14 @@ The Linux guest agent receives volume instructions through the guest initializat
The same guest agent bootstraps itself as native PID 1 or as a child of libkrun's init, with shared container and RPC behavior.
+## Clock recovery
+
+On Linux/native Boxes, the shim attempts `Guest.SyncClock` at startup and checks host time every 2 seconds. It uses `CLOCK_BOOTTIME` for the 6-second gap and 60-second periodic triggers, and pushes when the wall clock's change differs from elapsed time by more than 100ms. A failed push stays due until the guest responds successfully. The shim owns the task, including after a detached Box's creator exits. libkrun retains its existing clock synchronization mechanism.
+
+TCP and Unix listeners return `PermissionDenied` for `Guest.SyncClock`.
+
+The host samples current UTC after connecting and immediately before sending. The agent accepts the call only from the host control plane (the vsock listener rejects non-host peers before tonic sees them), validates a post-epoch timestamp with a valid subsecond part, then reads `CLOCK_REALTIME`. Only an absolute difference greater than 100ms calls `clock_settime`, in either direction; a difference of exactly 100ms or less returns success without adjusting the clock. The host is the clock authority, so legitimate timestamps after long sleeps have no ahead-of-guest bound. Invalid timestamps, clock-read failures, and clock-setting failures propagate as gRPC errors; only successful responses update the shim's successful-push baseline. The 100ms threshold is a decision to adjust, not a precision guarantee: transport and scheduling delay remain uncompensated. The correction never touches the RTC or `CLOCK_MONOTONIC`, so the guest's own RTC offset and alarms survive it, and user containers need no additional `CAP_SYS_TIME`.
+
## Startup ownership
| Responsibility | Native PID 1 | libkrun child |
diff --git a/src/guest/src/service/guest.rs b/src/guest/src/service/guest.rs
index afe290d1b..6c8cfd760 100644
--- a/src/guest/src/service/guest.rs
+++ b/src/guest/src/service/guest.rs
@@ -7,7 +7,8 @@ use crate::service::server::GuestServer;
use boxlite_shared::{
guest_init_response, Guest as GuestService, GuestInitError, GuestInitRequest,
GuestInitResponse, GuestInitSuccess, PingRequest, PingResponse, QuiesceRequest,
- QuiesceResponse, ShutdownRequest, ShutdownResponse, ThawRequest, ThawResponse,
+ QuiesceResponse, ShutdownRequest, ShutdownResponse, SyncClockRequest, SyncClockResponse,
+ ThawRequest, ThawResponse,
};
use tonic::{Request, Response, Status};
use tracing::{debug, error, info, warn};
@@ -215,10 +216,131 @@ impl GuestService for GuestServer {
Ok(Response::new(ThawResponse { thawed_count }))
}
+
+ /// Correct CLOCK_REALTIME from host-sampled UTC when drift exceeds 100ms.
+ ///
+ /// Success means no adjustment was needed or the kernel accepted the
+ /// setting. Validation, clock reads, and clock setting failures propagate
+ /// to the host.
+ async fn sync_clock(
+ &self,
+ request: Request<SyncClockRequest>,
+ ) -> Result<Response<SyncClockResponse>, Status> {
+ if !self.allow_clock_sync {
+ return Err(Status::permission_denied("clock sync requires host vsock"));
+ }
+ let ts = match sync_clock_timespec(request.into_inner()) {
+ Ok(ts) => ts,
+ Err(reject) => return Err(Status::invalid_argument(reject.reason())),
+ };
+ let mut current = nix::libc::timespec {
+ tv_sec: 0,
+ tv_nsec: 0,
+ };
+ // SAFETY: current is a valid writable timespec for clock_gettime.
+ if unsafe { nix::libc::clock_gettime(nix::libc::CLOCK_REALTIME, &mut current) } != 0 {
+ let error = std::io::Error::last_os_error();
+ error!(%error, "clock_gettime(CLOCK_REALTIME) failed");
+ return Err(Status::internal(format!(
+ "clock_gettime(CLOCK_REALTIME) failed: {error}"
+ )));
+ }
+ if !clock_correction_needed(&ts, &current) {
+ return Ok(Response::new(SyncClockResponse {}));
+ }
+ if let Err(error) = set_system_clock(&ts) {
+ error!(%error, "clock_settime(CLOCK_REALTIME) rejected the host time");
+ return Err(clock_settime_status(&error));
+ }
+ info!(
+ sec = ts.tv_sec,
+ nsec = ts.tv_nsec,
+ "Guest system clock set to host UTC"
+ );
+ Ok(Response::new(SyncClockResponse {}))
+ }
+}
+
+/// Why a host-supplied timestamp was rejected.
+///
+/// The host is the clock authority: the RPC arrives over the host control
+/// socket with a stamp the host sampled, and a guest-side ahead bound could
+/// only reject legitimate corrections after long host suspends. Validation
+/// stays structural.
+#[derive(Debug)]
+enum SyncClockReject {
+ NanosOutOfRange(i32),
+ BeforeEpoch,
+}
+
+impl SyncClockReject {
+ fn reason(&self) -> String {
+ match self {
+ Self::NanosOutOfRange(nanos) => {
+ format!("nanos out of range 0-999999999: {nanos}")
+ }
+ Self::BeforeEpoch => "unix_sec must be after the Unix epoch".into(),
+ }
+ }
+}
+
+/// Validate a host-supplied UTC instant into a `timespec`.
+///
+/// Structural bounds only: the nanosecond part must be a valid subsecond
+/// offset and the instant must sit after the epoch. The host is the clock
+/// authority — the stamp is what the host sampled — and a guest-side bound
+/// on how far ahead it may sit would reject legitimate corrections after
+/// long host suspends, so any post-epoch instant is accepted.
+fn sync_clock_timespec(request: SyncClockRequest) -> Result<nix::libc::timespec, SyncClockReject> {
+ const NANOS_UPPER_BOUND: i32 = 999_999_999;
+
+ let SyncClockRequest { unix_sec, nanos } = request;
+ if !(0..=NANOS_UPPER_BOUND).contains(&nanos) {
+ return Err(SyncClockReject::NanosOutOfRange(nanos));
+ }
+ if unix_sec <= 0 {
+ return Err(SyncClockReject::BeforeEpoch);
+ }
+ Ok(nix::libc::timespec {
+ tv_sec: unix_sec,
+ tv_nsec: i64::from(nanos),
+ })
+}
+
+fn clock_correction_needed(host: &nix::libc::timespec, guest: &nix::libc::timespec) -> bool {
+ let delta = (i128::from(host.tv_sec) - i128::from(guest.tv_sec)) * 1_000_000_000
+ + i128::from(host.tv_nsec)
+ - i128::from(guest.tv_nsec);
+ delta.abs() > 100_000_000
+}
+
+/// Set the guest system clock. Returns the raw OS error for callers to map.
+fn set_system_clock(ts: &nix::libc::timespec) -> Result<(), std::io::Error> {
+ // SAFETY: clock_settime only reads the timespec; there are no other inputs.
+ let rc = unsafe { nix::libc::clock_settime(nix::libc::CLOCK_REALTIME, ts) };
+ if rc != 0 {
+ return Err(std::io::Error::last_os_error());
+ }
+ Ok(())
+}
+
+/// Map a `clock_settime` failure to the RPC status the host should see.
+fn clock_settime_status(error: &std::io::Error) -> Status {
+ match error.kind() {
+ std::io::ErrorKind::PermissionDenied => Status::permission_denied(format!(
+ "the guest agent lacks permission to set the system clock: {error}"
+ )),
+ std::io::ErrorKind::InvalidInput => {
+ Status::invalid_argument(format!("the kernel rejected the timestamp: {error}"))
+ }
+ _ => Status::internal(format!("clock_settime(CLOCK_REALTIME) failed: {error}")),
+ }
}
#[cfg(test)]
mod tests {
+ use std::time::{SystemTime, UNIX_EPOCH};
+
use super::*;
use crate::layout::GuestLayout;
use crate::reaper::ExitSlot;
@@ -250,4 +372,128 @@ mod tests {
let written = boxlite_shared::layout::ExitRecord::read(&exit_file);
assert_eq!(written.map(|record| record.exit_code), Some(7));
}
+
+ /// Structural bounds only: a bad subsecond part or a pre-epoch instant
+ /// are rejected, while past instants, today's host time, and stamps far
+ /// ahead (a long host suspend) are accepted unchanged.
+ #[test]
+ fn sync_clock_rejects_invalid_timestamps() {
+ let now = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .expect("clock is after the epoch")
+ .as_secs() as i64;
+
+ for (unix_sec, nanos) in [(1, -1), (1, 1_000_000_000)] {
+ assert!(matches!(
+ sync_clock_timespec(SyncClockRequest { unix_sec, nanos }),
+ Err(SyncClockReject::NanosOutOfRange(_))
+ ));
+ }
+ for unix_sec in [0, -5] {
+ assert!(matches!(
+ sync_clock_timespec(SyncClockRequest { unix_sec, nanos: 0 }),
+ Err(SyncClockReject::BeforeEpoch)
+ ));
+ }
+ // A host that slept longer than a day is still authoritative; the
+ // stamp far ahead of the guest clock must be accepted.
+ let long_suspend = sync_clock_timespec(SyncClockRequest {
+ unix_sec: now + 90_000,
+ nanos: 0,
+ })
+ .expect("a host stamp ahead by more than a day is accepted");
+ assert_eq!(long_suspend.tv_sec, now + 90_000);
+
+ let behind = sync_clock_timespec(SyncClockRequest {
+ unix_sec: now - 100_000,
+ nanos: 500,
+ })
+ .expect("a past host instant is accepted");
+ assert_eq!(behind.tv_sec, now - 100_000);
+ let fresh = sync_clock_timespec(SyncClockRequest {
+ unix_sec: now,
+ nanos: 0,
+ })
+ .expect("the host's current instant is accepted");
+ assert_eq!((fresh.tv_sec, fresh.tv_nsec), (now, 0));
+ }
+
+ #[test]
+ fn sync_clock_corrects_only_beyond_100ms_in_both_directions() {
+ // Include a second boundary and timestamps near the i64 limit to
+ // exercise subtraction without overflowing seconds or nanoseconds.
+ for (seconds, nanos) in [(10, 500_000_000), (10, 950_000_000), (i64::MAX - 1, 0)] {
+ let earlier = nix::libc::timespec {
+ tv_sec: seconds,
+ tv_nsec: nanos,
+ };
+ for delta in [0, 99_999_999, 100_000_000, 100_000_001] {
+ let later = nix::libc::timespec {
+ tv_sec: seconds + (nanos + delta) / 1_000_000_000,
+ tv_nsec: (nanos + delta) % 1_000_000_000,
+ };
+ let expected = delta > 100_000_000;
+ assert_eq!(clock_correction_needed(&later, &earlier), expected);
+ assert_eq!(clock_correction_needed(&earlier, &later), expected);
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn sync_clock_within_tolerance_succeeds_without_clock_permission() {
+ crate::test_syscalls::deny(nix::libc::SYS_clock_settime);
+ let root = tempfile::tempdir().expect("tempdir");
+ let mut server = GuestServer::new(GuestLayout::with_base(root.path()));
+ server.allow_clock_sync = true;
+ let now = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .expect("clock after epoch");
+ server
+ .sync_clock(Request::new(SyncClockRequest {
+ unix_sec: now.as_secs() as i64,
+ nanos: now.subsec_nanos() as i32,
+ }))
+ .await
+ .expect("a current timestamp needs no clock_settime permission");
+ }
+
+ #[tokio::test]
+ async fn sync_clock_rejects_invalid_requests_before_setting_clock() {
+ crate::test_syscalls::deny(nix::libc::SYS_clock_settime);
+ let root = tempfile::tempdir().expect("tempdir");
+ let mut server = GuestServer::new(GuestLayout::with_base(root.path()));
+ server.allow_clock_sync = true;
+ for (unix_sec, nanos) in [(1, -1), (1, 1_000_000_000), (0, 0), (-1, 0)] {
+ let status = server
+ .sync_clock(Request::new(SyncClockRequest { unix_sec, nanos }))
+ .await
+ .expect_err("invalid timestamps must fail before clock_settime");
+ assert_eq!(status.code(), tonic::Code::InvalidArgument);
+ }
+ }
+
+ /// A guest that cannot set the clock (here: seccomp EPERM, standing in
+ /// for the non-root agent) must fail the RPC instead of reporting a
+ /// correction it did not apply.
+ #[tokio::test]
+ async fn sync_clock_propagates_clock_settime_denial() {
+ crate::test_syscalls::deny(nix::libc::SYS_clock_settime);
+ let now = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .expect("clock is after the epoch")
+ .as_secs() as i64;
+
+ let root = tempfile::tempdir().expect("tempdir");
+ let mut server = GuestServer::new(GuestLayout::with_base(root.path()));
+ server.allow_clock_sync = true;
+ let status = server
+ .sync_clock(Request::new(SyncClockRequest {
+ unix_sec: now + 90_000,
+ nanos: 0,
+ }))
+ .await
+ .expect_err("a denied clock_settime must fail the RPC");
+
+ assert_eq!(status.code(), tonic::Code::PermissionDenied);
+ }
}
diff --git a/src/guest/src/service/server.rs b/src/guest/src/service/server.rs
index 73b7b0414..9e0792577 100644
--- a/src/guest/src/service/server.rs
+++ b/src/guest/src/service/server.rs
@@ -45,6 +45,9 @@ pub(crate) struct GuestServer {
/// Mount points frozen by Quiesce RPC, thawed by Thaw RPC.
pub frozen_mounts: Mutex<Vec<PathBuf>>,
+ /// The listener verifies that clock-sync requests come from the host.
+ pub(super) allow_clock_sync: bool,
+
/// Set when a host-driven Shutdown RPC is in progress. The reaper's
/// init-exit action checks this to avoid powering the VM off underneath a
/// host-orchestrated teardown.
@@ -75,6 +78,7 @@ impl GuestServer {
registry: ExecutionRegistry::new(),
ssh_manager: crate::service::ssh::SshManager::default(),
frozen_mounts: Mutex::new(Vec::new()),
+ allow_clock_sync: false,
shutting_down: Arc::new(std::sync::atomic::AtomicBool::new(false)),
init_exits: Arc::new(Mutex::new(HashMap::new())),
}
@@ -87,7 +91,11 @@ impl GuestServer {
///
/// If `notify_uri` is provided, connects to that URI after the server
/// is ready to serve, signaling readiness to the host.
- pub async fn run(self, listen_uri: String, notify_uri: Option<String>) -> BoxliteResult<()> {
+ pub async fn run(
+ mut self,
+ listen_uri: String,
+ notify_uri: Option<String>,
+ ) -> BoxliteResult<()> {
info!("Starting tonic gRPC server");
// Parse the listen URI to determine transport type
@@ -100,6 +108,9 @@ impl GuestServer {
info!("Parsed transport from URI: {:?}", transport);
+ // Only the vsock listener verifies the host CID before serving RPCs.
+ self.allow_clock_sync = matches!(&transport, BoxTransport::Vsock { .. });
+
// Wrap self in Arc for sharing across services
let server = Arc::new(self);
server.ssh_manager.attach_guest(&server);
diff --git a/src/shared/proto/boxlite/v1/service.proto b/src/shared/proto/boxlite/v1/service.proto
index f3d0fa35e..5fd65f258 100644
--- a/src/shared/proto/boxlite/v1/service.proto
+++ b/src/shared/proto/boxlite/v1/service.proto
@@ -50,6 +50,16 @@ service Guest {
// Thaw previously quiesced filesystems (FITHAW ioctl).
// Must be called after SIGCONT to unblock writes.
rpc Thaw(ThawRequest) returns (ThawResponse);
+
+ // Correct CLOCK_REALTIME from host UTC only when absolute drift exceeds 100ms.
+ // Linux/native shim: initial push, then checks every 2s; pushes on a >=6s
+ // check gap, >=60s since success, no prior success, or host clock rollback.
+ // Runs for detached Boxes without D-Bus; the host samples after connecting,
+ // immediately before sending. Host-only: no RTC or monotonic clock changes.
+ // Success means drift <=100ms or clock_settime succeeded, in either direction.
+ // 100ms is an adjustment threshold, not an end-to-end precision guarantee.
+ // Invalid timestamps and clock-read/set failures are returned as errors.
+ rpc SyncClock(SyncClockRequest) returns (SyncClockResponse);
}
// Persistent SSH desired state and live listener control.
@@ -239,6 +249,15 @@ message ThawResponse {
uint32 thawed_count = 1;
}
+message SyncClockRequest {
+ // Seconds since the Unix epoch (UTC), sampled on the host.
+ int64 unix_sec = 1;
+ // Nanosecond part of the same instant (0-999999999).
+ int32 nanos = 2;
+}
+
+message SyncClockResponse {}
+
// ============================================================================
// SSH runtime configuration
// ============================================================================
diff --git a/src/shim/Cargo.toml b/src/shim/Cargo.toml
index 3dc254944..66427fad6 100644
--- a/src/shim/Cargo.toml
+++ b/src/shim/Cargo.toml
@@ -22,3 +22,8 @@ tokio = { version = "1.37", features = ["rt", "time"] }
tracing = "0.1"
tracing-appender = "0.2"
tracing-subscriber = { version = "0.3", features = ["fmt", "env-filter", "ansi"] }
+
+[dev-dependencies]
+tempfile = "3"
+tokio-stream = "0.1"
+tonic = "0.12"
diff --git a/src/shim/src/main.rs b/src/shim/src/main.rs
index 44475024b..474fc14c4 100644
--- a/src/shim/src/main.rs
+++ b/src/shim/src/main.rs
@@ -14,6 +14,7 @@
//! shim subprocess, not the main boxlite process.
mod crash_capture;
+mod timesync;
use std::path::Path;
use std::thread;
@@ -192,6 +193,7 @@ fn run_shim(mut config: InstanceSpec, timing: impl Fn(&str)) -> BoxliteResult<()
// Save detach/transport before config is moved into engine.create()
let detach = config.detach;
let transport = config.transport.clone();
+ let engine_kind = config.engine;
// Initialize engine options with defaults
let options = VmmConfig::default();
@@ -215,6 +217,9 @@ fn run_shim(mut config: InstanceSpec, timing: impl Fn(&str)) -> BoxliteResult<()
tracing::info!("Box instance created, handing over process control to Box");
+ // Owned by the shim so detached Boxes keep synchronizing after creator exit.
+ timesync::spawn(engine_kind, transport.clone());
+
// Install SIGTERM handler for graceful shutdown (all boxes, detached or not).
// When SIGTERM is received: Guest.Shutdown() RPC (flush qcow2) → re-raise SIGTERM.
install_graceful_shutdown_handler(transport);
diff --git a/src/shim/src/timesync.rs b/src/shim/src/timesync.rs
new file mode 100644
index 000000000..97db6ad15
--- /dev/null
+++ b/src/shim/src/timesync.rs
@@ -0,0 +1,485 @@
+//! Native clock alignment owned by the shim, including detached Boxes.
+//!
+//! Compare wall time with suspend-aware elapsed time every two seconds.
+//! A gap or clock step stays due until the guest accepts a fresh sample.
+
+#[cfg(target_os = "linux")]
+use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
+
+#[cfg(target_os = "linux")]
+use boxlite::GuestSession;
+use boxlite::vmm::VmmKind;
+use boxlite_shared::BoxTransport;
+
+#[cfg(target_os = "linux")]
+const CHECK_INTERVAL: Duration = Duration::from_secs(2);
+#[cfg(target_os = "linux")]
+const GAP_THRESHOLD: Duration = Duration::from_secs(6);
+#[cfg(target_os = "linux")]
+const CLOCK_STEP_THRESHOLD: Duration = Duration::from_millis(100);
+#[cfg(target_os = "linux")]
+const UPDATE_INTERVAL: Duration = Duration::from_secs(60);
+#[cfg(target_os = "linux")]
+const SYNC_TIMEOUT: Duration = Duration::from_secs(2);
+
+/// Keep the worker in the shim so a detached creator can exit independently.
+pub(crate) fn spawn(engine: VmmKind, transport: BoxTransport) {
+ if !enabled_for(engine) {
+ tracing::debug!(?engine, "shim clock sync stays off for this engine");
+ return;
+ }
+ if let Err(error) = std::thread::Builder::new()
+ .name("clock-sync".into())
+ .spawn(move || run(transport))
+ {
+ tracing::warn!(%error, "could not start the clock-sync thread");
+ }
+}
+
+fn enabled_for(engine: VmmKind) -> bool {
+ cfg!(target_os = "linux") && engine == VmmKind::Native
+}
+
+#[cfg(target_os = "linux")]
+fn run(transport: BoxTransport) {
+ let runtime = match tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ {
+ Ok(runtime) => runtime,
+ Err(error) => {
+ tracing::warn!(%error, "clock sync could not start a runtime");
+ return;
+ }
+ };
+ if let Err(error) = runtime.block_on(sync_loop(transport)) {
+ tracing::warn!(%error, "clock sync could not read host boottime");
+ }
+}
+
+#[cfg(not(target_os = "linux"))]
+fn run(_transport: BoxTransport) {}
+
+#[cfg(target_os = "linux")]
+#[derive(Debug)]
+struct HostTime {
+ wall: SystemTime,
+ boottime: Duration,
+}
+
+#[cfg(target_os = "linux")]
+impl HostTime {
+ fn now() -> std::io::Result<Self> {
+ let mut time = libc::timespec {
+ tv_sec: 0,
+ tv_nsec: 0,
+ };
+ // SAFETY: time is a valid writable timespec for clock_gettime.
+ if unsafe { libc::clock_gettime(libc::CLOCK_BOOTTIME, &mut time) } != 0 {
+ return Err(std::io::Error::last_os_error());
+ }
+ Ok(Self {
+ wall: SystemTime::now(),
+ boottime: Duration::new(time.tv_sec as u64, time.tv_nsec as u32),
+ })
+ }
+}
+
+#[cfg(target_os = "linux")]
+struct Schedule {
+ previous_check: HostTime,
+ last_successful_push: Option<Duration>,
+ pending: Option<&'static str>,
+}
+
+#[cfg(target_os = "linux")]
+impl Schedule {
+ fn check(&mut self, now: HostTime) -> Option<&'static str> {
+ // Record the check before the RPC so a suspend during it stays visible.
+ let previous = std::mem::replace(&mut self.previous_check, now);
+ if self.pending.is_some() {
+ return self.pending;
+ }
+ let now = &self.previous_check;
+ let elapsed = now.boottime.saturating_sub(previous.boottime);
+ self.pending = match self.last_successful_push {
+ None => Some("no_successful_push"),
+ Some(_) if elapsed >= GAP_THRESHOLD => Some("check_gap"),
+ Some(_)
+ if now.wall.duration_since(previous.wall).map_or_else(
+ |_| true,
+ |wall_elapsed| elapsed.abs_diff(wall_elapsed) > CLOCK_STEP_THRESHOLD,
+ ) =>
+ {
+ Some("host_clock_step")
+ }
+ Some(last) if now.boottime.saturating_sub(last) >= UPDATE_INTERVAL => Some("periodic"),
+ Some(_) => None,
+ };
+ self.pending
+ }
+
+ fn pushed(&mut self, boottime: Duration) {
+ self.last_successful_push = Some(boottime);
+ self.pending = None;
+ }
+}
+
+#[cfg(target_os = "linux")]
+async fn sync_loop(transport: BoxTransport) -> std::io::Result<()> {
+ let mut schedule = Schedule {
+ previous_check: HostTime::now()?,
+ last_successful_push: None,
+ pending: None,
+ };
+ let mut checks = tokio::time::interval(CHECK_INTERVAL);
+ // The first tick is immediate; missed checks never become a burst of RPCs.
+ checks.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
+ loop {
+ checks.tick().await;
+ if let Some(reason) = schedule.check(HostTime::now()?)
+ && let Ok(sampled_at) = sync_once(&transport, SYNC_TIMEOUT, reason).await
+ {
+ schedule.pushed(sampled_at.boottime);
+ }
+ }
+}
+
+/// Connect and send within one budget; sample UTC only after connecting.
+#[cfg(target_os = "linux")]
+async fn sync_once(
+ transport: &BoxTransport,
+ timeout: Duration,
+ reason: &str,
+) -> Result<HostTime, String> {
+ let started = Instant::now();
+ let mut sampled_at = None;
+ let result = tokio::time::timeout(timeout, async {
+ let session = GuestSession::new(transport.clone());
+ let mut guest = session.guest().await.map_err(|error| error.to_string())?;
+ let now = HostTime::now().map_err(|error| error.to_string())?;
+ sampled_at = Some(now.wall);
+ let utc = now
+ .wall
+ .duration_since(UNIX_EPOCH)
+ .map_err(|error| error.to_string())?;
+ guest
+ .sync_clock(utc.as_secs() as i64, utc.subsec_nanos() as i32)
+ .await
+ .map_err(|error| error.to_string())?;
+ Ok(now)
+ })
+ .await
+ .unwrap_or_else(|_| Err("guest clock synchronization timed out".into()));
+ let elapsed_ms = started.elapsed().as_millis();
+ match &result {
+ Ok(_) => tracing::info!(
+ reason,
+ ?sampled_at,
+ elapsed_ms,
+ "guest clock synchronization succeeded"
+ ),
+ Err(error) => {
+ tracing::warn!(reason, ?sampled_at, elapsed_ms, %error, "guest clock synchronization failed")
+ }
+ }
+ result
+}
+
+#[cfg(all(test, target_os = "linux"))]
+mod tests {
+ use super::*;
+ use boxlite_shared::SyncClockRequest;
+ use std::sync::{Arc, Mutex};
+
+ struct FakeGuest {
+ sync_status: Option<tonic::Status>,
+ received: Arc<Mutex<Option<SyncClockRequest>>>,
+ }
+
+ #[tonic::async_trait]
+ impl boxlite_shared::Guest for FakeGuest {
+ async fn init(
+ &self,
+ _: tonic::Request<boxlite_shared::GuestInitRequest>,
+ ) -> Result<tonic::Response<boxlite_shared::GuestInitResponse>, tonic::Status> {
+ Err(tonic::Status::unimplemented("test fake"))
+ }
+
+ async fn ping(
+ &self,
+ _: tonic::Request<boxlite_shared::PingRequest>,
+ ) -> Result<tonic::Response<boxlite_shared::PingResponse>, tonic::Status> {
+ Err(tonic::Status::unimplemented("test fake"))
+ }
+
+ async fn shutdown(
+ &self,
+ _: tonic::Request<boxlite_shared::ShutdownRequest>,
+ ) -> Result<tonic::Response<boxlite_shared::ShutdownResponse>, tonic::Status> {
+ Err(tonic::Status::unimplemented("test fake"))
+ }
+
+ async fn quiesce(
+ &self,
+ _: tonic::Request<boxlite_shared::QuiesceRequest>,
+ ) -> Result<tonic::Response<boxlite_shared::QuiesceResponse>, tonic::Status> {
+ Err(tonic::Status::unimplemented("test fake"))
+ }
+
+ async fn thaw(
+ &self,
+ _: tonic::Request<boxlite_shared::ThawRequest>,
+ ) -> Result<tonic::Response<boxlite_shared::ThawResponse>, tonic::Status> {
+ Err(tonic::Status::unimplemented("test fake"))
+ }
+
+ async fn sync_clock(
+ &self,
+ request: tonic::Request<SyncClockRequest>,
+ ) -> Result<tonic::Response<boxlite_shared::SyncClockResponse>, tonic::Status> {
+ *self.received.lock().expect("received lock") = Some(request.into_inner());
+ match self.sync_status.clone() {
+ Some(status) => Err(status),
+ None => Ok(tonic::Response::new(boxlite_shared::SyncClockResponse {})),
+ }
+ }
+ }
+
+ async fn serve_fake(
+ path: &std::path::Path,
+ sync_status: Option<tonic::Status>,
+ ) -> Arc<Mutex<Option<SyncClockRequest>>> {
+ use boxlite_shared::generated::guest_server::GuestServer;
+
+ let listener = tokio::net::UnixListener::bind(path).expect("bind the test socket");
+ let received = Arc::new(Mutex::new(None));
+ let fake = FakeGuest {
+ sync_status,
+ received: Arc::clone(&received),
+ };
+ tokio::spawn(
+ tonic::transport::Server::builder()
+ .add_service(GuestServer::new(fake))
+ .serve_with_incoming(tokio_stream::wrappers::UnixListenerStream::new(listener)),
+ );
+ received
+ }
+
+ fn unix_transport(path: &std::path::Path) -> BoxTransport {
+ BoxTransport::Unix {
+ socket_path: path.to_path_buf(),
+ }
+ }
+
+ fn socket_dir() -> tempfile::TempDir {
+ tempfile::Builder::new()
+ .prefix("clock-")
+ .tempdir_in("/tmp")
+ .expect("short socket directory")
+ }
+
+ #[test]
+ fn only_native_uses_the_shim_clock_worker() {
+ assert!(enabled_for(VmmKind::Native));
+ assert!(!enabled_for(VmmKind::Libkrun));
+ assert!(!enabled_for(VmmKind::Firecracker));
+ }
+
+ #[tokio::test]
+ async fn loop_pushes_at_startup_and_again_after_sixty_seconds() {
+ let dir = socket_dir();
+ let path = dir.path().join("guest.sock");
+ let received = serve_fake(&path, None).await;
+ let worker = tokio::spawn(sync_loop(unix_transport(&path)));
+ let first = tokio::time::timeout(Duration::from_secs(3), async {
+ loop {
+ if let Some(request) = received.lock().expect("capture lock").take() {
+ break request;
+ }
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ })
+ .await
+ .expect("startup push");
+ let second = tokio::time::timeout(Duration::from_secs(65), async {
+ loop {
+ if let Some(request) = received.lock().expect("capture lock").take() {
+ break request;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ })
+ .await
+ .expect("periodic push without a wake event");
+ worker.abort();
+ let delta = i128::from(second.unix_sec - first.unix_sec) * 1_000_000_000
+ + i128::from(second.nanos - first.nanos);
+ assert!(
+ delta >= 60_000_000_000,
+ "pushed before sixty seconds: {delta}ns"
+ );
+ }
+
+ #[tokio::test]
+ async fn delayed_connection_samples_after_the_listener_is_ready() {
+ let dir = socket_dir();
+ let path = dir.path().join("guest.sock");
+ let transport = unix_transport(&path);
+ let attempt =
+ tokio::spawn(async move { sync_once(&transport, SYNC_TIMEOUT, "test").await });
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ let ready_at = SystemTime::now();
+ let received = serve_fake(&path, None).await;
+ let sampled_at = attempt
+ .await
+ .expect("attempt task")
+ .expect("delayed channel recovered")
+ .wall;
+ assert!(
+ sampled_at >= ready_at,
+ "timestamp predates the available channel"
+ );
+ let sent = received
+ .lock()
+ .expect("capture lock")
+ .expect("RPC reached guest");
+ assert_eq!(
+ sampled_at,
+ UNIX_EPOCH + Duration::new(sent.unix_sec as u64, sent.nanos as u32)
+ );
+ }
+
+ #[test]
+ fn schedule_checks_thresholds_and_keeps_failures_due() {
+ let after = Duration::from_secs;
+ let at = |wall, boottime| HostTime {
+ wall: UNIX_EPOCH + after(wall),
+ boottime: after(boottime),
+ };
+ let mut schedule = Schedule {
+ previous_check: at(100, 100),
+ last_successful_push: None,
+ pending: None,
+ };
+ assert_eq!(schedule.check(at(100, 100)), Some("no_successful_push"));
+ assert_eq!(schedule.check(at(102, 102)), Some("no_successful_push"));
+ schedule.pushed(after(102));
+ assert_eq!(schedule.check(at(107, 107)), None);
+ assert_eq!(schedule.check(at(113, 113)), Some("check_gap"));
+ assert_eq!(schedule.check(at(115, 115)), Some("check_gap"));
+ schedule.pushed(after(115));
+ schedule.previous_check = at(172, 172);
+ assert_eq!(schedule.check(at(174, 174)), None);
+ assert_eq!(schedule.check(at(175, 175)), Some("periodic"));
+ assert_eq!(schedule.check(at(177, 177)), Some("periodic"));
+ schedule.pushed(after(177));
+ assert_eq!(schedule.check(at(179, 179)), None);
+ assert_eq!(schedule.check(at(180, 181)), Some("host_clock_step"));
+ schedule.pushed(after(181));
+ assert_eq!(schedule.check(at(182, 183)), None);
+ // Even a successful RPC must not erase a suspend during that RPC.
+ schedule.pushed(after(191));
+ assert_eq!(schedule.check(at(190, 191)), Some("check_gap"));
+ }
+
+ #[tokio::test]
+ async fn rpc_samples_current_time_and_propagates_rejections() {
+ for (index, status) in [
+ None,
+ Some(tonic::Status::permission_denied("no CAP_SYS_TIME")),
+ Some(tonic::Status::unimplemented("old agent")),
+ ]
+ .into_iter()
+ .enumerate()
+ {
+ let dir = socket_dir();
+ let path = dir.path().join("guest.sock");
+ let received = serve_fake(&path, status).await;
+ let before = SystemTime::now();
+ let result = sync_once(&unix_transport(&path), SYNC_TIMEOUT, "test").await;
+ let after = SystemTime::now();
+ let sent = received
+ .lock()
+ .expect("capture lock")
+ .expect("RPC reached guest");
+ let sent_at = UNIX_EPOCH + Duration::new(sent.unix_sec as u64, sent.nanos as u32);
+ assert!((before..=after).contains(&sent_at));
+ match index {
+ 0 => assert_eq!(result.expect("RPC succeeded").wall, sent_at),
+ 1 => assert!(
+ result
+ .expect_err("guest rejected")
+ .contains("PermissionDenied")
+ ),
+ _ => assert!(
+ result
+ .expect_err("old agent rejected")
+ .contains("Unimplemented")
+ ),
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn stalled_connection_respects_the_attempt_budget() {
+ let dir = socket_dir();
+ let path = dir.path().join("guest.sock");
+ let listener = tokio::net::UnixListener::bind(&path).expect("bind stalled socket");
+ let peer = tokio::spawn(async move {
+ let (_stream, _) = listener.accept().await.expect("accept");
+ std::future::pending::<()>().await;
+ });
+ let started = Instant::now();
+ let result = sync_once(&unix_transport(&path), Duration::from_millis(100), "test").await;
+ peer.abort();
+ assert!(
+ result
+ .expect_err("stalled peer times out")
+ .contains("timed out")
+ );
+ assert!(started.elapsed() < Duration::from_secs(2));
+ }
+
+ #[test]
+ fn rpc_runs_under_vmm_seccomp_without_a_system_bus() {
+ const CHILD: &str = "BOXLITE_CLOCK_SECCOMP_CHILD";
+ if std::env::var_os(CHILD).is_none() {
+ let output = std::process::Command::new(std::env::current_exe().expect("test binary"))
+ .args([
+ "--exact",
+ "timesync::tests::rpc_runs_under_vmm_seccomp_without_a_system_bus",
+ "--nocapture",
+ ])
+ .env(CHILD, "1")
+ .env(
+ "DBUS_SYSTEM_BUS_ADDRESS",
+ "unix:path=/nonexistent/clock-test-bus",
+ )
+ .output()
+ .expect("run isolated seccomp test");
+ assert!(
+ output.status.success(),
+ "child failed: {:?}\n{}\n{}",
+ output.status,
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ return;
+ }
+ let dir = socket_dir();
+ boxlite::jailer::seccomp::apply_vmm_filter("clock-sync-test").expect("install VMM filter");
+ let runtime = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .expect("runtime under filter");
+ runtime.block_on(async {
+ let path = dir.path().join("guest.sock");
+ let received = serve_fake(&path, None).await;
+ sync_once(&unix_transport(&path), SYNC_TIMEOUT, "test")
+ .await
+ .expect("RPC under filter");
+ assert!(received.lock().expect("capture lock").is_some());
+ });
+ }
+}