1use std::process::Child;
7use std::time::Duration;
8
9use vitrify_core::model::UtcTime;
10
11use super::worker::kill_group;
12
13pub fn should_renew(
15 now: UtcTime,
16 expires: UtcTime,
17 lease_minutes: i64,
18 renew_fraction: f64,
19) -> bool {
20 let remaining = expires.0 - now.0;
21 (remaining as f64) < renew_fraction * (lease_minutes as f64) * 60.0
22}
23
24pub trait Clock: Send + Sync {
26 fn now(&self) -> UtcTime;
27}
28
29pub struct RealClock;
30
31impl Clock for RealClock {
32 fn now(&self) -> UtcTime {
33 UtcTime::now()
34 }
35}
36
37#[derive(Debug, Clone)]
38pub enum RenewResult {
39 Renewed {
40 expires: UtcTime,
41 },
42 LeaseExpired,
45 Failed(String),
48}
49
50pub trait LeaseBackend: Send + Sync {
53 fn renew(&self, unit: &str, holder: &str) -> RenewResult;
54}
55
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub enum MonitorVerdict {
58 Exited,
60 TimedOut,
63 LeaseLost,
65}
66
67#[derive(Debug, Clone)]
68pub struct MonitorParams {
69 pub lease_minutes: i64,
70 pub renew_fraction: f64,
71 pub worker_timeout_minutes: i64,
72 pub tick: Duration,
73}
74
75pub struct MonitorTarget<'a> {
77 pub child: &'a mut Child,
78 pub pid: u32,
79 pub unit: &'a str,
80 pub holder: &'a str,
81 pub expires: UtcTime,
82}
83
84pub fn monitor_worker(
88 target: MonitorTarget<'_>,
89 params: &MonitorParams,
90 clock: &dyn Clock,
91 backend: &dyn LeaseBackend,
92) -> MonitorVerdict {
93 monitor_worker_tracked(target, params, clock, backend).0
94}
95
96pub fn monitor_worker_tracked(
100 target: MonitorTarget<'_>,
101 params: &MonitorParams,
102 clock: &dyn Clock,
103 backend: &dyn LeaseBackend,
104) -> (MonitorVerdict, UtcTime) {
105 let MonitorTarget {
106 child,
107 pid,
108 unit,
109 holder,
110 mut expires,
111 } = target;
112 let start = clock.now();
113 loop {
114 match child.try_wait() {
115 Ok(Some(_)) => return (MonitorVerdict::Exited, expires),
116 Ok(None) => {}
117 Err(_) => return (MonitorVerdict::Exited, expires),
118 }
119 let now = clock.now();
120 if now.0 - start.0 > params.worker_timeout_minutes * 60 {
121 kill_group(pid);
122 let _ = child.wait();
123 return (MonitorVerdict::TimedOut, expires);
124 }
125 if should_renew(now, expires, params.lease_minutes, params.renew_fraction) {
126 match backend.renew(unit, holder) {
127 RenewResult::Renewed { expires: e } => expires = e,
128 RenewResult::LeaseExpired => {
129 kill_group(pid);
130 let _ = child.wait();
131 return (MonitorVerdict::LeaseLost, expires);
132 }
133 RenewResult::Failed(_) => {
134 }
137 }
138 }
139 std::thread::sleep(params.tick);
140 }
141}
142
143#[derive(Default)]
147pub struct Keeper {
148 held: std::sync::Mutex<Vec<Held>>,
149 stop: std::sync::atomic::AtomicBool,
150}
151
152struct Held {
153 unit: String,
154 holder: String,
155 expires: UtcTime,
156}
157
158impl Keeper {
159 pub fn hold(&self, unit: &str, holder: &str, expires: UtcTime) {
161 let mut held = self.held.lock().unwrap_or_else(|e| e.into_inner());
162 held.retain(|h| h.unit != unit);
163 held.push(Held {
164 unit: unit.to_string(),
165 holder: holder.to_string(),
166 expires,
167 });
168 }
169
170 pub fn drop_unit(&self, unit: &str) {
172 self.held
173 .lock()
174 .unwrap_or_else(|e| e.into_inner())
175 .retain(|h| h.unit != unit);
176 }
177
178 pub fn stop(&self) {
179 self.stop.store(true, std::sync::atomic::Ordering::SeqCst);
180 }
181
182 pub fn renew_due(
185 &self,
186 params: &MonitorParams,
187 clock: &dyn Clock,
188 backend: &dyn LeaseBackend,
189 ) -> Vec<String> {
190 let due: Vec<(String, String)> = {
191 let held = self.held.lock().unwrap_or_else(|e| e.into_inner());
192 let now = clock.now();
193 held.iter()
194 .filter(|h| {
195 should_renew(now, h.expires, params.lease_minutes, params.renew_fraction)
196 })
197 .map(|h| (h.unit.clone(), h.holder.clone()))
198 .collect()
199 };
200 let mut lost = Vec::new();
201 for (unit, holder) in due {
202 let result = backend.renew(&unit, &holder);
203 let mut held = self.held.lock().unwrap_or_else(|e| e.into_inner());
204 match result {
205 RenewResult::Renewed { expires } => {
206 if let Some(h) = held.iter_mut().find(|h| h.unit == unit) {
207 h.expires = expires;
208 }
209 }
210 RenewResult::LeaseExpired => {
211 held.retain(|h| h.unit != unit);
212 lost.push(unit);
213 }
214 RenewResult::Failed(_) => {}
217 }
218 }
219 lost
220 }
221
222 pub fn run(&self, params: &MonitorParams, clock: &dyn Clock, backend: &dyn LeaseBackend) {
224 while !self.stop.load(std::sync::atomic::Ordering::SeqCst) {
225 self.renew_due(params, clock, backend);
226 std::thread::sleep(params.tick);
227 }
228 }
229}