use std::collections::HashMap;
use std::process::Stdio;
use std::sync::Arc;
use async_trait::async_trait;
use tokio::process::{Child, Command};
use tokio::sync::Mutex;
use tracing::{instrument, warn};
use windows::Win32::Foundation::HANDLE;
use cellos_core::ports::{CellBackend, CellHandle, TeardownReport};
use cellos_core::{CellosError, ExecutionCellDocument, RunCpuMax, SecretDeliveryMode};
use crate::job::JobObject;
const FIXED_PATH: &str = r"C:\Windows\System32;C:\Windows";
const DEFAULT_CPU_PERIOD_MICROS: u64 = 100_000;
struct TrackedCell {
child: Option<Child>,
job: JobObject,
}
pub struct WindowsCellBackend {
tracked: Arc<Mutex<HashMap<String, TrackedCell>>>,
}
impl Default for WindowsCellBackend {
fn default() -> Self {
Self::new()
}
}
impl WindowsCellBackend {
pub fn new() -> Self {
Self {
tracked: Arc::new(Mutex::new(HashMap::new())),
}
}
pub async fn tracked_cell_count(&self) -> usize {
self.tracked.lock().await.len()
}
pub async fn has_tracked_state(&self, cell_id: &str) -> bool {
self.tracked.lock().await.contains_key(cell_id)
}
}
fn cpu_rate_hundredths_percent(cpu: &RunCpuMax) -> Option<u32> {
let period = cpu.period_micros.unwrap_or(DEFAULT_CPU_PERIOD_MICROS);
if period == 0 {
return None;
}
let hundredths = (cpu.quota_micros as u128 * 10_000) / period as u128;
Some(hundredths.clamp(1, 10_000) as u32)
}
#[async_trait]
impl CellBackend for WindowsCellBackend {
#[instrument(skip(self, spec), fields(cell_id = %spec.spec.id))]
async fn create(&self, spec: &ExecutionCellDocument) -> Result<CellHandle, CellosError> {
let cell_id = spec.spec.id.clone();
if cell_id.is_empty() {
return Err(CellosError::InvalidSpec("spec.id must be non-empty".into()));
}
let run = spec.spec.run.as_ref();
if let Some(run) = run {
let has_secret_refs = spec
.spec
.authority
.secret_refs
.as_ref()
.is_some_and(|r| !r.is_empty());
if matches!(run.secret_delivery, SecretDeliveryMode::Env) && has_secret_refs {
return Err(CellosError::InvalidSpec(
"windows backend: secretDelivery=env with secretRefs is unsupported \
(this backend owns execution; use a broker-socket delivery mode such as \
the default runtimeLeasedBroker)"
.into(),
));
}
}
if spec
.spec
.authority
.egress_rules
.as_ref()
.is_some_and(|r| !r.is_empty())
{
warn!(
target: "cellos.host.windows",
cell_id = %cell_id,
"spec declares authority.egressRules but the Windows backend does NOT enforce \
network egress (no nft equivalent); rules are advisory only on this host"
);
}
let mut tracked = self.tracked.lock().await;
if tracked.contains_key(&cell_id) {
return Err(CellosError::Host(format!(
"cell id {cell_id:?} already active on host (no duplicate live cells)"
)));
}
let limits = run.and_then(|r| r.limits.as_ref());
let memory_max_bytes = limits.and_then(|l| l.memory_max_bytes);
let cpu_rate = limits
.and_then(|l| l.cpu_max.as_ref())
.and_then(cpu_rate_hundredths_percent);
let job = JobObject::create(memory_max_bytes, cpu_rate)?;
let child = match run {
Some(r) if !r.argv.is_empty() => {
let mut cmd = Command::new(&r.argv[0]);
if r.argv.len() > 1 {
cmd.args(&r.argv[1..]);
}
cmd.env_clear();
cmd.env("PATH", FIXED_PATH);
if let Some(wd) = &r.working_directory {
cmd.current_dir(wd);
}
cmd.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
let child = cmd.spawn().map_err(|e| {
CellosError::Host(format!("windows: spawn {:?} failed: {e}", r.argv[0]))
})?;
match child.raw_handle() {
Some(raw) => job.assign(HANDLE(raw))?,
None => {
return Err(CellosError::Host(
"windows: child raw handle unavailable; cannot assign to job".into(),
));
}
}
Some(child)
}
_ => None,
};
tracked.insert(cell_id.clone(), TrackedCell { child, job });
drop(tracked);
Ok(CellHandle {
cell_id,
cgroup_path: None,
nft_rules_applied: None,
kernel_digest_sha256: None,
rootfs_digest_sha256: None,
firecracker_digest_sha256: None,
})
}
#[instrument(skip(self))]
async fn wait_for_in_vm_exit(&self, cell_id: &str) -> Option<Result<i32, CellosError>> {
let mut tracked = self.tracked.lock().await;
match tracked.get(cell_id) {
Some(t) if t.child.is_some() => {}
_ => return None,
}
let mut entry = tracked.remove(cell_id).expect("entry present above");
drop(tracked);
let mut child = entry.child.take().expect("child present above");
let status = match child.wait().await {
Ok(s) => s,
Err(e) => {
return Some(Err(CellosError::Host(format!(
"windows: wait for workload of {cell_id}: {e}"
))));
}
};
Some(Ok(status.code().unwrap_or(-1)))
}
#[instrument(skip(self, handle), fields(cell_id = %handle.cell_id))]
async fn destroy(&self, handle: &CellHandle) -> Result<TeardownReport, CellosError> {
let mut tracked = self.tracked.lock().await;
let entry = tracked.remove(&handle.cell_id);
let peers_tracked_after = tracked.len();
drop(tracked);
if let Some(t) = entry {
if let Err(e) = t.job.terminate(1) {
warn!(
target: "cellos.host.windows",
cell_id = %handle.cell_id,
error = %e,
"TerminateJobObject failed (continuing; kill-on-close will still fire on drop)"
);
}
}
Ok(TeardownReport {
cell_id: handle.cell_id.clone(),
destroyed: true,
peers_tracked_after,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
fn doc_with_run(id: &str, argv: &[&str]) -> ExecutionCellDocument {
serde_json::from_value(serde_json::json!({
"apiVersion": "cellos.io/v1",
"kind": "ExecutionCell",
"spec": {
"id": id,
"authority": { "secretRefs": [] },
"lifetime": { "ttlSeconds": 60 },
"run": { "argv": argv }
}
}))
.unwrap()
}
fn doc_no_run(id: &str) -> ExecutionCellDocument {
serde_json::from_value(serde_json::json!({
"apiVersion": "cellos.io/v1",
"kind": "ExecutionCell",
"spec": {
"id": id,
"authority": { "secretRefs": [] },
"lifetime": { "ttlSeconds": 60 }
}
}))
.unwrap()
}
#[test]
fn cpu_rate_translation() {
assert_eq!(
cpu_rate_hundredths_percent(&RunCpuMax {
quota_micros: 50_000,
period_micros: Some(100_000)
}),
Some(5_000)
);
assert_eq!(
cpu_rate_hundredths_percent(&RunCpuMax {
quota_micros: 100_000,
period_micros: None
}),
Some(10_000)
);
assert_eq!(
cpu_rate_hundredths_percent(&RunCpuMax {
quota_micros: 1_000_000,
period_micros: Some(100_000)
}),
Some(10_000)
);
assert_eq!(
cpu_rate_hundredths_percent(&RunCpuMax {
quota_micros: 10,
period_micros: Some(0)
}),
None
);
}
#[tokio::test]
async fn empty_id_rejected() {
let host = WindowsCellBackend::new();
let err = host.create(&doc_no_run("")).await.unwrap_err();
assert!(matches!(err, CellosError::InvalidSpec(_)));
}
#[tokio::test]
async fn duplicate_id_rejected() {
let host = WindowsCellBackend::new();
let doc = doc_with_run("dup", &["cmd.exe", "/c", "ping -n 30 127.0.0.1 >NUL"]);
let h = host.create(&doc).await.unwrap();
let err = host.create(&doc).await.unwrap_err();
assert!(matches!(err, CellosError::Host(_)));
host.destroy(&h).await.unwrap();
}
#[tokio::test]
async fn env_secret_delivery_with_refs_refused() {
let host = WindowsCellBackend::new();
let doc: ExecutionCellDocument = serde_json::from_value(serde_json::json!({
"apiVersion": "cellos.io/v1",
"kind": "ExecutionCell",
"spec": {
"id": "secret-env",
"authority": { "secretRefs": ["db/password"] },
"lifetime": { "ttlSeconds": 60 },
"run": { "argv": ["cmd.exe", "/c", "exit 0"], "secretDelivery": "env" }
}
}))
.unwrap();
let err = host.create(&doc).await.unwrap_err();
assert!(matches!(err, CellosError::InvalidSpec(_)));
}
#[tokio::test]
async fn workload_runs_and_exit_code_is_surfaced() {
let host = WindowsCellBackend::new();
let doc = doc_with_run("rc", &["cmd.exe", "/c", "exit 7"]);
let h = host.create(&doc).await.unwrap();
assert_eq!(host.tracked_cell_count().await, 1);
let code = host.wait_for_in_vm_exit("rc").await;
assert_eq!(code.unwrap().unwrap(), 7);
assert_eq!(host.tracked_cell_count().await, 0);
let report = host.destroy(&h).await.unwrap();
assert!(report.destroyed);
assert_eq!(report.peers_tracked_after, 0);
}
#[tokio::test]
async fn destroy_before_exit_kills_tree_and_clears_residue() {
let host = WindowsCellBackend::new();
let doc = doc_with_run("kill-me", &["cmd.exe", "/c", "ping -n 60 127.0.0.1 >NUL"]);
let h = host.create(&doc).await.unwrap();
assert_eq!(host.tracked_cell_count().await, 1);
let report = host.destroy(&h).await.unwrap();
assert!(report.destroyed);
assert_eq!(report.peers_tracked_after, 0);
assert!(!host.has_tracked_state("kill-me").await);
}
#[tokio::test]
async fn peers_tracked_after_counts_remaining() {
let host = WindowsCellBackend::new();
let a = host
.create(&doc_with_run(
"a",
&["cmd.exe", "/c", "ping -n 60 127.0.0.1 >NUL"],
))
.await
.unwrap();
let _b = host
.create(&doc_with_run(
"b",
&["cmd.exe", "/c", "ping -n 60 127.0.0.1 >NUL"],
))
.await
.unwrap();
let r = host.destroy(&a).await.unwrap();
assert_eq!(r.peers_tracked_after, 1);
assert!(host.has_tracked_state("b").await);
}
#[tokio::test]
async fn no_workload_cell_defers_execution_to_supervisor() {
let host = WindowsCellBackend::new();
let h = host.create(&doc_no_run("bare")).await.unwrap();
assert!(host.wait_for_in_vm_exit("bare").await.is_none());
assert_eq!(host.tracked_cell_count().await, 1);
host.destroy(&h).await.unwrap();
assert_eq!(host.tracked_cell_count().await, 0);
}
}