Skip to main content

schedr_agent/
logs.rs

1//! The worker's log endpoint (see archive/PROJECT.md, Task logs): the webserver reads task logs
2//! from the worker that ran them, a part at a time.
3//!
4//! - **`GET /logs/{attempt_id}?from=<byte>&limit=<bytes>`** answers the log's bytes from
5//!   `from` (at most `limit`, between 4 bytes and 1 MiB), with headers saying which worker
6//!   answered (`Schedr-Worker-Id`), how long the log is now (`Schedr-Log-Size`) and whether
7//!   the attempt still runs here (`Schedr-Attempt-Running`, from the journal, checked before
8//!   the file is read: an attempt said to be finished has all its output in the answer's
9//!   size). Reading on from the size returned follows a running task's log.
10//! - **Errors** are JSON (`{"error": "…"}`): 400 for an ID that isn't an attempt ID, 404 for
11//!   a log this worker doesn't have (deleted by retention, or another worker's).
12//!
13//! Access is decided by TLS (`tls.mode = "app"`: only clients with a certificate from the
14//! CA) or by the mesh; the endpoint serves logs only, never actions.
15
16use std::io::SeekFrom;
17use std::path::PathBuf;
18
19use axum::extract::rejection::QueryRejection;
20use axum::extract::{Path, Query, State};
21use axum::http::{HeaderMap, HeaderValue, StatusCode};
22use axum::response::{IntoResponse, Response};
23use axum::routing::get;
24use axum::{Json, Router};
25use serde::{Deserialize, Serialize};
26use tokio::io::{AsyncReadExt, AsyncSeekExt};
27
28use schedr_model::logs::{
29    LOG_SIZE_HEADER, MAX_CHUNK, MAX_READ, MIN_CHUNK, RUNNING_HEADER, WORKER_ID_HEADER,
30};
31
32use crate::journal::{Journal, JournalRecord};
33
34#[cfg(test)]
35mod tests;
36
37/// What the endpoint serves.
38#[derive(Debug, Clone)]
39pub struct LogEndpoint {
40    /// This worker's ID, sent with every answer.
41    pub worker_id: String,
42    /// Where task logs are (`<log_dir>/<attempt_id>.log`).
43    pub log_dir: PathBuf,
44    /// The journal, which knows the attempts running here.
45    pub journal: Journal,
46}
47
48/// The query of a log request.
49#[derive(Debug, Clone, Copy, Default, Deserialize)]
50#[serde(deny_unknown_fields)]
51pub struct LogQuery {
52    /// The first byte wanted (0 by default).
53    pub from: Option<u64>,
54    /// How many bytes at most ([`MAX_CHUNK`] by default; between [`MIN_CHUNK`] and [`MAX_READ`]).
55    pub limit: Option<u64>,
56}
57
58/// An error answer.
59#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
60pub struct LogError {
61    /// What went wrong.
62    pub error: String,
63}
64
65/// The endpoint's routes.
66pub fn router(endpoint: LogEndpoint) -> Router {
67    Router::new()
68        .route("/logs/{attempt_id}", get(get_log))
69        .with_state(endpoint)
70}
71
72/// Whether `text` looks like an attempt ID (a UUID): nothing else names a log file here.
73#[must_use]
74pub fn is_attempt_id(text: &str) -> bool {
75    text.len() == 36
76        && text.bytes().enumerate().all(|(i, b)| {
77            matches!(i, 8 | 13 | 18 | 23) == (b == b'-') && (b == b'-' || b.is_ascii_hexdigit())
78        })
79}
80
81async fn get_log(
82    State(endpoint): State<LogEndpoint>,
83    Path(attempt_id): Path<String>,
84    query: Result<Query<LogQuery>, QueryRejection>,
85) -> Response {
86    let mut headers = HeaderMap::new();
87    if let Ok(id) = HeaderValue::from_str(&endpoint.worker_id) {
88        headers.insert(WORKER_ID_HEADER, id);
89    }
90    let error = |status: StatusCode, error: String| {
91        (status, headers.clone(), Json(LogError { error })).into_response()
92    };
93    let Ok(Query(query)) = query else {
94        return error(
95            StatusCode::BAD_REQUEST,
96            "the query takes `from` and `limit`, as numbers of bytes".to_owned(),
97        );
98    };
99    if !is_attempt_id(&attempt_id) {
100        return error(
101            StatusCode::BAD_REQUEST,
102            format!("`{attempt_id}` isn't an attempt ID"),
103        );
104    }
105    // Before the file: what ran before the attempt was recorded finished is all in the file.
106    let journal = endpoint.journal.clone();
107    let id = attempt_id.clone();
108    let running = tokio::task::spawn_blocking(move || journal.record(&id))
109        .await
110        .ok()
111        .and_then(Result::ok)
112        .flatten()
113        .is_some_and(|record| matches!(record, JournalRecord::Running(_)));
114    let path = endpoint.log_dir.join(format!("{attempt_id}.log"));
115    let read = read_part(
116        &path,
117        query.from.unwrap_or(0),
118        query.limit.unwrap_or(MAX_CHUNK),
119    )
120    .await;
121    let (size, bytes) = match read {
122        Ok(part) => part,
123        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
124            return error(
125                StatusCode::NOT_FOUND,
126                format!(
127                    "worker `{}` has no log of attempt `{attempt_id}` (it may have been deleted)",
128                    endpoint.worker_id
129                ),
130            );
131        }
132        Err(e) => {
133            tracing::warn!(path = %path.display(), error = %e, "can't read a task log");
134            return error(
135                StatusCode::INTERNAL_SERVER_ERROR,
136                format!("worker `{}` can't read the log: {e}", endpoint.worker_id),
137            );
138        }
139    };
140    headers.insert(LOG_SIZE_HEADER, HeaderValue::from(size));
141    headers.insert(
142        RUNNING_HEADER,
143        HeaderValue::from_static(if running { "true" } else { "false" }),
144    );
145    headers.insert(
146        axum::http::header::CONTENT_TYPE,
147        HeaderValue::from_static("application/octet-stream"),
148    );
149    (StatusCode::OK, headers, bytes).into_response()
150}
151
152/// The file's size and up to `limit` (between [`MIN_CHUNK`] and [`MAX_READ`]) bytes from
153/// `from`.
154async fn read_part(
155    path: &std::path::Path,
156    from: u64,
157    limit: u64,
158) -> std::io::Result<(u64, Vec<u8>)> {
159    let mut options = tokio::fs::OpenOptions::new();
160    options.read(true);
161    let mut file = crate::process::open_regular(options, path).await?;
162    let size = file.metadata().await?.len();
163    let from = from.min(size);
164    file.seek(SeekFrom::Start(from)).await?;
165    let mut bytes = Vec::new();
166    file.take(limit.clamp(MIN_CHUNK, MAX_READ).min(size - from))
167        .read_to_end(&mut bytes)
168        .await?;
169    Ok((size, bytes))
170}