forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

reaper.rs175 lines, 6.6 KiBHistoryRawDownload
1//! Background upkeep for CI. Every 30 seconds it marks running jobs whose runner stopped
2//! heartbeating as Error and syncs the statuses of their runs. Once a day it deletes job logs and
3//! artifacts past their retention, from `[ci]` in the config.
4
5use std::collections::HashSet;
6use std::path::PathBuf;
7use std::time::Duration;
8
9use forge_core::time::stamp_ago;
10use tokio::time::{Instant, MissedTickBehavior};
11
12use super::{artifact_key, log_path, sync_run_statuses};
13use crate::state::AppState;
14
15/// How often lost jobs are reaped.
16const REAP_EVERY: Duration = Duration::from_secs(30);
17/// A running job with no heartbeat for this long is lost.
18const LOST_AFTER: Duration = Duration::from_secs(120);
19/// How often the alert checks that look at the disk and the backup history run. They share this
20/// loop rather than adding their own.
21const ALERTS_SLOW_EVERY: Duration = Duration::from_secs(5 * 60);
22/// How often retention runs.
23const PURGE_EVERY: Duration = Duration::from_secs(24 * 60 * 60);
24/// How often the health page is woken. Its disk, uptime and mail figures change with the clock and
25/// the disk, not with a write; its fingerprint drops a wake that changed nothing.
26const HEALTH_EVERY: Duration = Duration::from_secs(60);
27
28/// Starts the reaper task. It runs until the process exits.
29pub fn spawn(state: AppState) {
30 tokio::spawn(run(state));
31}
32
33async fn run(state: AppState) {
34 let mut tick = tokio::time::interval(REAP_EVERY);
35 tick.set_missed_tick_behavior(MissedTickBehavior::Delay);
36 // Retention runs on the first pass after boot, then once a day.
37 let mut next_purge = Instant::now();
38 let mut next_slow_alerts = Instant::now() + ALERTS_SLOW_EVERY;
39 let mut next_health = Instant::now() + HEALTH_EVERY;
40 // After a restart or a self-update, every running job's last heartbeat is as old as the
41 // downtime. Its runner kept working and beats again within seconds, so nothing is reaped
42 // until a full LOST_AFTER has passed since boot.
43 let booted = Instant::now();
44 loop {
45 tick.tick().await;
46 if booted.elapsed() >= LOST_AFTER {
47 reap_once(&state).await;
48 }
49 crate::alerts::check_runners(&state).await;
50 if Instant::now() >= next_health {
51 crate::live::admin().bump(&crate::live::Topic::AdminHealth);
52 next_health = Instant::now() + HEALTH_EVERY;
53 }
54 if Instant::now() >= next_slow_alerts {
55 crate::alerts::check_slow(&state).await;
56 next_slow_alerts = Instant::now() + ALERTS_SLOW_EVERY;
57 }
58 if Instant::now() >= next_purge {
59 purge_once(&state).await;
60 next_purge = Instant::now() + PURGE_EVERY;
61 }
62 }
63}
64
65/// Marks lost jobs as Error and syncs the statuses of every run they belong to. Returns how many
66/// jobs were reaped.
67pub async fn reap_once(state: &AppState) -> usize {
68 reap_before(state, &stamp_ago(LOST_AFTER)).await
69}
70
71/// [`reap_once`] with an explicit cutoff: running jobs whose heartbeat is older than `older_than`
72/// are lost.
73pub async fn reap_before(state: &AppState, older_than: &str) -> usize {
74 let jobs = match state.store.reap_lost_jobs(older_than).await {
75 Ok(jobs) => jobs,
76 Err(e) => {
77 tracing::error!(error = %e, "ci: reaping lost jobs failed");
78 return 0;
79 }
80 };
81 let mut seen = HashSet::new();
82 let mut wake = false;
83 for job in &jobs {
84 state.ci_live.close_job(&job.id);
85 state.ci_live.bump_run(&job.run_id);
86 if !seen.insert(job.run_id.clone()) {
87 continue;
88 }
89 match state.store.run_by_id(&job.run_id).await {
90 Ok(Some(run)) => {
91 state.ci_live.bump_repo(&run.repo_id);
92 match sync_run_statuses(state, &run).await {
93 Ok(queued) => wake |= queued,
94 Err(e) => {
95 tracing::error!(error = %e, run_id = %run.id, "ci: syncing statuses failed")
96 }
97 }
98 }
99 Ok(None) => {}
100 Err(e) => tracing::error!(error = %e, run_id = %job.run_id, "ci: loading run failed"),
101 }
102 }
103 if wake {
104 state.ci_waker.notify_waiters();
105 }
106 if !jobs.is_empty() {
107 state.ci_live.bump_runners();
108 tracing::warn!(count = jobs.len(), "ci: reaped lost jobs");
109 }
110 jobs.len()
111}
112
113/// Deletes the logs and artifacts past retention. Rows go first (in the store); files follow.
114/// Missing files are fine. Returns `(logs deleted, artifacts deleted)` as attempted.
115pub async fn purge_once(state: &AppState) -> (usize, usize) {
116 let live = state.live();
117 let ci = &live.ci;
118 let day = |days: u64| Duration::from_secs(days.saturating_mul(24 * 60 * 60));
119 let logs_before = stamp_ago(day(ci.log_retention_days));
120 let artifacts_before = stamp_ago(day(ci.artifact_retention_days));
121 let max_total_bytes = ci.artifact_max_total_mb.saturating_mul(1024 * 1024);
122 let (job_ids, artifact_ids, run_ids) = match state
123 .store
124 .purge_old(
125 &logs_before,
126 &artifacts_before,
127 ci.artifact_keep_runs,
128 max_total_bytes,
129 )
130 .await
131 {
132 Ok(ids) => ids,
133 Err(e) => {
134 tracing::error!(error = %e, "ci: retention purge failed");
135 return (0, 0);
136 }
137 };
138 let logs: Vec<PathBuf> = job_ids
139 .iter()
140 .map(|id| log_path(&state.config.data_dir, id))
141 .collect();
142 let log_count = logs.len();
143 let removed = tokio::task::spawn_blocking(move || {
144 for path in &logs {
145 if let Err(e) = std::fs::remove_file(path)
146 && e.kind() != std::io::ErrorKind::NotFound
147 {
148 tracing::error!(error = %e, path = %path.display(), "ci: deleting a log failed");
149 }
150 }
151 })
152 .await;
153 if let Err(e) = removed {
154 tracing::error!(error = %e, "ci: log deletion task failed");
155 }
156 let artifact_count = artifact_ids.len();
157 for id in &artifact_ids {
158 if let Err(e) = state.blobs.delete(&artifact_key(id)).await {
159 tracing::error!(error = %e, artifact_id = %id, "ci: deleting an artifact failed");
160 }
161 }
162 // The rows are gone and the files too: the pages that list or show the logs and artifacts
163 // re-read them now.
164 for id in &job_ids {
165 state.ci_live.bump_job(id);
166 }
167 for id in &run_ids {
168 state.ci_live.bump_run(id);
169 // The run page follows its repo's stream.
170 if let Ok(Some(run)) = state.store.run_by_id(id).await {
171 state.ci_live.bump_repo(&run.repo_id);
172 }
173 }
174 (log_count, artifact_count)
175}