Skip to main content

schedr_api/
logs.rs

1//! Task logs, read from the worker that ran the attempt (see archive/PROJECT.md, Task logs): the
2//! webserver proxies them, so clients never reach workers.
3//!
4//! A worker's address is what it advertised when it registered (`workers.log_endpoint`), so
5//! it is found by the worker's ID. Every answer names the worker that gave it
6//! (`Schedr-Worker-Id`): an address that now belongs to another worker is noticed instead of
7//! passing for a deleted log. Requests to workers never go through an HTTP proxy, and in
8//! `tls.mode = "app"` present the webserver's certificate and expect the worker's to name
9//! `[tls] worker_name`.
10
11use std::fmt;
12use std::fmt::Write as _;
13use std::pin::Pin;
14use std::sync::{Mutex, PoisonError};
15use std::time::Duration;
16
17use schedr_model::logs::{LOG_SIZE_HEADER, RUNNING_HEADER, WORKER_ID_HEADER};
18use schedr_tls::{Tls, error_text};
19
20#[cfg(test)]
21mod tests;
22
23/// How long connecting to a worker may take.
24pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
25
26/// How long a whole request to a worker may take.
27pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
28
29/// A part of a log, as a worker gave it.
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct WorkerLog {
32    /// The worker that answered.
33    pub worker_id: Option<String>,
34    /// The log's size when it was read.
35    pub size: u64,
36    /// Whether the attempt still runs there.
37    pub running: bool,
38    /// The bytes asked for.
39    pub bytes: Vec<u8>,
40}
41
42/// Why a worker gave no log.
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub enum LogFetchError {
45    /// The worker has no such log (deleted, or another worker's).
46    Missing {
47        /// The worker that answered.
48        worker_id: Option<String>,
49    },
50    /// The worker can't be reached, or failed.
51    Unreachable(String),
52}
53
54/// The future of a [`LogSource::fetch`].
55pub type LogFuture<'a> =
56    Pin<Box<dyn Future<Output = Result<WorkerLog, LogFetchError>> + Send + 'a>>;
57
58/// Where the webserver gets logs from (workers over HTTP; something else in tests).
59pub trait LogSource: Send + Sync + fmt::Debug {
60    /// Up to `limit` bytes from `from` of the log of `attempt_id`, from the worker whose log
61    /// endpoint is `endpoint`.
62    fn fetch<'a>(
63        &'a self,
64        endpoint: &'a str,
65        attempt_id: &'a str,
66        from: u64,
67        limit: u64,
68    ) -> LogFuture<'a>;
69}
70
71/// Logs from workers over HTTP (TLS in `app` mode), never through a proxy.
72#[derive(Debug)]
73pub struct HttpLogSource {
74    tls: Option<Tls>,
75    connect_timeout: Duration,
76    request_timeout: Duration,
77    /// The client, with the TLS generation it was built for.
78    client: Mutex<Option<(u64, reqwest::Client)>>,
79}
80
81impl HttpLogSource {
82    /// Logs over TLS with `tls` (`app` mode), or plain HTTP (`mesh` mode, standalone).
83    #[must_use]
84    pub const fn new(tls: Option<Tls>) -> Self {
85        Self {
86            tls,
87            connect_timeout: CONNECT_TIMEOUT,
88            request_timeout: REQUEST_TIMEOUT,
89            client: Mutex::new(None),
90        }
91    }
92
93    /// This, with the time connecting to a worker and a whole request may take (`[webserver]
94    /// worker_connect_timeout`, `worker_request_timeout`).
95    #[must_use]
96    pub fn with_timeouts(self, connect: Duration, request: Duration) -> Self {
97        Self {
98            connect_timeout: connect,
99            request_timeout: request,
100            ..self
101        }
102    }
103
104    /// The client for the material in use, rebuilt when the certificates changed.
105    fn client(&self) -> Result<reqwest::Client, String> {
106        let generation = self.tls.as_ref().map_or(0, Tls::generation);
107        let mut cached = self.client.lock().unwrap_or_else(PoisonError::into_inner);
108        if let Some((built, client)) = cached.as_ref()
109            && *built == generation
110        {
111            return Ok(client.clone());
112        }
113        // Never redirected (B133): a log comes only from the worker's own address, over the
114        // TLS asked for.
115        let mut builder = reqwest::Client::builder()
116            .no_proxy()
117            .redirect(reqwest::redirect::Policy::none())
118            .connect_timeout(self.connect_timeout)
119            .timeout(self.request_timeout);
120        if let Some(tls) = &self.tls {
121            builder = builder.tls_backend_preconfigured((*tls.worker_client()).clone());
122        }
123        let client = builder
124            .build()
125            .map_err(|e| format!("can't set up the HTTP client: {e}"))?;
126        *cached = Some((generation, client.clone()));
127        Ok(client)
128    }
129
130    async fn get(
131        &self,
132        endpoint: &str,
133        attempt_id: &str,
134        from: u64,
135        limit: u64,
136    ) -> Result<WorkerLog, LogFetchError> {
137        let https = endpoint.starts_with("https://");
138        if https != self.tls.is_some() {
139            let (theirs, ours) = if https {
140                ("https", "mesh")
141            } else {
142                ("plain http", "app")
143            };
144            return Err(LogFetchError::Unreachable(format!(
145                "it serves logs over {theirs} but [tls] mode is `{ours}` here: give every role \
146                 the same [tls] mode"
147            )));
148        }
149        let client = self.client().map_err(LogFetchError::Unreachable)?;
150        let url = format!(
151            "{}/logs/{attempt_id}?from={from}&limit={limit}",
152            endpoint.trim_end_matches('/')
153        );
154        let response = client
155            .get(&url)
156            .send()
157            .await
158            .map_err(|e| LogFetchError::Unreachable(error_text(&e)))?;
159        let header = |name: &str| {
160            response
161                .headers()
162                .get(name)
163                .and_then(|v| v.to_str().ok())
164                .map(str::to_owned)
165        };
166        let worker_id = header(WORKER_ID_HEADER);
167        let status = response.status();
168        if status == reqwest::StatusCode::NOT_FOUND {
169            return Err(LogFetchError::Missing { worker_id });
170        }
171        let size = header(LOG_SIZE_HEADER).and_then(|s| s.parse().ok());
172        let running = header(RUNNING_HEADER).is_some_and(|r| r == "true");
173        let bytes = response
174            .bytes()
175            .await
176            .map_err(|e| LogFetchError::Unreachable(error_text(&e)))?;
177        if !status.is_success() {
178            let message = serde_json::from_slice::<serde_json::Value>(&bytes)
179                .ok()
180                .and_then(|v| v["error"].as_str().map(str::to_owned))
181                .unwrap_or_else(|| format!("it answered {status}"));
182            return Err(LogFetchError::Unreachable(message));
183        }
184        let size = size.ok_or_else(|| {
185            LogFetchError::Unreachable(format!("its answer has no `{LOG_SIZE_HEADER}`"))
186        })?;
187        Ok(WorkerLog {
188            worker_id,
189            size,
190            running,
191            bytes: bytes.to_vec(),
192        })
193    }
194}
195
196impl LogSource for HttpLogSource {
197    fn fetch<'a>(
198        &'a self,
199        endpoint: &'a str,
200        attempt_id: &'a str,
201        from: u64,
202        limit: u64,
203    ) -> LogFuture<'a> {
204        Box::pin(self.get(endpoint, attempt_id, from, limit))
205    }
206}
207
208/// A part of a log as shown: masked, whole lines only.
209#[derive(Debug, Clone, PartialEq, Eq)]
210pub struct MaskedPart {
211    /// The bytes skipped at its start (the rest of a line begun before it).
212    pub skipped: usize,
213    /// Its text, masked.
214    pub content: String,
215    /// The bytes it covers after the skipped ones.
216    pub used: usize,
217}
218
219/// `bytes`, a part of a log, as shown: masked (a task may print an address with its
220/// password), whole lines only, so no secret is shown in pieces (a reader picks where a part
221/// starts and how long it is). Not starting a line (`at_line` false), it starts after its
222/// first newline, all of it skipped when it has none. With `more` to come, it ends after its
223/// last newline, the rest left for the next part. With none in it, it waits for its line's
224/// end, unless it is `full` (as long as asked) and starts a line: then it is shown to its
225/// last whitespace (its last token may go on), ending with a note that it is cut, and the
226/// rest of that line is skipped, as a part not starting a line is. A short part shows a
227/// line's start at most, never its pieces. `before`, the bytes just before the part, is
228/// masked with it, not shown: a value begun there (a quoted one going on over lines) is
229/// hidden in the part too.
230#[must_use]
231pub fn masked_lines(
232    before: &[u8],
233    bytes: &[u8],
234    at_line: bool,
235    more: bool,
236    full: bool,
237) -> MaskedPart {
238    let newline = |b: &u8| *b == b'\n';
239    let skipped = if at_line {
240        0
241    } else {
242        bytes
243            .iter()
244            .position(newline)
245            .map_or(bytes.len(), |at| at + 1)
246    };
247    let rest = &bytes[skipped..];
248    let (lines, used) = if more {
249        match rest.iter().rposition(newline) {
250            Some(at) => (at + 1, at + 1),
251            // Its last token may go on in the next part: not shown. Nothing to show
252            // (no whitespace in a whole part): the line is passed over.
253            None if full && at_line => (
254                rest.iter()
255                    .rposition(u8::is_ascii_whitespace)
256                    .map_or(0, |at| at + 1),
257                rest.len(),
258            ),
259            None => (0, 0),
260        }
261    } else {
262        (rest.len(), rest.len())
263    };
264    let (text, whole) = text_of(&rest[..lines], more && lines == rest.len());
265    // What precedes the text shown: the bytes before the part, and those skipped in it.
266    let mut preceding = before.to_vec();
267    preceding.extend_from_slice(&bytes[..skipped]);
268    let mut content =
269        schedr_config::masked::mask_text_after(&String::from_utf8_lossy(&preceding), &text);
270    let cut = lines != used;
271    if cut {
272        let _ = writeln!(
273            content,
274            "… (the rest of this line is not shown: it is over {} bytes)",
275            rest.len()
276        );
277    }
278    MaskedPart {
279        skipped,
280        content,
281        used: if cut { used } else { whole },
282    }
283}
284
285/// `bytes` as text, and how many of them it covers: a character cut at the end (more of the
286/// log follows) is left for the next part, so following a log never garbles one; invalid
287/// bytes become `U+FFFD`.
288#[must_use]
289pub fn text_of(bytes: &[u8], more: bool) -> (String, usize) {
290    let whole = if more {
291        bytes.len() - cut_at_end(bytes)
292    } else {
293        bytes.len()
294    };
295    (String::from_utf8_lossy(&bytes[..whole]).into_owned(), whole)
296}
297
298/// How many bytes at the end of `bytes` begin a UTF-8 character that isn't complete yet.
299fn cut_at_end(bytes: &[u8]) -> usize {
300    // A character has at most 4 bytes: its lead byte is among the last 3 if it is cut.
301    for back in 1..=bytes.len().min(3) {
302        let byte = bytes[bytes.len() - back];
303        if byte & 0b1100_0000 == 0b1000_0000 {
304            continue;
305        }
306        let needed = match byte {
307            0xC0..=0xDF => 2,
308            0xE0..=0xEF => 3,
309            0xF0..=0xF7 => 4,
310            _ => return 0,
311        };
312        return if back < needed { back } else { 0 };
313    }
314    0
315}