1use std::collections::BTreeMap;
5
6use jiff::Timestamp;
7use schedr_model::usage::{NodeUsage, WorkerParts, WorkerUsage};
8
9use crate::backend::Backend;
10use crate::database::{Database, DbError};
11use crate::query::{db_time, from_json, in_tx, on_pool, parse_time, sql, sql_text, to_json};
12
13#[cfg(test)]
14mod tests;
15
16pub const MINUTE: u32 = 60;
18
19pub const ROLLUP: u32 = 900;
21
22const ROWS_PER_INSERT: usize = 500;
24
25#[derive(Debug, Clone, PartialEq)]
27pub struct Sample {
28 pub process_id: String,
30 pub step_s: u32,
32 pub at: Timestamp,
34 pub roles: BTreeMap<String, String>,
36 pub resident_avg: u64,
38 pub resident_peak: u64,
40 pub memory_avg: u64,
43 pub memory_peak: u64,
45 pub minutes: u32,
47 pub cpu_minutes: u32,
49 pub container_minutes: u32,
51 pub covered: u32,
53 pub cpu_seconds: Option<f64>,
55 pub cpu_avg: Option<f64>,
57 pub cpu_peak: Option<f64>,
59 pub container_avg: Option<u64>,
61 pub container_peak: Option<u64>,
63 pub container_limit: Option<u64>,
65 pub parts: Option<WorkerParts>,
67}
68
69#[derive(Debug, Clone, PartialEq)]
71pub struct Source {
72 pub process_id: String,
74 pub role: &'static str,
76 pub node_id: String,
78 pub usage: NodeUsage,
80 pub parts: Option<WorkerParts>,
82 pub at: Timestamp,
84}
85
86const MOST_BYTES: u64 = 1 << 52;
89
90fn int(value: u64) -> i64 {
91 i64::try_from(value.min(MOST_BYTES)).unwrap_or(i64::MAX)
92}
93
94fn unsigned(value: i64) -> u64 {
95 u64::try_from(value).unwrap_or(0)
96}
97
98#[derive(sqlx::FromRow)]
99struct Row {
100 process_id: String,
101 step_s: i64,
102 at: String,
103 roles: String,
104 resident_avg: i64,
105 resident_peak: i64,
106 memory_avg: i64,
107 memory_peak: i64,
108 minutes: i64,
109 cpu_minutes: i64,
110 container_minutes: i64,
111 covered: i64,
112 cpu_seconds: Option<f64>,
113 cpu_avg: Option<f64>,
114 cpu_peak: Option<f64>,
115 container_avg: Option<i64>,
116 container_peak: Option<i64>,
117 container_limit: Option<i64>,
118 parts: Option<String>,
119}
120
121fn sample(row: Row) -> Result<Sample, DbError> {
122 let count = |n: i64| u32::try_from(n).unwrap_or(0);
123 Ok(Sample {
124 process_id: row.process_id,
125 step_s: count(row.step_s),
126 at: parse_time("samples.at", &row.at)?,
127 roles: from_json("samples.roles", &row.roles)?,
128 resident_avg: unsigned(row.resident_avg),
129 resident_peak: unsigned(row.resident_peak),
130 memory_avg: unsigned(row.memory_avg),
131 memory_peak: unsigned(row.memory_peak),
132 minutes: count(row.minutes),
133 cpu_minutes: count(row.cpu_minutes),
134 container_minutes: count(row.container_minutes),
135 covered: count(row.covered),
136 cpu_seconds: row.cpu_seconds,
137 cpu_avg: row.cpu_avg,
138 cpu_peak: row.cpu_peak,
139 container_avg: row.container_avg.map(unsigned),
140 container_peak: row.container_peak.map(unsigned),
141 container_limit: row.container_limit.map(unsigned),
142 parts: row
143 .parts
144 .map(|parts| from_json("samples.parts", &parts))
145 .transpose()?,
146 })
147}
148
149impl Database {
150 pub async fn sample_sources(
158 &self,
159 masters_since: Timestamp,
160 workers_since: Timestamp,
161 ) -> Result<Vec<Source>, DbError> {
162 const MASTERS: &str = "SELECT process_id, master_id, usage{text}, \
163 {ts<}heard_at{>ts} FROM masters \
164 WHERE heard_at >= $1{ts} AND usage IS NOT NULL ORDER BY master_id";
165 const WORKERS: &str = "SELECT process_id, worker_id, usage{text}, \
166 {ts<}usage_at{>ts} FROM workers \
167 WHERE state IN ('active', 'draining') AND last_heartbeat_at >= $1{ts} \
168 AND usage IS NOT NULL AND usage_at IS NOT NULL AND process_id IS NOT NULL \
169 ORDER BY worker_id";
170 type Row = (String, String, String, String);
171 let masters: Vec<Row> = on_pool!(self, |pool, backend| {
172 sqlx::query_as(sql(backend, MASTERS))
173 .bind(db_time(masters_since))
174 .fetch_all(pool)
175 .await?
176 });
177 let workers: Vec<Row> = on_pool!(self, |pool, backend| {
178 sqlx::query_as(sql(backend, WORKERS))
179 .bind(db_time(workers_since))
180 .fetch_all(pool)
181 .await?
182 });
183 let mut sources = Vec::with_capacity(masters.len() + workers.len());
184 for (process_id, node_id, usage, at) in masters {
185 sources.push(Source {
186 process_id,
187 role: "master",
188 node_id,
189 usage: from_json("masters.usage", &usage)?,
190 parts: None,
191 at: parse_time("masters.heard_at", &at)?,
192 });
193 }
194 for (process_id, node_id, usage, at) in workers {
195 let usage: WorkerUsage = from_json("workers.usage", &usage)?;
196 sources.push(Source {
197 process_id,
198 role: "worker",
199 node_id,
200 parts: Some(usage.parts()),
201 usage: usage.process,
202 at: parse_time("workers.usage_at", &at)?,
203 });
204 }
205 Ok(sources)
206 }
207
208 pub async fn insert_samples(&self, samples: &[Sample]) -> Result<(), DbError> {
214 if samples.is_empty() {
215 return Ok(());
216 }
217 let queries: Vec<(String, &[Sample])> = samples
221 .chunks(ROWS_PER_INSERT)
222 .map(|chunk| (insert_query(chunk.len()), chunk))
223 .collect();
224 in_tx!(self, |tx, backend| {
225 for (query, chunk) in &queries {
226 let text = sql_text(backend, query);
227 let mut insert = sqlx::query(text);
228 for sample in *chunk {
229 insert = insert
230 .bind(sample.process_id.clone())
231 .bind(i64::from(sample.step_s))
232 .bind(db_time(sample.at))
233 .bind(to_json(&sample.roles))
234 .bind(int(sample.resident_avg))
235 .bind(int(sample.resident_peak))
236 .bind(int(sample.memory_avg))
237 .bind(int(sample.memory_peak))
238 .bind(i64::from(sample.minutes))
239 .bind(i64::from(sample.cpu_minutes))
240 .bind(i64::from(sample.container_minutes))
241 .bind(i64::from(sample.covered))
242 .bind(sample.cpu_seconds)
243 .bind(sample.cpu_avg)
244 .bind(sample.cpu_peak)
245 .bind(sample.container_avg.map(int))
246 .bind(sample.container_peak.map(int))
247 .bind(sample.container_limit.map(int))
248 .bind(sample.parts.as_ref().map(to_json))
249 .bind(sample.parts.as_ref().map(|p| int(p.fork_servers_bytes)))
250 .bind(sample.parts.as_ref().map(|p| int(p.watcher_hosts_bytes)))
251 .bind(sample.parts.as_ref().map(|p| int(p.tasks_bytes)));
252 }
253 insert.execute(&mut *tx).await?;
254 }
255 });
256 Ok(())
257 }
258
259 pub async fn oldest_minute_sample(&self) -> Result<Option<Timestamp>, DbError> {
265 const OLDEST: &str = "SELECT {ts<}MIN(at){>ts} FROM samples WHERE step_s = $1";
266 let oldest: Option<String> = on_pool!(self, |pool, backend| {
267 sqlx::query_scalar(sql(backend, OLDEST))
268 .bind(i64::from(MINUTE))
269 .fetch_one(pool)
270 .await?
271 });
272 oldest.map(|at| parse_time("samples.at", &at)).transpose()
273 }
274
275 pub async fn delete_old_samples(&self, step_s: u32, before: Timestamp) -> Result<u64, DbError> {
281 const DELETE: &str = "DELETE FROM samples WHERE step_s = $1 AND at < $2{ts}";
282 let deleted = in_tx!(self, |tx, backend| {
283 sqlx::query(sql(backend, DELETE))
284 .bind(i64::from(step_s))
285 .bind(db_time(before))
286 .execute(&mut *tx)
287 .await?
288 .rows_affected()
289 });
290 Ok(deleted)
291 }
292
293 pub async fn samples(
299 &self,
300 step_s: u32,
301 from: Timestamp,
302 to: Timestamp,
303 ) -> Result<Vec<Sample>, DbError> {
304 self.samples_of(step_s, from, to, None).await
305 }
306
307 pub async fn samples_of(
313 &self,
314 step_s: u32,
315 from: Timestamp,
316 to: Timestamp,
317 process: Option<&str>,
318 ) -> Result<Vec<Sample>, DbError> {
319 const SAMPLES: &str = "SELECT process_id, CAST(step_s AS BIGINT) AS step_s, \
320 {ts<}at{>ts} AS at, roles, resident_avg, resident_peak, memory_avg, memory_peak, \
321 CAST(minutes AS BIGINT) AS minutes, CAST(cpu_minutes AS BIGINT) AS cpu_minutes, \
322 CAST(container_minutes AS BIGINT) AS container_minutes, \
323 CAST(covered AS BIGINT) AS covered, cpu_seconds, cpu_avg, cpu_peak, container_avg, \
324 container_peak, container_limit, parts{text} AS parts FROM samples \
325 WHERE step_s = $1 AND at >= $2{ts} AND at < $3{ts} \
326 AND ($4{text} IS NULL OR process_id = $4{text}) ORDER BY process_id, at";
327 let rows: Vec<Row> = on_pool!(self, |pool, backend| {
328 sqlx::query_as(sql(backend, SAMPLES))
329 .bind(i64::from(step_s))
330 .bind(db_time(from))
331 .bind(db_time(to))
332 .bind(process)
333 .fetch_all(pool)
334 .await?
335 });
336 rows.into_iter().map(sample).collect()
337 }
338
339 pub async fn sample_buckets(
348 &self,
349 (from, cut, to): (Timestamp, Timestamp, Timestamp),
350 bucket_s: u32,
351 process: Option<&str>,
352 ) -> Result<Vec<Bucket>, DbError> {
353 type BucketRow = (
354 String,
355 i64,
356 i64,
357 i64,
358 i64,
359 i64,
360 i64,
361 Option<f64>,
362 Option<f64>,
363 Option<i64>,
364 Option<i64>,
365 Option<i64>,
366 Option<i64>,
367 Option<i64>,
368 Option<i64>,
369 i64,
370 );
371 let rows: Vec<BucketRow> = on_pool!(self, |pool, backend| {
372 sqlx::query_as(sql_text(backend, &bucket_query(backend)))
373 .bind(db_time(from))
374 .bind(db_time(within(from, cut, to)))
375 .bind(db_time(to))
376 .bind(i64::from(bucket_s.max(1)))
377 .bind(process)
378 .fetch_all(pool)
379 .await?
380 });
381 rows.into_iter()
382 .map(|row| {
383 Ok(Bucket {
384 process_id: row.0,
385 at: from_epoch(row.1)?,
386 minutes: u32::try_from(row.2).unwrap_or(0),
387 resident_avg: unsigned(row.3),
388 resident_peak: unsigned(row.4),
389 memory_avg: unsigned(row.5),
390 memory_peak: unsigned(row.6),
391 cpu_avg: row.7,
392 cpu_peak: row.8,
393 container_avg: row.9.map(unsigned),
394 container_peak: row.10.map(unsigned),
395 container_limit: row.11.map(unsigned),
396 parts: row
397 .12
398 .zip(row.13)
399 .zip(row.14)
400 .map(|((forks, hosts), tasks)| {
401 (unsigned(forks), unsigned(hosts), unsigned(tasks))
402 }),
403 covered: u32::try_from(row.15).unwrap_or(0),
404 })
405 })
406 .collect()
407 }
408
409 pub async fn latest_of(
416 &self,
417 from: Timestamp,
418 to: Timestamp,
419 process: Option<&str>,
420 ) -> Result<BTreeMap<String, Latest>, DbError> {
421 const LATEST: &str = "SELECT s.process_id, s.roles, s.container_limit, \
425 CAST(s.step_s AS BIGINT), {ts<}s.at{>ts} FROM \
426 (SELECT process_id, MAX(at) AS last FROM samples \
427 WHERE step_s IN (60, 900) AND at >= $1{ts} AND at < $2{ts} \
428 AND ($3{text} IS NULL OR process_id = $3{text}) GROUP BY process_id) l \
429 CROSS JOIN samples s \
430 WHERE s.process_id = l.process_id AND s.step_s IN (60, 900) AND s.at = l.last";
431 let rows: Vec<(String, String, Option<i64>, i64, String)> =
432 on_pool!(self, |pool, backend| {
433 sqlx::query_as(sql(backend, LATEST))
434 .bind(db_time(from))
435 .bind(db_time(to))
436 .bind(process)
437 .fetch_all(pool)
438 .await?
439 });
440 let mut latest = BTreeMap::new();
441 for (process_id, roles, limit, step, at) in rows {
443 if step == i64::from(ROLLUP) && latest.contains_key(&process_id) {
444 continue;
445 }
446 latest.insert(
447 process_id,
448 Latest {
449 at: parse_time("samples.at", &at)?,
450 roles: from_json("samples.roles", &roles)?,
451 container_limit: limit.map(unsigned),
452 },
453 );
454 }
455 Ok(latest)
456 }
457
458 pub async fn rolled_up_to(&self) -> Result<Option<Timestamp>, DbError> {
464 const NEWEST: &str = "SELECT {ts<}MAX(at){>ts} FROM samples WHERE step_s = $1";
465 let newest: Option<String> = on_pool!(self, |pool, backend| {
466 sqlx::query_scalar(sql(backend, NEWEST))
467 .bind(i64::from(ROLLUP))
468 .fetch_one(pool)
469 .await?
470 });
471 newest
472 .map(|at| {
473 let at = parse_time("samples.at", &at)?;
474 Ok(at
475 .checked_add(jiff::SignedDuration::from_secs(i64::from(ROLLUP)))
476 .unwrap_or(at))
477 })
478 .transpose()
479 }
480
481 pub async fn memory_totals(
491 &self,
492 (from, cut, to): (Timestamp, Timestamp, Timestamp),
493 bucket_s: u32,
494 ) -> Result<Vec<(Timestamp, u64)>, DbError> {
495 let rows: Vec<(i64, i64)> = on_pool!(self, |pool, backend| {
496 sqlx::query_as(sql_text(backend, &totals_query(backend)))
497 .bind(db_time(from))
498 .bind(db_time(within(from, cut, to)))
499 .bind(db_time(to))
500 .bind(i64::from(bucket_s.max(1)))
501 .fetch_all(pool)
502 .await?
503 });
504 rows.into_iter()
505 .map(|(at, total)| Ok((from_epoch(at)?, unsigned(total))))
506 .collect()
507 }
508}
509
510#[derive(Debug, Clone, PartialEq)]
512pub struct Bucket {
513 pub process_id: String,
515 pub at: Timestamp,
517 pub minutes: u32,
519 pub resident_avg: u64,
521 pub resident_peak: u64,
523 pub memory_avg: u64,
525 pub memory_peak: u64,
527 pub cpu_avg: Option<f64>,
529 pub cpu_peak: Option<f64>,
531 pub container_avg: Option<u64>,
533 pub container_peak: Option<u64>,
535 pub container_limit: Option<u64>,
537 pub parts: Option<(u64, u64, u64)>,
540 pub covered: u32,
543}
544
545fn insert_query(rows: usize) -> String {
547 let mut query = String::from(
548 "INSERT INTO samples (process_id, step_s, at, roles, resident_avg, resident_peak, \
549 memory_avg, memory_peak, minutes, cpu_minutes, container_minutes, covered, cpu_seconds, \
550 cpu_avg, cpu_peak, container_avg, container_peak, container_limit, parts, forks_avg, \
551 hosts_avg, tasks_avg) VALUES ",
552 );
553 for row in 0..rows {
554 let n = row * 22;
555 if row > 0 {
556 query.push_str(", ");
557 }
558 let cell = |k: usize| match k {
560 3 => format!("${}{{ts}}", n + k),
561 19 => format!("${}{{json}}", n + k),
562 _ => format!("${}", n + k),
563 };
564 query.push('(');
565 query.push_str(&(1..=22).map(cell).collect::<Vec<_>>().join(", "));
566 query.push(')');
567 }
568 query.push_str(" ON CONFLICT (process_id, step_s, at) DO NOTHING");
569 query
570}
571
572#[derive(Debug, Clone, PartialEq, Eq)]
574pub struct Latest {
575 pub at: Timestamp,
577 pub roles: BTreeMap<String, String>,
579 pub container_limit: Option<u64>,
581}
582
583fn from_epoch(seconds: i64) -> Result<Timestamp, DbError> {
585 Timestamp::from_second(seconds).map_err(|e| DbError::InvalidData {
586 what: "samples.at",
587 reason: e.to_string(),
588 })
589}
590
591const fn epoch(backend: Backend) -> &'static str {
593 match backend {
594 Backend::Sqlite => "CAST(strftime('%s', at) AS INTEGER)",
595 Backend::Postgres => "CAST(EXTRACT(EPOCH FROM at) AS BIGINT)",
596 }
597}
598
599const RANGE: &str = "((step_s = 900 AND at >= $1{ts} AND at < $2{ts}) \
603 OR (step_s = 60 AND at >= $2{ts} AND at < $3{ts}))";
604
605fn within(from: Timestamp, cut: Timestamp, to: Timestamp) -> Timestamp {
607 cut.max(from).min(to.max(from))
608}
609
610fn round(backend: Backend, expr: &str) -> String {
613 match backend {
614 Backend::Sqlite => format!("ROUND({expr})"),
615 Backend::Postgres => format!("ROUND(CAST({expr} AS NUMERIC))"),
616 }
617}
618
619fn weighted(x: &str, weight: &str) -> String {
621 format!("SUM(CAST({x} AS DOUBLE PRECISION) * {weight})")
622}
623
624fn bucket_query(backend: Backend) -> String {
626 let avg = |x: &str, weight: &str| {
628 format!(
629 "CAST({} AS BIGINT)",
630 round(
631 backend,
632 &format!("{} / NULLIF(SUM({weight}), 0)", weighted(x, weight))
633 )
634 )
635 };
636 let part = |x: &str| {
638 format!(
639 "CASE WHEN COUNT({x}) = 0 THEN NULL ELSE CAST({} AS BIGINT) END",
640 round(
641 backend,
642 &format!(
643 "{} / SUM(minutes)",
644 weighted(&format!("COALESCE({x}, 0)"), "minutes")
645 )
646 )
647 )
648 };
649 format!(
653 "SELECT p.*, CAST(c.sampled AS BIGINT) FROM \
654 (SELECT process_id, ({e} / $4) * $4 AS bucket, CAST(SUM(minutes) AS BIGINT) AS m, \
655 {res} AS r, MAX(resident_peak) AS rp, {mem} AS mm, MAX(memory_peak) AS mp, \
656 {cpu} / NULLIF(SUM(cpu_minutes), 0) AS ca, MAX(cpu_peak) AS cp, {cont} AS ka, \
657 MAX(container_peak) AS kp, MAX(container_limit) AS kl, {forks} AS fa, {hosts} AS ha, \
658 {tasks} AS ta FROM samples WHERE {RANGE} \
659 AND ($5{{text}} IS NULL OR process_id = $5{{text}}) GROUP BY process_id, bucket) p \
660 JOIN ({c}) c ON c.bucket = p.bucket ORDER BY p.process_id, p.bucket",
661 c = coverage_rows(backend),
662 e = epoch(backend),
663 res = avg("resident_avg", "minutes"),
664 mem = avg("memory_avg", "minutes"),
665 cpu = weighted("cpu_avg", "cpu_minutes"),
666 cont = avg("container_avg", "container_minutes"),
667 forks = part("forks_avg"),
668 hosts = part("hosts_avg"),
669 tasks = part("tasks_avg"),
670 )
671}
672
673fn coverage_rows(backend: Backend) -> String {
675 format!(
676 "SELECT bucket, SUM(covered) AS sampled FROM \
677 (SELECT ({e} / $4) * $4 AS bucket, at, MAX(covered) AS covered FROM samples \
678 WHERE {RANGE} GROUP BY bucket, at) w GROUP BY bucket",
679 e = epoch(backend),
680 )
681}
682
683fn totals_query(backend: Backend) -> String {
685 format!(
686 "SELECT m.bucket, CAST({r} AS BIGINT) FROM \
687 (SELECT ({e} / $4) * $4 AS bucket, {w} AS weighted FROM samples WHERE {RANGE} \
688 GROUP BY bucket) m JOIN ({c}) c ON c.bucket = m.bucket ORDER BY m.bucket",
689 e = epoch(backend),
690 w = weighted("memory_avg", "minutes"),
691 c = coverage_rows(backend),
692 r = round(backend, "m.weighted / NULLIF(c.sampled, 0)"),
693 )
694}