Skip to main content

brep_plm/
bake_worker.rs

1//! Administrator control of one server-owned native bake worker.
2//! Executable, credentials and server URL are operator configuration; HTTP
3//! callers cannot supply commands or obtain token contents.
4
5use crate::Error;
6use serde::Serialize;
7use std::fs::OpenOptions;
8use std::path::{Path, PathBuf};
9use std::process::{Child, Command, Stdio};
10use std::sync::Mutex;
11
12#[derive(Debug, Clone)]
13pub struct Config {
14    pub executable: PathBuf,
15    pub token_file: PathBuf,
16    pub server_url: String,
17}
18
19#[derive(Default)]
20struct Process {
21    child: Option<Child>,
22    last_exit: Option<i32>,
23    error: Option<String>,
24}
25
26#[derive(Default)]
27pub struct Controller(Mutex<Process>);
28
29#[derive(Serialize)]
30pub struct Status {
31    pub configured: bool,
32    pub running: bool,
33    pub pid: Option<u32>,
34    pub last_exit: Option<i32>,
35    pub error: Option<String>,
36}
37
38impl Process {
39    fn refresh(&mut self) -> Result<(), Error> {
40        if let Some(child) = self.child.as_mut() {
41            if let Some(status) = child.try_wait().map_err(Error::internal)? {
42                self.last_exit = status.code();
43                self.error = (!status.success()).then(|| format!("Worker exited with {status}. See bake-worker.log in the server data directory."));
44                self.child = None;
45            }
46        }
47        Ok(())
48    }
49
50    fn status(&self, configured: bool) -> Status {
51        Status {
52            configured,
53            running: self.child.is_some(),
54            pid: self.child.as_ref().map(Child::id),
55            last_exit: self.last_exit,
56            error: self.error.clone(),
57        }
58    }
59}
60
61impl Controller {
62    pub fn status(&self, config: Option<&Config>) -> Result<Status, Error> {
63        let mut process = self
64            .0
65            .lock()
66            .map_err(|_| Error::internal("worker controller unavailable"))?;
67        process.refresh()?;
68        Ok(process.status(config.is_some()))
69    }
70
71    pub fn start(&self, config: Option<&Config>, root: &Path) -> Result<Status, Error> {
72        let config = config.ok_or_else(|| Error::bad_request("The server operator must configure --bake-worker-executable, --bake-worker-token-file and --bake-worker-url."))?;
73        let mut process = self
74            .0
75            .lock()
76            .map_err(|_| Error::internal("worker controller unavailable"))?;
77        process.refresh()?;
78        if process.child.is_some() {
79            return Ok(process.status(true));
80        }
81        if !config.executable.is_file() || !config.token_file.is_file() {
82            return Err(Error::bad_request(
83                "The configured worker executable or token file is missing.",
84            ));
85        }
86        let log = OpenOptions::new()
87            .create(true)
88            .append(true)
89            .open(root.join("bake-worker.log"))
90            .map_err(Error::internal)?;
91        let stderr = log.try_clone().map_err(Error::internal)?;
92        let child = Command::new(&config.executable)
93            .arg("--bake-worker")
94            .arg("--plm-url")
95            .arg(&config.server_url)
96            .arg("--plm-token-file")
97            .arg(&config.token_file)
98            .args(["--poll", "5"])
99            .stdin(Stdio::null())
100            .stdout(log)
101            .stderr(stderr)
102            .spawn()
103            .map_err(|e| Error::bad_request(format!("Could not start bake worker: {e}")))?;
104        process.child = Some(child);
105        process.last_exit = None;
106        process.error = None;
107        process.refresh()?;
108        Ok(process.status(true))
109    }
110
111    pub fn stop(&self, config: Option<&Config>) -> Result<Status, Error> {
112        let mut process = self
113            .0
114            .lock()
115            .map_err(|_| Error::internal("worker controller unavailable"))?;
116        process.refresh()?;
117        if let Some(child) = process.child.as_mut() {
118            child.kill().map_err(Error::internal)?;
119            child.wait().map_err(Error::internal)?;
120            process.child = None;
121            process.last_exit = None;
122            process.error = None;
123        }
124        Ok(process.status(config.is_some()))
125    }
126}
127
128impl Drop for Controller {
129    fn drop(&mut self) {
130        if let Ok(process) = self.0.get_mut() {
131            if let Some(child) = process.child.as_mut() {
132                let _ = child.kill();
133                let _ = child.wait();
134            }
135        }
136    }
137}
138