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(), &|_| {
80 Err(NO_HTTPS.to_owned())
81 });
82 let action = estate_clock::adjust::choose(phase, &polled.verdict.decision);
83 let applied = estate_clock::adjust::apply(action).map_err(|err| err.to_string());
84 Report::from_poll(phase, &polled, action, applied)
85 }
86 Err(why) => Report::without_sources(phase, Outcome::Misconfigured, why.clone()),
87 Ok(Config::NotConfigured) => Report::without_sources(
88 phase,
89 Outcome::NotConfigured,
90 format!("no clock source is configured ({CLOCK_ENV})"),
91 ),
92 Ok(Config::Off) => Report::without_sources(
93 phase,
94 Outcome::Off,
95 format!("{CLOCK_ENV}=off: this machine was told not to set its own clock"),
96 ),
97 };
98 estate_clock::report::record(report.clone());
99 report
100}
101
102/// Whether this process may set the machine's clock at all.
103///
104/// Gated exactly as `crate::disktest` and `crate::dashboard` are — PID 1 **and**
105/// `korp.entry=` on the kernel command line. A container entrypoint is PID 1 of
106/// its namespace too, and a privileged container shares the host's clock:
107/// stepping it there would move somebody's real machine. Naming sources in
108/// [`CLOCK_ENV`] (or its Gunnar alias `GUNNAR_CLOCK`) explicitly turns it on
109/// regardless, which is what the installtest rig and a developer reproducing a
110/// refusal need; the syscall still needs `CAP_SYS_TIME` and a refusal is still
111/// only a report.
112fn owns_the_clock() -> bool {
113 std::env::var_os(CLOCK_ENV).is_some()
114 || estate_clock::config::gunnar_alias(CLOCK_ENV)
115 .is_some_and(|alias| std::env::var_os(alias).is_some())
116 || (appliance_pid1::net::is_init() && appliance_pid1::net::booted_by_korp_start())
117}
118
119/// Say what an attempt concluded, at the level it deserves.
120fn log(report: &Report) {
121 let summary = report.summary();
122 match report.outcome {
123 Outcome::Stepped | Outcome::Slewed | Outcome::AlreadyRight => {
124 tracing::info!(
125 outcome = report.outcome.as_str(),
126 offset_ms = report.offset_ms,
127 "clock: {summary}"
128 )
129 }
130 Outcome::NotConfigured | Outcome::Off => {
131 tracing::info!(outcome = report.outcome.as_str(), "clock: {summary}")
132 }
133 Outcome::Misconfigured | Outcome::NoQuorum | Outcome::Disagree | Outcome::ApplyFailed => {
134 tracing::warn!(
135 outcome = report.outcome.as_str(),
136 "clock: {summary}. If this box's clock is wrong, every credential it is handed \
137 will be refused."
138 )
139 }
140 }
141 for row in &report.sources {
142 match (&row.offset_ms, &row.error) {
143 (_, Some(why)) => tracing::warn!(source = %row.source, %why, "clock source failed"),
144 (Some(offset_ms), None) => {
145 tracing::info!(source = %row.source, offset_ms, "clock source answered")
146 }
147 (None, None) => {}
148 }
149 }
150}
151
152/// One attempt on the blocking pool; the report is recorded by `sync` itself.
153async fn attempt(phase: Trigger) -> Report {
154 let config = crate::feed::clock_config();
155 match tokio::task::spawn_blocking(move || sync(&config, phase)).await {
156 Ok(report) => report,
157 Err(err) => {
158 let report = Report::without_sources(
159 phase,
160 Outcome::ApplyFailed,
161 format!("the clock sync task did not complete: {err}"),
162 );
163 estate_clock::report::record(report.clone());
164 report
165 }
166 }
167}
168
169/// **The boot call.** Sync once, stepping if the source says so.
170pub async fn synchronise_at_boot() {
171 if !owns_the_clock() {
172 let report = Report::without_sources(
173 Trigger::Boot,
174 Outcome::Off,
175 "not the appliance's PID 1, so the system clock is somebody else's to set",
176 );
177 tracing::debug!("clock: {}", report.summary());
178 estate_clock::report::record(report);
179 return;
180 }
181 log(&attempt(Trigger::Boot).await);
182}
183
184/// Whether a clock is configured at all (the medium's or the feed's).
185fn configured() -> bool {
186 !matches!(
187 crate::feed::clock_config(),
188 Ok(Config::NotConfigured) | Ok(Config::Off)
189 )
190}
191
192/// **The running triggers**: a credential refused for skew, and the 6-hour
193/// safety timer (`estate_clock::trigger::arm` has the rules and why there are
194/// only these, and arms them once per process). Called after the boot sync, and
195/// by a fed run before its first pause. Does nothing on a box that does not
196/// own its clock, or whose clock is not configured — a clock the installer's
197/// door feeds later arms them then ([`fed_arrived`]).
198///
199/// Both run on plain threads, never on the runtime: the skew handler is started
200/// by the credential gate and must not borrow a worker for a TCP exchange, and a
201/// sync is blocking by nature.
202pub fn arm_triggers() {
203 if !owns_the_clock() || !configured() {
204 return;
205 }
206 estate_clock::trigger::arm(|trigger| {
207 let config = crate::feed::clock_config();
208 log(&sync(&config, trigger));
209 });
210}
211
212/// One sync of the clock in force (the feed read now), logged.
213fn fed_sync() -> Outcome {
214 let config = crate::feed::clock_config();
215 let report = sync(&config, Trigger::Timer);
216 log(&report);
217 report.outcome
218}
219
220/// This process's fed clock runs (`estate_clock::offer::FedRun`): the
221/// triggers armed first, then syncs backing off while the front does not
222/// answer; one run at a time, off the caller's thread; the tunnel coming up
223/// cuts a pause short.
224static FED: FedRun = FedRun::new(fed_sync, arm_triggers);
225
226/// **The installer's door fed a clock source or key while this box runs**
227/// (the pairing loop's first answer, `crate::feed`). Every sync already reads
228/// the feed ([`crate::feed::clock_config`]), so this only makes the first one
229/// happen NOW — a first boot whose medium carries no clock would otherwise
230/// wait for the 6-hour timer, which was never armed — and arms the triggers.
231///
232/// ★ **Returns at once: the syncs run on their own thread** (cov-E r3
233/// 2026-10-06, runs 2 and 4): called from the installer's FEED, a twin fed
234/// before its tunnel was up once ran the whole backoff on the feed's thread
235/// and for 219 s answered nobody. A clock re-fed meanwhile gets one more run
236/// of its own when the one under way ends.
237pub fn fed_arrived() {
238 if !owns_the_clock() || !configured() {
239 return;
240 }
241 if !FED.start() {
242 tracing::warn!(
243 "clock: the fed sync could not get a thread of its own; the triggers take over"
244 );
245 }
246}
247
248/// **This box's tunnel just came up** (the pairing loop's `TunnelUp`).
249///
250/// The fed clock source is the front's utility address, reached through
251/// this tunnel on a box whose fed syncs ran before it was up (i54a run23:
252/// the twin's three syncs timed out, then it paused 20 s while its tunnel
253/// came up and the front's `BecomeTwin` was refused for skew seven times).
254/// So: a clock not yet set right is asked NOW — the pause under way is cut
255/// short, and a run is started if none is. Once per process; nothing when
256/// the clock is already right.
257pub fn tunnel_up() {
258 if !owns_the_clock() || !configured() {
259 return;
260 }
261 FED.tunnel_up(last_outcome());
262}
263
264#[cfg(test)]
265mod airgap {
266 use super::*;
267 use estate_clock::config::Source;
268
269 /// A loopback listener that would see any dial, and an https source aimed at it.
270 fn trap() -> (std::net::TcpListener, Result<Config, String>) {
271 let trap = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
272 trap.set_nonblocking(true).unwrap();
273 let url = format!("https://{}/", trap.local_addr().unwrap());
274 (
275 trap,
276 Ok(Config::Sources {
277 sources: vec![Source::Https(url)],
278 peer_key: None,
279 }),
280 )
281 }
282
283 fn dialled(trap: &std::net::TcpListener) -> bool {
284 std::thread::sleep(std::time::Duration::from_millis(100));
285 trap.accept().is_ok()
286 }
287
288 /// ★ **AIRGAP: a default build asks no https:// clock source.** The source is refused by
289 /// the feature's name, and the trap on loopback saw no connection.
290 #[cfg(not(feature = "clock-fetch"))]
291 #[test]
292 fn a_default_build_refuses_an_https_clock_source_by_name_and_dials_nothing() {
293 let (trap, config) = trap();
294 let report = sync(&config, Trigger::Timer);
295 let said = format!("{report:?}");
296 assert!(
297 said.contains("clock-fetch"),
298 "the refusal names the feature: {said}"
299 );
300 assert!(
301 !dialled(&trap),
302 "a default build dialled the https clock source"
303 );
304 }
305
306 /// With `clock-fetch` on, today's behaviour: the https source is asked.
307 #[cfg(feature = "clock-fetch")]
308 #[test]
309 fn a_clock_fetch_build_asks_its_https_clock_source_as_before() {
310 let (trap, config) = trap();
311 let report = sync(&config, Trigger::Timer);
312 assert!(
313 dialled(&trap),
314 "a clock-fetch build did not ask its https source: {report:?}"
315 );
316 }
317}