Skip to main content

git_policy_cli/landing/
claim_time.rs

1//! What:
2//!  A reading of the clocks a claim's lease is judged by: the machine and the boot the host is in, the host's monotonic clock,
3//!  and the wall clock. Two readings of one boot are compared by the monotonic clock; a reading of an earlier boot of the same
4//!  machine is past at once; the wall clock judges every other pair.
5//! Why:
6//!  A lease must run out when its holder stopped, not when somebody sets the date. The wall clock steps (a time sync, a person,
7//!  a virtual machine resuming), and a step forward made a live holder look an hour stale while a step back kept a dead
8//!  holder's claim alive. `CLOCK_MONOTONIC` is one clock for every process of a host, never steps, and does not count a
9//!  suspended host's sleep, so a holder and a recoverer on one boot agree on how long a claim went unrenewed. It restarts at
10//!  every boot, so a reading carries the boot ID (`/proc/sys/kernel/random/boot_id`). A restart ends the holder, so a claim of an
11//!  earlier boot has run out at once, and a wall clock set back at boot cannot strand it. That holds only when both readings
12//!  are of one machine: two hosts that share a work directory have unrelated boot IDs, and the other host's boot is not the
13//!  end of its holder. So a reading also carries the machine ID (`/etc/machine-id`), and a different boot ID is evidence of a
14//!  restart only beside an equal, known machine ID. Equal non-empty boot IDs still compare by the monotonic clock. Where either
15//!  reading has no boot ID, only the wall clock is left to compare; where either has no machine ID, a different boot ID proves
16//!  no restart, so the wall clock judges that pair as the fallback. Machines cloned with one machine ID cannot be told
17//!  apart; their claims are judged as one machine's.
18//!
19//! In TS you'd write (pseudocode):
20//! ```ts
21//! const stamp = { machineId: readMachineId(), bootId: readBootId(), monotonicMillis: hrtimeMillis(), wallSeconds: Date.now() / 1000 };
22//! const pastBoot = (now, then) => now.machineId !== '' && now.machineId === then.machineId
23//!   && now.bootId !== '' && then.bootId !== '' && now.bootId !== then.bootId;
24//! const elapsed = (now, then) => now.bootId !== '' && now.bootId === then.bootId ? now.monotonicMillis - then.monotonicMillis : (now.wallSeconds - then.wallSeconds) * 1000;
25//! ```
26
27use crate::service_replay::capture_stamp;
28use std::path::Path;
29use std::sync::OnceLock;
30use std::time::{Duration, SystemTime, UNIX_EPOCH};
31
32/// Separates the parts of a reading when it is written into a claim's file name.
33const FIELD_SEPARATOR: char = '~';
34
35/// The length of a boot ID without its dashes, and of a machine ID.
36const BOOT_ID_LENGTH: usize = 32;
37
38/// Where a machine ID is kept, in the order they are tried (`/var/lib/dbus/machine-id` is the older place and often a link to the first).
39const MACHINE_ID_PATHS: [&str; 2] = ["/etc/machine-id", "/var/lib/dbus/machine-id"];
40
41/// The number of parts in a reading's text before the machine ID was added, and after.
42const PARTS_WITHOUT_MACHINE: usize = 3;
43const PARTS_WITH_MACHINE: usize = 4;
44
45/// What:
46///  One reading of the three clocks.
47/// Why:
48///   A claim carries the reading taken when it was last renewed; whoever judges the claim takes a reading of its own.
49///
50/// In TS you'd write (pseudocode):
51/// ```ts
52/// type ClaimTime = { bootId: string; monotonicMillis: number; wallSeconds: number };
53/// ```
54#[derive(Clone, Debug, Eq, PartialEq)]
55pub struct ClaimTime {
56    /// The machine the reading was taken on; empty where the host has none or the reading predates machine IDs.
57    machine_id: String,
58    /// The boot the monotonic reading belongs to; empty where the host has no boot ID or no monotonic clock.
59    boot_id: String,
60    /// Milliseconds of `CLOCK_MONOTONIC`.
61    monotonic_millis: u64,
62    /// Seconds since the Unix epoch of the wall clock.
63    wall_seconds: u64,
64}
65
66/// Whether `text` is 32 hexadecimal digits, which is what a boot ID without dashes and a machine ID are.
67fn is_compact_hex_id(text: &str) -> bool {
68    return text.len() == BOOT_ID_LENGTH && text.bytes().all(|byte| { return byte.is_ascii_hexdigit(); });
69}
70
71/// The boot ID of this host's current boot, without dashes, or nothing when it cannot be read.
72pub(crate) fn current_boot_id() -> &'static str {
73    static BOOT_ID: OnceLock<String> = OnceLock::new();
74    return BOOT_ID
75        .get_or_init(|| {
76            let Ok(text) = std::fs::read_to_string("/proc/sys/kernel/random/boot_id") else {
77                return String::new();
78            };
79            let compact: String = text.trim().chars().filter(|character| { return *character != '-'; }).collect();
80            return if is_compact_hex_id(compact.as_str()) { compact } else { String::new() };
81        })
82        .as_str();
83}
84
85/// What:
86///  The first machine ID that `paths` hold, or nothing when none holds one.
87/// Why:
88///   A file that is missing, empty or not 32 hexadecimal digits (a fresh image holds the text `uninitialized`, a container
89///  may have no file) is no evidence of a machine, and the next place may still hold one. Taking the text as an ID would
90///  make every such host look like one machine.
91fn machine_id_from(paths: &[&Path]) -> String {
92    for path in paths {
93        let Ok(text) = std::fs::read_to_string(path) else {
94            continue;
95        };
96        if is_compact_hex_id(text.trim()) {
97            return text.trim().to_owned();
98        }
99    }
100    return String::new();
101}
102
103/// The machine ID of this host, read once, or nothing when it cannot be read.
104fn current_machine_id() -> &'static str {
105    static MACHINE_ID: OnceLock<String> = OnceLock::new();
106    return MACHINE_ID
107        .get_or_init(|| {
108            let paths: Vec<&Path> = MACHINE_ID_PATHS.iter().map(|path| { return Path::new(*path); }).collect();
109            return machine_id_from(paths.as_slice());
110        })
111        .as_str();
112}
113
114/// Methods over a reading.
115impl ClaimTime {
116    /// A reading of the clocks now.
117    pub fn read() -> ClaimTime {
118        let monotonic_millis: u64 = capture_stamp() / 1_000_000;
119        // Without a monotonic clock the boot ID would pair with a meaningless number, so the reading has none.
120        let boot_id: String = if monotonic_millis == 0 { String::new() } else { String::from(current_boot_id()) };
121        let wall_seconds: u64 = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |elapsed| { return elapsed.as_secs(); });
122        return ClaimTime { machine_id: String::from(current_machine_id()), boot_id, monotonic_millis, wall_seconds };
123    }
124
125    /// A reading of the given parts on a machine with no ID, which is how a test says what the clocks showed.
126    pub fn from_parts(boot_id: &str, monotonic: Duration, wall: Duration) -> ClaimTime {
127        return ClaimTime {
128            machine_id: String::new(),
129            boot_id: boot_id.to_owned(),
130            monotonic_millis: u64::try_from(monotonic.as_millis()).unwrap_or(u64::MAX),
131            wall_seconds: wall.as_secs(),
132        };
133    }
134
135    /// The reading `by` later on both clocks, which is time passing.
136    pub fn advanced(&self, by: Duration) -> ClaimTime {
137        return ClaimTime {
138            machine_id: self.machine_id.clone(),
139            boot_id: self.boot_id.clone(),
140            monotonic_millis: self.monotonic_millis.saturating_add(u64::try_from(by.as_millis()).unwrap_or(u64::MAX)),
141            wall_seconds: self.wall_seconds.saturating_add(by.as_secs()),
142        };
143    }
144
145    /// The reading `by` earlier on both clocks, which is how a test makes a claim whose holder last renewed that long ago.
146    pub fn rewound(&self, by: Duration) -> ClaimTime {
147        return ClaimTime {
148            machine_id: self.machine_id.clone(),
149            boot_id: self.boot_id.clone(),
150            monotonic_millis: self.monotonic_millis.saturating_sub(u64::try_from(by.as_millis()).unwrap_or(u64::MAX)),
151            wall_seconds: self.wall_seconds.saturating_sub(by.as_secs()),
152        };
153    }
154
155    /// The reading with the wall clock set `by` forward and the monotonic clock untouched, which is a clock step.
156    pub fn wall_stepped_forward(&self, by: Duration) -> ClaimTime {
157        return ClaimTime { wall_seconds: self.wall_seconds.saturating_add(by.as_secs()), ..self.clone() };
158    }
159
160    /// The reading with the wall clock set `by` back and the monotonic clock untouched, which is a clock step.
161    pub fn wall_stepped_back(&self, by: Duration) -> ClaimTime {
162        return ClaimTime { wall_seconds: self.wall_seconds.saturating_sub(by.as_secs()), ..self.clone() };
163    }
164
165    /// The reading in another boot, which is a restart of the host.
166    pub fn in_boot(&self, boot_id: &str) -> ClaimTime {
167        return ClaimTime { boot_id: boot_id.to_owned(), ..self.clone() };
168    }
169
170    /// The reading on the machine with the given ID, which is how a test puts two readings on one machine or on two.
171    pub fn on_machine(&self, machine_id: &str) -> ClaimTime {
172        return ClaimTime { machine_id: machine_id.to_owned(), ..self.clone() };
173    }
174
175    /// The reading a wall-clock time stands for where there is nothing else, such as the modification time of a claim an
176    /// earlier release stamped.
177    pub fn from_wall(wall: SystemTime) -> ClaimTime {
178        return ClaimTime {
179            machine_id: String::new(),
180            boot_id: String::new(),
181            monotonic_millis: 0,
182            wall_seconds: wall.duration_since(UNIX_EPOCH).map_or(0, |elapsed| { return elapsed.as_secs(); }),
183        };
184    }
185
186    /// How long ago `earlier` was, by the clock the two readings share: the monotonic clock within one boot, the wall clock
187    /// where either has no boot ID. A reading from the future of this one counts as no time at all. Readings of two different
188    /// boots share no clock that says how long the earlier holder lived, so a judge asks `is_past_the_boot_of` first.
189    pub fn elapsed_since(&self, earlier: &ClaimTime) -> Duration {
190        if !self.boot_id.is_empty() && self.boot_id == earlier.boot_id {
191            return Duration::from_millis(self.monotonic_millis.saturating_sub(earlier.monotonic_millis));
192        }
193        return Duration::from_secs(self.wall_seconds.saturating_sub(earlier.wall_seconds));
194    }
195
196    /// What:
197    ///  Whether `earlier` was read in a boot this reading is not in, on the same machine, so whoever took it is gone.
198    /// Why:
199    ///   A restart ends every process of the host, so the holder of an earlier boot's claim is dead and waiting out its
200    ///  lease on the wall clock only strands the claim when the clock was set back at boot. A different boot ID of another
201    ///  machine says nothing about the holder, which may be running there, so the answer is yes only when both machine IDs
202    ///  are known and equal. Without a boot ID or a machine ID on either side there is nothing to compare, and the answer is
203    ///  no: the lease decides.
204    ///
205    /// In TS you'd write (pseudocode):
206    /// ```ts
207    /// now.machineId !== '' && now.machineId === then.machineId
208    ///   && now.bootId !== '' && then.bootId !== '' && now.bootId !== then.bootId
209    /// ```
210    pub fn is_past_the_boot_of(&self, earlier: &ClaimTime) -> bool {
211        let same_known_machine: bool = !self.machine_id.is_empty() && self.machine_id == earlier.machine_id;
212        return same_known_machine && !self.boot_id.is_empty() && !earlier.boot_id.is_empty() && self.boot_id != earlier.boot_id;
213    }
214
215    /// The reading as the file-name parts `boot~monotonic~wall~machine`; a reading with no machine ID leaves the last part
216    /// out, which is the form every release before machine IDs wrote and reads.
217    pub fn encode(&self) -> String {
218        let without_machine: String = format!("{}{FIELD_SEPARATOR}{}{FIELD_SEPARATOR}{}", self.boot_id, self.monotonic_millis, self.wall_seconds);
219        if self.machine_id.is_empty() {
220            return without_machine;
221        }
222        return format!("{without_machine}{FIELD_SEPARATOR}{}", self.machine_id);
223    }
224
225    /// The reading `encode` wrote, or nothing for any other text. The form without a machine ID, which releases before
226    /// machine IDs wrote into claims that may still be on disk, reads as a reading with none.
227    pub fn decode(text: &str) -> Option<ClaimTime> {
228        let parts: Vec<&str> = text.split(FIELD_SEPARATOR).collect();
229        if parts.len() != PARTS_WITHOUT_MACHINE && parts.len() != PARTS_WITH_MACHINE {
230            return None;
231        }
232        let boot_id: &str = parts[0];
233        let monotonic_millis: u64 = parts[1].parse().ok()?;
234        let wall_seconds: u64 = parts[2].parse().ok()?;
235        let machine_id: &str = parts.get(PARTS_WITH_MACHINE - 1).copied().unwrap_or("");
236        let boot_id_fits: bool = boot_id.is_empty() || is_compact_hex_id(boot_id);
237        let machine_id_fits: bool = parts.len() == PARTS_WITHOUT_MACHINE || is_compact_hex_id(machine_id);
238        if !boot_id_fits || !machine_id_fits {
239            return None;
240        }
241        return Some(ClaimTime { machine_id: machine_id.to_owned(), boot_id: boot_id.to_owned(), monotonic_millis, wall_seconds });
242    }
243}
244
245/// Clock controls stay out of the release executable.
246#[cfg(test)]
247#[path = "claim_time_tests.rs"]
248mod tests;