use super::*;
pub(super) fn spawn_reopen_task(
matched: Vec<ProcessInfo>,
pumps: Vec<(ProcessInfo, mpsc::Sender<LogCtl>)>,
reply: oneshot::Sender<Result<Vec<ProcessInfo>, SupervisorError>>,
) {
tokio::spawn(async move {
let mut failures = Vec::new();
for (info, log_ctl) in &pumps {
if let Err(error) = reopen_logs(log_ctl).await {
failures.push(format!("{} (id {}): {error}", info.name, info.id));
}
}
let _ = reply.send(if failures.is_empty() {
Ok(matched)
} else {
Err(SupervisorError::ReopenFailed(failures.join("; ")))
});
});
}
pub(super) async fn reopen_logs(log_ctl: &mpsc::Sender<LogCtl>) -> Result<(), ReopenError> {
let (done, ack) = oneshot::channel();
if log_ctl.send(LogCtl::Reopen { done }).await.is_err() {
return Ok(());
}
ack.await.unwrap_or(Ok(()))
}
pub(super) fn spawn_flush_task(
matched: Vec<ProcessInfo>,
pumps: Vec<mpsc::Sender<LogCtl>>,
paths: BTreeSet<PathBuf>,
reply: oneshot::Sender<Result<Vec<ProcessInfo>, SupervisorError>>,
) {
tokio::spawn(async move {
let mut failures = Vec::new();
for log_ctl in &pumps {
if let Err(error) = flush_logs(log_ctl).await {
failures.push(error.message);
}
}
for path in paths {
if let Err(error) = truncate_log(&path).await {
failures.push(error.message);
}
}
let _ = reply.send(if failures.is_empty() {
Ok(matched)
} else {
Err(SupervisorError::FlushFailed(failures.join("; ")))
});
});
}
pub(super) async fn flush_logs(log_ctl: &mpsc::Sender<LogCtl>) -> Result<(), FlushError> {
let (done, ack) = oneshot::channel();
if log_ctl.send(LogCtl::Flush { done }).await.is_err() {
return Ok(());
}
ack.await.unwrap_or(Ok(()))
}
pub(super) async fn truncate_log(path: &Path) -> Result<(), FlushError> {
let refused = |error: &dyn fmt::Display| FlushError {
message: format!("{}: {error}", path.display()),
};
if let Err(error) = check_log_ancestry(path) {
return Err(refused(&error));
}
let mut options = tokio::fs::OpenOptions::new();
options.write(true).truncate(true);
match open_log_path(&mut options, path).await {
Ok(_) => Ok(()),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(refused(&error)),
}
}