| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | |
|
| 6 | |
|
| 7 | |
|
| 8 | |
|
| 9 | |
|
| 10 | |
|
| 11 | | use crate::{db, Shared}; |
| 12 | | use axum::extract::State; |
| 13 | | use axum::http::{header, HeaderMap, StatusCode}; |
| 14 | | use axum::response::{IntoResponse, Response}; |
| 15 | | use std::collections::HashMap; |
| 16 | | use std::fmt::Write; |
| 17 | | use std::sync::atomic::{AtomicU64, Ordering}; |
| 18 | | use std::sync::Mutex; |
| 19 | |
|
| 20 | |
|
| 21 | | pub static MAIL_SENT: AtomicU64 = AtomicU64::new(0); |
| 22 | | pub static MAIL_FAILED: AtomicU64 = AtomicU64::new(0); |
| 23 | |
|
| 24 | |
|
| 25 | | const BUCKETS: [f64; 12] = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0]; |
| 26 | |
|
| 27 | | const MAX_ROUTES: usize = 300; |
| 28 | |
|
| 29 | | #[derive(Default)] |
| 30 | | struct Hist { |
| 31 | | |
| 32 | | by_status: [u64; 4], |
| 33 | | buckets: [u64; BUCKETS.len()], |
| 34 | | sum: f64, |
| 35 | | count: u64, |
| 36 | | } |
| 37 | |
|
| 38 | | static HTTP: Mutex<Option<HashMap<(String, String), Hist>>> = Mutex::new(None); |
| 39 | |
|
| 40 | |
|
| 41 | |
|
| 42 | | static PROTOCOL: Mutex<std::collections::BTreeMap<&'static str, (u64, u64)>> = Mutex::new(std::collections::BTreeMap::new()); |
| 43 | |
|
| 44 | |
|
| 45 | 1120× | pub fn protocol_bytes(endpoint: &'static str, received: u64, sent: u64) { |
| 46 | 1120× | let mut g = PROTOCOL.lock().unwrap_or_else(|p| p.into_inner()); |
| 47 | 1120× | let e = g.entry(endpoint).or_default(); |
| 48 | 1120× | e.0 += received; |
| 49 | 1120× | e.1 += sent; |
| 50 | 1120× | } |
| 51 | |
|
| 52 | |
|
| 53 | |
|
| 54 | 3932× | pub fn route_class(path: &str) -> String { |
| 55 | 16516× | let segs: Vec<&str> = path.trim_start_matches('/').split('/').filter(|s| !s.is_empty()).collect(); |
| 56 | 21133× | let tab = |s: &str| s.chars().all(|c| c.is_ascii_lowercase() || c == '-' || c == '.') && s.len() <= 24; |
| 57 | 3932× | match segs.as_slice() { |
| 58 | 3932× | [] => "page:home".into(), |
| 59 | 3920× | ["static", ..] => "static".into(), |
| 60 | 3154× | ["api", "v1", area, ..] if tab(area) => format!("api:{area}"), |
| 61 | 2886× | ["api", ..] => "api".into(), |
| 62 | 2886× | ["log", ..] => "tlog".into(), |
| 63 | 2869× | [".well-known", ..] => "well-known".into(), |
| 64 | 2834× | ["live", ..] => "live".into(), |
| 65 | 2827× | ["avatar", ..] => "avatar".into(), |
| 66 | 1302× | [_, _, "oxy", "v1", endpoint, ..] if tab(endpoint) => format!("protocol:{endpoint}"), |
| 67 | 1012× | [_, _, "oxy", ..] => "protocol".into(), |
| 68 | 1012× | [_, _, t, ..] if tab(t) => format!("page:{t}"), |
| 69 | 705× | [_, _] => "page:repository".into(), |
| 70 | 378× | [one] if tab(one) => format!("page:{one}"), |
| 71 | 172× | _ => "page:other".into(), |
| 72 | | } |
| 73 | 3932× | } |
| 74 | |
|
| 75 | |
|
| 76 | 3923× | pub fn observe(method: &str, path: &str, status: u16, seconds: f64) { |
| 77 | 3923× | let mut g = HTTP.lock().unwrap_or_else(|p| p.into_inner()); |
| 78 | 3923× | let map = g.get_or_insert_with(HashMap::new); |
| 79 | 3923× | let mut route = route_class(path); |
| 80 | 3923× | if !map.contains_key(&(route.clone(), method.to_string())) && map.len() >= MAX_ROUTES { |
| 81 | 0× | route = "other".into(); |
| 82 | 3923× | } |
| 83 | 3923× | let h = map.entry((route, method.to_string())).or_default(); |
| 84 | 3923× | let class = (status / 100).clamp(2, 5) as usize - 2; |
| 85 | 3923× | h.by_status[class] += 1; |
| 86 | 47076× | for (i, b) in BUCKETS.iter().enumerate() { |
| 87 | 47076× | if seconds <= *b { |
| 88 | 43232× | h.buckets[i] += 1; |
| 89 | 43232× | } |
| 90 | | } |
| 91 | 3923× | h.sum += seconds; |
| 92 | 3923× | h.count += 1; |
| 93 | 3923× | } |
| 94 | |
|
| 95 | 4× | fn http_families(out: &mut String) { |
| 96 | 4× | let g = HTTP.lock().unwrap_or_else(|p| p.into_inner()); |
| 97 | 4× | let Some(map) = g.as_ref() else { return }; |
| 98 | 3× | let mut keys: Vec<&(String, String)> = map.keys().collect(); |
| 99 | 3× | keys.sort(); |
| 100 | 3× | let _ = writeln!(out, "# HELP oxyhub_http_requests_total HTTP requests by route class, method and status class."); |
| 101 | 3× | let _ = writeln!(out, "# TYPE oxyhub_http_requests_total counter"); |
| 102 | 10× | for k in &keys { |
| 103 | 10× | let h = &map[*k]; |
| 104 | 40× | for (i, n) in h.by_status.iter().enumerate().filter(|(_, n)| **n > 0) { |
| 105 | 10× | let _ = writeln!( |
| 106 | 10× | out, |
| 107 | 10× | "oxyhub_http_requests_total{{route=\"{}\",method=\"{}\",status=\"{}xx\"}} {n}", |
| 108 | 10× | label(&k.0), |
| 109 | 10× | label(&k.1), |
| 110 | 10× | i + 2 |
| 111 | 10× | ); |
| 112 | 10× | } |
| 113 | | } |
| 114 | 3× | let _ = writeln!(out, "# HELP oxyhub_http_request_duration_seconds How long requests took, by route class and method."); |
| 115 | 3× | let _ = writeln!(out, "# TYPE oxyhub_http_request_duration_seconds histogram"); |
| 116 | 10× | for k in &keys { |
| 117 | 10× | let h = &map[*k]; |
| 118 | 10× | let l = format!("route=\"{}\",method=\"{}\"", label(&k.0), label(&k.1)); |
| 119 | 120× | for (i, b) in BUCKETS.iter().enumerate() { |
| 120 | 120× | let _ = writeln!(out, "oxyhub_http_request_duration_seconds_bucket{{{l},le=\"{b}\"}} {}", h.buckets[i]); |
| 121 | 120× | } |
| 122 | 10× | let _ = writeln!(out, "oxyhub_http_request_duration_seconds_bucket{{{l},le=\"+Inf\"}} {}", h.count); |
| 123 | 10× | let _ = writeln!(out, "oxyhub_http_request_duration_seconds_sum{{{l}}} {}", h.sum); |
| 124 | 10× | let _ = writeln!(out, "oxyhub_http_request_duration_seconds_count{{{l}}} {}", h.count); |
| 125 | | } |
| 126 | 4× | } |
| 127 | |
|
| 128 | |
|
| 129 | 96× | fn family(out: &mut String, name: &str, help: &str, kind: &str, samples: &[(String, f64)]) { |
| 130 | 96× | let _ = writeln!(out, "# HELP {name} {help}"); |
| 131 | 96× | let _ = writeln!(out, "# TYPE {name} {kind}"); |
| 132 | 168× | for (labels, v) in samples { |
| 133 | 168× | if labels.is_empty() { |
| 134 | 40× | let _ = writeln!(out, "{name} {v}"); |
| 135 | 128× | } else { |
| 136 | 128× | let _ = writeln!(out, "{name}{{{labels}}} {v}"); |
| 137 | 128× | } |
| 138 | | } |
| 139 | 96× | } |
| 140 | |
|
| 141 | |
|
| 142 | 45× | fn label(v: &str) -> String { |
| 143 | 45× | v.replace('\\', "\\\\").replace('"', "\\\"").replace('\n', "\\n") |
| 144 | 45× | } |
| 145 | |
|
| 146 | |
|
| 147 | 4× | fn resident_bytes() -> Option<f64> { |
| 148 | 4× | let statm = std::fs::read_to_string("/proc/self/statm").ok()?; |
| 149 | 4× | let pages: f64 = statm.split_whitespace().nth(1)?.parse().ok()?; |
| 150 | 4× | Some(pages * 4096.0) |
| 151 | 4× | } |
| 152 | |
|
| 153 | |
|
| 154 | 4× | pub async fn render(app: &Shared) -> String { |
| 155 | 4× | let mut out = String::new(); |
| 156 | 4× | family( |
| 157 | 4× | &mut out, |
| 158 | 4× | "oxyhub_build_info", |
| 159 | 4× | "The hub's version and build.", |
| 160 | 4× | "gauge", |
| 161 | 4× | &[(format!("version=\"{}\",build=\"{}\"", env!("CARGO_PKG_VERSION"), label(env!("OXY_BUILD_ID"))), 1.0)], |
| 162 | | ); |
| 163 | 4× | family( |
| 164 | 4× | &mut out, |
| 165 | 4× | "oxyhub_uptime_seconds", |
| 166 | 4× | "Seconds since the hub started.", |
| 167 | 4× | "gauge", |
| 168 | 4× | &[(String::new(), app.started.elapsed().as_secs_f64())], |
| 169 | | ); |
| 170 | 4× | if let Some(rss) = resident_bytes() { |
| 171 | 4× | family(&mut out, "oxyhub_resident_memory_bytes", "The process's resident memory.", "gauge", &[(String::new(), rss)]); |
| 172 | 4× | } |
| 173 | 4× | let (states, weight, summaries) = app.repos.cache().stats(); |
| 174 | 4× | family(&mut out, "oxyhub_state_cache_states", "States the state cache holds.", "gauge", &[(String::new(), states as f64)]); |
| 175 | 4× | family( |
| 176 | 4× | &mut out, |
| 177 | 4× | "oxyhub_state_cache_bytes", |
| 178 | 4× | "What the state cache's states are estimated to weigh.", |
| 179 | 4× | "gauge", |
| 180 | 4× | &[(String::new(), weight as f64)], |
| 181 | | ); |
| 182 | 4× | family( |
| 183 | 4× | &mut out, |
| 184 | 4× | "oxyhub_state_cache_budget_bytes", |
| 185 | 4× | "What the state cache may hold.", |
| 186 | 4× | "gauge", |
| 187 | 4× | &[(String::new(), crate::repos::cache::budget() as f64)], |
| 188 | | ); |
| 189 | 4× | family(&mut out, "oxyhub_state_cache_summaries", "Summaries the state cache holds.", "gauge", &[(String::new(), summaries as f64)]); |
| 190 | 4× | let strata = oxy_strata::stats(); |
| 191 | 4× | family( |
| 192 | 4× | &mut out, |
| 193 | 4× | "oxyhub_bucket_clients_opened_total", |
| 194 | 4× | "Bucket store clients opened.", |
| 195 | 4× | "counter", |
| 196 | 4× | &[(String::new(), strata.opens as f64)], |
| 197 | | ); |
| 198 | 4× | family( |
| 199 | 4× | &mut out, |
| 200 | 4× | "oxyhub_bucket_requests_total", |
| 201 | 4× | "Requests to bucket stores, by kind.", |
| 202 | 4× | "counter", |
| 203 | 48× | &strata.ops().map(|(k, n)| (format!("kind=\"{k}\""), n as f64)).collect::<Vec<_>>(), |
| 204 | | ); |
| 205 | 4× | family( |
| 206 | 4× | &mut out, |
| 207 | 4× | "oxyhub_bucket_request_seconds_total", |
| 208 | 4× | "Time spent in requests to bucket stores.", |
| 209 | 4× | "counter", |
| 210 | 4× | &[(String::new(), strata.millis as f64 / 1000.0)], |
| 211 | | ); |
| 212 | 4× | let jobs: Vec<(String, i64)> = |
| 213 | 4× | sqlx::query_as("SELECT status, COUNT(*) FROM flow_jobs WHERE status IN ('queued', 'running') GROUP BY status") |
| 214 | 4× | .fetch_all(&app.db) |
| 215 | 4× | .await |
| 216 | 4× | .unwrap_or_default(); |
| 217 | 8× | let count = |s: &str| jobs.iter().find(|(k, _)| k == s).map(|(_, n)| *n).unwrap_or(0) as f64; |
| 218 | 4× | let waiting: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM flow_jobs WHERE status = 'queued' AND approval = 'waiting'") |
| 219 | 4× | .fetch_one(&app.db) |
| 220 | 4× | .await |
| 221 | 4× | .unwrap_or(0); |
| 222 | 4× | family( |
| 223 | 4× | &mut out, |
| 224 | 4× | "oxyhub_flow_jobs", |
| 225 | 4× | "OxygenFlow jobs now, by state (waiting: for a person's approval).", |
| 226 | 4× | "gauge", |
| 227 | 4× | &[ |
| 228 | 4× | ("state=\"queued\"".into(), count("queued") - waiting as f64), |
| 229 | 4× | ("state=\"waiting\"".into(), waiting as f64), |
| 230 | 4× | ("state=\"running\"".into(), count("running")), |
| 231 | 4× | ], |
| 232 | | ); |
| 233 | 4× | let runners = db::runners::list(&app.db).await.unwrap_or_default(); |
| 234 | 4× | family( |
| 235 | 4× | &mut out, |
| 236 | 4× | "oxyhub_flow_runners", |
| 237 | 4× | "Registered OxygenFlow runners, by whether they reported in the last minutes.", |
| 238 | 4× | "gauge", |
| 239 | | &[ |
| 240 | 4× | ("online=\"true\"".into(), runners.iter().filter(|r| r.online()).count() as f64), |
| 241 | 4× | ("online=\"false\"".into(), runners.iter().filter(|r| !r.online()).count() as f64), |
| 242 | | ], |
| 243 | | ); |
| 244 | 4× | let now = db::now_ms(); |
| 245 | 4× | family( |
| 246 | 4× | &mut out, |
| 247 | 4× | "oxyhub_flow_runner_last_seen_seconds", |
| 248 | 4× | "Seconds since each registered runner last called the hub.", |
| 249 | 4× | "gauge", |
| 250 | 4× | &runners |
| 251 | 4× | .iter() |
| 252 | 4× | .filter_map(|r| r.last_seen_ms.map(|t| (format!("runner=\"{}\"", label(&r.name)), (now - t).max(0) as f64 / 1000.0))) |
| 253 | 4× | .collect::<Vec<_>>(), |
| 254 | | ); |
| 255 | 4× | let since = now - 86_400_000; |
| 256 | 4× | let runs: Vec<(String, i64)> = sqlx::query_as("SELECT status, COUNT(*) FROM flow_runs WHERE finished_ms > $1 GROUP BY status") |
| 257 | 4× | .bind(since) |
| 258 | 4× | .fetch_all(&app.db) |
| 259 | 4× | .await |
| 260 | 4× | .unwrap_or_default(); |
| 261 | 4× | family( |
| 262 | 4× | &mut out, |
| 263 | 4× | "oxyhub_flow_runs_last_day", |
| 264 | 4× | "OxygenFlow runs finished in the last 24 hours, by result.", |
| 265 | 4× | "gauge", |
| 266 | 4× | &["passed", "failed", "error"] |
| 267 | 4× | .iter() |
| 268 | 12× | .map(|r| (format!("result=\"{r}\""), runs.iter().find(|(s, _)| s == r).map(|(_, n)| *n).unwrap_or(0) as f64)) |
| 269 | 4× | .collect::<Vec<_>>(), |
| 270 | | ); |
| 271 | 4× | family(&mut out, "oxyhub_tlog_entries", "Entries in the transparency log.", "gauge", &[(String::new(), app.tlog.size() as f64)]); |
| 272 | 4× | let protocol: Vec<(&'static str, (u64, u64))> = |
| 273 | 6× | PROTOCOL.lock().unwrap_or_else(|p| p.into_inner()).iter().map(|(k, v)| (*k, *v)).collect(); |
| 274 | 4× | family( |
| 275 | 4× | &mut out, |
| 276 | 4× | "oxyhub_protocol_bytes_total", |
| 277 | 4× | "Bytes the Oxygen protocol received and sent since the hub started, by endpoint, before compression: push carries pushes, fetch and objects carry fetches.", |
| 278 | 4× | "counter", |
| 279 | 4× | &protocol |
| 280 | 4× | .iter() |
| 281 | 6× | .flat_map(|(e, (rx, tx))| { |
| 282 | 6× | [(format!("endpoint=\"{e}\",direction=\"received\""), *rx as f64), (format!("endpoint=\"{e}\",direction=\"sent\""), *tx as f64)] |
| 283 | 6× | }) |
| 284 | 4× | .collect::<Vec<_>>(), |
| 285 | | ); |
| 286 | 4× | family( |
| 287 | 4× | &mut out, |
| 288 | 4× | "oxyhub_mail_total", |
| 289 | 4× | "Messages the hub sent and failed to send since it started.", |
| 290 | 4× | "counter", |
| 291 | 4× | &[ |
| 292 | 4× | ("result=\"sent\"".into(), MAIL_SENT.load(Ordering::Relaxed) as f64), |
| 293 | 4× | ("result=\"failed\"".into(), MAIL_FAILED.load(Ordering::Relaxed) as f64), |
| 294 | 4× | ], |
| 295 | | ); |
| 296 | 4× | family( |
| 297 | 4× | &mut out, |
| 298 | 4× | "oxyhub_db_connections", |
| 299 | 4× | "The database pool's connections, by whether they are idle.", |
| 300 | 4× | "gauge", |
| 301 | 4× | &[ |
| 302 | 4× | ("idle=\"true\"".into(), app.db.num_idle() as f64), |
| 303 | 4× | ("idle=\"false\"".into(), (app.db.size() as f64 - app.db.num_idle() as f64).max(0.0)), |
| 304 | 4× | ], |
| 305 | | ); |
| 306 | 4× | let (ok, refused): (Option<i64>, Option<i64>) = |
| 307 | 4× | sqlx::query_as("SELECT SUM(CASE WHEN ok THEN 1 ELSE 0 END), SUM(CASE WHEN ok THEN 0 ELSE 1 END) FROM pushes WHERE at_ms > $1") |
| 308 | 4× | .bind(since) |
| 309 | 4× | .fetch_one(&app.db) |
| 310 | 4× | .await |
| 311 | 4× | .unwrap_or((None, None)); |
| 312 | 4× | family( |
| 313 | 4× | &mut out, |
| 314 | 4× | "oxyhub_pushes_last_day", |
| 315 | 4× | "Reference updates pushed in the last 24 hours, by whether they were accepted.", |
| 316 | 4× | "gauge", |
| 317 | 4× | &[("result=\"accepted\"".into(), ok.unwrap_or(0) as f64), ("result=\"refused\"".into(), refused.unwrap_or(0) as f64)], |
| 318 | | ); |
| 319 | 4× | let backups: Vec<(String, String, i64, Option<i64>)> = sqlx::query_as( |
| 320 | 4× | "SELECT owner, status, started_ms, finished_ms FROM backup_runs WHERE id IN (SELECT MAX(id) FROM backup_runs GROUP BY owner) ORDER BY owner", |
| 321 | 4× | ) |
| 322 | 4× | .fetch_all(&app.db) |
| 323 | 4× | .await |
| 324 | 4× | .unwrap_or_default(); |
| 325 | 4× | family( |
| 326 | 4× | &mut out, |
| 327 | 4× | "oxyhub_backup_last_run_age_seconds", |
| 328 | 4× | "Seconds since each owner's latest backup run started.", |
| 329 | 4× | "gauge", |
| 330 | 4× | &backups.iter().map(|(o, _, s, _)| (format!("owner=\"{}\"", label(o)), (now - s) as f64 / 1000.0)).collect::<Vec<_>>(), |
| 331 | | ); |
| 332 | 4× | family( |
| 333 | 4× | &mut out, |
| 334 | 4× | "oxyhub_backup_last_run_ok", |
| 335 | 4× | "Whether each owner's latest finished backup run succeeded (1), was partial or failed (0); running ones are left out.", |
| 336 | 4× | "gauge", |
| 337 | 4× | &backups |
| 338 | 4× | .iter() |
| 339 | 4× | .filter(|(_, st, _, f)| f.is_some() && st != "running") |
| 340 | 4× | .map(|(o, st, _, _)| (format!("owner=\"{}\"", label(o)), if st == "ok" { 1.0 } else { 0.0 })) |
| 341 | 4× | .collect::<Vec<_>>(), |
| 342 | | ); |
| 343 | 4× | flow_timings(app, &mut out, now).await; |
| 344 | 4× | if let Ok((waiting, dead)) = db::queue::counts(&app.db).await { |
| 345 | 4× | family( |
| 346 | 4× | &mut out, |
| 347 | 4× | "oxyhub_queue_items", |
| 348 | 4× | "Items in the durable work queue (#276): waiting (due, backing off or claimed) and dead (failed every attempt).", |
| 349 | 4× | "gauge", |
| 350 | 4× | &[("state=\"waiting\"".into(), waiting as f64), ("state=\"dead\"".into(), dead as f64)], |
| 351 | 4× | ); |
| 352 | 4× | } |
| 353 | 4× | http_families(&mut out); |
| 354 | 4× | out |
| 355 | 4× | } |
| 356 | |
|
| 357 | |
|
| 358 | |
|
| 359 | | type JobTimes = (String, String, String, Option<i64>, Option<i64>, Option<i64>); |
| 360 | |
|
| 361 | |
|
| 362 | | const JOB_SECONDS: [f64; 11] = [1.0, 5.0, 15.0, 30.0, 60.0, 120.0, 300.0, 600.0, 1200.0, 1800.0, 3600.0]; |
| 363 | |
|
| 364 | |
|
| 365 | |
|
| 366 | |
|
| 367 | 4× | async fn flow_timings(app: &Shared, out: &mut String, now: i64) { |
| 368 | 4× | let rows: Vec<JobTimes> = sqlx::query_as( |
| 369 | 4× | "SELECT runner, status, error, COALESCE(ready_ms, queued_ms), started_ms, finished_ms FROM flow_jobs \ |
| 370 | 4× | WHERE finished_ms >= $1 AND status IN ('passed', 'failed', 'error', 'cancelled')", |
| 371 | 4× | ) |
| 372 | 4× | .bind(now - 86_400_000) |
| 373 | 4× | .fetch_all(&app.db) |
| 374 | 4× | .await |
| 375 | 4× | .unwrap_or_default(); |
| 376 | 4× | let mut queue: std::collections::BTreeMap<String, Vec<f64>> = Default::default(); |
| 377 | 4× | let mut run: std::collections::BTreeMap<String, Vec<f64>> = Default::default(); |
| 378 | 4× | let mut finished: std::collections::BTreeMap<(String, String), f64> = Default::default(); |
| 379 | 4× | let mut reused = 0.0; |
| 380 | 4× | for (runner, status, error, ready, started, finished_ms) in &rows { |
| 381 | 0× | if error.starts_with("reused from run #") { |
| 382 | 0× | reused += 1.0; |
| 383 | 0× | continue; |
| 384 | 0× | } |
| 385 | 0× | let r = if runner.is_empty() { "none".to_string() } else { runner.clone() }; |
| 386 | 0× | *finished.entry((r.clone(), status.clone())).or_default() += 1.0; |
| 387 | 0× | if let (Some(ready), Some(started)) = (ready, started) { |
| 388 | 0× | queue.entry(r.clone()).or_default().push((started - ready).max(0) as f64 / 1000.0); |
| 389 | 0× | } |
| 390 | 0× | if let (Some(started), Some(f)) = (started, finished_ms) { |
| 391 | 0× | run.entry(r).or_default().push((f - started).max(0) as f64 / 1000.0); |
| 392 | 0× | } |
| 393 | | } |
| 394 | 4× | histogram( |
| 395 | 4× | out, |
| 396 | 4× | "oxyhub_flow_job_queue_seconds", |
| 397 | 4× | "How long finished jobs of the last day waited from ready to started, by runner.", |
| 398 | 4× | &queue, |
| 399 | | ); |
| 400 | 4× | histogram(out, "oxyhub_flow_job_run_seconds", "How long finished jobs of the last day ran, by runner.", &run); |
| 401 | | |
| 402 | 4× | let phases: Vec<String> = sqlx::query_scalar("SELECT phases FROM flow_jobs WHERE finished_ms >= $1 AND phases != ''") |
| 403 | 4× | .bind(now - 86_400_000) |
| 404 | 4× | .fetch_all(&app.db) |
| 405 | 4× | .await |
| 406 | 4× | .unwrap_or_default(); |
| 407 | 4× | let mut by_phase: std::collections::BTreeMap<String, Vec<f64>> = Default::default(); |
| 408 | 4× | for json in &phases { |
| 409 | 0× | let m: std::collections::BTreeMap<String, u64> = serde_json::from_str(json).unwrap_or_default(); |
| 410 | 0× | for (phase, ms) in m { |
| 411 | 0× | by_phase.entry(phase).or_default().push(ms as f64 / 1000.0); |
| 412 | 0× | } |
| 413 | | } |
| 414 | 4× | histogram_by( |
| 415 | 4× | out, |
| 416 | 4× | "oxyhub_flow_job_phase_seconds", |
| 417 | 4× | "Where finished jobs of the last day spent their time, by phase: image (fetching it), prepare, run, finish.", |
| 418 | 4× | "phase", |
| 419 | 4× | &by_phase, |
| 420 | | ); |
| 421 | 4× | family( |
| 422 | 4× | out, |
| 423 | 4× | "oxyhub_flow_jobs_finished_last_day", |
| 424 | 4× | "Jobs that finished in the last day, by runner and result (none: never placed).", |
| 425 | 4× | "gauge", |
| 426 | 4× | &finished.iter().map(|((r, st), n)| (format!("runner=\"{}\",status=\"{}\"", label(r), label(st)), *n)).collect::<Vec<_>>(), |
| 427 | | ); |
| 428 | 4× | family( |
| 429 | 4× | out, |
| 430 | 4× | "oxyhub_flow_jobs_reused_last_day", |
| 431 | 4× | "Jobs of the last day that reused a pass on the same state instead of running (#265).", |
| 432 | 4× | "gauge", |
| 433 | 4× | &[(String::new(), reused)], |
| 434 | | ); |
| 435 | 4× | } |
| 436 | |
|
| 437 | |
|
| 438 | 9× | fn histogram(out: &mut String, name: &str, help: &str, by_runner: &std::collections::BTreeMap<String, Vec<f64>>) { |
| 439 | 9× | histogram_by(out, name, help, "runner", by_runner) |
| 440 | 9× | } |
| 441 | |
|
| 442 | |
|
| 443 | 13× | fn histogram_by(out: &mut String, name: &str, help: &str, key: &str, by: &std::collections::BTreeMap<String, Vec<f64>>) { |
| 444 | 13× | let _ = writeln!(out, "# HELP {name} {help}"); |
| 445 | 13× | let _ = writeln!(out, "# TYPE {name} histogram"); |
| 446 | 13× | for (runner, samples) in by { |
| 447 | 1× | let l = format!("{key}=\"{}\"", label(runner)); |
| 448 | 11× | for b in JOB_SECONDS { |
| 449 | 33× | let n = samples.iter().filter(|s| **s <= b).count(); |
| 450 | 11× | let _ = writeln!(out, "{name}_bucket{{{l},le=\"{b}\"}} {n}"); |
| 451 | | } |
| 452 | 1× | let _ = writeln!(out, "{name}_bucket{{{l},le=\"+Inf\"}} {}", samples.len()); |
| 453 | 1× | let _ = writeln!(out, "{name}_sum{{{l}}} {}", samples.iter().sum::<f64>()); |
| 454 | 1× | let _ = writeln!(out, "{name}_count{{{l}}} {}", samples.len()); |
| 455 | | } |
| 456 | 13× | } |
| 457 | |
|
| 458 | |
|
| 459 | 2× | pub async fn metrics(State(app): State<Shared>, headers: HeaderMap) -> Response { |
| 460 | 2× | let want = &app.config.server.metrics_token; |
| 461 | 2× | if want.is_empty() { |
| 462 | 1× | return (StatusCode::NOT_FOUND, "metrics are off: set [server] metrics_token in hub.toml\n").into_response(); |
| 463 | 1× | } |
| 464 | 1× | let given = oxy_server::bearer_token(&headers).unwrap_or(""); |
| 465 | 1× | if !crate::auth::mac_equal(given, want) { |
| 466 | 0× | return (StatusCode::UNAUTHORIZED, [(header::WWW_AUTHENTICATE, "Bearer")], "a bearer token is needed\n").into_response(); |
| 467 | 1× | } |
| 468 | 1× | ([(header::CONTENT_TYPE, "text/plain; version=0.0.4; charset=utf-8"), (header::CACHE_CONTROL, "no-store")], render(&app).await) |
| 469 | 1× | .into_response() |
| 470 | 2× | } |
| 471 | |
|
| 472 | | #[cfg(test)] |
| 473 | | mod tests { |
| 474 | |
|
| 475 | | #[test] |
| 476 | 1× | fn job_times_are_cumulative_buckets_per_runner() { |
| 477 | 1× | let mut by: std::collections::BTreeMap<String, Vec<f64>> = Default::default(); |
| 478 | 1× | by.insert("earth-1".into(), vec![0.5, 20.0, 4000.0]); |
| 479 | 1× | let mut out = String::new(); |
| 480 | 1× | super::histogram(&mut out, "x_seconds", "help", &by); |
| 481 | 1× | assert!(out.contains("x_seconds_bucket{runner=\"earth-1\",le=\"1\"} 1"), "{out}"); |
| 482 | 1× | assert!(out.contains("x_seconds_bucket{runner=\"earth-1\",le=\"30\"} 2"), "{out}"); |
| 483 | 1× | assert!(out.contains("x_seconds_bucket{runner=\"earth-1\",le=\"3600\"} 2"), "{out}"); |
| 484 | 1× | assert!( |
| 485 | 1× | out.contains("x_seconds_bucket{runner=\"earth-1\",le=\"+Inf\"} 3") && out.contains("x_seconds_count{runner=\"earth-1\"} 3"), |
| 486 | | "{out}" |
| 487 | | ); |
| 488 | 1× | } |
| 489 | |
|
| 490 | | #[test] |
| 491 | 1× | fn route_classes_hold_no_names() { |
| 492 | 9× | for (path, class) in [ |
| 493 | 1× | ("/", "page:home"), |
| 494 | 1× | ("/static/hub.js", "static"), |
| 495 | 1× | ("/api/v1/repos/andy/demo/issues", "api:repos"), |
| 496 | 1× | ("/andy/demo/oxy/v1/negotiate", "protocol:negotiate"), |
| 497 | 1× | ("/andy/demo/issue/3", "page:issue"), |
| 498 | 1× | ("/andy/demo", "page:repository"), |
| 499 | 1× | ("/explore", "page:explore"), |
| 500 | 1× | ("/Andy_McCall", "page:other"), |
| 501 | 1× | ("/log/tile/0/000", "tlog"), |
| 502 | 1× | ] { |
| 503 | 9× | assert_eq!(super::route_class(path), class, "{path}"); |
| 504 | | } |
| 505 | 1× | } |
| 506 | | } |