152 lines
5.5 KiB
Rust
152 lines
5.5 KiB
Rust
//! Opt-in packaged worker. The host still supplies the ELF's shared libraries.
|
|
use std::{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>, crate::BoxError> {
|
|
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<(), crate::BoxError> {
|
|
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, crate::BoxError> {
|
|
Err("embedded worker execution requires Linux".into())
|
|
}
|
|
|
|
#[cfg(target_os = "linux")]
|
|
fn materialize(bytes: &[u8]) -> Result<EmbeddedEngine, crate::BoxError> {
|
|
use std::{
|
|
io::Write,
|
|
os::fd::{AsRawFd, FromRawFd},
|
|
};
|
|
let fd = create_memfd();
|
|
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,
|
|
})
|
|
}
|
|
|
|
/// The raw `memfd_create` result (negative on failure, errno set), retrying without `MFD_EXEC` on old kernels.
|
|
#[cfg(target_os = "linux")]
|
|
fn create_memfd() -> libc::c_int {
|
|
// SAFETY: constant NUL-terminated name, supported flags, no borrowed pointers retained.
|
|
let 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.
|
|
return unsafe {
|
|
libc::memfd_create(
|
|
c"strata-engine".as_ptr(),
|
|
libc::MFD_CLOEXEC | libc::MFD_ALLOW_SEALING,
|
|
)
|
|
};
|
|
}
|
|
fd
|
|
}
|
|
|
|
#[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, os::unix::fs::MetadataExt};
|
|
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());
|
|
// Keep a witness open so this inode cannot be recycled during the check.
|
|
// Parallel tests can reuse the original descriptor number after Drop.
|
|
let original = other.metadata().unwrap();
|
|
assert_eq!(std::fs::metadata(&path).unwrap().ino(), original.ino());
|
|
drop(engine);
|
|
match std::fs::metadata(&path) {
|
|
Ok(current) => assert_ne!(
|
|
(current.dev(), current.ino()),
|
|
(original.dev(), original.ino()),
|
|
"original descriptor still refers to the payload after Drop"
|
|
),
|
|
Err(error) => assert_eq!(error.kind(), std::io::ErrorKind::NotFound),
|
|
}
|
|
drop(other);
|
|
}
|
|
}
|