Files
leleka/control-plane/src/service_unit.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 72fc3b0820 style: cargo fmt on strata-control, strata-desktop-core, leleka-runtime-client; clear Clippy lints and two red tests on main
Mechanical rustfmt (control-plane, desktop-core and the runtime client had 360 hunks of drift; the CI format steps for control-plane and
desktop-core were red), plus, found by running `cargo clippy -D warnings` and the tests on Linux:
* control-plane/tests/log_failure_sse.rs `no_panicking_log_macros_in_the_serving_crate` was red on main since the observability merge: two
  test-only `eprintln!` samples (prometheus.rs, request_log.rs) trip its source scan. They now write to stderr with `write_fmt` and
  ignore a failed write, which is what the test asks for; the output is the same.
* tool_output.rs `is_multiple_of(2)`, an unneeded `mut` in a control-plane test, a collapsible `if` in leleka-inference.rs,
  `#[allow(dead_code)]` on observer_adaptive_slots (compiled into leleka-inference-evaluation too).
* crates/deploy/src/facts.rs: `lab_holder_running` moved above `mod tests` (clippy::items_after_test_module); code moved, not changed.
Kept as its own commit so it can be redone with `cargo fmt` if other branches touch these crates first. No behaviour change.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-03 00:30:27 +01:00

137 lines
4.7 KiB
Rust

//! Render only: installation and lifecycle remain explicit operator actions.
use std::path::Path;
pub fn render(
executable: &Path,
config: &Path,
working_dir: &Path,
env_file: Option<&Path>,
) -> Result<String, String> {
let executable = checked_path(executable, false)?;
if executable.contains(['\'', '"', '\\']) {
return Err(
"systemd executable paths cannot contain quotes or backslashes; relocate the binary"
.into(),
);
}
let executable = quote(&executable);
let config = quote(&checked_path(config, false)?);
checked_path(working_dir, true)?;
let canonical_dir = working_dir.canonicalize().map_err(|e| e.to_string())?;
// These path directives are not shell-style token lists. Quotes and
// backslashes are literal; a final '/.' prevents line continuation/trim.
let working_dir = format!(
"{}/.",
checked_path(&canonical_dir, true)?.trim_end_matches('/')
)
.replace('%', "%%");
let environment = match env_file {
Some(path) => {
let value = checked_path(path, false)?;
// EnvironmentFile supports globs. Fail rather than load a different
// file, or silently treat a missing optional file as success.
if value.contains(['*', '?', '[', '\\']) || value.ends_with(char::is_whitespace) {
return Err("environment-file paths cannot contain glob characters/backslashes or end in whitespace".into());
}
format!("EnvironmentFile={}\n", value.replace('%', "%%"))
}
None => String::new(),
};
// ':' disables ExecStart environment-variable substitution; %% escapes
// specifiers. Do not wrap this in a shell or reset the worker restart budget.
Ok(format!(
"# Generated by strata-next service-unit; install as a user unit.\n\
[Unit]\n\
Description=Strata Next native Responses runtime\n\
\n\
[Service]\n\
Type=exec\n\
WorkingDirectory={working_dir}\n\
{environment}\
ExecStart=:{executable} serve --config {config}\n\
UMask=0077\n\
NoNewPrivileges=yes\n\
KillSignal=SIGTERM\n\
KillMode=mixed\n\
TimeoutStopSec=45\n\
SendSIGKILL=yes\n\
Restart=no\n\
StandardOutput=journal\n\
StandardError=journal\n\
\n\
[Install]\n\
WantedBy=default.target\n"
))
}
fn checked_path(path: &Path, directory: bool) -> Result<String, String> {
let value = path.to_str().ok_or("service paths must be valid UTF-8")?;
if !path.is_absolute() || value.chars().any(char::is_control) {
return Err("service paths must be absolute and contain no control characters".into());
}
if if directory {
!path.is_dir()
} else {
!path.is_file()
} {
return Err(format!(
"service path has wrong type or does not exist: {value}"
));
}
Ok(value.to_owned())
}
fn quote(value: &str) -> String {
format!(
"\"{}\"",
value
.replace('\\', "\\\\")
.replace('"', "\\\"")
.replace('%', "%%")
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn special_characters_are_literal() {
assert_eq!(
quote("/srv/a b/%n/${HOME}/\"quoted\"/back\\slash"),
"\"/srv/a b/%%n/${HOME}/\\\"quoted\\\"/back\\\\slash\""
);
}
#[test]
fn refuses_relative_control_and_missing_paths() {
for path in ["relative.json", "/tmp/line\nbreak", "/tmp/zero\0byte"] {
assert!(checked_path(Path::new(path), false).is_err());
}
let missing = std::env::temp_dir().join(format!(
"strata-service-missing-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
assert!(checked_path(&missing, false).is_err());
}
#[cfg(unix)] // systemd unit text
#[test]
fn render_does_not_require_or_launch_an_engine() {
let executable = std::env::current_exe().unwrap();
let directory = executable.parent().unwrap();
let unit = render(&executable, &executable, directory, Some(&executable)).unwrap();
assert!(unit.contains("ExecStart=:"));
assert!(unit.contains(" serve --config "));
assert!(unit.contains("EnvironmentFile="));
assert!(unit.contains("KillMode=mixed\nTimeoutStopSec=45\n"));
assert!(unit.contains("Restart=no\n"));
assert!(render(&executable, directory, directory, None).is_err());
assert!(render(&executable, &executable, &executable, None).is_err());
}
}