1use std::fs::{self, File};
29use std::io::{self, Write};
30use std::os::unix::fs::OpenOptionsExt;
31use std::path::{Path, PathBuf};
32use std::time::{Duration, Instant};
33
34use prost::Message;
35use rustix::process::{Pid, Signal, kill_process_group};
36use schedr_model::runner::CleanupHandle;
37use schedr_proto::pb;
38use serde::{Deserialize, Serialize};
39
40#[cfg(test)]
41mod tests;
42
43const TEMP_PREFIX: &str = ".tmp-";
45
46const KEPT_EXTENSION: &str = "attempt";
48
49const HANDLES_EXTENSION: &str = "handles";
51
52pub const LOCK_FILE: &str = ".lock";
54
55const ORPHAN_POLL: Duration = Duration::from_millis(50);
57
58const ORPHAN_KILL_WAIT: Duration = Duration::from_secs(5);
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
63pub struct ProcessIdentity {
64 pub pgid: i32,
66 pub start_time: u64,
68}
69
70#[derive(Debug, Clone, PartialEq)]
72pub enum JournalRecord {
73 Running(Option<ProcessIdentity>),
75 Finished(pb::Finished),
77 Cleaning(pb::Finished, Option<ProcessIdentity>),
79}
80
81#[derive(Debug, Clone, PartialEq)]
83pub struct KeptAttempt {
84 pub assign: pb::AssignTask,
86 pub code_dir: Option<PathBuf>,
88 pub code_hash: Option<String>,
90 pub root_copies: std::collections::BTreeMap<String, PathBuf>,
92 pub script_dir: Option<PathBuf>,
94}
95
96#[derive(Serialize, Deserialize)]
98#[serde(deny_unknown_fields)]
99struct StoredAttempt {
100 assign: String,
102 code_dir: Option<PathBuf>,
103 code_hash: Option<String>,
104 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
105 root_copies: std::collections::BTreeMap<String, PathBuf>,
106 #[serde(default, skip_serializing_if = "Option::is_none")]
107 script_dir: Option<PathBuf>,
108}
109
110#[derive(Serialize, Deserialize)]
112#[serde(tag = "state", rename_all = "snake_case", deny_unknown_fields)]
113enum Stored {
114 Running {
115 attempt_id: String,
116 process: Option<ProcessIdentity>,
117 },
118 Finished {
119 attempt_id: String,
120 finished: String,
122 },
123 Cleaning {
124 attempt_id: String,
125 finished: String,
127 process: Option<ProcessIdentity>,
128 },
129}
130
131#[derive(Debug, Clone, PartialEq, Eq)]
133pub struct Journal {
134 dir: PathBuf,
135}
136
137impl Journal {
138 #[must_use]
140 pub const fn new(dir: PathBuf) -> Self {
141 Self { dir }
142 }
143
144 #[must_use]
146 pub fn dir(&self) -> &Path {
147 &self.dir
148 }
149
150 pub fn lock(&self) -> io::Result<File> {
158 fs::create_dir_all(&self.dir)?;
159 let file = fs::OpenOptions::new()
160 .create(true)
161 .truncate(false)
162 .write(true)
163 .open(self.dir.join(LOCK_FILE))?;
164 rustix::fs::flock(&file, rustix::fs::FlockOperation::NonBlockingLockExclusive)?;
165 Ok(file)
166 }
167
168 pub fn write(&self, attempt_id: &str, record: &JournalRecord) -> io::Result<()> {
176 let path = self.path(attempt_id)?;
177 let json = encoded(attempt_id, record)?;
178 self.replace(attempt_id, &path, &json)
179 }
180
181 pub fn write_many(&self, records: &[(&str, &JournalRecord)]) -> io::Result<()> {
191 let files = records
192 .iter()
193 .map(|(attempt_id, record)| {
194 Ok((
195 *attempt_id,
196 self.path(attempt_id)?,
197 encoded(attempt_id, record)?,
198 ))
199 })
200 .collect::<io::Result<Vec<_>>>()?;
201 fs::create_dir_all(&self.dir)?;
202 let written: Vec<io::Result<()>> = std::thread::scope(|scope| {
203 let threads: Vec<_> = files
204 .iter()
205 .map(|(attempt_id, _, json)| {
206 let temp = self.dir.join(format!("{TEMP_PREFIX}{attempt_id}"));
207 scope.spawn(move || -> io::Result<()> {
208 let mut file = private_file().truncate(true).open(&temp)?;
209 file.write_all(json)?;
210 file.sync_all()
211 })
212 })
213 .collect();
214 threads
215 .into_iter()
216 .map(|t| {
217 t.join()
218 .unwrap_or_else(|_| Err(io::Error::other("a write panicked")))
219 })
220 .collect()
221 });
222 for ((attempt_id, path, _), done) in files.iter().zip(written) {
223 done?;
224 fs::rename(self.dir.join(format!("{TEMP_PREFIX}{attempt_id}")), path)?;
225 }
226 self.sync_dir()
227 }
228}
229
230fn encoded(attempt_id: &str, record: &JournalRecord) -> io::Result<Vec<u8>> {
232 {
233 let stored = match record {
234 JournalRecord::Running(process) => Stored::Running {
235 attempt_id: attempt_id.to_owned(),
236 process: *process,
237 },
238 JournalRecord::Finished(finished) => Stored::Finished {
239 attempt_id: attempt_id.to_owned(),
240 finished: to_hex(&finished.encode_to_vec()),
241 },
242 JournalRecord::Cleaning(finished, process) => Stored::Cleaning {
243 attempt_id: attempt_id.to_owned(),
244 finished: to_hex(&finished.encode_to_vec()),
245 process: *process,
246 },
247 };
248 serde_json::to_vec(&stored).map_err(io::Error::other)
249 }
250}
251
252impl Journal {
253 fn replace(&self, attempt_id: &str, path: &Path, content: &[u8]) -> io::Result<()> {
255 fs::create_dir_all(&self.dir)?;
256 let temp = self.dir.join(format!("{TEMP_PREFIX}{attempt_id}"));
257 let mut file = private_file().truncate(true).open(&temp)?;
258 file.write_all(content)?;
259 file.sync_all()?;
260 drop(file);
261 fs::rename(&temp, path)?;
262 self.sync_dir()
263 }
264
265 pub fn keep(&self, attempt_id: &str, kept: &KeptAttempt) -> io::Result<()> {
273 let path = self.path(attempt_id)?.with_extension(KEPT_EXTENSION);
274 let stored = StoredAttempt {
275 assign: to_hex(&kept.assign.encode_to_vec()),
276 code_dir: kept.code_dir.clone(),
277 code_hash: kept.code_hash.clone(),
278 root_copies: kept.root_copies.clone(),
279 script_dir: kept.script_dir.clone(),
280 };
281 let json = serde_json::to_vec(&stored).map_err(io::Error::other)?;
282 self.replace(attempt_id, &path, &json)
283 }
284
285 pub fn kept(&self, attempt_id: &str) -> io::Result<Option<KeptAttempt>> {
292 let path = self.path(attempt_id)?.with_extension(KEPT_EXTENSION);
293 let Some(bytes) = read_if_there(&path)? else {
294 return Ok(None);
295 };
296 let invalid = |message: String| io::Error::new(io::ErrorKind::InvalidData, message);
297 let stored: StoredAttempt =
298 serde_json::from_slice(&bytes).map_err(|e| invalid(e.to_string()))?;
299 let assign = from_hex(&stored.assign).ok_or_else(|| invalid("not hex".to_owned()))?;
300 Ok(Some(KeptAttempt {
301 assign: pb::AssignTask::decode(assign.as_slice())
302 .map_err(|e| invalid(e.to_string()))?,
303 code_dir: stored.code_dir,
304 code_hash: stored.code_hash,
305 root_copies: stored.root_copies,
306 script_dir: stored.script_dir,
307 }))
308 }
309
310 pub fn add_handle(&self, attempt_id: &str, handle: &CleanupHandle) -> io::Result<()> {
317 let path = self.path(attempt_id)?.with_extension(HANDLES_EXTENSION);
318 let mut line = serde_json::to_vec(handle).map_err(io::Error::other)?;
319 line.push(b'\n');
320 fs::create_dir_all(&self.dir)?;
321 let new = !path.exists();
322 let mut file = private_file().append(true).open(&path)?;
323 file.write_all(&line)?;
324 file.sync_all()?;
325 if new {
326 self.sync_dir()?;
327 }
328 Ok(())
329 }
330
331 pub fn handles(&self, attempt_id: &str) -> io::Result<Vec<CleanupHandle>> {
339 let path = self.path(attempt_id)?.with_extension(HANDLES_EXTENSION);
340 let bytes = read_if_there(&path)?.unwrap_or_default();
341 let complete = bytes
342 .iter()
343 .rposition(|byte| *byte == b'\n')
344 .map_or(&[][..], |end| &bytes[..end]);
345 if complete.is_empty() {
346 return Ok(Vec::new());
347 }
348 complete
349 .split(|byte| *byte == b'\n')
350 .map(|line| {
351 serde_json::from_slice(line)
352 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
353 })
354 .collect()
355 }
356
357 pub fn remove(&self, attempt_id: &str) -> io::Result<()> {
364 let path = self.path(attempt_id)?;
365 for extension in [KEPT_EXTENSION, HANDLES_EXTENSION] {
367 match fs::remove_file(path.with_extension(extension)) {
368 Err(error) if error.kind() != io::ErrorKind::NotFound => return Err(error),
369 _ => {}
370 }
371 }
372 match fs::remove_file(path) {
373 Ok(()) => self.sync_dir(),
374 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
375 Err(error) => Err(error),
376 }
377 }
378
379 pub fn recover(&self) -> io::Result<Vec<(String, JournalRecord)>> {
387 fs::create_dir_all(&self.dir)?;
388 self.scan(true)
389 }
390
391 pub fn records(&self) -> io::Result<Vec<(String, JournalRecord)>> {
398 self.scan(false)
399 }
400
401 pub fn record(&self, attempt_id: &str) -> io::Result<Option<JournalRecord>> {
408 Ok(read(&self.path(attempt_id)?, attempt_id).ok())
409 }
410
411 fn scan(&self, clean: bool) -> io::Result<Vec<(String, JournalRecord)>> {
412 let mut records = Vec::new();
413 for entry in fs::read_dir(&self.dir)? {
414 let path = entry?.path();
415 let name = path
416 .file_name()
417 .map(|n| n.to_string_lossy().into_owned())
418 .unwrap_or_default();
419 if name.starts_with(TEMP_PREFIX) {
420 if clean {
421 remove_logged(&path, "temporary journal file");
422 }
423 continue;
424 }
425 let Some(attempt_id) = name.strip_suffix(".json") else {
426 continue;
427 };
428 match read(&path, attempt_id) {
429 Ok(record) => records.push((attempt_id.to_owned(), record)),
430 Err(error) if clean => {
431 tracing::warn!(path = %path.display(), %error, "unreadable journal file");
432 remove_logged(&path, "unreadable journal file");
433 }
434 Err(_) => {}
435 }
436 }
437 records.sort_by(|a, b| a.0.cmp(&b.0));
438 if clean {
439 self.remove_strays(&records)?;
440 }
441 Ok(records)
442 }
443
444 fn remove_strays(&self, records: &[(String, JournalRecord)]) -> io::Result<()> {
446 for entry in fs::read_dir(&self.dir)? {
447 let path = entry?.path();
448 let extension = path.extension().and_then(|e| e.to_str());
449 let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("");
450 if matches!(extension, Some(KEPT_EXTENSION | HANDLES_EXTENSION))
451 && !records.iter().any(|(id, _)| id == stem)
452 {
453 remove_logged(&path, "journal file with no record");
454 }
455 }
456 Ok(())
457 }
458
459 fn path(&self, attempt_id: &str) -> io::Result<PathBuf> {
460 let safe = !attempt_id.is_empty()
461 && attempt_id
462 .bytes()
463 .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_');
464 if safe {
465 Ok(self.dir.join(format!("{attempt_id}.json")))
466 } else {
467 Err(io::Error::new(
468 io::ErrorKind::InvalidInput,
469 format!("attempt ID `{attempt_id}` isn't a safe file name"),
470 ))
471 }
472 }
473
474 fn sync_dir(&self) -> io::Result<()> {
475 File::open(&self.dir)?.sync_all()
476 }
477}
478
479fn private_file() -> fs::OpenOptions {
481 let mut options = fs::OpenOptions::new();
482 options.create(true).write(true).mode(0o600);
483 options
484}
485
486fn read_if_there(path: &Path) -> io::Result<Option<Vec<u8>>> {
488 match fs::read(path) {
489 Ok(bytes) => Ok(Some(bytes)),
490 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
491 Err(error) => Err(error),
492 }
493}
494
495fn remove_logged(path: &Path, what: &str) {
498 if let Err(error) = fs::remove_file(path) {
499 tracing::warn!(path = %path.display(), %error, "can't remove {what}");
500 }
501}
502
503fn read(path: &Path, attempt_id: &str) -> io::Result<JournalRecord> {
504 let invalid = |message: String| io::Error::new(io::ErrorKind::InvalidData, message);
505 let stored: Stored =
506 serde_json::from_slice(&fs::read(path)?).map_err(|e| invalid(e.to_string()))?;
507 let (id, record) = match stored {
508 Stored::Running {
509 attempt_id,
510 process,
511 } => (attempt_id, JournalRecord::Running(process)),
512 Stored::Finished {
513 attempt_id,
514 finished,
515 } => {
516 let bytes = from_hex(&finished).ok_or_else(|| invalid("not hex".to_owned()))?;
517 let finished =
518 pb::Finished::decode(bytes.as_slice()).map_err(|e| invalid(e.to_string()))?;
519 (attempt_id, JournalRecord::Finished(finished))
520 }
521 Stored::Cleaning {
522 attempt_id,
523 finished,
524 process,
525 } => {
526 let bytes = from_hex(&finished).ok_or_else(|| invalid("not hex".to_owned()))?;
527 let finished =
528 pb::Finished::decode(bytes.as_slice()).map_err(|e| invalid(e.to_string()))?;
529 (attempt_id, JournalRecord::Cleaning(finished, process))
530 }
531 };
532 if id == attempt_id {
533 Ok(record)
534 } else {
535 Err(invalid(format!("it is for attempt `{id}`")))
536 }
537}
538
539fn to_hex(bytes: &[u8]) -> String {
540 use std::fmt::Write as _;
541 bytes.iter().fold(String::new(), |mut hex, b| {
542 let _ = write!(hex, "{b:02x}");
543 hex
544 })
545}
546
547fn from_hex(hex: &str) -> Option<Vec<u8>> {
548 if !hex.len().is_multiple_of(2) {
549 return None;
550 }
551 (0..hex.len())
552 .step_by(2)
553 .map(|i| u8::from_str_radix(hex.get(i..i + 2)?, 16).ok())
554 .collect()
555}
556
557pub fn process_identity(pid: i32) -> io::Result<ProcessIdentity> {
564 let stat = fs::read_to_string(format!("/proc/{pid}/stat"))?;
565 let start_time = stat
568 .rsplit_once(')')
569 .and_then(|(_, rest)| rest.split_whitespace().nth(22 - 3))
570 .and_then(|field| field.parse().ok())
571 .ok_or_else(|| {
572 io::Error::new(
573 io::ErrorKind::InvalidData,
574 format!("`/proc/{pid}/stat` has no start time"),
575 )
576 })?;
577 Ok(ProcessIdentity {
578 pgid: pid,
579 start_time,
580 })
581}
582
583fn orphan_group(pgid: i32) -> Option<Pid> {
586 if pgid <= 1 {
587 return None;
588 }
589 Pid::from_raw(pgid)
590}
591
592#[derive(Debug, Clone, Copy, PartialEq, Eq)]
594pub enum Orphan {
595 Gone,
597 Stopped,
599 Killed,
601}
602
603#[derive(Debug, Clone, Copy, PartialEq, Eq)]
605pub struct OrphanWaits {
606 pub poll: Duration,
608 pub kill_wait: Duration,
610}
611
612impl Default for OrphanWaits {
613 fn default() -> Self {
615 Self {
616 poll: ORPHAN_POLL,
617 kill_wait: ORPHAN_KILL_WAIT,
618 }
619 }
620}
621
622pub async fn stop_orphan(
629 identity: ProcessIdentity,
630 grace: Duration,
631 waits: OrphanWaits,
632) -> io::Result<Orphan> {
633 if process_identity(identity.pgid).ok() != Some(identity) {
634 return Ok(Orphan::Gone);
635 }
636 let Some(group) = orphan_group(identity.pgid) else {
637 return Ok(Orphan::Gone);
638 };
639 let signal = |signal| match kill_process_group(group, signal) {
640 Ok(()) | Err(rustix::io::Errno::SRCH) => Ok(()),
641 Err(error) => Err(io::Error::from(error)),
642 };
643 signal(Signal::TERM)?;
644 if gone_within(group, grace, waits.poll).await {
645 return Ok(Orphan::Stopped);
646 }
647 signal(Signal::KILL)?;
648 if !gone_within(group, waits.kill_wait, waits.poll).await {
649 tracing::warn!(
650 pgid = identity.pgid,
651 "a killed task process group hasn't gone yet"
652 );
653 }
654 Ok(Orphan::Killed)
655}
656
657async fn gone_within(group: Pid, wait: Duration, poll: Duration) -> bool {
659 let deadline = Instant::now() + wait;
660 loop {
661 if !crate::process::group_running(group) {
662 return true;
663 }
664 let left = deadline.saturating_duration_since(Instant::now());
665 if left.is_zero() {
666 return false;
667 }
668 tokio::time::sleep(poll.min(left)).await;
669 }
670}