1use crate::error::{DomainError, ErrorCode};
2use anyhow::{Context, Result, bail};
3use fs2::FileExt;
4use std::{
5 fs::{File, OpenOptions},
6 io::Read,
7 path::Path,
8 process::{Child, Command, ExitStatus, Stdio},
9 sync::{
10 Arc,
11 atomic::{AtomicBool, Ordering},
12 },
13 thread,
14 time::{Duration, Instant},
15};
16
17pub struct MediaLock {
18 _file: File,
19}
20
21pub fn owned_child(command: &mut Command) -> &mut Command {
23 #[cfg(target_os = "linux")]
24 {
25 use std::os::unix::process::CommandExt;
26 let parent = std::process::id();
27 unsafe {
29 command.pre_exec(move || {
30 if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL) < 0 {
31 return Err(std::io::Error::last_os_error());
32 }
33 if libc::getppid() != parent as libc::pid_t {
34 libc::_exit(1);
35 }
36 Ok(())
37 });
38 }
39 }
40 command
41}
42pub fn spawn_owned(command: Command) -> std::io::Result<Child> {
45 type Request = (Command, std::sync::mpsc::SyncSender<std::io::Result<Child>>);
46 static SPAWNER: std::sync::OnceLock<std::sync::mpsc::Sender<Request>> =
47 std::sync::OnceLock::new();
48 let sender = SPAWNER.get_or_init(|| {
49 let (sender, receiver) = std::sync::mpsc::channel::<Request>();
50 thread::Builder::new()
51 .name("radio-process-spawner".into())
52 .spawn(move || {
53 for (mut command, reply) in receiver {
54 let child = owned_child(&mut command).spawn();
55 if let Err(error) = reply.send(child)
56 && let Ok(mut child) = error.0
57 {
58 let _ = child.kill();
59 let _ = child.wait();
60 }
61 }
62 })
63 .expect("cannot start process supervisor");
64 sender
65 });
66 let (reply, result) = std::sync::mpsc::sync_channel(1);
67 sender
68 .send((command, reply))
69 .map_err(|_| std::io::Error::other("process supervisor stopped"))?;
70 result
71 .recv()
72 .map_err(|_| std::io::Error::other("process supervisor stopped"))?
73}
74
75impl MediaLock {
76 pub fn acquire(dir: &Path) -> Result<Self> {
77 let file = OpenOptions::new()
78 .create(true)
79 .truncate(false)
80 .read(true)
81 .write(true)
82 .open(dir.join("media.lock"))?;
83 file.try_lock_exclusive()
84 .context(DomainError::new(ErrorCode::MediaBusy))?;
85 Ok(Self { _file: file })
86 }
87}
88
89impl Drop for MediaLock {
90 fn drop(&mut self) {
91 let _ = fs2::FileExt::unlock(&self._file);
95 }
96}
97
98pub fn drain(mut reader: impl Read + Send + 'static, cap: usize) -> thread::JoinHandle<Vec<u8>> {
99 thread::spawn(move || {
100 let mut result = Vec::new();
101 let mut buf = [0u8; 4096];
102 while let Ok(n) = reader.read(&mut buf) {
103 if n == 0 {
104 break;
105 }
106 let room = cap.saturating_sub(result.len());
107 result.extend_from_slice(&buf[..n.min(room)]);
108 }
109 result
110 })
111}
112
113pub fn wait_until(child: &mut Child, timeout: Duration, stop: &AtomicBool) -> Result<ExitStatus> {
114 let deadline = Instant::now() + timeout;
115 loop {
116 if let Some(status) = child.try_wait()? {
117 return Ok(status);
118 }
119 if stop.load(Ordering::Relaxed) || Instant::now() >= deadline {
120 let _ = child.kill();
121 let _ = child.wait();
122 bail!(DomainError::new(ErrorCode::ProcessTimeout));
123 }
124 thread::sleep(Duration::from_millis(30));
125 }
126}
127
128pub fn output(command: &mut Command, timeout: Duration, stop: &Arc<AtomicBool>) -> Result<Vec<u8>> {
129 command
130 .stdin(Stdio::null())
131 .stdout(Stdio::piped())
132 .stderr(Stdio::piped());
133 let configured = std::mem::replace(command, Command::new("unused"));
135 let program = configured.get_program().to_string_lossy().into_owned();
136 let mut child = spawn_owned(configured)
137 .context(DomainError::new(ErrorCode::MissingDependency).with("program", program))?;
138 let stdout = drain(child.stdout.take().unwrap(), 256 * 1024);
139 let stderr = drain(child.stderr.take().unwrap(), 16 * 1024);
140 let status = wait_until(&mut child, timeout, stop);
141 let data = stdout.join().unwrap_or_default();
142 let error = stderr.join().unwrap_or_default();
143 if !status?.success() {
144 bail!(DomainError::new(ErrorCode::ProcessFailed).with(
145 "reason",
146 crate::clean_text(&String::from_utf8_lossy(&error))
147 ));
148 }
149 Ok(data)
150}
151
152pub struct Background<T> {
155 cancel: Arc<AtomicBool>,
156 result: std::sync::mpsc::Receiver<Result<T>>,
157}
158impl<T: Send + 'static> Background<T> {
159 pub fn start(
160 name: &str,
161 work: impl FnOnce(Arc<AtomicBool>) -> Result<T> + Send + 'static,
162 ) -> Result<Self> {
163 let cancel = Arc::new(AtomicBool::new(false));
164 let flag = cancel.clone();
165 let (sender, result) = std::sync::mpsc::sync_channel(1);
166 thread::Builder::new().name(name.into()).spawn(move || {
167 let _ = sender.send(work(flag));
168 })?;
169 Ok(Self { cancel, result })
170 }
171 pub fn poll(&self) -> Option<Result<T>> {
172 match self.result.try_recv() {
173 Ok(value) => Some(value),
174 Err(std::sync::mpsc::TryRecvError::Empty) => None,
175 Err(std::sync::mpsc::TryRecvError::Disconnected) => Some(Err(anyhow::anyhow!(
176 DomainError::new(ErrorCode::BackgroundFailed)
177 ))),
178 }
179 }
180
181 pub(crate) fn cancel(&self) {
182 self.cancel.store(true, Ordering::Relaxed);
183 }
184}
185impl<T> Drop for Background<T> {
186 fn drop(&mut self) {
187 self.cancel.store(true, Ordering::Relaxed);
188 }
189}