Skip to main content

gunnar_server/
clock.rs

1//! **The appliance's wall clock**: glue between PID 1 and edda `estate-clock`.
2//!
3//! Every rule — the sources, the quorum, the sanity window, the signed-peer
4//! protocol, step-at-boot and slew-while-running, the first fed syncs and the
5//! running triggers — lives in edda's `estate-clock` crate (where Gunnar's own
6//! `gunnar-clock` moved, lane L10 2026-10-21), which the front's gunnar-front
7//! links too. This file decides only *whether* this process owns the clock,
8//! *where* its feed is, and *what it says* about the answer.
9//!
10//! **Both wires during the move**: a box asks in `ESTATE-TIME/1` and asks again
11//! in `GUNNAR-TIME/1` when an old front answers in Gunnar's dialect
12//! (`estate_clock::peer::query`); `GUNNAR_CLOCK*` (the kit's
13//! `korp.env.GUNNAR_CLOCK=`) is read as an alias of `ESTATE_CLOCK*`
14//! (`estate_clock::config::var`).
15//!
16//! # What went wrong with the first cut (gunnar `5792dda`), measured
17//!
18//! The appliance booted two hours fast; `5792dda` asked three internet HTTPS
19//! hosts for a `Date` at boot and was re-imaged on 2026-09-14 — and the box
20//! still refused credentials `7199529 ms away`. Through the control plane, with
21//! a credential deliberately signed 7 199 500 ms fast so the gate let it
22//! through, `gunnar control mirror add … https://github.com/…` answered
23//! `github.com could not be resolved: failed to lookup address information: Try
24//! again`. UpCloud's firewall catch-all `drop` drops the replies to outbound
25//! UDP (from the front: `dig +notcp` times out, `dig +tcp` answers), musl's
26//! resolver asks over UDP only, so every source was unreachable, the verdict was
27//! "no quorum", and the clock was left alone. The only record was a log line on a
28//! VGA console. See the `estate-clock` crate note for the full measurement.
29//!
30//! # What it does now
31//!
32//! * **The source is configuration** (`korp.env.GUNNAR_CLOCK=` on the kernel
33//!   command line). On gunnar.rs that is `peer://10.13.8.99:50123` — the front,
34//!   by IP literal over the utility network, answering a nonce with a signed
35//!   timestamp (`GUNNAR_CLOCK_KEY` names its public key). No internet, no DNS.
36//!   Unset means **not configured**, and nothing is asked: an appliance in an
37//!   airgap has no business dialling Stripe for the time.
38//! * **At boot**, after the network and before any listener: one sync, steps.
39//! * **While running**, only when a credential is refused for skew (rate-limited
40//!   to one sync a minute) and on a 6-hour safety timer — `estate_clock::trigger`.
41//!   Small offsets slew, large ones step — `estate_clock::adjust`.
42//! * **Every attempt is recorded** (`estate_clock::report`) and served on the
43//!   control plane: `Admin.Health` carries the boot and the last report, and
44//!   `Bootstrap.Status` — the one call that needs no credential — carries the
45//!   last one and this server's own clock. When the clock is wrong a credential
46//!   is exactly what gets refused, so the credential-free call is the one that
47//!   makes a wrong clock diagnosable from the front.
48//!
49//! # Why it can never stop the boot or the server
50//!
51//! Every function here returns `()` and swallows everything. A forge that
52//! refuses to come up because a clock fetch failed is strictly worse than a
53//! forge with a wrong clock: the wrong clock refuses credentials, the dead
54//! forge refuses everything — including the call an operator uses to find out
55//! why. The periodic sync runs on the blocking pool, never on a request path.
56
57use estate_clock::config::{Config, CLOCK_ENV};
58use estate_clock::offer::FedRun;
59use estate_clock::report::{Outcome, Report, Trigger};
60
61pub use estate_clock::offer::{last_outcome, outcome_is_right};
62
63/// **One sync** (AIRGAP, owner rule 2026-10-25). With `clock-fetch` it is estate-clock's own,
64/// HTTPS Date sources included. Without it (the default build) the same rule over peer and
65/// SNTP sources only: an `https://` source is refused by [`NO_HTTPS`] and never dialled.
66#[cfg(feature = "clock-fetch")]
67fn sync(config: &Result<Config, String>, phase: Trigger) -> Report {
68    estate_clock::fetch::sync(config, phase)
69}
70
71/// The refusal an `https://` clock source gets in a build without `clock-fetch`.
72pub const NO_HTTPS: &str =
73    "an https:// clock source needs gunnar-server's `clock-fetch` feature (off by default: this build asks peer and SNTP sources only)";
74
75#[cfg(not(feature = "clock-fetch"))]
76fn sync(config: &Result<Config, String>, phase: Trigger) -> Report {
77    let report = match config {
78        Ok(Config::Sources { sources, peer_key }) => {
79            let polled = estate_clock::poll::poll_with(sources, peer_key.as_deref(), &|_| Err(NO_HTTPS.to_owned()));
80            let action = estate_clock::adjust::choose(phase, &polled.verdict.decision);
81            let applied = estate_clock::adjust::apply(action).map_err(|err| err.to_string());
82            Report::from_poll(phase, &polled, action, applied)
83        }
84        Err(why) => Report::without_sources(phase, Outcome::Misconfigured, why.clone()),
85        Ok(Config::NotConfigured) => Report::without_sources(phase, Outcome::NotConfigured, format!("no clock source is configured ({CLOCK_ENV})")),
86        Ok(Config::Off) => Report::without_sources(phase, Outcome::Off, format!("{CLOCK_ENV}=off: this machine was told not to set its own clock")),
87    };
88    estate_clock::report::record(report.clone());
89    report
90}
91
92/// Whether this process may set the machine's clock at all.
93///
94/// Gated exactly as `crate::disktest` and `crate::dashboard` are — PID 1 **and**
95/// `korp.entry=` on the kernel command line. A container entrypoint is PID 1 of
96/// its namespace too, and a privileged container shares the host's clock:
97/// stepping it there would move somebody's real machine. Naming sources in
98/// [`CLOCK_ENV`] (or its Gunnar alias `GUNNAR_CLOCK`) explicitly turns it on
99/// regardless, which is what the installtest rig and a developer reproducing a
100/// refusal need; the syscall still needs `CAP_SYS_TIME` and a refusal is still
101/// only a report.
102fn owns_the_clock() -> bool {
103    std::env::var_os(CLOCK_ENV).is_some()
104        || estate_clock::config::gunnar_alias(CLOCK_ENV).is_some_and(|alias| std::env::var_os(alias).is_some())
105        || (appliance_pid1::net::is_init() && appliance_pid1::net::booted_by_korp_start())
106}
107
108/// Say what an attempt concluded, at the level it deserves.
109fn log(report: &Report) {
110    let summary = report.summary();
111    match report.outcome {
112        Outcome::Stepped | Outcome::Slewed | Outcome::AlreadyRight => {
113            tracing::info!(
114                outcome = report.outcome.as_str(),
115                offset_ms = report.offset_ms,
116                "clock: {summary}"
117            )
118        }
119        Outcome::NotConfigured | Outcome::Off => {
120            tracing::info!(outcome = report.outcome.as_str(), "clock: {summary}")
121        }
122        Outcome::Misconfigured | Outcome::NoQuorum | Outcome::Disagree | Outcome::ApplyFailed => {
123            tracing::warn!(
124                outcome = report.outcome.as_str(),
125                "clock: {summary}. If this box's clock is wrong, every credential it is handed \
126                 will be refused."
127            )
128        }
129    }
130    for row in &report.sources {
131        match (&row.offset_ms, &row.error) {
132            (_, Some(why)) => tracing::warn!(source = %row.source, %why, "clock source failed"),
133            (Some(offset_ms), None) => {
134                tracing::info!(source = %row.source, offset_ms, "clock source answered")
135            }
136            (None, None) => {}
137        }
138    }
139}
140
141/// One attempt on the blocking pool; the report is recorded by `sync` itself.
142async fn attempt(phase: Trigger) -> Report {
143    let config = crate::feed::clock_config();
144    match tokio::task::spawn_blocking(move || sync(&config, phase)).await {
145        Ok(report) => report,
146        Err(err) => {
147            let report = Report::without_sources(
148                phase,
149                Outcome::ApplyFailed,
150                format!("the clock sync task did not complete: {err}"),
151            );
152            estate_clock::report::record(report.clone());
153            report
154        }
155    }
156}
157
158/// **The boot call.** Sync once, stepping if the source says so.
159pub async fn synchronise_at_boot() {
160    if !owns_the_clock() {
161        let report = Report::without_sources(
162            Trigger::Boot,
163            Outcome::Off,
164            "not the appliance's PID 1, so the system clock is somebody else's to set",
165        );
166        tracing::debug!("clock: {}", report.summary());
167        estate_clock::report::record(report);
168        return;
169    }
170    log(&attempt(Trigger::Boot).await);
171}
172
173/// Whether a clock is configured at all (the medium's or the feed's).
174fn configured() -> bool {
175    !matches!(crate::feed::clock_config(), Ok(Config::NotConfigured) | Ok(Config::Off))
176}
177
178/// **The running triggers**: a credential refused for skew, and the 6-hour
179/// safety timer (`estate_clock::trigger::arm` has the rules and why there are
180/// only these, and arms them once per process). Called after the boot sync, and
181/// by a fed run before its first pause. Does nothing on a box that does not
182/// own its clock, or whose clock is not configured — a clock the installer's
183/// door feeds later arms them then ([`fed_arrived`]).
184///
185/// Both run on plain threads, never on the runtime: the skew handler is started
186/// by the credential gate and must not borrow a worker for a TCP exchange, and a
187/// sync is blocking by nature.
188pub fn arm_triggers() {
189    if !owns_the_clock() || !configured() {
190        return;
191    }
192    estate_clock::trigger::arm(|trigger| {
193        let config = crate::feed::clock_config();
194        log(&sync(&config, trigger));
195    });
196}
197
198/// One sync of the clock in force (the feed read now), logged.
199fn fed_sync() -> Outcome {
200    let config = crate::feed::clock_config();
201    let report = sync(&config, Trigger::Timer);
202    log(&report);
203    report.outcome
204}
205
206/// This process's fed clock runs (`estate_clock::offer::FedRun`): the
207/// triggers armed first, then syncs backing off while the front does not
208/// answer; one run at a time, off the caller's thread; the tunnel coming up
209/// cuts a pause short.
210static FED: FedRun = FedRun::new(fed_sync, arm_triggers);
211
212/// **The installer's door fed a clock source or key while this box runs**
213/// (the pairing loop's first answer, `crate::feed`). Every sync already reads
214/// the feed ([`crate::feed::clock_config`]), so this only makes the first one
215/// happen NOW — a first boot whose medium carries no clock would otherwise
216/// wait for the 6-hour timer, which was never armed — and arms the triggers.
217///
218/// ★ **Returns at once: the syncs run on their own thread** (cov-E r3
219/// 2026-10-06, runs 2 and 4): called from the installer's FEED, a twin fed
220/// before its tunnel was up once ran the whole backoff on the feed's thread
221/// and for 219 s answered nobody. A clock re-fed meanwhile gets one more run
222/// of its own when the one under way ends.
223pub fn fed_arrived() {
224    if !owns_the_clock() || !configured() {
225        return;
226    }
227    if !FED.start() {
228        tracing::warn!("clock: the fed sync could not get a thread of its own; the triggers take over");
229    }
230}
231
232/// **This box's tunnel just came up** (the pairing loop's `TunnelUp`).
233///
234/// The fed clock source is the front's utility address, reached through
235/// this tunnel on a box whose fed syncs ran before it was up (i54a run23:
236/// the twin's three syncs timed out, then it paused 20 s while its tunnel
237/// came up and the front's `BecomeTwin` was refused for skew seven times).
238/// So: a clock not yet set right is asked NOW — the pause under way is cut
239/// short, and a run is started if none is. Once per process; nothing when
240/// the clock is already right.
241pub fn tunnel_up() {
242    if !owns_the_clock() || !configured() {
243        return;
244    }
245    FED.tunnel_up(last_outcome());
246}
247
248#[cfg(test)]
249mod airgap {
250    use super::*;
251    use estate_clock::config::Source;
252
253    /// A loopback listener that would see any dial, and an https source aimed at it.
254    fn trap() -> (std::net::TcpListener, Result<Config, String>) {
255        let trap = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
256        trap.set_nonblocking(true).unwrap();
257        let url = format!("https://{}/", trap.local_addr().unwrap());
258        (trap, Ok(Config::Sources { sources: vec![Source::Https(url)], peer_key: None }))
259    }
260
261    fn dialled(trap: &std::net::TcpListener) -> bool {
262        std::thread::sleep(std::time::Duration::from_millis(100));
263        trap.accept().is_ok()
264    }
265
266    /// ★ **AIRGAP: a default build asks no https:// clock source.** The source is refused by
267    /// the feature's name, and the trap on loopback saw no connection.
268    #[cfg(not(feature = "clock-fetch"))]
269    #[test]
270    fn a_default_build_refuses_an_https_clock_source_by_name_and_dials_nothing() {
271        let (trap, config) = trap();
272        let report = sync(&config, Trigger::Timer);
273        let said = format!("{report:?}");
274        assert!(said.contains("clock-fetch"), "the refusal names the feature: {said}");
275        assert!(!dialled(&trap), "a default build dialled the https clock source");
276    }
277
278    /// With `clock-fetch` on, today's behaviour: the https source is asked.
279    #[cfg(feature = "clock-fetch")]
280    #[test]
281    fn a_clock_fetch_build_asks_its_https_clock_source_as_before() {
282        let (trap, config) = trap();
283        let report = sync(&config, Trigger::Timer);
284        assert!(dialled(&trap), "a clock-fetch build did not ask its https source: {report:?}");
285    }
286}