forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

selflog.rs288 lines, 9.0 KiBHistoryRawDownload
1//! The runner's own log, shipped to the forge. A tracing layer formats every INFO (or more severe)
2//! event into a bounded in-memory ring. [`ship`] posts the lines the forge has not seen yet, so the
3//! runner's page on the forge shows what it was doing, for example why a job waited in the queue.
4//! Job logs are not part of this. They have their own path, see [`crate::logs`].
5
6use std::collections::VecDeque;
7use std::fmt::{Debug, Write as _};
8use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError};
9use std::time::{Duration, SystemTime, UNIX_EPOCH};
10
11use forge_ci::proto::{RunnerLogBatch, RunnerLogLine};
12use reqwest::StatusCode;
13use tokio_util::sync::CancellationToken;
14use tracing::field::{Field, Visit};
15use tracing::{Event, Level, Subscriber};
16use tracing_subscriber::Layer;
17use tracing_subscriber::layer::Context;
18
19use crate::client::{ClientError, ForgeClient};
20
21/// Most lines the ring holds. The oldest are dropped first.
22pub const CAPACITY: usize = 2000;
23/// Longest text kept for one line, in bytes. Longer text is cut on a character boundary.
24pub const MAX_TEXT: usize = 4096;
25/// Most lines in one batch.
26pub const BATCH: usize = 500;
27/// Time between two shipping attempts.
28const EVERY: Duration = Duration::from_secs(2);
29/// Event targets that are noise. Shipping uses HTTP, so these would feed back into the ring.
30const SKIP_TARGETS: [&str; 4] = ["reqwest", "hyper", "h2", "rustls"];
31
32static RING: OnceLock<Arc<Ring>> = OnceLock::new();
33
34/// The ring shared by the layer and the shipper.
35pub fn ring() -> Arc<Ring> {
36 RING.get_or_init(|| Arc::new(Ring::new(CAPACITY))).clone()
37}
38
39/// The layer that fills the ring. Add it to the subscriber with `.with(selflog::layer())`.
40pub fn layer() -> SelfLog {
41 SelfLog { ring: ring() }
42}
43
44/// A bounded buffer of log lines. Each line gets the next sequence number, counting from 0 for
45/// the process. Lines are shipped by sequence number, so a line keeps its number after older
46/// ones are dropped.
47pub struct Ring {
48 capacity: usize,
49 state: Mutex<State>,
50}
51
52#[derive(Default)]
53struct State {
54 lines: VecDeque<RunnerLogLine>,
55 /// The number the next line gets. Also how many lines were ever pushed.
56 next: u64,
57}
58
59impl Ring {
60 /// An empty ring that holds at most `capacity` lines.
61 pub fn new(capacity: usize) -> Self {
62 Self {
63 capacity,
64 state: Mutex::new(State::default()),
65 }
66 }
67
68 fn lock(&self) -> MutexGuard<'_, State> {
69 self.state.lock().unwrap_or_else(PoisonError::into_inner)
70 }
71
72 /// Adds a line, dropping the oldest one when the ring is full.
73 pub fn push(&self, line: RunnerLogLine) {
74 let mut state = self.lock();
75 if state.lines.len() >= self.capacity {
76 state.lines.pop_front();
77 }
78 state.lines.push_back(line);
79 state.next += 1;
80 }
81
82 /// The number the next line will get.
83 pub fn end(&self) -> u64 {
84 self.lock().next
85 }
86
87 /// Up to `max` lines from number `from` on. Lines already dropped are skipped, so the first
88 /// returned number is `from` or later. The number is returned with the lines.
89 pub fn batch(&self, from: u64, max: usize) -> (u64, Vec<RunnerLogLine>) {
90 let state = self.lock();
91 let oldest = state.next - state.lines.len() as u64;
92 let first = from.max(oldest);
93 if first >= state.next {
94 return (first, Vec::new());
95 }
96 let skip = (first - oldest) as usize;
97 let lines = state.lines.iter().skip(skip).take(max).cloned().collect();
98 (first, lines)
99 }
100}
101
102/// The tracing layer that puts INFO (and more severe) events into the ring.
103pub struct SelfLog {
104 ring: Arc<Ring>,
105}
106
107impl<S: Subscriber> Layer<S> for SelfLog {
108 fn on_event(&self, event: &Event<'_>, _ctx: Context<'_, S>) {
109 let meta = event.metadata();
110 if *meta.level() > Level::INFO {
111 return;
112 }
113 if SKIP_TARGETS
114 .iter()
115 .any(|prefix| meta.target().starts_with(prefix))
116 {
117 return;
118 }
119 let mut text = Text::default();
120 event.record(&mut text);
121 self.ring.push(RunnerLogLine {
122 at_ms: now_ms(),
123 level: level_name(*meta.level()).to_owned(),
124 text: truncate(text.finish()),
125 });
126 }
127}
128
129/// Collects an event's message and fields into one line, in the same shape the fmt layer uses:
130/// the message, then `key=value` for each field.
131#[derive(Default)]
132struct Text {
133 message: String,
134 fields: String,
135}
136
137impl Text {
138 fn finish(self) -> String {
139 match (self.message.is_empty(), self.fields.is_empty()) {
140 (_, true) => self.message,
141 (true, false) => self.fields.trim_start().to_owned(),
142 (false, false) => format!("{}{}", self.message, self.fields),
143 }
144 }
145}
146
147impl Visit for Text {
148 fn record_str(&mut self, field: &Field, value: &str) {
149 if field.name() == "message" {
150 self.message.push_str(value);
151 } else {
152 let _ = write!(self.fields, " {}={value}", field.name());
153 }
154 }
155
156 fn record_debug(&mut self, field: &Field, value: &dyn Debug) {
157 if field.name() == "message" {
158 let _ = write!(self.message, "{value:?}");
159 } else {
160 let _ = write!(self.fields, " {}={value:?}", field.name());
161 }
162 }
163}
164
165fn level_name(level: Level) -> &'static str {
166 match level {
167 Level::ERROR => "error",
168 Level::WARN => "warn",
169 Level::INFO => "info",
170 Level::DEBUG => "debug",
171 _ => "trace",
172 }
173}
174
175pub(crate) fn now_ms() -> i64 {
176 SystemTime::now()
177 .duration_since(UNIX_EPOCH)
178 .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX))
179}
180
181/// Cuts `text` to at most [`MAX_TEXT`] bytes, on a character boundary.
182fn truncate(mut text: String) -> String {
183 if text.len() > MAX_TEXT {
184 let mut end = MAX_TEXT;
185 while !text.is_char_boundary(end) {
186 end -= 1;
187 }
188 text.truncate(end);
189 }
190 text
191}
192
193/// Posts the lines the forge has not seen yet, every two seconds, under the boot id of this
194/// process. Failures are logged at debug level and retried on the next tick. When `stop` is
195/// cancelled, the lines still held are sent before returning, so the caller may bound this with a
196/// timeout. An older forge without the endpoint answers 404, and then shipping stops for good.
197pub async fn ship(client: ForgeClient, runner_secret: String, stop: CancellationToken) {
198 let ring = ring();
199 let boot_id = crate::restart::boot_id();
200 let mut next_seq = 0_u64;
201 let mut ticker = tokio::time::interval(EVERY);
202 loop {
203 let stopping = tokio::select! {
204 _ = ticker.tick() => false,
205 () = stop.cancelled() => true,
206 };
207 loop {
208 let (first_seq, lines) = ring.batch(next_seq, BATCH);
209 if lines.is_empty() {
210 break;
211 }
212 let batch = RunnerLogBatch {
213 boot_id: boot_id.to_owned(),
214 first_seq,
215 lines,
216 };
217 match client.post_runner_log(&runner_secret, &batch).await {
218 Ok(ack) => {
219 let moved = ack.next_seq != next_seq;
220 next_seq = ack.next_seq;
221 // A final flush sends batch after batch, but only while the forge moves on.
222 if !stopping || !moved {
223 break;
224 }
225 }
226 Err(ClientError::Status {
227 status: StatusCode::NOT_FOUND,
228 ..
229 }) => return,
230 Err(e) => {
231 tracing::debug!(error = %e, "cannot ship the runner log, retrying");
232 break;
233 }
234 }
235 }
236 if stopping {
237 return;
238 }
239 }
240}
241
242#[cfg(test)]
243mod tests {
244 use super::*;
245
246 fn line(text: &str) -> RunnerLogLine {
247 RunnerLogLine {
248 at_ms: 0,
249 level: "info".into(),
250 text: text.into(),
251 }
252 }
253
254 #[test]
255 fn ring_drops_the_oldest_lines() {
256 let ring = Ring::new(3);
257 for i in 0..5 {
258 ring.push(line(&i.to_string()));
259 }
260 assert_eq!(ring.end(), 5);
261 let (first, lines) = ring.batch(0, 10);
262 assert_eq!(first, 2);
263 let texts: Vec<_> = lines.iter().map(|l| l.text.as_str()).collect();
264 assert_eq!(texts, ["2", "3", "4"]);
265 }
266
267 #[test]
268 fn sequence_numbers_follow_the_request() {
269 let ring = Ring::new(10);
270 for i in 0..4 {
271 ring.push(line(&i.to_string()));
272 }
273 let (first, lines) = ring.batch(1, 2);
274 assert_eq!(first, 1);
275 assert_eq!(lines.len(), 2);
276 assert_eq!(lines[0].text, "1");
277 // Nothing at or after the end.
278 assert!(ring.batch(4, 10).1.is_empty());
279 }
280
281 #[test]
282 fn long_text_is_cut_on_a_char_boundary() {
283 let text = "é".repeat(MAX_TEXT);
284 let cut = truncate(text);
285 assert!(cut.len() <= MAX_TEXT);
286 assert!(cut.ends_with('é'));
287 }
288}