mod job;
#[cfg(any(target_os = "macos", target_os = "linux"))]
pub mod lines;
#[cfg(any(target_os = "macos", target_os = "linux", test))]
pub mod loaded;
#[cfg(any(target_os = "macos", test))]
pub mod plist;
#[cfg(any(target_os = "macos", target_os = "linux", test))]
pub mod read_back;
#[cfg(any(target_os = "linux", test))]
pub mod unit;
#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
mod unsupported;
#[cfg(target_os = "linux")]
use linux as platform;
#[cfg(target_os = "macos")]
use macos as platform;
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
use unsupported as platform;
use std::path::PathBuf;
use anyhow::Result;
#[cfg(any(target_os = "macos", target_os = "linux"))]
use serde::Serialize;
use crate::home::Home;
pub use job::{APPROVALS, Job, PROXY};
#[cfg(all(any(target_os = "macos", target_os = "linux"), debug_assertions))]
pub(crate) fn skip_exec() -> bool {
std::env::var_os("MOAT_SERVICE_SKIP_EXEC").is_some_and(|v| v == "1")
}
#[cfg(all(any(target_os = "macos", target_os = "linux"), not(debug_assertions)))]
pub(crate) fn skip_exec() -> bool {
false
}
#[cfg(any(target_os = "macos", target_os = "linux"))]
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "state", rename_all = "kebab-case")]
pub enum State {
NotInstalled,
Stopped,
Running,
DriftBlocked,
Crashlooping,
Unknown { details: String },
}
#[cfg(any(target_os = "macos", target_os = "linux"))]
impl State {
pub fn describe(&self, job: &Job, path: &std::path::Path) -> String {
match self {
Self::NotInstalled => {
format!(
"not installed; `{}` keeps {} running",
job.install, job.noun
)
}
Self::Stopped => format!("installed but stopped ({})", path.display()),
Self::Running => format!("installed and running ({})", path.display()),
Self::DriftBlocked => format!("installed; {} ({})", job.exit_64, path.display()),
Self::Crashlooping => format!(
"installed; restart budget exhausted. Check the service log, then \
`{}` to retry ({})",
job.install,
path.display()
),
Self::Unknown { details } => format!("installed; state unknown: {details}"),
}
}
}
pub trait Manager {
fn install(&self, binary: &std::path::Path, moat_home: &std::path::Path) -> Result<PathBuf>;
fn uninstall(&self) -> Result<Option<PathBuf>>;
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn file_path(&self) -> Result<PathBuf>;
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn render(&self, binary: &std::path::Path, moat_home: &std::path::Path) -> Result<String>;
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn environment(&self) -> fn(&str) -> Option<Vec<String>>;
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn job(&self) -> &'static Job;
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn started_as_service(&self, program: &[String]) -> Result<()>;
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn state(&self) -> Result<State>;
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn restart(&self) -> Result<()>;
}
pub fn manager(home: &Home, job: &'static Job) -> Result<Box<dyn Manager>> {
platform::manager(home, job)
}
#[cfg(any(target_os = "macos", target_os = "linux"))]
pub fn read_back(
manager: &dyn Manager,
binary: &std::path::Path,
moat_home: &std::path::Path,
) -> Vec<String> {
let Ok(path) = manager.file_path() else {
return Vec::new();
};
let text = match std::fs::read(&path) {
Ok(text) => text,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Vec::new(),
Err(e) => return vec![format!("cannot be read: {e}")],
};
let expected = match manager.render(binary, moat_home) {
Ok(expected) => expected,
Err(e) => return vec![format!("cannot be compared: {e:#}")],
};
let installed = read_back::Installed {
text: &text,
mode: mode(&path),
};
read_back::findings(&expected, &installed, manager.environment(), manager.job())
}
#[cfg(any(target_os = "macos", target_os = "linux"))]
pub fn check_started(home: &Home, job: &'static Job) -> Result<()> {
use anyhow::bail;
let manager = manager(home, job)?;
let path = manager.file_path()?;
if !path.exists() {
bail!(
"no service is installed at {}; `{}` installs it, and a person runs \
`openmoat {}` in a terminal",
path.display(),
job.install,
job.terminal
);
}
let findings = lines::findings(home, manager.as_ref());
if !findings.is_empty() {
bail!(
"refusing to run from the service file {}: it {}; `{}` writes it again",
path.display(),
findings.join("; it "),
job.install
);
}
let binary = crate::install::hook_binary()?;
let program: Vec<String> = std::iter::once(binary.to_string_lossy().into_owned())
.chain(job.args.iter().map(|a| (*a).to_owned()))
.collect();
manager.started_as_service(&program)
}
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
pub fn check_started(_home: &Home, job: &'static Job) -> Result<()> {
anyhow::bail!(
"no user service on {}; run `openmoat {}` in a terminal",
std::env::consts::OS,
job.terminal
)
}
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn log_paths(job: &Job) -> Result<(PathBuf, PathBuf)> {
let logs = Home::locate()?.root().join("logs");
Ok((
logs.join(format!("{}.out.log", job.log)),
logs.join(format!("{}.err.log", job.log)),
))
}
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn prepare_logs(job: &Job) -> Result<()> {
use std::os::unix::fs::{OpenOptionsExt as _, PermissionsExt as _};
use anyhow::Context as _;
let (stdout, stderr) = log_paths(job)?;
let Some(dir) = stdout.parent() else {
return Ok(());
};
std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
if !job.private {
return Ok(());
}
for path in [&stdout, &stderr] {
std::fs::OpenOptions::new()
.append(true)
.create(true)
.mode(0o600)
.open(path)
.with_context(|| format!("creating {}", path.display()))?;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))
.with_context(|| format!("making {} readable by your account alone", path.display()))?;
}
Ok(())
}
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn mode(path: &std::path::Path) -> Option<u32> {
use std::os::unix::fs::PermissionsExt as _;
std::fs::metadata(path).ok().map(|m| m.permissions().mode())
}
pub fn display_name() -> &'static str {
platform::DISPLAY
}
#[cfg(all(test, any(target_os = "macos", target_os = "linux")))]
mod tests {
use super::*;
#[test]
fn state_describe_names_the_fix_for_each_variant() {
let path = std::path::Path::new("/x/plist");
let describe = |state: State| state.describe(&PROXY, path);
assert!(describe(State::NotInstalled).contains("not installed"));
assert!(describe(State::Stopped).contains("stopped"));
assert!(describe(State::Running).contains("running"));
assert!(describe(State::DriftBlocked).contains("drift"));
assert!(describe(State::Crashlooping).contains("restart"));
assert!(
describe(State::Unknown {
details: "no bus".into(),
})
.contains("no bus")
);
let listener = State::NotInstalled.describe(&APPROVALS, path);
assert!(listener.contains("`openmoat approvals install` keeps the listener"));
let stopped = State::DriftBlocked.describe(&APPROVALS, path);
assert!(stopped.contains("its log says why") && !stopped.contains("drift"));
}
}