Files
leleka/control-plane/src/embedded_engine.rs
T
Pavlo Ratushnyi 4013e0c9bd
Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
Import tracked Strata Next source snapshot
2026-10-05 18:15:08 +02:00

134 lines
4.7 KiB
Rust

//! Opt-in packaged worker. The host still supplies the ELF's shared libraries.
use std::{error::Error, ffi::OsStr, fs::File, path::PathBuf};
mod payload {
include!(concat!(env!("OUT_DIR"), "/embedded-engine.rs"));
}
pub fn info() -> serde_json::Value {
serde_json::json!({
"embedded": !payload::BYTES.is_empty(),
"bytes": payload::BYTES.len(),
"sha256": (!payload::BYTES.is_empty()).then_some(payload::SHA256),
"declared_source_revision": (!payload::BYTES.is_empty()).then_some(payload::SOURCE_REVISION),
"target_os": std::env::consts::OS,
"target_arch": std::env::consts::ARCH,
"shared_libraries_bundled": false,
"model_bundled": false,
"selection": "engine.executable=@embedded",
})
}
/// Holds the anonymous executable alive for initial spawn and all worker restarts.
pub struct EmbeddedEngine {
_file: File,
pub executable: PathBuf,
}
pub fn resolve(executable: &OsStr) -> Result<Option<EmbeddedEngine>, Box<dyn Error>> {
if executable != OsStr::new("@embedded") {
return Ok(None);
}
if payload::BYTES.is_empty() {
return Err(
"this binary has no embedded engine; use an external executable or a payload build"
.into(),
);
}
materialize(payload::BYTES).map(Some)
}
/// Explicit loader/help probe; this is not an inference or readiness check.
pub fn help() -> Result<(), Box<dyn Error>> {
let engine = resolve(OsStr::new("@embedded"))?.ok_or("no embedded engine")?;
let status = std::process::Command::new(&engine.executable)
.arg("--help")
.env("CUDA_VISIBLE_DEVICES", "")
.status()?;
if !status.success() {
return Err(format!("embedded engine help exited with {status}").into());
}
Ok(())
}
#[cfg(not(target_os = "linux"))]
fn materialize(_: &[u8]) -> Result<EmbeddedEngine, Box<dyn Error>> {
Err("embedded worker execution requires Linux".into())
}
#[cfg(target_os = "linux")]
fn materialize(bytes: &[u8]) -> Result<EmbeddedEngine, Box<dyn Error>> {
use std::{
io::Write,
os::fd::{AsRawFd, FromRawFd},
};
// SAFETY: constant NUL-terminated name, supported flags, no borrowed pointers retained.
let mut fd = unsafe {
libc::memfd_create(
c"strata-engine".as_ptr(),
libc::MFD_CLOEXEC | libc::MFD_ALLOW_SEALING | libc::MFD_EXEC,
)
};
if fd < 0 && std::io::Error::last_os_error().raw_os_error() == Some(libc::EINVAL) {
// Older kernels do not know MFD_EXEC. Do not retry EPERM/EACCES policy failures.
// SAFETY: same constant name; legacy flags have been available since Linux 3.17.
fd = unsafe {
libc::memfd_create(
c"strata-engine".as_ptr(),
libc::MFD_CLOEXEC | libc::MFD_ALLOW_SEALING,
)
};
}
if fd < 0 {
return Err(std::io::Error::last_os_error().into());
}
// SAFETY: successful memfd_create transfers a new owned fd exactly once.
let mut file = unsafe { File::from_raw_fd(fd) };
file.write_all(bytes)?;
let seals = libc::F_SEAL_WRITE | libc::F_SEAL_GROW | libc::F_SEAL_SHRINK | libc::F_SEAL_SEAL;
// SAFETY: valid owned fd, integer fcntl argument for F_ADD_SEALS.
if unsafe { libc::fcntl(file.as_raw_fd(), libc::F_ADD_SEALS, seals) } < 0 {
return Err(std::io::Error::last_os_error().into());
}
// Use the parent's fd path: CLOEXEC does not need to leak a descriptor to children.
let executable = PathBuf::from(format!(
"/proc/{}/fd/{}",
std::process::id(),
file.as_raw_fd()
));
Ok(EmbeddedEngine {
_file: file,
executable,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn external_selection_never_materializes_an_engine() {
assert!(resolve(OsStr::new("/external/strata")).unwrap().is_none());
assert_eq!(info()["shared_libraries_bundled"], false);
if payload::BYTES.is_empty() {
assert!(resolve(OsStr::new("@embedded")).is_err());
}
}
#[cfg(target_os = "linux")]
#[test]
fn sealed_payload_is_exact_immutable_and_removed_on_drop() {
use std::io::Write;
let engine = materialize(b"immutable fixture bytes").unwrap();
let path = engine.executable.clone();
assert_eq!(std::fs::read(&path).unwrap(), b"immutable fixture bytes");
let mut other = std::fs::OpenOptions::new().write(true).open(&path).unwrap();
assert!(other.write_all(b"x").is_err());
assert!(other.set_len(0).is_err());
assert!(other.set_len(100).is_err());
drop(other);
drop(engine);
assert!(!path.exists());
}
}