1use std::collections::{BTreeMap, HashMap};
7use std::time::Duration;
8
9use jiff::{SignedDuration, Timestamp};
10use schedr_db::database::{Database, DbError};
11use schedr_db::samples::{MINUTE, ROLLUP, Sample, Source};
12use schedr_model::usage::{NodeUsage, WorkerParts};
13
14#[cfg(test)]
15mod tests;
16
17pub const ROLL_GRACE: SignedDuration = SignedDuration::from_mins(2);
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub struct SampleSettings {
23 pub interval: Duration,
25 pub minutes_kept: Duration,
27 pub rollups_kept: Duration,
29 pub rollup_grace: Duration,
32 pub node_heartbeat: Duration,
35}
36
37impl Default for SampleSettings {
38 fn default() -> Self {
39 Self {
40 interval: Duration::from_mins(1),
41 minutes_kept: Duration::from_hours(24),
42 rollups_kept: Duration::from_hours(24 * 30),
43 rollup_grace: ROLL_GRACE.unsigned_abs(),
44 node_heartbeat: Duration::from_secs(10),
45 }
46 }
47}
48
49pub const MASTERS_HEARD_BEATS: u32 = 3;
51
52const WORKERS_HEARD: SignedDuration = SignedDuration::from_secs(120);
54
55fn floor(at: Timestamp, step: u32) -> Timestamp {
57 let step = i64::from(step);
58 let seconds = at.as_second().div_euclid(step) * step;
59 Timestamp::from_second(seconds).unwrap_or(at)
60}
61
62#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
66pub struct Pass {
67 pub written: usize,
69 pub rolled: u64,
71 pub statements: u32,
73}
74
75#[derive(Debug, Default)]
78pub struct Sampler {
79 cpu: HashMap<String, (Timestamp, f64, Option<f64>)>,
80 rolled: Option<Timestamp>,
81 prune: bool,
84}
85
86impl Sampler {
87 fn cores(&mut self, process: &str, measured: Timestamp, cpu_seconds: f64) -> Option<f64> {
92 if let Some((then, _, cores)) = self.cpu.get(process)
93 && *then == measured
94 {
95 return *cores;
96 }
97 let before = self.cpu.get(process).copied();
98 let cores = before.and_then(|(then, was, _)| {
99 let elapsed = measured.duration_since(then).as_secs_f64();
100 let used = cpu_seconds - was;
101 (elapsed > 0.0 && used >= 0.0 && used.is_finite()).then(|| used / elapsed)
102 });
103 self.cpu
104 .insert(process.to_owned(), (measured, cpu_seconds, cores));
105 cores
106 }
107
108 pub fn samples(
112 &mut self,
113 sources: Vec<Source>,
114 at: Timestamp,
115 own: Option<(&str, &BTreeMap<String, String>)>,
116 ) -> Vec<Sample> {
117 let mut by_process: BTreeMap<String, (BTreeMap<String, String>, Option<Source>)> =
118 BTreeMap::new();
119 for source in sources {
120 let entry = by_process.entry(source.process_id.clone()).or_default();
121 entry
122 .0
123 .insert(source.role.to_owned(), source.node_id.clone());
124 let keep = match &entry.1 {
125 None => true,
126 Some(kept) => kept.parts.is_none() && source.parts.is_some(),
127 };
128 if keep {
129 entry.1 = Some(source);
130 }
131 }
132 if let Some((process, roles)) = own
133 && let Some(entry) = by_process.get_mut(process)
134 {
135 entry
136 .0
137 .extend(roles.iter().map(|(k, v)| (k.clone(), v.clone())));
138 }
139 by_process
140 .into_iter()
141 .filter_map(|(process, (roles, source))| {
142 let source = source?;
143 Some(self.sample(
144 (process, roles),
145 &source.usage,
146 source.parts,
147 (at, source.at),
148 ))
149 })
150 .collect()
151 }
152
153 pub fn sample(
156 &mut self,
157 (process, roles): (String, BTreeMap<String, String>),
158 usage: &NodeUsage,
159 parts: Option<WorkerParts>,
160 (at, measured): (Timestamp, Timestamp),
161 ) -> Sample {
162 let cpu = self.cores(&process, measured, usage.cpu_seconds);
163 let memory = usage
165 .resident_bytes
166 .saturating_add(parts.as_ref().map_or(0, |p| {
167 p.fork_servers_bytes
168 .saturating_add(p.watcher_hosts_bytes)
169 .saturating_add(p.tasks_bytes)
170 }));
171 Sample {
172 process_id: process,
173 step_s: MINUTE,
174 at,
175 roles,
176 resident_avg: usage.resident_bytes,
177 resident_peak: usage.resident_bytes,
178 memory_avg: memory,
179 memory_peak: memory,
180 minutes: 1,
181 cpu_minutes: u32::from(cpu.is_some()),
182 container_minutes: u32::from(usage.container_bytes.is_some()),
183 covered: 1,
184 cpu_seconds: Some(usage.cpu_seconds),
185 cpu_avg: cpu,
186 cpu_peak: cpu,
187 container_avg: usage.container_bytes,
188 container_peak: usage.container_bytes,
189 container_limit: usage.container_limit_bytes,
190 parts,
191 }
192 }
193
194 pub async fn pass(
202 &mut self,
203 db: &Database,
204 settings: &SampleSettings,
205 now: Timestamp,
206 own: Option<(&str, &BTreeMap<String, String>)>,
207 ) -> Result<Pass, DbError> {
208 let minute = floor(now, MINUTE);
209 let sources = db
210 .sample_sources(
211 now.checked_sub(within(
212 settings.node_heartbeat.saturating_mul(MASTERS_HEARD_BEATS),
213 ))
214 .unwrap_or(now),
215 now.checked_sub(WORKERS_HEARD).unwrap_or(now),
216 )
217 .await?;
218 let mut pass = Pass {
219 statements: 2,
220 ..Pass::default()
221 };
222 let samples = self.samples(sources, minute, own);
223 if !samples.is_empty() {
224 db.insert_samples(&samples).await?;
225 pass.statements += 1;
226 }
227 pass.written = samples.len();
228 let grace = within(settings.rollup_grace);
234 let closed = floor(minute.checked_sub(grace).unwrap_or(minute), ROLLUP)
235 .checked_sub(SignedDuration::from_secs(i64::from(ROLLUP)))
236 .unwrap_or(minute);
237 let window = SignedDuration::from_secs(i64::from(ROLLUP));
238 let mut next = if let Some(rolled) = self.rolled {
239 rolled.checked_add(window).unwrap_or(rolled)
240 } else {
241 pass.statements += 1;
242 db.oldest_minute_sample()
243 .await?
244 .map_or(closed, |oldest| floor(oldest, ROLLUP))
245 };
246 if next > closed && self.rolled.is_none() {
248 self.rolled = Some(closed);
249 }
250 while next <= closed {
251 let (rolled, statements) = roll_up(db, next).await?;
252 pass.rolled += rolled;
253 pass.statements += statements;
254 self.rolled = Some(next);
255 self.prune = true;
256 match next.checked_add(window) {
257 Ok(later) => next = later,
258 Err(_) => break,
259 }
260 }
261 if self.prune {
262 let keep = |kept: Duration| {
263 SignedDuration::try_from(kept)
264 .ok()
265 .and_then(|kept| now.checked_sub(kept).ok())
266 .unwrap_or(Timestamp::UNIX_EPOCH)
267 };
268 db.delete_old_samples(MINUTE, keep(settings.minutes_kept))
269 .await?;
270 db.delete_old_samples(ROLLUP, keep(settings.rollups_kept))
271 .await?;
272 pass.statements += 2;
273 self.prune = false;
274 }
275 Ok(pass)
276 }
277}
278
279async fn roll_up(db: &Database, from: Timestamp) -> Result<(u64, u32), DbError> {
282 let to = from
283 .checked_add(SignedDuration::from_secs(i64::from(ROLLUP)))
284 .unwrap_or(from);
285 let minutes = db.samples(MINUTE, from, to).await?;
286 let rolled = rolled_up(&minutes, from);
287 if rolled.is_empty() {
288 return Ok((0, 1));
289 }
290 db.insert_samples(&rolled).await?;
291 Ok((u64::try_from(rolled.len()).unwrap_or(u64::MAX), 2))
292}
293
294#[must_use]
300pub fn rolled_up(minutes: &[Sample], at: Timestamp) -> Vec<Sample> {
301 let covered = u32::try_from(
303 minutes
304 .iter()
305 .map(|s| s.at)
306 .collect::<std::collections::BTreeSet<_>>()
307 .len(),
308 )
309 .unwrap_or(u32::MAX);
310 let mut by_process: BTreeMap<&str, Vec<&Sample>> = BTreeMap::new();
311 for sample in minutes {
312 by_process
313 .entry(&sample.process_id)
314 .or_default()
315 .push(sample);
316 }
317 by_process
318 .into_iter()
319 .map(|(process, samples)| {
320 #[expect(clippy::cast_precision_loss, reason = "an average of byte counts")]
321 let average = |values: &[u64]| {
322 (!values.is_empty()).then(|| {
323 let sum: f64 = values.iter().map(|v| *v as f64).sum();
324 #[expect(
325 clippy::cast_possible_truncation,
326 clippy::cast_sign_loss,
327 reason = "a rounded average of byte counts: non-negative, in range"
328 )]
329 let rounded = (sum / values.len() as f64).round() as u64;
330 rounded
331 })
332 };
333 let resident: Vec<u64> = samples.iter().map(|s| s.resident_avg).collect();
334 let memory: Vec<u64> = samples.iter().map(|s| s.memory_avg).collect();
335 let container: Vec<u64> = samples.iter().filter_map(|s| s.container_avg).collect();
336 let cpu: Vec<f64> = samples.iter().filter_map(|s| s.cpu_avg).collect();
337 #[expect(clippy::cast_precision_loss, reason = "a count of minutes")]
338 let cpu_avg = (!cpu.is_empty()).then(|| cpu.iter().sum::<f64>() / cpu.len() as f64);
339 Sample {
340 process_id: process.to_owned(),
341 step_s: ROLLUP,
342 at,
343 roles: samples
344 .iter()
345 .flat_map(|s| s.roles.iter().map(|(k, v)| (k.clone(), v.clone())))
346 .collect(),
347 resident_avg: average(&resident).unwrap_or(0),
348 resident_peak: samples.iter().map(|s| s.resident_peak).max().unwrap_or(0),
349 memory_avg: average(&memory).unwrap_or(0),
350 memory_peak: samples.iter().map(|s| s.memory_peak).max().unwrap_or(0),
351 minutes: samples.iter().map(|s| s.minutes).sum(),
352 cpu_minutes: samples.iter().map(|s| s.cpu_minutes).sum(),
353 container_minutes: samples.iter().map(|s| s.container_minutes).sum(),
354 covered,
355 cpu_seconds: None,
356 cpu_avg,
357 cpu_peak: samples.iter().filter_map(|s| s.cpu_peak).reduce(f64::max),
358 container_avg: average(&container),
359 container_peak: samples.iter().filter_map(|s| s.container_peak).max(),
360 container_limit: samples.last().and_then(|s| s.container_limit),
362 parts: {
365 let ran = samples.iter().any(|s| s.parts.is_some());
366 let part = |of: fn(&WorkerParts) -> u64| {
367 average(
368 &samples
369 .iter()
370 .map(|s| s.parts.as_ref().map_or(0, of))
371 .collect::<Vec<_>>(),
372 )
373 .unwrap_or(0)
374 };
375 ran.then(|| WorkerParts {
376 fork_servers_bytes: part(|p| p.fork_servers_bytes),
377 watcher_hosts_bytes: part(|p| p.watcher_hosts_bytes),
378 tasks_bytes: part(|p| p.tasks_bytes),
379 largest_tasks: Vec::new(),
380 })
381 },
382 }
383 })
384 .collect()
385}
386
387pub async fn sample_webserver(
390 db: Database,
391 interval: Duration,
392 process_id: String,
393 usage: fn() -> Option<NodeUsage>,
394 stop: impl Future<Output = ()>,
395) {
396 tokio::pin!(stop);
397 let mut sampler = Sampler::default();
398 let roles: BTreeMap<String, String> =
399 BTreeMap::from([("webserver".to_owned(), process_id.clone())]);
400 loop {
401 if let Some(usage) = usage() {
402 let measured = Timestamp::now();
403 let sample = sampler.sample(
404 (process_id.clone(), roles.clone()),
405 &usage,
406 None,
407 (floor(measured, MINUTE), measured),
408 );
409 if let Err(error) = db.insert_samples(&[sample]).await {
410 tracing::warn!(%error, "this webserver's sample not stored; trying again in a minute");
411 }
412 }
413 tokio::select! {
414 () = &mut stop => return,
415 () = tokio::time::sleep(interval) => {}
416 }
417 }
418}
419
420fn within(duration: Duration) -> SignedDuration {
422 SignedDuration::try_from(duration).unwrap_or(SignedDuration::MAX)
423}