253 lines
9.4 KiB
Rust
253 lines
9.4 KiB
Rust
//! systemd unit for the supervisor (`leleka run`). One unit runs the whole service; the supervisor owns the
|
|
//! engine, gateway and API children, restarts the engine without copying the archive again, and drains on
|
|
//! SIGTERM/SIGINT.
|
|
use std::path::Path;
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub enum UnitScope {
|
|
/// `/etc/systemd/system`, started at boot, `User=` the owner of the state directory.
|
|
System,
|
|
/// `~/.config/systemd/user`; needs `loginctl enable-linger USER` to start without a login session.
|
|
User,
|
|
}
|
|
|
|
fn quote(path: &Path) -> Result<String, String> {
|
|
let text = path.to_str().ok_or("path is not UTF-8")?;
|
|
if !text.starts_with('/')
|
|
|| text
|
|
.chars()
|
|
.any(|c| c.is_control() || c == '"' || c == '\\' || c == '%' || c == '$')
|
|
{
|
|
return Err(format!(
|
|
"path {text:?} cannot be used in a unit file (must be absolute without quotes, %, $ or control characters)"
|
|
));
|
|
}
|
|
Ok(if text.contains(' ') {
|
|
format!("\"{text}\"")
|
|
} else {
|
|
text.to_owned()
|
|
})
|
|
}
|
|
|
|
/// Render the unit. `user` is only used for the system scope.
|
|
pub fn render(
|
|
scope: UnitScope,
|
|
prefix: &Path,
|
|
state: &Path,
|
|
user: Option<&str>,
|
|
) -> Result<String, String> {
|
|
let bin = quote(&prefix.join("bin/leleka"))?;
|
|
let config = quote(&state.join("leleka.json"))?;
|
|
let env_file = quote(&state.join("runtime.env"))?;
|
|
let state_q = quote(state)?;
|
|
let prefix_q = quote(prefix)?;
|
|
let lab_q = quote(&state.join("lab-mode"))?;
|
|
let mut unit = unit_section(&state_q, &prefix_q, &lab_q);
|
|
unit.push_str(&service_section(scope, user, &env_file, &bin, &config)?);
|
|
unit.push_str("[Install]\n");
|
|
unit.push_str(match scope {
|
|
UnitScope::System => "WantedBy=multi-user.target\n",
|
|
UnitScope::User => "WantedBy=default.target\n",
|
|
});
|
|
Ok(unit)
|
|
}
|
|
|
|
/// The header and the `[Unit]` section.
|
|
fn unit_section(state_q: &str, prefix_q: &str, lab_q: &str) -> String {
|
|
let mut unit = String::new();
|
|
unit.push_str("# Generated by `leleka up`; edit the run configuration, not this file.\n");
|
|
unit.push_str("[Unit]\n");
|
|
unit.push_str("Description=Leleka runtime (engine, gateway and API on loopback)\n");
|
|
unit.push_str("Documentation=https://github.com/paveldhq/strata-next\n");
|
|
unit.push_str("After=network.target\n");
|
|
// The model volume and the state must be mounted first; `lab-mode` in the state directory keeps the service from
|
|
// starting while the GPU belongs to the lab queue (`docs/unattended.md`).
|
|
unit.push_str(&format!("RequiresMountsFor={state_q} {prefix_q}\n"));
|
|
unit.push_str(&format!("ConditionPathExists=!{lab_q}\n"));
|
|
// Never give up for good: an unattended host must come back by itself. The delay between starts grows (30 s up to
|
|
// 10 min) so that a persistent failure does not re-read 55 GB in a tight loop.
|
|
unit.push_str("StartLimitIntervalSec=0\n\n");
|
|
unit
|
|
}
|
|
|
|
/// The `[Service]` section.
|
|
fn service_section(
|
|
scope: UnitScope,
|
|
user: Option<&str>,
|
|
env_file: &str,
|
|
bin: &str,
|
|
config: &str,
|
|
) -> Result<String, String> {
|
|
let mut unit = String::new();
|
|
unit.push_str("[Service]\n");
|
|
unit.push_str("Type=exec\n");
|
|
unit.push_str(&service_user_line(scope, user)?);
|
|
unit.push_str(&format!("EnvironmentFile={env_file}\n"));
|
|
unit.push_str("UMask=0077\nNoNewPrivileges=yes\n");
|
|
unit.push_str(&limits_and_logging(scope));
|
|
unit.push_str(&format!("ExecStart={bin} run --config {config}\n"));
|
|
// A failed start must be looked at: the first start copies 55 GB. Exit 2 is a configuration error.
|
|
unit.push_str(concat!(
|
|
"Restart=on-failure\nRestartSec=30\nRestartSteps=6\n",
|
|
"RestartMaxDelaySec=600\nRestartPreventExitStatus=2\n"
|
|
));
|
|
// The supervisor turns SIGTERM into a graceful stop of the API (drain), the gateway and the engine.
|
|
unit.push_str("KillSignal=SIGTERM\nTimeoutStopSec=180\nKillMode=mixed\n\n");
|
|
Ok(unit)
|
|
}
|
|
|
|
/// `User=` for a system unit (the name is checked); nothing for a user unit.
|
|
fn service_user_line(scope: UnitScope, user: Option<&str>) -> Result<String, String> {
|
|
if scope != UnitScope::System {
|
|
return Ok(String::new());
|
|
}
|
|
let user = user.ok_or("a system unit needs a service user")?;
|
|
if user.is_empty()
|
|
|| !user
|
|
.bytes()
|
|
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.'))
|
|
{
|
|
return Err("service user must be [A-Za-z0-9_.-]+".into());
|
|
}
|
|
Ok(format!("User={user}\n"))
|
|
}
|
|
|
|
fn limits_and_logging(scope: UnitScope) -> String {
|
|
let mut unit = String::new();
|
|
// Pinned host memory (cudaHostAlloc/Register) is counted against RLIMIT_MEMLOCK on some drivers.
|
|
unit.push_str("LimitMEMLOCK=infinity\n");
|
|
// No core dump: the engine holds 100+ GB of RAM, and writing that to the root disk after a crash would stall the
|
|
// host.
|
|
unit.push_str("LimitCORE=0\nLimitNOFILE=1048576\nTasksMax=8192\n");
|
|
if scope == UnitScope::System {
|
|
// The kernel's OOM killer should look at other processes first.
|
|
unit.push_str("OOMScoreAdjust=-500\n");
|
|
}
|
|
// Bounded journal traffic; the service keeps its own rotated logs in the state directory.
|
|
unit.push_str("LogRateLimitIntervalSec=30s\nLogRateLimitBurst=1000\n");
|
|
unit
|
|
}
|
|
|
|
pub fn unit_path(
|
|
scope: UnitScope,
|
|
home: Option<&Path>,
|
|
name: &str,
|
|
) -> Result<std::path::PathBuf, String> {
|
|
match scope {
|
|
UnitScope::System => Ok(Path::new("/etc/systemd/system").join(name)),
|
|
UnitScope::User => {
|
|
let home = home.ok_or("HOME is not set")?;
|
|
Ok(home.join(".config/systemd/user").join(name))
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
// systemd unit files exist on Linux hosts only: the paths in them are Unix paths.
|
|
#[cfg(unix)]
|
|
#[test]
|
|
fn system_unit_is_complete_and_bounded() {
|
|
let unit = render(
|
|
UnitScope::System,
|
|
Path::new("/opt/leleka"),
|
|
Path::new("/var/lib/leleka/state"),
|
|
Some("leleka"),
|
|
)
|
|
.unwrap();
|
|
for needle in [
|
|
"User=leleka",
|
|
"EnvironmentFile=/var/lib/leleka/state/runtime.env",
|
|
"ExecStart=/opt/leleka/bin/leleka run --config /var/lib/leleka/state/leleka.json",
|
|
"Restart=on-failure",
|
|
"RestartPreventExitStatus=2",
|
|
"StartLimitIntervalSec=0",
|
|
"RestartSteps=6",
|
|
"RestartMaxDelaySec=600",
|
|
"ConditionPathExists=!/var/lib/leleka/state/lab-mode",
|
|
"RequiresMountsFor=/var/lib/leleka/state /opt/leleka",
|
|
"LimitCORE=0",
|
|
"OOMScoreAdjust=-500",
|
|
"LogRateLimitBurst=1000",
|
|
"LimitMEMLOCK=infinity",
|
|
"KillSignal=SIGTERM",
|
|
"WantedBy=multi-user.target",
|
|
] {
|
|
assert!(unit.contains(needle), "missing {needle}\n{unit}");
|
|
}
|
|
assert!(!unit.contains("Password") && !unit.contains("TOKEN"));
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
#[test]
|
|
fn user_unit_has_no_user_line_and_targets_default() {
|
|
let unit = render(
|
|
UnitScope::User,
|
|
Path::new("/home/p/.local/share/leleka"),
|
|
Path::new("/home/p/.local/state/leleka"),
|
|
None,
|
|
)
|
|
.unwrap();
|
|
assert!(!unit.contains("User=") && unit.contains("WantedBy=default.target"));
|
|
// A user unit cannot lower its own OOM score.
|
|
assert!(!unit.contains("OOMScoreAdjust"));
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
#[test]
|
|
fn dangerous_paths_and_users_are_refused() {
|
|
let refused = |prefix: &str, state: &str, user: Option<&str>| {
|
|
render(UnitScope::System, Path::new(prefix), Path::new(state), user).is_err()
|
|
};
|
|
assert!(refused("/opt/le%leka", "/s", Some("u")));
|
|
assert!(refused("/opt/leleka", "relative", Some("u")));
|
|
assert!(refused("/opt/leleka", "/s", Some("a b")));
|
|
assert!(refused("/opt/leleka", "/s", None));
|
|
let spaced = render(
|
|
UnitScope::User,
|
|
Path::new("/opt/my leleka"),
|
|
Path::new("/s"),
|
|
None,
|
|
)
|
|
.unwrap();
|
|
assert!(spaced.contains("\"/opt/my leleka/bin/leleka\""));
|
|
}
|
|
|
|
// `scripts/ops/leleka.service` is the unit the owner installs on the 5090 server
|
|
// (`scripts/ops/install-leleka-service.sh`). It must be exactly what `leleka up --mode system --service-user para`
|
|
// writes for the server's layout.
|
|
#[cfg(unix)]
|
|
#[test]
|
|
fn the_owner_install_unit_is_what_up_would_write_for_the_server_layout() {
|
|
let rendered = render(
|
|
UnitScope::System,
|
|
Path::new("/data/leleka-e2e/service/prefix"),
|
|
Path::new("/data/leleka-e2e/service/state"),
|
|
Some("para"),
|
|
)
|
|
.unwrap();
|
|
let shipped = include_str!("../../../scripts/ops/leleka.service").replace("\r\n", "\n");
|
|
assert_eq!(shipped, rendered);
|
|
}
|
|
|
|
#[test]
|
|
fn unit_locations() {
|
|
assert_eq!(
|
|
unit_path(UnitScope::System, None, "leleka.service").unwrap(),
|
|
Path::new("/etc/systemd/system/leleka.service")
|
|
);
|
|
assert_eq!(
|
|
unit_path(
|
|
UnitScope::User,
|
|
Some(Path::new("/home/p")),
|
|
"leleka.service"
|
|
)
|
|
.unwrap(),
|
|
Path::new("/home/p/.config/systemd/user/leleka.service")
|
|
);
|
|
assert!(unit_path(UnitScope::User, None, "x").is_err());
|
|
}
|
|
}
|