forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

runner_log.rs237 lines, 8.3 KiBHistoryRawDownload
1//! The runner's own log, kept in memory so an admin can read it on the runner's page. A runner
2//! ships its lines in batches (`POST /api/v1/ci/runners/log`) and the forge keeps the newest
3//! `MAX_LINES` per runner. Lines are not stored in the database: a restart of the forge drops them,
4//! and the runner resends what it still holds on its next batch.
5//!
6//! The forge also writes its own lines (`from_forge`): why a claim got no job, and which job it
7//! took. A reason that repeats is written once, see `note`.
8
9use std::collections::{HashMap, VecDeque};
10use std::sync::{Mutex, MutexGuard};
11
12use forge_ci::proto::RunnerLogBatch;
13
14/// Most lines kept per runner. The oldest go first.
15const MAX_LINES: usize = 2000;
16/// Most lines taken from one batch. The rest are left for the runner to resend.
17const MAX_BATCH_LINES: usize = 1000;
18/// Longest text kept per line, in bytes. Longer text is cut on a character boundary.
19const MAX_TEXT_BYTES: usize = 4096;
20/// Longest boot id kept, in bytes.
21const MAX_BOOT_ID_BYTES: usize = 64;
22/// The levels a runner may send. Any other level is stored as `info`.
23const LEVELS: [&str; 5] = ["error", "warn", "info", "debug", "trace"];
24
25/// One line of a runner's log, as the admin page shows it.
26#[derive(Clone, Debug, PartialEq, Eq)]
27pub struct Line {
28 /// Unix time in milliseconds.
29 pub at_ms: i64,
30 pub level: String,
31 pub text: String,
32 /// True for a line the forge wrote, false for a line the runner sent.
33 pub from_forge: bool,
34}
35
36/// What the forge holds for one runner.
37#[derive(Debug, Default)]
38struct PerRunner {
39 /// The boot id of the runner process the lines come from. Empty before the first batch.
40 boot_id: String,
41 /// The number of the next line the forge wants from the runner for `boot_id`.
42 next_seq: u64,
43 lines: VecDeque<Line>,
44 /// The last forge note written, so a reason that repeats is not written again.
45 last_note: Option<String>,
46}
47
48/// The lines of every runner, by runner id. Shared through `AppState`.
49#[derive(Debug, Default)]
50pub struct RunnerLogs {
51 runners: Mutex<HashMap<String, PerRunner>>,
52}
53
54impl RunnerLogs {
55 /// Takes a batch from a runner and returns the next line number the forge wants. A new boot id
56 /// starts a fresh numbering, and the lines already in `lines` are kept. Lines before the
57 /// wanted number are skipped, so a resent batch adds only what is new.
58 pub fn ingest(&self, runner_id: &str, batch: &RunnerLogBatch) -> u64 {
59 if batch.boot_id.is_empty() || batch.boot_id.len() > MAX_BOOT_ID_BYTES {
60 return self.next_seq(runner_id);
61 }
62 let mut runners = self.lock();
63 let entry = runners.entry(runner_id.to_owned()).or_default();
64 if entry.boot_id != batch.boot_id {
65 entry.boot_id = batch.boot_id.clone();
66 entry.next_seq = 0;
67 let short: String = batch.boot_id.chars().take(8).collect();
68 push(entry, forge_line(format!("runner started (boot {short})")));
69 }
70 if batch.first_seq > entry.next_seq {
71 let missing = batch.first_seq - entry.next_seq;
72 push(entry, forge_line(format!("{missing} lines missing")));
73 }
74 for (i, line) in batch.lines.iter().take(MAX_BATCH_LINES).enumerate() {
75 let seq = batch.first_seq + i as u64;
76 if seq < entry.next_seq {
77 continue;
78 }
79 push(
80 entry,
81 Line {
82 at_ms: line.at_ms,
83 level: level_of(&line.level),
84 text: cut(&line.text, MAX_TEXT_BYTES),
85 from_forge: false,
86 },
87 );
88 }
89 let taken = batch.lines.len().min(MAX_BATCH_LINES) as u64;
90 entry.next_seq = entry.next_seq.max(batch.first_seq + taken);
91 entry.next_seq
92 }
93
94 /// Writes a forge line saying why the runner got no job. Writes nothing when `text` is the
95 /// last note for this runner. Returns true when a line was written.
96 pub fn note(&self, runner_id: &str, text: &str) -> bool {
97 let mut runners = self.lock();
98 let entry = runners.entry(runner_id.to_owned()).or_default();
99 if entry.last_note.as_deref() == Some(text) {
100 return false;
101 }
102 entry.last_note = Some(text.to_owned());
103 push(entry, forge_line(text.to_owned()));
104 true
105 }
106
107 /// Forgets the last note, so the next refusal of this runner is written again. Called when a
108 /// job is handed out.
109 pub fn clear_note(&self, runner_id: &str) {
110 if let Some(entry) = self.lock().get_mut(runner_id) {
111 entry.last_note = None;
112 }
113 }
114
115 /// The lines of a runner, oldest first. Empty for a runner that never sent a line.
116 pub fn lines(&self, runner_id: &str) -> Vec<Line> {
117 self.lock()
118 .get(runner_id)
119 .map(|entry| entry.lines.iter().cloned().collect())
120 .unwrap_or_default()
121 }
122
123 fn next_seq(&self, runner_id: &str) -> u64 {
124 self.lock().get(runner_id).map_or(0, |entry| entry.next_seq)
125 }
126
127 fn lock(&self) -> MutexGuard<'_, HashMap<String, PerRunner>> {
128 // A panic while the lock was held leaves the map usable, so a poisoned lock is taken as is.
129 self.runners.lock().unwrap_or_else(|e| e.into_inner())
130 }
131}
132
133/// Adds a line and drops the oldest lines beyond `MAX_LINES`.
134fn push(entry: &mut PerRunner, line: Line) {
135 entry.lines.push_back(line);
136 while entry.lines.len() > MAX_LINES {
137 entry.lines.pop_front();
138 }
139}
140
141/// A line the forge wrote now, at level `info`.
142fn forge_line(text: String) -> Line {
143 let at_ms = std::time::SystemTime::now()
144 .duration_since(std::time::UNIX_EPOCH)
145 .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX));
146 Line {
147 at_ms,
148 level: "info".to_owned(),
149 text,
150 from_forge: true,
151 }
152}
153
154/// The level as sent, or `info` for a level the forge does not know.
155fn level_of(level: &str) -> String {
156 if LEVELS.contains(&level) {
157 level.to_owned()
158 } else {
159 "info".to_owned()
160 }
161}
162
163/// `text` cut to at most `max` bytes, on a character boundary.
164fn cut(text: &str, max: usize) -> String {
165 if text.len() <= max {
166 return text.to_owned();
167 }
168 let mut end = max;
169 while !text.is_char_boundary(end) {
170 end -= 1;
171 }
172 text[..end].to_owned()
173}
174
175#[cfg(test)]
176mod tests {
177 use super::*;
178 use forge_ci::proto::RunnerLogLine;
179
180 fn batch(boot: &str, first_seq: u64, texts: &[&str]) -> RunnerLogBatch {
181 RunnerLogBatch {
182 boot_id: boot.to_owned(),
183 first_seq,
184 lines: texts
185 .iter()
186 .map(|t| RunnerLogLine {
187 at_ms: 1,
188 level: "info".to_owned(),
189 text: (*t).to_owned(),
190 })
191 .collect(),
192 }
193 }
194
195 /// A resent batch adds only the lines the forge has not seen, and a gap is marked.
196 #[test]
197 fn ingest_skips_what_is_known_and_marks_gaps() {
198 let logs = RunnerLogs::default();
199 assert_eq!(
200 logs.ingest("r1", &batch("bootaaaaaaaaaa", 0, &["a", "b"])),
201 2
202 );
203 // Resend of 0..=2: only "c" is new.
204 assert_eq!(
205 logs.ingest("r1", &batch("bootaaaaaaaaaa", 0, &["a", "b", "c"])),
206 3
207 );
208 // Lines 3 and 4 were lost before the forge saw them: a marker, then the batch.
209 assert_eq!(logs.ingest("r1", &batch("bootaaaaaaaaaa", 5, &["f"])), 6);
210
211 let texts: Vec<String> = logs.lines("r1").into_iter().map(|l| l.text).collect();
212 assert_eq!(
213 texts,
214 [
215 "runner started (boot bootaaaa)",
216 "a",
217 "b",
218 "c",
219 "2 lines missing",
220 "f"
221 ]
222 );
223 }
224
225 /// A reason is written once while it repeats, and again after the runner gets a job.
226 #[test]
227 fn note_is_written_once_until_cleared() {
228 let logs = RunnerLogs::default();
229 assert!(logs.note("r1", "a restart is pending"));
230 assert!(!logs.note("r1", "a restart is pending"));
231 logs.clear_note("r1");
232 assert!(logs.note("r1", "a restart is pending"));
233 let lines = logs.lines("r1");
234 assert_eq!(lines.len(), 2);
235 assert!(lines.iter().all(|l| l.from_forge));
236 }
237}