1use 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#[derive(Debug, Clone)]
39pub struct LogEndpoint {
40 pub worker_id: String,
42 pub log_dir: PathBuf,
44 pub journal: Journal,
46}
47
48#[derive(Debug, Clone, Copy, Default, Deserialize)]
50#[serde(deny_unknown_fields)]
51pub struct LogQuery {
52 pub from: Option<u64>,
54 pub limit: Option<u64>,
56}
57
58#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
60pub struct LogError {
61 pub error: String,
63}
64
65pub fn router(endpoint: LogEndpoint) -> Router {
67 Router::new()
68 .route("/logs/{attempt_id}", get(get_log))
69 .with_state(endpoint)
70}
71
72#[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 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
152async 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}