diff --git a/docs/architecture.md b/docs/architecture.md index 5c2cc4a0..64870ecf 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -71,13 +71,15 @@ flowchart LR **Sandbox nodes**, set up at boot by [vm_init.py](../sandboxes/vm_init.py): -- `ucloud-sandbox-node`, the Python node agent. Its Warden owns every sandbox - on the node (OCI bundles, cgroups, `runsc` processes, network namespaces, - lifecycle journals, the node registry) and it sends heartbeats. - `ucloud-sandbox-noded`, the Rust daemon `ucloud-noded` ([runtime/noded](../runtime/noded)), which owns the port, creates, execs - and the pause tier, and behind a flag admission (see - [below](#the-python-agent-and-ucloud-noded)). + and the pause tier, and behind `sandbox.direct_node_standalone_rust` + runs standalone (`--standalone-config`) for every worker route without + `ucloud-sandbox-node` (see [below](#the-python-agent-and-ucloud-noded)). +- `ucloud-sandbox-node`, the legacy Python node agent (omitted when + `sandbox.direct_node_standalone_rust` is enabled). When running alongside + `ucloud-noded`, its Warden handles the remaining lifecycle routes and + heartbeats. - `ucloud-storage-native`: writable volumes, memory backing, checkpoint publication. - `ucloud-environment-io`: serves immutable image roots from the chunk store. @@ -86,8 +88,9 @@ Docker never owns a sandbox. Builders pull and build OCI images with it; on sandbox workers it supplies only `docker-init`, its FORWARD DROP policy and the quota mount that holds the image cache. -**Builder nodes** run BuildKit for Dockerfile builds that cannot run inside a -sandbox; the autoscaler starts them on build demand. **The store node** sits +**Builder nodes** run BuildKit via the standalone +[builder_agent.py](../sandboxes/builder_agent.py) server for Dockerfile builds +that cannot run inside a sandbox; the autoscaler starts them on build demand. **The store node** sits outside the pool and caches the content-addressed chunk store from object storage (workers verify every chunk, so it is untrusted), plus a package cache for builds. See [images.md](images.md). @@ -303,19 +306,26 @@ to the agent's Unix socket; the node registry and the create pipeline (unsupported creates, such as relay egress, DNS-named egress and migration imports, go to the agent unchanged); execs on running sandboxes and managed-job reads, start and signal; and the pause tier: thaw-on-exec, idle -pauses, paused reclaim, escalation decisions and node-local model waits. One -slice is still behind a flag, off by default: `sandbox.direct_node_rust_admission` -moves the transition ledger, slots, growth forecasts and resident sampling. -The flags of the other slices are retired; deployment files may still name -them, as true only. - -Always in the Python agent: heartbeats; park, wake, migration and delete -with their lifecycle locks; the drain row; workspace growth. The processes -coordinate through the kernel and files, not a lock manager: per-sandbox -flocks fence execs against parks, and admission claims are tokens bound to -the agent's session, so a restart of either side cannot leak or double a -grant. Managed-job state sits in a host-visible bind mount, so noded serves -job status and logs without entering, thawing or locking the guest. +pauses, paused reclaim, escalation decisions and node-local model waits. Two +flags remain off by default: `sandbox.direct_node_rust_admission` moves the +transition ledger, slots, growth forecasts and resident sampling into +`ucloud-noded`, and `sandbox.direct_node_standalone_rust` launches +`ucloud-noded --standalone-config` as the sole sandbox worker daemon — owning +file I/O, archive upload, image pulls (with pure-Rust Ed25519 manifest +verification), RAM-backed park/wake, snapshot publication, migration, +commit-export, `/healthz`, `/v1/heartbeat` (including `storage-native` metrics), +`/v1/drain`, heartbeat pushing, and boot-time/TTL reconciliation with no Python +node agent process. The flags of the earlier slices are retired; deployment +files may still name them, as true only. + +When `sandbox.direct_node_standalone_rust` is off, the Python agent still owns +heartbeats, park/wake/migration/delete with their lifecycle locks, the drain +row, and workspace growth. In that split mode the processes coordinate through +the kernel and files, not a lock manager: per-sandbox flocks fence execs +against parks, and admission claims are tokens bound to the agent's session, so +a restart of either side cannot leak or double a grant. Managed-job state sits +in a host-visible bind mount, so noded serves job status and logs without +entering, thawing or locking the guest. ## Managed agents and the model relay diff --git a/docs/decisions.md b/docs/decisions.md index cb4d1108..45949a99 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -99,8 +99,9 @@ Full record: `git show a04c1ad:docs/managed-process-reads.md` `runsc pause` takes 9–26 ms; memory goes to swap only under pressure. At 140 rollouts this cut wake p95 from 14.2 s to 0.13 s; a full checkpoint copies every written byte (48–96 s after 2.5 GB). The node watches relay TCP headers (NFLOG, never payloads), -saving ~20 PostgreSQL statements per wait; it needs `guest_relay_url`. zswap is off: it -freed ~13 MB per reclaim on incompressible memory. +saving ~20 PostgreSQL statements per wait; trainers set `guest_relay_url`, so the older +relay/gateway-driven park-and-wake protocol is retired. zswap is off: it freed ~13 MB per +reclaim on incompressible memory. Full record: `git show a04c1ad:docs/rl-scale-architecture-plan.md` (§9 qualification results, ledger 2026-10-03), `git show a04c1ad:docs/rollout-0.8.0.md` ("0.8.5"), @@ -109,12 +110,19 @@ results, ledger 2026-10-03), `git show a04c1ad:docs/rollout-0.8.0.md` ("0.8.5"), `git show a04c1ad:docs/node-local-model-waits.md`, `git show a04c1ad:docs/benchmarks/node-local-wake-2026-10-03/README.md` -### Live guest memory is RAM-backed, separate from the workspace volume +### Live guest memory is swappable RAM-backed only; file-active and reflink-restore are retired -Splitting it cut physical writes ~87%; a disk-file split raised them ~6.4×. Backing -capacity is admitted on its own: free host RAM did not prove tmpfs room (16 SIGBUS -deaths at 256 × 1.5 GiB). `O_DIRECT` on the storage upper was rejected: random IOPS -fell from 169,732 to 9,341. +Splitting live guest memory from the workspace volume cut physical writes ~87%, while a +disk-file split raised them ~6.4×. Backing capacity is admitted on its own: free host RAM +did not prove tmpfs room (16 SIGBUS deaths at 256 × 1.5 GiB). `O_DIRECT` on the storage +upper was rejected: random IOPS fell from 169,732 to 9,341. + +Swappable RAM-backed (`direct_ram_memory_backing`) is the single memory mode: it pairs +with `ucloud-noded`'s pause tier (`runsc pause` + `memory.reclaim` to NVMe swap) and keeps +running sandboxes at a 64 MiB checkpoint disk claim so RAM + swap rather than disk bounds +density. File-active backing and XFS `reflink-restore` (`direct_reflink_memory_restore`, +which forced dual `ram`/`file` live modes, mode-conversion journals and retention project +IDs to speed up rare cold restores) are retired. Full record: `git show a04c1ad:docs/benchmarks/split-memory-2026-09-23/README.md`, `git show a04c1ad:docs/reviews/hybrid-memory-pressure-2026-09-23.md`, @@ -152,7 +160,8 @@ Full record: `git show a04c1ad:docs/chunk-store-design.md`, Kernel EROFS over NBD attaches in ~0.2 s and keeps mtimes (zeroed mtimes made `.pyc` recompile: 3.74 s against 0.9 s). The chunk dictionary panicked at 254 blobs and `merge` corrupted images. Our Python NBD reader capped at ~45 MB/s; nydusd took 64 cold -images in 10.6 s against 31.5 s, so the planned custom Rust reader was dropped. +images in 10.6 s against 31.5 s, so the planned custom Rust reader was dropped. Sandbox +workers attach immutable chunk-store environments only; legacy OCI pulls stay on builders. Full record: `git show a04c1ad:docs/benchmarks/nydus-spike-2026-10-02/README.md`, `git show a04c1ad:docs/benchmarks/nydusd-spike-2026-10-03/README.md`, diff --git a/docs/roadmap.md b/docs/roadmap.md index 8ad3811b..39d20b07 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -7,11 +7,14 @@ under [Open decisions](#open-decisions). ## Node daemon (`ucloud-noded`) -- **File writes and archive uploads in noded.** Still served by the Python agent; the - largest setup cost left at 512 rollouts (`node_agent.py`, `runtime/noded/src/exec_front.rs`). -- **Park, wake, migration, commit, reconcile and heartbeats in noded**, then delete the - Python agent (`direct_service.py`, `direct_warden.py`, `hibernation.py`, `node_agent.py`, - `heartbeat_sender.py`). +- **Flip `sandbox.direct_node_standalone_rust` to default on**, then delete the legacy + Python sandbox node daemon (`node_agent.py` direct path, `direct_service.py`, + `direct_warden.py`, `hibernation.py`, `heartbeat_sender.py`, `transition_admission.py`). + Standalone Rust `ucloud-noded --standalone-config` now implements all sandbox worker routes + (create, exec, jobs, files/archive/environment, list/delete, images/pull with pure-Rust + Ed25519 verification, RAM-only park/wake, snapshot publication, migration, commit-export, + `/healthz`, `/v1/heartbeat`, `/v1/drain`, heartbeat pusher, and boot-time/TTL reconciler), + and the builder-only HTTP server is split into `sandboxes/builder_agent.py`. - **Create-path tails.** `runsc_create`, storage prepare (`mkfs.xfs` per create) and registry commit set node-side create p95 (`runtime/noded/src/`: `create.rs`, `storage.rs`, `registry/`). - **CPU QoS for background work** (`cpu.idle`/`cpu.weight` for prefetch, publication, offload, cache fill). @@ -79,8 +82,12 @@ under [Open decisions](#open-decisions). ## Open decisions -- **Turn on `sandbox.direct_node_rust_admission`** once the two gates pass. -- **Retire relay-driven park and wake** once every trainer sets `guest_relay_url`. -- **Registry disk guard on a shared drive:** replace `statvfs` percentages with a byte bound, or turn it off. -- **One memory mode:** pick one of split, RAM or reflink-restore backing and delete the rest. -- **A second store node:** removes the ~1.5 h cache-refill window after a loss, at a monthly cost. +- **Second store node (deferred):** removes the ~1.5 h cache-refill window after a loss, at a monthly cost; revisit only if that refill window violates training SLOs. + +### Decided (2026-11-27) + +- **Single memory mode:** standardize on swappable RAM-backed (`direct_ram_memory_backing`) and delete file-active (`direct_reflink_memory_restore` is removed). +- **No legacy OCI pulls on sandbox workers:** workers attach immutable chunk-store environments only; Docker/OCI pulls stay on builders. +- **Turn on `sandbox.direct_node_rust_admission`** once its two benchmark gates pass, then delete the Python admission ledger. +- **Retire relay-driven park and wake** (`guest_relay_url` + node-local model waits replace it). +- **Registry disk guard on shared drives:** `registry_disk_guard_enabled: false` disables `statvfs` percentage refusal on shared drives. diff --git a/pyproject.toml b/pyproject.toml index 38ab0c95..2d625769 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -47,4 +47,4 @@ select = ["C901", "E4", "E7", "E9", "F"] [tool.ruff.lint.mccabe] # Functions above this carry `# noqa: C901`. Lower it, and drop their # noqa, as functions are split. -max-complexity = 40 +max-complexity = 33 diff --git a/runtime/noded/src/commit_export.rs b/runtime/noded/src/commit_export.rs new file mode 100644 index 00000000..2385bfc4 --- /dev/null +++ b/runtime/noded/src/commit_export.rs @@ -0,0 +1,378 @@ +//! Worker half of C3.1 sandbox commit export (`sandboxes/node_commit.py` & +//! `sandboxes/commit_policy.py`). +//! +//! `POST /v1/sandboxes/{id}/commit-export` is idempotent per `operation_id` and +//! doubles as the poll endpoint: 202 while exporting/uploading, 200 once staged +//! or terminally failed. + +use std::collections::HashMap; +use std::ffi::CString; +use std::fs::File; +use std::io::Read; +use std::os::unix::ffi::OsStrExt; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, SystemTime}; + +use bytes::Bytes; +use hyper::StatusCode; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; + +use crate::registry::{is_operation_id, is_sandbox_id}; +use crate::registry_client::RegistryHttpClient; + +pub const EXPORT_SCHEMA: &str = "ucloud-commit-export-v1"; +pub const SCRATCH_SLACK_BYTES: u64 = 64 * 1024 * 1024; +pub const MIN_FREE_BYTES: u64 = 1024 * 1024 * 1024; +const RESULT_RETENTION: Duration = Duration::from_secs(7 * 86_400); + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct CommitExportRequest { + pub operation_id: String, + pub generation: i64, + pub image_id: String, + pub resume: bool, + pub max_bytes: u64, +} + +impl CommitExportRequest { + pub fn from_value(raw: &Value) -> Result { + let Some(obj) = raw.as_object() else { + return Err("invalid commit export request".into()); + }; + if obj.len() != 5 { + return Err("invalid commit export request".into()); + } + let op = obj.get("operation_id").and_then(Value::as_str).ok_or("invalid commit export request")?; + let generation = obj.get("generation").and_then(Value::as_i64).ok_or("invalid commit export request")?; + let img = obj.get("image_id").and_then(Value::as_str).ok_or("invalid commit export request")?; + let resume = obj.get("resume").and_then(Value::as_bool).ok_or("invalid commit export request")?; + let max_bytes = obj.get("max_bytes").and_then(Value::as_u64).ok_or("invalid commit export request")?; + if !is_operation_id(op) || generation < 1 || !is_sandbox_id(img) || max_bytes == 0 || max_bytes > (1u64 << 40) { + return Err("invalid commit export request".into()); + } + Ok(CommitExportRequest { + operation_id: op.to_string(), + generation, + image_id: img.to_string(), + resume, + max_bytes, + }) + } +} + +pub fn staging_repository(image_id: &str) -> String { + let hex: String = Sha256::digest(image_id.as_bytes()).iter().map(|b| format!("{b:02x}")).collect(); + format!("commits/{}", &hex[..32]) +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct CommitExport { + pub schema: String, + pub sandbox_id: String, + pub request: CommitExportRequest, + pub state: String, + pub was_paused: bool, + pub identity: Vec, + pub repository: String, + #[serde(default)] + pub blob_digest: String, + #[serde(default)] + pub size: u64, + #[serde(default)] + pub error_code: String, +} + +#[derive(Debug)] +pub struct CommitRefused { + pub code: &'static str, + pub detail: String, + pub status: StatusCode, + pub retryable: bool, +} + +impl CommitRefused { + pub fn new(code: &'static str, detail: impl Into, status: StatusCode, retryable: bool) -> Self { + CommitRefused { code, detail: detail.into(), status, retryable } + } + + pub fn payload(&self) -> Value { + json!({ + "error": format!("{}: {}", self.code, self.detail), + "error_code": self.code, + "retryable": self.retryable, + }) + } +} + +pub type ExportHook = Arc< + dyn Fn(&str, i64, &Path, bool) -> Result<(bool, Vec, u64), CommitRefused> + Send + Sync, +>; + +pub struct CommitExports { + results_dir: PathBuf, + staging_dir: PathBuf, + registry: Option, + min_free_bytes: u64, + state: Mutex, +} + +#[derive(Default)] +struct ExportState { + active: HashMap, + reserved: u64, +} + +impl CommitExports { + pub fn open(state_root: &Path, registry: Option) -> std::io::Result> { + Self::open_with_min_free(state_root, registry, MIN_FREE_BYTES) + } + + pub fn open_with_min_free( + state_root: &Path, + registry: Option, + min_free_bytes: u64, + ) -> std::io::Result> { + let results_dir = state_root.join("commit-exports"); + let staging_dir = state_root.join("commit-staging"); + std::fs::create_dir_all(&results_dir)?; + std::fs::create_dir_all(&staging_dir)?; + // Clean stale staging files from previous runs. + if let Ok(entries) = std::fs::read_dir(&staging_dir) { + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() && !path.is_symlink() { + let _ = std::fs::remove_dir_all(&path); + } else { + let _ = std::fs::remove_file(&path); + } + } + } + // Prune expired replay cache entries. + if let Ok(entries) = std::fs::read_dir(&results_dir) { + let now = SystemTime::now(); + for entry in entries.flatten() { + if let Ok(meta) = entry.metadata() { + if meta.is_file() + && meta.modified().ok().and_then(|m| now.duration_since(m).ok()).is_some_and(|age| age > RESULT_RETENTION) + { + let _ = std::fs::remove_file(entry.path()); + } + } + } + } + Ok(Arc::new(CommitExports { + results_dir, + staging_dir, + registry, + min_free_bytes, + state: Mutex::new(ExportState::default()), + })) + } + + fn load(&self, path: &Path) -> Option { + let bytes = std::fs::read(path).ok()?; + serde_json::from_slice(&bytes).ok() + } + + fn save(&self, path: &Path, record: &CommitExport) -> std::io::Result<()> { + let bytes = serde_json::to_vec(record).map_err(std::io::Error::other)?; + crate::fsutil::atomic_write(path, &bytes) + } + + fn reserve(&self, operation: &str, bytes: u64) -> Result<(), CommitRefused> { + let available = statvfs_available(&self.staging_dir).unwrap_or(0); + let mut guard = self.state.lock().expect("not poisoned"); + if available.saturating_sub(guard.reserved).saturating_sub(bytes) < self.min_free_bytes { + return Err(CommitRefused::new( + "commit_scratch_full", + "worker commit staging is waiting for disk space", + StatusCode::SERVICE_UNAVAILABLE, + true, + )); + } + let prev = guard.active.insert(operation.to_string(), bytes).unwrap_or(0); + guard.reserved = guard.reserved.saturating_sub(prev).saturating_add(bytes); + Ok(()) + } + + fn release(&self, operation: &str) { + let mut guard = self.state.lock().expect("not poisoned"); + if let Some(prev) = guard.active.remove(operation) { + guard.reserved = guard.reserved.saturating_sub(prev); + } + } + + pub fn request( + self: &Arc, + sandbox_id: &str, + raw: &Value, + exporter: ExportHook, + ) -> Result<(StatusCode, Value), CommitRefused> { + let req = CommitExportRequest::from_value(raw) + .map_err(|msg| CommitRefused::new("invalid_request", msg, StatusCode::BAD_REQUEST, false))?; + let record_path = self.results_dir.join(format!("{}.json", req.operation_id)); + let recorded = { + let mut guard = self.state.lock().expect("not poisoned"); + let existing = self.load(&record_path); + if let Some(ref rec) = existing { + if rec.sandbox_id != sandbox_id || rec.request != req { + return Err(CommitRefused::new( + "commit_conflict", + "operation_id is bound to another commit export", + StatusCode::CONFLICT, + false, + )); + } + } + if guard.active.contains_key(&req.operation_id) + || existing.as_ref().is_some_and(|r| r.state != "exporting") + { + return Ok(answer_record(existing.as_ref())); + } + if self.registry.is_none() { + return Err(CommitRefused::new( + "commit_export_unavailable", + "this worker has no registry for commit staging", + StatusCode::SERVICE_UNAVAILABLE, + false, + )); + } + guard.active.insert(req.operation_id.clone(), 0); + existing + }; + + let tar_path = self.staging_dir.join(format!("{}.tar", req.operation_id)); + let export_res = exporter(sandbox_id, req.generation, &tar_path, req.resume); + let (was_paused, identity, filestore_bytes) = match export_res { + Ok(tuple) => tuple, + Err(refused) => { + let _ = std::fs::remove_file(&tar_path); + self.release(&req.operation_id); + return Err(refused); + } + }; + if filestore_bytes > req.max_bytes { + let _ = std::fs::remove_file(&tar_path); + self.release(&req.operation_id); + return Err(CommitRefused::new( + "commit_too_large", + "the sandbox's filesystem writes exceed max_bytes", + StatusCode::PAYLOAD_TOO_LARGE, + false, + )); + } + if let Err(refused) = self.reserve(&req.operation_id, filestore_bytes.saturating_add(SCRATCH_SLACK_BYTES)) { + let _ = std::fs::remove_file(&tar_path); + self.release(&req.operation_id); + return Err(refused); + } + + let intent = recorded.unwrap_or_else(|| CommitExport { + schema: EXPORT_SCHEMA.into(), + sandbox_id: sandbox_id.to_string(), + request: req.clone(), + state: "exporting".into(), + was_paused, + identity, + repository: staging_repository(&req.image_id), + blob_digest: String::new(), + size: 0, + error_code: String::new(), + }); + if let Err(err) = self.save(&record_path, &intent) { + let _ = std::fs::remove_file(&tar_path); + self.release(&req.operation_id); + return Err(CommitRefused::new( + "commit_export_failed", + err.to_string(), + StatusCode::SERVICE_UNAVAILABLE, + true, + )); + } + + let this = self.clone(); + let intent_bg = intent.clone(); + let registry = self.registry.clone().expect("checked above"); + tokio::spawn(async move { + this.upload_background(registry, intent_bg, record_path, tar_path).await; + }); + + Ok((StatusCode::ACCEPTED, json!({"export": intent}))) + } + + async fn upload_background( + self: Arc, + registry: RegistryHttpClient, + mut intent: CommitExport, + record_path: PathBuf, + tar_path: PathBuf, + ) { + let op = intent.request.operation_id.clone(); + let hashed = tokio::task::spawn_blocking({ + let tar = tar_path.clone(); + move || -> std::io::Result<(String, Vec)> { + let mut file = File::open(&tar)?; + let mut data = Vec::new(); + file.read_to_end(&mut data)?; + let hex: String = Sha256::digest(&data).iter().map(|b| format!("{b:02x}")).collect(); + Ok((format!("sha256:{hex}"), data)) + } + }) + .await; + + let upload_ok = match hashed { + Ok(Ok((digest, bytes))) => { + let size = bytes.len() as u64; + let res = registry.put_blob(&intent.repository, &digest, Bytes::from(bytes)).await; + let _ = std::fs::remove_file(&tar_path); + match res { + Ok(()) => { + intent.state = "staged".into(); + intent.blob_digest = digest; + intent.size = size; + self.save(&record_path, &intent).is_ok() + } + Err(err) => { + eprintln!("ucloud-noded: commit export {op} upload failed: {err}"); + false + } + } + } + _ => { + let _ = std::fs::remove_file(&tar_path); + false + } + }; + if !upload_ok { + let _ = std::fs::remove_file(&record_path); + } + self.release(&op); + } +} + +fn answer_record(recorded: Option<&CommitExport>) -> (StatusCode, Value) { + match recorded { + None => (StatusCode::ACCEPTED, json!({"export": null})), + Some(rec) => { + let status = if rec.state == "exporting" { + StatusCode::ACCEPTED + } else { + StatusCode::OK + }; + (status, json!({"export": rec})) + } + } +} + +fn statvfs_available(path: &Path) -> std::io::Result { + let cpath = CString::new(path.as_os_str().as_bytes()) + .map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidInput, "path contains NUL"))?; + let mut stat: libc::statvfs = unsafe { std::mem::zeroed() }; + if unsafe { libc::statvfs(cpath.as_ptr(), &mut stat) } != 0 { + return Err(std::io::Error::last_os_error()); + } + Ok((stat.f_bavail as u64).saturating_mul(stat.f_frsize as u64)) +} diff --git a/runtime/noded/src/control_front.rs b/runtime/noded/src/control_front.rs new file mode 100644 index 00000000..696af52c --- /dev/null +++ b/runtime/noded/src/control_front.rs @@ -0,0 +1,518 @@ +//! Sandbox inspection and deletion routes in the daemon (Wave B2): +//! +//! - `GET /v1/sandboxes` (all non-deleting sandboxes) +//! - `GET /v1/sandboxes?sandbox_id=` (single-sandbox snapshot) +//! - `DELETE /v1/sandboxes/{id}` (fenced generation-checked deletion) +//! +//! While the Python agent still owns parked-snapshot publication caches and +//! legacy (non-`--rust-admission`) admission ledgers, parked records, expired +//! TTL lists, `?sandbox_id=` recovery confirms (whose `activity_epoch` +//! shares Python's heartbeat clock), and non-`--rust-admission` deletes +//! cleanly forward to the agent. + +use std::future::Future; +use std::pin::Pin; +use std::sync::{Arc, OnceLock}; + +use bytes::Bytes; +use http_body_util::{BodyExt, Full}; +use hyper::header::{self, HeaderName, HeaderValue}; +use hyper::{Method, Request, Response, StatusCode}; +use serde_json::{Value, json}; + +use crate::Body; +use crate::exec_front::Outcome; +use crate::node_pipeline::{DeleteError, NodePipeline}; +use crate::registry::{Phase, is_operation_id}; +use crate::sandbox_record::{is_expired_at, now_utc_ns, sandbox_record_json}; + +const SANDBOX_GENERATION_HEADER: &str = "x-ucloud-sandbox-generation"; +const SANDBOX_OPERATION_ID_HEADER: &str = "x-ucloud-sandbox-operation-id"; + +pub type BoxFuture = Pin + Send>>; + +#[derive(Debug)] +pub enum ListOutcome { + Sandboxes(Vec), + Single { sandboxes: Vec, node_epoch: String, activity_epoch: i64 }, + Forward(&'static str), +} + +#[derive(Debug)] +pub enum DeleteOutcome { + Deleted(Option), + Conflict(String), + Busy(String), + Invalid(String), + Failed(String), + Forward(&'static str), +} + +pub trait ControlNode: Send + Sync { + fn ready(&self) -> bool; + fn list_sandboxes(&self) -> BoxFuture; + fn get_sandbox(&self, sandbox_id: &str) -> BoxFuture; + fn delete_sandbox(&self, sandbox_id: &str, generation: i64) -> BoxFuture; +} + +#[derive(Clone)] +struct StandaloneControl { + heartbeat: Arc, + lifecycle: Arc, +} + +pub struct NodeControl { + node: Arc>>, + standalone: Option, +} + +impl NodeControl { + pub fn new(node: Arc>>) -> Self { + NodeControl { node, standalone: None } + } + + pub fn standalone( + node: Arc>>, + heartbeat: Arc, + lifecycle: Arc, + ) -> Self { + NodeControl { + node, + standalone: Some(StandaloneControl { heartbeat, lifecycle }), + } + } +} + +fn registration_state(node: &NodePipeline, reg: &crate::registry::Registration) -> String { + if reg.phase != Phase::Owned { + return reg.phase.as_str().to_string(); + } + match node.warden().journal().load(reg.sandbox_id(), reg.sandbox_generation as u64) { + Ok(Some(record)) => record + .get("state") + .and_then(Value::as_str) + .unwrap_or("unavailable") + .to_string(), + _ => "unavailable".to_string(), + } +} + +impl ControlNode for NodeControl { + fn ready(&self) -> bool { + self.node.get().is_some() + } + + fn list_sandboxes(&self) -> BoxFuture { + let cell = self.node.clone(); + let standalone = self.standalone.clone(); + Box::pin(async move { + let Some(node) = cell.get().cloned() else { + return ListOutcome::Forward("node not ready"); + }; + let is_standalone = standalone.is_some(); + tokio::task::spawn_blocking(move || { + let Ok(snapshot) = node.registry().snapshot() else { + return ListOutcome::Forward("registry unreadable"); + }; + let now = now_utc_ns(); + let mut active: Vec<_> = snapshot + .records + .iter() + .filter(|reg| reg.phase != Phase::Deleting) + .collect(); + active.sort_by(|a, b| a.sandbox_id().cmp(b.sandbox_id())); + let mut out = Vec::with_capacity(active.len()); + for reg in active { + if is_expired_at(reg, now) { + if !is_standalone { + // Let Python run its non-blocking expired cleanup loop until standalone. + return ListOutcome::Forward("expired sandbox needs cleanup"); + } + continue; + } + let state = registration_state(&node, reg); + if state == "parked" && !is_standalone { + // Parked records attach Python's cached published snapshot in proxy mode. + return ListOutcome::Forward("parked sandbox snapshot cache"); + } + let mut record = sandbox_record_json(reg, &state); + if state == "parked" { + if let Some(st) = &standalone { + if let Some(pub_snap) = st.lifecycle.published_snapshot(reg.sandbox_id(), reg.sandbox_generation) { + if let Some(obj) = record.as_object_mut() { + obj.insert("published_snapshot".into(), pub_snap); + } + } + } + } + out.push(record); + } + ListOutcome::Sandboxes(out) + }) + .await + .unwrap_or(ListOutcome::Forward("list worker failed")) + }) + } + + fn get_sandbox(&self, sandbox_id: &str) -> BoxFuture { + let Some(st) = self.standalone.clone() else { + return Box::pin(async { ListOutcome::Forward("recovery confirmation uses heartbeat clock") }); + }; + let cell = self.node.clone(); + let id = sandbox_id.to_string(); + Box::pin(async move { + let Some(node) = cell.get().cloned() else { + return ListOutcome::Forward("node not ready"); + }; + let node_epoch = st.heartbeat.config().node_epoch.clone(); + let activity_epoch = st.heartbeat.advance_activity_epoch(); + let sandboxes = tokio::task::spawn_blocking(move || { + let Ok(Some(reg)) = node.registry().get(&id) else { + return Vec::new(); + }; + if reg.phase == Phase::Deleting { + return Vec::new(); + } + let state = registration_state(&node, ®); + let mut record = sandbox_record_json(®, &state); + if state == "parked" { + if let Some(pub_snap) = st.lifecycle.published_snapshot(reg.sandbox_id(), reg.sandbox_generation) { + if let Some(obj) = record.as_object_mut() { + obj.insert("published_snapshot".into(), pub_snap); + } + } + } + vec![record] + }) + .await + .unwrap_or_default(); + ListOutcome::Single { + sandboxes, + node_epoch, + activity_epoch, + } + }) + } + + fn delete_sandbox(&self, sandbox_id: &str, generation: i64) -> BoxFuture { + let cell = self.node.clone(); + let standalone = self.standalone.clone(); + let id = sandbox_id.to_string(); + Box::pin(async move { + let Some(node) = cell.get().cloned() else { + return DeleteOutcome::Forward("node not ready"); + }; + // In proxy mode only intercept DELETE live when noded owns the admission ledger. + if standalone.is_none() && node.admission().is_none() { + return DeleteOutcome::Forward("python owns admission ledger"); + } + if standalone.is_none() { + let check_node = node.clone(); + let check_id = id.clone(); + let preflight = tokio::task::spawn_blocking(move || { + let reg = check_node.registry().get(&check_id).ok().flatten(); + match reg { + None => Ok(None), + Some(reg) => { + if reg.sandbox_generation != generation { + return Err("delete generation does not own direct sandbox"); + } + let state = registration_state(&check_node, ®); + if state == "parked" { + return Ok(Some(true)); + } + Ok(Some(false)) + } + } + }) + .await; + match preflight { + Ok(Err(msg)) => return DeleteOutcome::Conflict(msg.into()), + Ok(Ok(Some(true))) => return DeleteOutcome::Forward("parked sandbox publication"), + Err(_) => return DeleteOutcome::Forward("preflight worker failed"), + Ok(Ok(None)) | Ok(Ok(Some(false))) => {} + } + } + let res = match node.delete_sandbox(&id, generation).await { + Ok(deleted) => { + if let Some(st) = &standalone { + st.heartbeat.advance_activity_epoch(); + } + DeleteOutcome::Deleted(deleted) + } + Err(DeleteError::Conflict(msg)) => DeleteOutcome::Conflict(msg), + Err(DeleteError::Busy(msg)) => DeleteOutcome::Busy(msg), + Err(DeleteError::Invalid(msg)) => DeleteOutcome::Invalid(msg), + Err(DeleteError::Failed(msg)) => DeleteOutcome::Failed(msg), + }; + res + }) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +enum ControlRoute { + List, + Delete(String), +} + +fn percent_decode(raw: &str, plus_as_space: bool) -> Option { + let bytes = raw.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + match bytes[i] { + b'+' if plus_as_space => { + out.push(b' '); + i += 1; + } + b'%' if i + 2 < bytes.len() => { + let hi = hex_val(bytes[i + 1])?; + let lo = hex_val(bytes[i + 2])?; + out.push((hi << 4) | lo); + i += 3; + } + b'%' => return None, + byte => { + out.push(byte); + i += 1; + } + } + } + String::from_utf8(out).ok() +} + +fn hex_val(byte: u8) -> Option { + match byte { + b'0'..=b'9' => Some(byte - b'0'), + b'a'..=b'f' => Some(byte - b'a' + 10), + b'A'..=b'F' => Some(byte - b'A' + 10), + _ => None, + } +} + +fn parse_route(method: &Method, path: &str) -> Option { + match method { + &Method::GET if path == "/v1/sandboxes" => Some(ControlRoute::List), + &Method::DELETE if path.starts_with("/v1/sandboxes/") => { + let raw_id = path.strip_prefix("/v1/sandboxes/")?; + if raw_id.contains('/') { + return None; + } + let id = percent_decode(raw_id, false)?; + Some(ControlRoute::Delete(id)) + } + _ => None, + } +} + +fn sandbox_id_query(query: &str) -> Option { + for pair in query.split('&') { + if pair.is_empty() { + continue; + } + let (k, v) = pair.split_once('=').unwrap_or((pair, "")); + if percent_decode(k, true).as_deref() == Some("sandbox_id") { + let decoded = percent_decode(v, true)?; + if !decoded.is_empty() { + return Some(decoded); + } + } + } + None +} + +fn parse_delete_headers(headers: &hyper::HeaderMap) -> Result<(i64, String), String> { + let Some(gen_raw) = headers.get(SANDBOX_GENERATION_HEADER) else { + return Err( + "X-UCloud-Sandbox-Generation and X-UCloud-Sandbox-Operation-Id must be supplied together".into(), + ); + }; + let Some(op_raw) = headers.get(SANDBOX_OPERATION_ID_HEADER) else { + return Err( + "X-UCloud-Sandbox-Generation and X-UCloud-Sandbox-Operation-Id must be supplied together".into(), + ); + }; + let gen_str = gen_raw + .to_str() + .map_err(|_| "X-UCloud-Sandbox-Generation must be an integer".to_string())?; + let generation: i64 = gen_str + .trim() + .parse() + .map_err(|_| "X-UCloud-Sandbox-Generation must be an integer".to_string())?; + if generation < 1 { + return Err("X-UCloud-Sandbox-Generation must be positive".into()); + } + let op_str = op_raw + .to_str() + .map_err(|_| "X-UCloud-Sandbox-Operation-Id cannot be empty".to_string())? + .trim(); + if op_str.is_empty() { + return Err("X-UCloud-Sandbox-Operation-Id cannot be empty".into()); + } + if !is_operation_id(op_str) { + return Err("delete operation id is invalid".into()); + } + Ok((generation, op_str.to_string())) +} + +fn constant_time_eq(left: &[u8], right: &[u8]) -> bool { + left.len() == right.len() && left.iter().zip(right).fold(0u8, |acc, (a, b)| acc | (a ^ b)) == 0 +} + +fn full(bytes: impl Into) -> Body { + Full::new(bytes.into()).map_err(|never| match never {}).boxed() +} + +fn json_response(status: StatusCode, payload: Value, extra_headers: &[(&str, &str)]) -> Response { + let body = serde_json::to_vec(&payload).unwrap_or_else(|_| b"{}".to_vec()); + let mut response = Response::new(full(body)); + *response.status_mut() = status; + let headers = response.headers_mut(); + headers.insert(header::CONTENT_TYPE, HeaderValue::from_static("application/json")); + for (name, value) in extra_headers { + if let (Ok(name), Ok(value)) = (HeaderName::from_bytes(name.as_bytes()), HeaderValue::from_str(value)) { + headers.insert(name, value); + } + } + response +} + +pub struct ControlFront { + node: Arc, + token: Bytes, +} + +impl ControlFront { + pub fn new(node: Arc>>, token: &str) -> Arc { + Self::with_node(Arc::new(NodeControl::new(node)), token) + } + + pub fn standalone( + node: Arc>>, + heartbeat: Arc, + lifecycle: Arc, + token: &str, + ) -> Arc { + Self::with_node(Arc::new(NodeControl::standalone(node, heartbeat, lifecycle)), token) + } + + pub fn with_node(node: Arc, token: &str) -> Arc { + Arc::new(ControlFront { + node, + token: Bytes::copy_from_slice(token.as_bytes()), + }) + } + + fn authorized(&self, request: &Request) -> bool { + let supplied = request + .headers() + .get(header::AUTHORIZATION) + .map(|v| v.as_bytes()) + .and_then(|v| v.strip_prefix(b"Bearer ")); + supplied.is_some_and(|supplied| !supplied.is_empty() && constant_time_eq(supplied, &self.token)) + } + + pub fn intercepts(&self, request: &Request) -> bool { + if parse_route(request.method(), request.uri().path()).is_none() { + return false; + } + if !self.authorized(request) { + return false; + } + self.node.ready() + } + + pub async fn handle(&self, request: Request) -> Outcome { + let Some(route) = parse_route(request.method(), request.uri().path()) else { + return Outcome::Forward(request); + }; + match route { + ControlRoute::List => { + let outcome = match sandbox_id_query(request.uri().query().unwrap_or("")) { + Some(id) => self.node.get_sandbox(&id).await, + None => self.node.list_sandboxes().await, + }; + match outcome { + ListOutcome::Sandboxes(sandboxes) => { + Outcome::Response(json_response(StatusCode::OK, json!({"sandboxes": sandboxes}), &[])) + } + ListOutcome::Single { + sandboxes, + node_epoch, + activity_epoch, + } => Outcome::Response(json_response( + StatusCode::OK, + json!({ + "sandboxes": sandboxes, + "node_epoch": node_epoch, + "activity_epoch": activity_epoch, + }), + &[], + )), + ListOutcome::Forward(_) => Outcome::Forward(request), + } + } + ControlRoute::Delete(sandbox_id) => { + if sandbox_id.is_empty() { + return Outcome::Response(json_response( + StatusCode::BAD_REQUEST, + json!({"error": "sandbox id is required"}), + &[], + )); + } + let (generation, _op_id) = match parse_delete_headers(request.headers()) { + Ok(pair) => pair, + Err(msg) => { + return Outcome::Response(json_response(StatusCode::BAD_REQUEST, json!({"error": msg}), &[])); + } + }; + match self.node.delete_sandbox(&sandbox_id, generation).await { + DeleteOutcome::Deleted(record) => { + Outcome::Response(json_response(StatusCode::OK, json!({"deleted": record}), &[])) + } + DeleteOutcome::Conflict(msg) => { + Outcome::Response(json_response(StatusCode::CONFLICT, json!({"error": msg}), &[])) + } + DeleteOutcome::Busy(msg) => Outcome::Response(json_response( + StatusCode::SERVICE_UNAVAILABLE, + json!({"error": msg, "error_code": "memory_publication_draining", "retryable": true}), + &[("Retry-After", "1"), ("X-UCloud-Sandbox-Retryable", "true")], + )), + DeleteOutcome::Invalid(msg) => { + Outcome::Response(json_response(StatusCode::BAD_REQUEST, json!({"error": msg}), &[])) + } + DeleteOutcome::Failed(msg) => { + Outcome::Response(json_response(StatusCode::SERVICE_UNAVAILABLE, json!({"error": msg}), &[])) + } + DeleteOutcome::Forward(_) => Outcome::Forward(request), + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_control_routes_and_delete_headers() { + assert_eq!(parse_route(&Method::GET, "/v1/sandboxes"), Some(ControlRoute::List)); + assert_eq!(parse_route(&Method::DELETE, "/v1/sandboxes/sb-1"), Some(ControlRoute::Delete("sb-1".into()))); + assert_eq!(parse_route(&Method::DELETE, "/v1/sandboxes/"), Some(ControlRoute::Delete(String::new()))); + assert_eq!(parse_route(&Method::DELETE, "/v1/sandboxes/sb-1/extra"), None); + assert_eq!(parse_route(&Method::POST, "/v1/sandboxes"), None); + assert_eq!(sandbox_id_query("sandbox_id=sb-1"), Some("sb-1".into())); + assert_eq!(sandbox_id_query(""), None); + + let mut hdrs = hyper::HeaderMap::new(); + assert!(parse_delete_headers(&hdrs).is_err()); + hdrs.insert(SANDBOX_GENERATION_HEADER, HeaderValue::from_static("2")); + hdrs.insert(SANDBOX_OPERATION_ID_HEADER, HeaderValue::from_static("op-del-1")); + assert_eq!(parse_delete_headers(&hdrs).unwrap(), (2, "op-del-1".into())); + + hdrs.insert(SANDBOX_GENERATION_HEADER, HeaderValue::from_static("0")); + assert!(parse_delete_headers(&hdrs).is_err()); + } +} diff --git a/runtime/noded/src/create.rs b/runtime/noded/src/create.rs index 70d83c46..2af2e6e0 100644 --- a/runtime/noded/src/create.rs +++ b/runtime/noded/src/create.rs @@ -167,9 +167,15 @@ pub enum Outcome { Forward(Request), } +pub struct StandaloneCreate { + pub node: Arc, + pub heartbeat: Arc, +} + pub struct CreateFront { - agent: Arc, + agent: Option>, pipeline: Arc, + standalone: Option, token: Bytes, } @@ -239,7 +245,28 @@ fn parse_operation(raw: &Value) -> Option<(u64, String, String)> { impl CreateFront { pub fn new(agent: Arc, pipeline: Arc, token: &str) -> Self { - CreateFront { agent, pipeline, token: Bytes::copy_from_slice(token.as_bytes()) } + CreateFront { + agent: Some(agent), + pipeline, + standalone: None, + token: Bytes::copy_from_slice(token.as_bytes()), + } + } + + /// Standalone Rust create front: admits, runs, and finishes creates + /// completely in-process with zero Python RPCs. + pub fn standalone( + node: Arc, + heartbeat: Arc, + token: &str, + ) -> Arc { + let pipeline: Arc = node.clone(); + Arc::new(CreateFront { + agent: None, + pipeline, + standalone: Some(StandaloneCreate { node, heartbeat }), + token: Bytes::copy_from_slice(token.as_bytes()), + }) } /// Whether to read this request ourselves: an authorized create with a @@ -271,6 +298,11 @@ impl CreateFront { } }; let read_request_ms = started.elapsed().as_millis() as u64; + if let Some(ctx) = &self.standalone { + return Outcome::Response( + self.handle_standalone(ctx, bytes, &parts.headers, read_request_ms, started).await, + ); + } let forward = |bytes: Bytes| Outcome::Forward(Request::from_parts(parts.clone(), full(bytes))); let parse_started = Instant::now(); let Ok(Value::Object(mut raw)) = serde_json::from_slice::(&bytes) else { return forward(bytes) }; @@ -329,10 +361,11 @@ impl CreateFront { Err(refusal) => return Some(refused(refusal)), } } + let agent = self.agent.as_ref().expect("proxy mode requires agent"); // The agent's two requests, whole: its own phases (slot, capacity, // lock) are inside admit; the rest is the RPC and the agent's GIL. let admit_started = timings.start(); - let reply = match self.agent.call(Method::POST, "/internal/v1/creates/admit", Some(&admit)).await { + let reply = match agent.call(Method::POST, "/internal/v1/creates/admit", Some(&admit)).await { Ok(reply) => reply, // Nothing reached the agent: it can still create this itself. Err(RpcError::Unavailable(_)) => return None, @@ -399,10 +432,11 @@ impl CreateFront { /// Finish is the only way the agent learns the outcome, so it is retried /// while the agent is unreachable or out of request threads. async fn finish(&self, token: &str, body: &Value) -> Result { + let agent = self.agent.as_ref().expect("proxy mode requires agent"); let path = format!("/internal/v1/creates/{token}/finish"); let mut delay = Duration::from_millis(50); for _ in 0..40 { - match self.agent.call(Method::POST, &path, Some(body)).await { + match agent.call(Method::POST, &path, Some(body)).await { Err(RpcError::Unavailable(_)) => {} Ok(reply) if reply.status == StatusCode::SERVICE_UNAVAILABLE && reply.json().ok().and_then(|body| body.get("error_code").cloned()) @@ -420,6 +454,167 @@ impl CreateFront { json_response(status, Bytes::from(body.to_string()), &HeaderMap::new()) } + /// Standalone Rust create path: validates spec, admits via in-process + /// `AdmissionService`, runs `NodePipeline::create`, and returns the exact + /// node API response envelope without any Python agent RPCs. + async fn handle_standalone( + &self, + ctx: &StandaloneCreate, + bytes: Bytes, + headers: &HeaderMap, + read_request_ms: u64, + started: Instant, + ) -> Response { + let parse_started = Instant::now(); + let Ok(Value::Object(mut raw)) = serde_json::from_slice::(&bytes) else { + return self.error(CreateError::Invalid("sandbox payload must be a JSON object".into())); + }; + let Some((generation, operation_id, spec_hash)) = + raw.remove("_ucloud_operation").as_ref().and_then(parse_operation) + else { + return self.error(CreateError::Invalid("sandbox create requires a valid _ucloud_operation".into())); + }; + let spec_value = Value::Object(raw.clone()); + let spec = match crate::registry::SandboxSpec::from_dict(&spec_value) { + Ok(spec) => spec, + Err(msg) => return self.error(CreateError::Invalid(msg)), + }; + if spec.sha256() != spec_hash { + return self.error(CreateError::Invalid("create operation spec_hash does not match spec".into())); + } + let sandbox_id = spec.id().to_string(); + let wait = headers + .get(ADMISSION_WAIT_HEADER) + .and_then(|v| v.to_str().ok()) + .and_then(parse_admission_wait); + let shape = admission_shape(&raw).unwrap_or((Shape { vcpu: 0.0, memory_mb: 0, disk_mb: 0 }, false)); + let parse_spec_ms = parse_started.elapsed().as_millis() as u64; + + let manager_started = Instant::now(); + let mut timings = Timings::default(); + + // Acquire in-process admission claim (held past response assembly: I18). + let mut _claim: Option = None; + if let Some(service) = ctx.node.admission().cloned() { + let owner = (sandbox_id.clone(), generation); + match service.startup(&Holder::Noded, &owner, shape.0.clone(), shape.1, wait).await { + Ok(grant) => { + timings.add_ms("startup_admission", grant.startup_admission_ms as u64); + timings.add_ms("active_capacity", grant.active_capacity_ms as u64); + _claim = Some(NodedClaim { service, token: grant.token }); + } + Err(refusal) => return refused(refusal), + } + } + + // Fence concurrent transitions on this sandbox_id. + let locks_dir = ctx.node.config().exec.warden_locks_dir.clone(); + let sid_fence = sandbox_id.clone(); + let _fence = match tokio::task::spawn_blocking(move || { + crate::exec_fence::ExecFence::new(locks_dir).acquire_transition(&sid_fence) + }) + .await + { + Ok(Ok(guard)) => guard, + Ok(Err(e)) => return self.error(CreateError::Unavailable(format!("create fence failed: {e}"))), + Err(e) => return self.error(CreateError::Unavailable(format!("create fence worker failed: {e}"))), + }; + + // Matches sandboxes/direct_provisioner.py::create_layout + sandboxes/disk_claims.py::initial_claim. + let split = ctx.node.config().split_memory_backing && spec.parkable(); + let grant = ctx.node.config().workspace_initial_grant_mb as i64; + let demonstrated = ctx.node.config().demonstrated_memory; + let claim_enabled = grant > 0 || demonstrated; + let disk_mb = spec.disk_mb().unwrap_or(0); + let requested_disk_mb = spec.requested_disk_mb().unwrap_or(disk_mb); + let initial_claim = if split && claim_enabled { + let workspace_mb = if grant > 0 && disk_mb > 0 { grant.min(disk_mb) } else { disk_mb }; + let memory_ceiling_mb = requested_disk_mb.saturating_sub(disk_mb); + let memory_mb = if demonstrated { 64 } else { memory_ceiling_mb }; + Some(json!({"workspace_mb": workspace_mb, "memory_mb": memory_mb})) + } else { + None + }; + let admitted = Admitted { + token: String::new(), + sandbox_id: sandbox_id.clone(), + generation, + operation_id, + spec_hash, + spec: spec.to_dict().clone(), + requested_resources: json!({ + "vcpu": shape.0.vcpu, + "memory_mb": shape.0.memory_mb, + "disk_mb": requested_disk_mb, + }), + initial_claim, + split, + config_sha256: ctx.node.config().config_sha256.clone(), + }; + + let runtime_started = match ctx.node.create(&admitted, &mut timings).await { + Ok(started_flag) => started_flag, + Err(CreateError::Capacity(message)) => { + let body = json!({ + "error": message, + "error_code": "node_active_admission_deferred", + "retryable": true, + }); + let mut hdrs = HeaderMap::new(); + hdrs.insert(header::RETRY_AFTER, HeaderValue::from_static("1")); + hdrs.insert("x-ucloud-sandbox-retryable", HeaderValue::from_static("true")); + return json_response(StatusCode::SERVICE_UNAVAILABLE, Bytes::from(body.to_string()), &hdrs); + } + Err(err) => return self.error(err), + }; + + let reg_store = ctx.node.registry().clone(); + let sid_q = sandbox_id.clone(); + let reg = match tokio::task::spawn_blocking(move || reg_store.get(&sid_q)).await { + Ok(Ok(Some(reg))) => reg, + Ok(Ok(None)) => return self.error(CreateError::Unavailable("created sandbox registration disappeared".into())), + Ok(Err(e)) => return self.error(CreateError::Unavailable(e.to_string())), + Err(e) => return self.error(CreateError::Unavailable(format!("registry worker failed: {e}"))), + }; + let state = ctx + .node + .warden() + .journal() + .load(&sandbox_id, generation) + .ok() + .flatten() + .and_then(|j| j.get("state").and_then(Value::as_str).map(str::to_string)) + .unwrap_or_else(|| "running".to_string()); + let mut record = crate::sandbox_record::sandbox_record_json(®, &state); + if let Some(obj) = record.as_object_mut() { + obj.insert("node_epoch".into(), json!(ctx.heartbeat.config().node_epoch)); + obj.insert("activity_epoch".into(), json!(ctx.heartbeat.advance_activity_epoch())); + } + let status = if runtime_started { StatusCode::CREATED } else { StatusCode::OK }; + let manager_ms = manager_started.elapsed().as_millis() as u64; + let mut phases = Map::new(); + for (name, value) in timings.phases() { + phases.insert(name.clone(), Value::from(*value)); + } + let response_body = json!({ + "sandbox": record, + "timings": { + "total_ms": started.elapsed().as_millis() as u64, + "phases": { + "read_request_ms": read_request_ms, + "parse_spec_ms": parse_spec_ms, + "manager_create_ms": manager_ms, + }, + "manager": { + "idempotent": status == StatusCode::OK, + "total_ms": manager_ms, + "phases": phases, + }, + }, + }); + json_response(status, Bytes::from(response_body.to_string()), &HeaderMap::new()) + } + /// `{"sandbox": , "timings": {...}}`. fn created( &self, diff --git a/runtime/noded/src/ed25519.rs b/runtime/noded/src/ed25519.rs new file mode 100644 index 00000000..d9583f74 --- /dev/null +++ b/runtime/noded/src/ed25519.rs @@ -0,0 +1,520 @@ +//! Pure-Rust RFC 8032 Ed25519 signature verification and trusted producer key +//! loading (`sandboxes/environment_config.py::load_trusted_keys`). +//! +//! Verification-only, built on `sha2::Sha512` with zero additional crate +//! dependencies. + +use std::collections::HashMap; +use std::fs::OpenOptions; +use std::io::Read; +use std::os::unix::fs::{MetadataExt, OpenOptionsExt}; +use std::path::Path; + +use sha2::{Digest, Sha256, Sha512}; + +const MAX_TRUSTED_KEYS_BYTES: u64 = 64 * 1024; + +// --- Field element modulo p = 2^255 - 19 using 5 limbs of 51 bits --- + +const MASK51: u64 = (1u64 << 51) - 1; + +#[derive(Clone, Copy, Debug)] +struct Fe([u64; 5]); + +impl Fe { + const ZERO: Fe = Fe([0, 0, 0, 0, 0]); + const ONE: Fe = Fe([1, 0, 0, 0, 0]); + + fn from_u64(v: u64) -> Fe { + Fe([v & MASK51, v >> 51, 0, 0, 0]) + } + + /// Decode 32 little-endian bytes (clearing top bit 255 as per RFC 8032, + /// returning `None` if the 255-bit integer is `>= p`). + fn from_bytes_canonical(bytes: &[u8; 32]) -> Option<(Fe, u8)> { + let sign = (bytes[31] >> 7) & 1; + let mut b = *bytes; + b[31] &= 0x7f; + let load8 = |off: usize| -> u64 { + u64::from_le_bytes(b[off..off + 8].try_into().unwrap()) + }; + let l0 = load8(0) & MASK51; + let l1 = (load8(6) >> 3) & MASK51; + let l2 = (load8(12) >> 6) & MASK51; + let l3 = (load8(19) >> 1) & MASK51; + let l4 = (load8(24) >> 12) & MASK51; + // Canonical check: integer < 2^255 - 19. + // If l1..l4 are all MASK51 and l0 >= MASK51 - 18 (= 2^51 - 19), reject. + if l1 == MASK51 && l2 == MASK51 && l3 == MASK51 && l4 == MASK51 && l0 >= MASK51 - 18 { + return None; + } + Some((Fe([l0, l1, l2, l3, l4]), sign)) + } + + fn reduce_partial(mut t: [u128; 5]) -> Fe { + for _ in 0..2 { + let c0 = t[0] >> 51; + t[0] &= u128::from(MASK51); + t[1] += c0; + let c1 = t[1] >> 51; + t[1] &= u128::from(MASK51); + t[2] += c1; + let c2 = t[2] >> 51; + t[2] &= u128::from(MASK51); + t[3] += c2; + let c3 = t[3] >> 51; + t[3] &= u128::from(MASK51); + t[4] += c3; + let c4 = t[4] >> 51; + t[4] &= u128::from(MASK51); + t[0] += c4 * 19; + } + Fe([t[0] as u64, t[1] as u64, t[2] as u64, t[3] as u64, t[4] as u64]) + } + + fn canonical(self) -> [u64; 5] { + let mut h = Self::reduce_partial([ + u128::from(self.0[0]), + u128::from(self.0[1]), + u128::from(self.0[2]), + u128::from(self.0[3]), + u128::from(self.0[4]), + ]) + .0; + // Compute q = (h + 19) >> 255 + let mut q = (h[0] + 19) >> 51; + q = (h[1] + q) >> 51; + q = (h[2] + q) >> 51; + q = (h[3] + q) >> 51; + q = (h[4] + q) >> 51; + h[0] += 19 * q; + let c0 = h[0] >> 51; + h[0] &= MASK51; + h[1] += c0; + let c1 = h[1] >> 51; + h[1] &= MASK51; + h[2] += c1; + let c2 = h[2] >> 51; + h[2] &= MASK51; + h[3] += c2; + let c3 = h[3] >> 51; + h[3] &= MASK51; + h[4] += c3; + h[4] &= MASK51; + h + } + + fn to_bytes(self) -> [u8; 32] { + let h = self.canonical(); + let mut out = [0u8; 32]; + let mut acc: u128 = 0; + let mut bits = 0u32; + let mut idx = 0usize; + for limb in h { + acc |= u128::from(limb) << bits; + bits += 51; + while bits >= 8 && idx < 32 { + out[idx] = (acc & 0xff) as u8; + acc >>= 8; + bits -= 8; + idx += 1; + } + } + if idx < 32 { + out[idx] = (acc & 0xff) as u8; + } + out + } + + fn is_zero(self) -> bool { + self.canonical() == [0, 0, 0, 0, 0] + } + + fn is_odd(self) -> u8 { + (self.canonical()[0] & 1) as u8 + } + + fn eq_fe(self, other: Fe) -> bool { + self.canonical() == other.canonical() + } + + fn add(self, rhs: Fe) -> Fe { + Self::reduce_partial([ + u128::from(self.0[0]) + u128::from(rhs.0[0]), + u128::from(self.0[1]) + u128::from(rhs.0[1]), + u128::from(self.0[2]) + u128::from(rhs.0[2]), + u128::from(self.0[3]) + u128::from(rhs.0[3]), + u128::from(self.0[4]) + u128::from(rhs.0[4]), + ]) + } + + fn sub(self, rhs: Fe) -> Fe { + // Add 2*p before subtracting rhs (each limb of rhs < 2^52). + const TWO_P: [u128; 5] = [ + 2 * ((1u128 << 51) - 19), + 2 * ((1u128 << 51) - 1), + 2 * ((1u128 << 51) - 1), + 2 * ((1u128 << 51) - 1), + 2 * ((1u128 << 51) - 1), + ]; + Self::reduce_partial([ + u128::from(self.0[0]) + TWO_P[0] - u128::from(rhs.0[0]), + u128::from(self.0[1]) + TWO_P[1] - u128::from(rhs.0[1]), + u128::from(self.0[2]) + TWO_P[2] - u128::from(rhs.0[2]), + u128::from(self.0[3]) + TWO_P[3] - u128::from(rhs.0[3]), + u128::from(self.0[4]) + TWO_P[4] - u128::from(rhs.0[4]), + ]) + } + + fn neg(self) -> Fe { + Fe::ZERO.sub(self) + } + + fn mul(self, rhs: Fe) -> Fe { + let a = self.0.map(u128::from); + let b = rhs.0.map(u128::from); + let b1_19 = b[1] * 19; + let b2_19 = b[2] * 19; + let b3_19 = b[3] * 19; + let b4_19 = b[4] * 19; + let t = [ + a[0] * b[0] + a[1] * b4_19 + a[2] * b3_19 + a[3] * b2_19 + a[4] * b1_19, + a[0] * b[1] + a[1] * b[0] + a[2] * b4_19 + a[3] * b3_19 + a[4] * b2_19, + a[0] * b[2] + a[1] * b[1] + a[2] * b[0] + a[3] * b4_19 + a[4] * b3_19, + a[0] * b[3] + a[1] * b[2] + a[2] * b[1] + a[3] * b[0] + a[4] * b4_19, + a[0] * b[4] + a[1] * b[3] + a[2] * b[2] + a[3] * b[1] + a[4] * b[0], + ]; + Self::reduce_partial(t) + } + + fn square(self) -> Fe { + self.mul(self) + } + + fn pow_bytes_le(self, exp: &[u8; 32]) -> Fe { + let mut acc = Fe::ONE; + let mut base = self; + for &byte in exp { + for bit in 0..8 { + if (byte >> bit) & 1 == 1 { + acc = acc.mul(base); + } + base = base.square(); + } + } + acc + } + + /// Multiplicative inverse: `self^(p - 2) mod p`. + fn invert(self) -> Fe { + // p - 2 = 2^255 - 21 + let mut exp = [0xffu8; 32]; + exp[0] = 0xeb; // 256 - 21 = 235 = 0xeb + exp[31] = 0x7f; + self.pow_bytes_le(&exp) + } +} + +fn fe_d() -> Fe { + // d = -121665 / 121666 mod p + Fe::from_u64(121_665).neg().mul(Fe::from_u64(121_666).invert()) +} + +fn fe_sqrt_m1() -> Fe { + // sqrt(-1) = 2^((p - 1) / 4) mod p = 2^(2^253 - 5) mod p + let mut exp = [0xffu8; 32]; + exp[0] = 0xfb; // 256 - 5 = 251 = 0xfb + exp[31] = 0x1f; + Fe::from_u64(2).pow_bytes_le(&exp) +} + +// --- Extended twisted Edwards coordinates (X:Y:Z:T) where x=X/Z, y=Y/Z, xy=T/Z --- + +#[derive(Clone, Copy)] +struct Point { + x: Fe, + y: Fe, + z: Fe, + t: Fe, +} + +impl Point { + const IDENTITY: Point = Point { x: Fe::ZERO, y: Fe::ONE, z: Fe::ONE, t: Fe::ZERO }; + + fn base() -> Point { + // B_y = 4/5 mod p, B_x even (sign bit 0). + let y = Fe::from_u64(4).mul(Fe::from_u64(5).invert()); + let mut bytes = y.to_bytes(); + bytes[31] &= 0x7f; + Point::decompress(&bytes).expect("RFC 8032 base point") + } + + fn decompress(bytes: &[u8; 32]) -> Option { + let (y, sign) = Fe::from_bytes_canonical(bytes)?; + let y2 = y.square(); + let u = y2.sub(Fe::ONE); + let v = fe_d().mul(y2).add(Fe::ONE); + // Candidate x = u * v^3 * (u * v^7)^((p - 5) / 8) + let v3 = v.square().mul(v); + let v7 = v3.square().mul(v); + let mut exp = [0xffu8; 32]; + exp[0] = 0xfd; // (2^255 - 24) / 8 = 2^252 - 3 -> low byte 0xfd, high byte 0x0f + exp[31] = 0x0f; + let mut x = u.mul(v3).mul(u.mul(v7).pow_bytes_le(&exp)); + let vx2 = v.mul(x.square()); + if !vx2.eq_fe(u) { + if vx2.eq_fe(u.neg()) { + x = x.mul(fe_sqrt_m1()); + } else { + return None; + } + } + if x.is_zero() && sign == 1 { + return None; + } + if x.is_odd() != sign { + x = x.neg(); + } + Some(Point { x, y, z: Fe::ONE, t: x.mul(y) }) + } + + fn add(self, other: Point) -> Point { + // RFC 8032 §5.1.4 unified extended coordinates addition. + let a = self.y.sub(self.x).mul(other.y.sub(other.x)); + let b = self.y.add(self.x).mul(other.y.add(other.x)); + let c = self.t.mul(fe_d().add(fe_d())).mul(other.t); + let d = self.z.add(self.z).mul(other.z); + let e = b.sub(a); + let f = d.sub(c); + let g = d.add(c); + let h = b.add(a); + Point { x: e.mul(f), y: g.mul(h), z: f.mul(g), t: e.mul(h) } + } + + fn double(self) -> Point { + self.add(self) + } + + fn scalar_mul_le(self, scalar: &[u8]) -> Point { + let mut acc = Point::IDENTITY; + let mut cur = self; + for &byte in scalar { + for bit in 0..8 { + if (byte >> bit) & 1 == 1 { + acc = acc.add(cur); + } + cur = cur.double(); + } + } + acc + } + + fn eq_point(self, other: Point) -> bool { + // X1*Z2 == X2*Z1 and Y1*Z2 == Y2*Z1 + self.x.mul(other.z).eq_fe(other.x.mul(self.z)) && self.y.mul(other.z).eq_fe(other.y.mul(self.z)) + } +} + +/// Group order L in little-endian bytes. +const ORDER_L: [u8; 32] = [ + 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, +]; + +fn scalar_less_than_l(s: &[u8; 32]) -> bool { + for i in (0..32).rev() { + if s[i] < ORDER_L[i] { + return true; + } + if s[i] > ORDER_L[i] { + return false; + } + } + false +} + +/// Verify an RFC 8032 Ed25519 signature. +pub fn verify(public_key: &[u8; 32], message: &[u8], signature: &[u8; 64]) -> bool { + let r_bytes: [u8; 32] = signature[0..32].try_into().unwrap(); + let s_bytes: [u8; 32] = signature[32..64].try_into().unwrap(); + if !scalar_less_than_l(&s_bytes) { + return false; + } + let Some(a) = Point::decompress(public_key) else { return false }; + let Some(r) = Point::decompress(&r_bytes) else { return false }; + + let mut hasher = Sha512::new(); + hasher.update(r_bytes); + hasher.update(public_key); + hasher.update(message); + let h = hasher.finalize(); + + // Check [8]([S]B) == [8](R + [h]A) (cofactorless RFC 8032 equation; since + // [8]([L]P) == O for every curve point P, 512-bit h needs no reduction). + let lhs = Point::base().scalar_mul_le(&s_bytes).double().double().double(); + let rhs = r.add(a.scalar_mul_le(&h)).double().double().double(); + lhs.eq_point(rhs) +} + +/// Strict RFC 4648 base64 decoder (`base64.b64decode(..., validate=True)`). +pub fn decode_base64_strict(input: &str) -> Result, String> { + let bytes = input.as_bytes(); + if bytes.len() % 4 != 0 { + return Err("invalid base64 length".into()); + } + let decode_char = |b: u8| -> Option { + match b { + b'A'..=b'Z' => Some(b - b'A'), + b'a'..=b'z' => Some(b - b'a' + 26), + b'0'..=b'9' => Some(b - b'0' + 52), + b'+' => Some(62), + b'/' => Some(63), + _ => None, + } + }; + let mut out = Vec::with_capacity((bytes.len() / 4) * 3); + for (idx, chunk) in bytes.chunks_exact(4).enumerate() { + let is_last = (idx + 1) * 4 == bytes.len(); + let a = decode_char(chunk[0]).ok_or("invalid base64 character")?; + let b = decode_char(chunk[1]).ok_or("invalid base64 character")?; + match (chunk[2], chunk[3]) { + (b'=', b'=') if is_last => { + out.push((a << 2) | (b >> 4)); + } + (c, b'=') if is_last => { + let c = decode_char(c).ok_or("invalid base64 character")?; + out.push((a << 2) | (b >> 4)); + out.push((b << 4) | (c >> 2)); + } + (c, d) => { + let c = decode_char(c).ok_or("invalid base64 character")?; + let d = decode_char(d).ok_or("invalid base64 character")?; + out.push((a << 2) | (b >> 4)); + out.push((b << 4) | (c >> 2)); + out.push((c << 6) | d); + } + } + } + Ok(out) +} + +pub fn content_digest(bytes: &[u8]) -> String { + let hex: String = Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect(); + format!("sha256:{hex}") +} + +/// Port of `sandboxes/environment_config.py::load_trusted_keys`. +pub fn load_trusted_keys(path: &Path) -> Result, String> { + let mut file = OpenOptions::new() + .read(true) + .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC) + .open(path) + .map_err(|e| format!("cannot open trusted keys {}: {e}", path.display()))?; + let meta = file.metadata().map_err(|e| e.to_string())?; + let euid = unsafe { libc::geteuid() }; + if !meta.file_type().is_file() || (meta.uid() != 0 && meta.uid() != euid) || (meta.mode() & 0o022 != 0) { + return Err("environment producer trust file must be owned and not writable by others".into()); + } + let mut data = Vec::new(); + file.by_ref() + .take(MAX_TRUSTED_KEYS_BYTES + 1) + .read_to_end(&mut data) + .map_err(|e| e.to_string())?; + if data.len() as u64 > MAX_TRUSTED_KEYS_BYTES { + return Err("environment producer trust file exceeds its bound".into()); + } + let raw: serde_json::Value = + serde_json::from_slice(&data).map_err(|e| format!("invalid trusted keys JSON: {e}"))?; + let Some(map) = raw.as_object() else { + return Err("environment producer trust must be a nonempty key mapping".into()); + }; + if map.is_empty() { + return Err("environment producer trust must be a nonempty key mapping".into()); + } + let mut keys = HashMap::with_capacity(map.len()); + for (identity, value) in map { + let Some(encoded) = value.as_str() else { + return Err("environment producer key must be a base64 string".into()); + }; + let decoded = decode_base64_strict(encoded)?; + if decoded.len() != 32 || content_digest(&decoded) != *identity { + return Err("environment producer key identity mismatch".into()); + } + let key: [u8; 32] = decoded.try_into().unwrap(); + keys.insert(identity.clone(), key); + } + Ok(keys) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn hex(s: &str) -> Vec { + (0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap()).collect() + } + + #[test] + fn rfc8032_test_vectors_verify_and_mutations_fail() { + // RFC 8032 §7.1 TEST 1 (empty message) + let pk1: [u8; 32] = hex("d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a").try_into().unwrap(); + let sig1: [u8; 64] = hex( + "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e06522490155\ + 5fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b", + ) + .try_into() + .unwrap(); + assert!(verify(&pk1, b"", &sig1)); + assert!(!verify(&pk1, b"x", &sig1)); + let mut bad_sig = sig1; + bad_sig[0] ^= 1; + assert!(!verify(&pk1, b"", &bad_sig)); + + // RFC 8032 §7.1 TEST 2 (1-byte message 0x72) + let pk2: [u8; 32] = hex("3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c").try_into().unwrap(); + let sig2: [u8; 64] = hex( + "92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da\ + 085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00", + ) + .try_into() + .unwrap(); + assert!(verify(&pk2, &[0x72], &sig2)); + assert!(!verify(&pk2, &[0x73], &sig2)); + + // RFC 8032 §7.1 TEST 3 (2-byte message 0xaf 0x82) + let pk3: [u8; 32] = hex("fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025").try_into().unwrap(); + let sig3: [u8; 64] = hex( + "6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac\ + 18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a", + ) + .try_into() + .unwrap(); + assert!(verify(&pk3, &[0xaf, 0x82], &sig3)); + + // Non-canonical S == L must be rejected. + let mut bad_s = sig1; + bad_s[32..64].copy_from_slice(&ORDER_L); + assert!(!verify(&pk1, b"", &bad_s)); + } + + #[test] + fn base64_and_trusted_keys_load() { + assert_eq!(decode_base64_strict("SGVsbG8=").unwrap(), b"Hello"); + assert!(decode_base64_strict("not-base64!").is_err()); + let dir = std::env::temp_dir().join(format!("noded-keys-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let key_path = dir.join("trusted.json"); + let raw_key = [7u8; 32]; + let digest = content_digest(&raw_key); + // Base64 of 32 bytes of 0x07 + let b64 = "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc="; + assert_eq!(decode_base64_strict(b64).unwrap(), raw_key); + std::fs::write(&key_path, format!("{{\"{digest}\":\"{b64}\"}}")).unwrap(); + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&key_path, std::fs::Permissions::from_mode(0o600)).unwrap(); + let keys = load_trusted_keys(&key_path).unwrap(); + assert_eq!(keys.get(&digest), Some(&raw_key)); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/runtime/noded/src/environment.rs b/runtime/noded/src/environment.rs new file mode 100644 index 00000000..278f1e49 --- /dev/null +++ b/runtime/noded/src/environment.rs @@ -0,0 +1,197 @@ +//! Conservative environment preflight (`sandboxes/environment_contract.py`). +//! +//! Pure projection from a stored [`SandboxSpec`] to the JSON object returned by +//! `GET /v1/sandboxes/{id}/environment`. + +use serde_json::{Map, Value, json}; + +use crate::registry::SandboxSpec; + +const FEATURES: [(&str, &str, &str); 8] = [ + ("linux-kernel", "unsupported", "The current backend runs gVisor, not a guest Linux kernel."), + ("system-boot", "unsupported", "No booted-system backend is implemented."), + ("framework-network-policy", "unsupported", "Framework-aware egress enforcement is not implemented."), + ( + "posix-acl", + "unqualified", + "Requires placement on a qualified runtime and filesystem; configuration alone does not establish support.", + ), + ("filesystem-xattrs", "unqualified", "Support depends on the filesystem and runtime version."), + ( + "filesystem-locks", + "unqualified", + "Requires placement on a runtime qualified for the requested lock and lifecycle operations.", + ), + ( + "filesystem-notifications", + "unqualified", + "Notification behavior has not been qualified across lifecycle operations.", + ), + ("nested-containers", "unqualified", "Nested container requirements have not been qualified."), +]; + +/// Port of `sandboxes/environment_contract.py::describe_environment`. +pub fn describe_environment(spec: &SandboxSpec) -> Value { + let mut features = Map::new(); + for (name, status, reason) in FEATURES { + features.insert(name.to_string(), json!({"status": status, "reason": reason})); + } + features.insert( + "network-off".to_string(), + json!({ + "status": if spec.network() == "none" { "configured" } else { "unsupported" }, + "reason": format!("Selected network mode is {}.", spec.network()), + }), + ); + features.insert( + "static-file-management".to_string(), + json!({ + "status": if spec.management_helper() == "static" { "configured" } else { "unsupported" }, + "reason": "Requires the updated static supervisor artifact on the selected node.", + }), + ); + + let mut problems = Vec::new(); + for name in spec.required_features() { + let (status, reason) = match features.get(name) { + Some(entry) => ( + entry.get("status").and_then(Value::as_str).unwrap_or("unknown"), + entry.get("reason").and_then(Value::as_str).unwrap_or("Unknown feature name."), + ), + None => ("unknown", "Unknown feature name."), + }; + if status != "configured" { + problems.push(json!({"feature": name, "status": status, "reason": reason})); + } + } + + let mut warnings = Vec::new(); + if spec.workspace_is_tmpfs() { + warnings.push( + "Workspace tmpfs hides image contents at its mount point and consumes memory; it is not a disk quota.", + ); + } + if spec.enforce_disk_quota() { + warnings.push( + "enforce_disk_quota is a legacy workspace-tmpfs selector; use workspace_storage explicitly.", + ); + } + if matches!(spec.profile(), "linux_host" | "linux_session") { + warnings.push("Session startup requires image shell utilities; no system init is booted."); + } + + let mut network_policy = Map::new(); + network_policy.insert("egress".to_string(), Value::String(spec.network_egress().to_string())); + if let Some(relay) = spec.network_relay() { + network_policy.insert("relay".to_string(), Value::String(relay.to_string())); + } + + let dns_servers: Vec<&str> = if spec.network() == "bridge" && spec.network_egress() == "direct" { + if spec.dns_servers().is_empty() { + vec!["1.1.1.1", "8.8.8.8"] + } else { + spec.dns_servers().iter().map(String::as_str).collect() + } + } else { + Vec::new() + }; + + json!({ + "schema_version": 1, + "backend": "gvisor", + "evidence_level": "configuration", + "requested": { + "profile": spec.profile(), + "required_features": spec.required_features(), + "working_dir": spec.working_dir(), + "user": spec.security_user(), + "supplementary_groups": spec.supplementary_groups(), + }, + "configured": { + "workspace": spec.workspace_path(), + "management_helper": spec.management_helper(), + "workspace_storage": if spec.workspace_is_tmpfs() { "tmpfs" } else { "image" }, + "tmpfs_mb": spec.tmpfs_mb(), + "run_tmpfs_mb": spec.run_tmpfs_mb(), + "shm_mb": spec.shm_mb(), + "network": spec.network(), + "network_policy": Value::Object(network_policy), + "dns_servers": dns_servers, + }, + "unresolved": [ + "image_digest", + "runtime_digest", + "image_identity", + "effective_cwd", + "home", + "live_features", + "lifecycle_persistence", + ], + "features": Value::Object(features), + "requirements_satisfied": problems.is_empty(), + "problems": problems, + "warnings": warnings, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn describes_default_and_static_helper_specs() { + let spec = SandboxSpec::from_dict(&json!({ + "id": "env-1", + "image": "alpine:latest", + "cpus": 1.0, + "memory_mb": 512, + "disk_mb": 1024, + "network": "bridge", + "filesystem": {"management_helper": "static", "workspace_storage": "tmpfs"}, + "required_features": ["static-file-management", "linux-kernel"], + })) + .unwrap(); + let report = describe_environment(&spec); + assert_eq!(report["schema_version"], 1); + assert_eq!(report["backend"], "gvisor"); + assert_eq!(report["configured"]["management_helper"], "static"); + assert_eq!(report["configured"]["workspace_storage"], "tmpfs"); + assert_eq!(report["configured"]["dns_servers"], json!(["1.1.1.1", "8.8.8.8"])); + assert_eq!(report["features"]["static-file-management"]["status"], "configured"); + assert_eq!(report["features"]["network-off"]["status"], "unsupported"); + assert_eq!(report["requirements_satisfied"], false); + assert_eq!(report["problems"].as_array().unwrap().len(), 1); + assert_eq!(report["problems"][0]["feature"], "linux-kernel"); + assert_eq!(report["warnings"].as_array().unwrap().len(), 1); + } + + #[test] + fn relay_network_and_none_network_omit_default_dns() { + let none_spec = SandboxSpec::from_dict(&json!({ + "id": "env-2", + "image": "alpine:latest", + "cpus": 1.0, + "memory_mb": 512, + "disk_mb": 1024, + "network": "none", + })) + .unwrap(); + let report = describe_environment(&none_spec); + assert_eq!(report["configured"]["dns_servers"], json!([])); + assert_eq!(report["features"]["network-off"]["status"], "configured"); + + let relay_spec = SandboxSpec::from_dict(&json!({ + "id": "env-3", + "image": "alpine:latest", + "cpus": 1.0, + "memory_mb": 512, + "disk_mb": 1024, + "network": "bridge", + "network_policy": {"egress": "relay", "relay": "default"}, + })) + .unwrap(); + let relay_report = describe_environment(&relay_spec); + assert_eq!(relay_report["configured"]["dns_servers"], json!([])); + assert_eq!(relay_report["configured"]["network_policy"], json!({"egress": "relay", "relay": "default"})); + } +} diff --git a/runtime/noded/src/exec_fence.rs b/runtime/noded/src/exec_fence.rs index cd20bf33..b3e0e182 100644 --- a/runtime/noded/src/exec_fence.rs +++ b/runtime/noded/src/exec_fence.rs @@ -87,6 +87,45 @@ fn locked(path: &Path, operation: libc::c_int) -> std::io::Result> } } +/// A held exclusive T lock for a lifecycle transition (e.g. delete). +#[derive(Debug)] +pub struct TransitionGuard { + _transition: File, + activity_path: PathBuf, + transition_path: PathBuf, +} + +impl TransitionGuard { + /// Unlink A then T while still holding exclusive T (`ExecFence.discard`). + pub fn discard(self) { + let _ = std::fs::remove_file(&self.activity_path); + let _ = std::fs::remove_file(&self.transition_path); + } +} + +/// Open and flock (blocking if `nonblocking` is false), retrying while the +/// lock landed on an unlinked or replaced inode. +fn locked_blocking(path: &Path, operation: libc::c_int) -> std::io::Result { + loop { + let file = open(path)?; + // SAFETY: a valid descriptor. + if unsafe { libc::flock(file.as_raw_fd(), operation) } != 0 { + let error = std::io::Error::last_os_error(); + if error.kind() == std::io::ErrorKind::Interrupted { + continue; + } + return Err(error); + } + let held = file.metadata()?; + match std::fs::symlink_metadata(path) { + Ok(current) if (current.dev(), current.ino()) == (held.dev(), held.ino()) => return Ok(file), + Ok(_) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(error), + } + } +} + impl ExecFence { pub fn new(directory: impl Into) -> Self { ExecFence { directory: directory.into() } @@ -106,6 +145,19 @@ impl ExecFence { let Some(file) = locked(&activity, libc::LOCK_SH)? else { return Ok(Fenced::Busy) }; Ok(Fenced::Held(ActivityLease { file })) } + + /// Exclusive T lock (allow_shared=true, for delete): blocks until any + /// competing transition finishes while tolerating active execs holding A. + pub fn acquire_transition(&self, sandbox_id: &str) -> std::io::Result { + let (Some(transition_path), Some(activity_path)) = + (self.path(sandbox_id, "transition"), self.path(sandbox_id, "activity")) + else { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "sandbox id is invalid")); + }; + std::fs::create_dir_all(&self.directory)?; + let transition = locked_blocking(&transition_path, libc::LOCK_EX)?; + Ok(TransitionGuard { _transition: transition, activity_path, transition_path }) + } } #[cfg(test)] diff --git a/runtime/noded/src/exec_front.rs b/runtime/noded/src/exec_front.rs index 2f6131a3..1fd2ef62 100644 --- a/runtime/noded/src/exec_front.rs +++ b/runtime/noded/src/exec_front.rs @@ -102,6 +102,10 @@ fn forwarded(reason: &'static str) { impl ExecFront { pub fn new(node: Arc>>, token: &str) -> Arc { + Self::with_limits(node, token, ExecLimits::default()) + } + + pub fn with_limits(node: Arc>>, token: &str, limits: ExecLimits) -> Arc { let hook: crate::exec::ActivityHook = Arc::new(|_, guard| { if let Some(lease) = guard.downcast_ref::() { lease.touch(); @@ -109,7 +113,7 @@ impl ExecFront { }); Arc::new(ExecFront { node, - manager: ExecManager::new(ExecLimits::default(), Some(hook)), + manager: ExecManager::new(limits, Some(hook)), token: Bytes::copy_from_slice(token.as_bytes()), }) } @@ -120,11 +124,11 @@ impl ExecFront { } /// The node, when it serves execs: the session limits are the ones this - /// build implements. + /// manager is configured with. fn node(&self) -> Option<&Arc> { let node = self.node.get()?; let exec = &node.config().exec; - let limits = ExecLimits::default(); + let limits = self.manager.limits(); let same = exec.sessions.max_sessions == limits.max_sessions && exec.sessions.max_events_per_session == limits.max_events_per_session; same.then_some(node) diff --git a/runtime/noded/src/files_front.rs b/runtime/noded/src/files_front.rs new file mode 100644 index 00000000..1ef03147 --- /dev/null +++ b/runtime/noded/src/files_front.rs @@ -0,0 +1,1072 @@ +//! File I/O, archive upload, and environment description routes in the daemon: +//! +//! - `GET /v1/sandboxes/{id}/environment` +//! - `GET /v1/sandboxes/{id}/files?path=...` +//! - `PUT /v1/sandboxes/{id}/files?path=...` +//! - `PUT /v1/sandboxes/{id}/archive?path=...` +//! +//! Owned, running sandboxes (including paused sandboxes that thaw in-process) +//! execute directly via fenced `runsc exec`, without touching the Python agent. +//! Parked, unknown, draining, or memory-constrained sandboxes forward untouched +//! to the Python agent. + +use std::fs::File; +use std::future::Future; +use std::io::{Seek, SeekFrom, Write}; +use std::path::PathBuf; +use std::pin::Pin; +use std::process::Stdio; +use std::sync::{Arc, OnceLock}; +use std::time::{Duration, Instant}; + +use bytes::Bytes; +use http_body_util::{BodyExt, Full}; +use hyper::header::{self, HeaderName, HeaderValue}; +use hyper::{Method, Request, Response, StatusCode}; +use serde_json::{Value, json}; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt}; +use tokio::sync::Semaphore; + +use crate::Body; +use crate::environment::describe_environment; +use crate::exec_fence::{ExecFence, Fenced}; +use crate::exec_front::{Outcome, running}; +use crate::node_pipeline::NodePipeline; +use crate::registry::{Phase, SandboxSpec, validate_guest_path}; +use crate::upload_archive::{ + ArchiveError, ArchiveSource, NormalizedArchive, TRANSFER_CHUNK_BYTES, UploadSpool, archive_helper_unsupported, + normalized_archive, plan_archive, sandbox_archive_extract_script, sandbox_file_write_script, +}; +use crate::warden::Sandbox; + +const SANDBOX_GENERATION_HEADER: &str = "x-ucloud-sandbox-generation"; +const MANAGED_PROCESS_BINARY: &str = "/.ucloud-job-init"; +const MAX_HELPER_OUTPUT_BYTES: usize = 64 * 1024; + +pub type BoxFuture = Pin + Send>>; + +#[derive(Clone, Debug)] +pub struct FileTarget { + pub sandbox_id: String, + pub generation: i64, + pub container_id: String, + pub bundle: PathBuf, + pub memory_directory: String, + pub spec_sha256: String, + pub spec: SandboxSpec, + pub static_helper: bool, + pub running: bool, + pub admission_open: bool, + pub memory_floor_ok: bool, +} + +#[derive(Debug)] +pub enum FileLookup { + Owned(FileTarget), + NotFound, + Forward(&'static str), +} + +pub enum ExecStdin { + None, + Bytes(Bytes), + File(File), +} + +#[derive(Debug)] +pub struct FileExecResult { + pub exit_code: i32, + pub stdout: Vec, + pub stderr: Vec, +} + +#[derive(Debug)] +pub enum FileExecError { + Conflict(String), + OutputTooLarge(String), + Forward(&'static str), + Failed(String), +} + +pub trait FileNode: Send + Sync { + fn ready(&self) -> bool; + fn max_file_body_bytes(&self) -> u64; + fn max_read_concurrency(&self) -> usize; + fn admission_wait(&self) -> Duration; + fn upload_spool(&self) -> Option>; + fn lookup(&self, sandbox_id: &str) -> BoxFuture; + fn exec_file( + &self, + target: &FileTarget, + expected_generation: i64, + argv: Vec, + stdin: ExecStdin, + max_stdout: usize, + max_stderr: usize, + ) -> BoxFuture>; +} + +pub struct NodeFiles { + node: Arc>>, + spool: OnceLock>, +} + +impl NodeFiles { + pub fn new(node: Arc>>) -> Self { + NodeFiles { node, spool: OnceLock::new() } + } +} + +fn available_mib() -> Option { + let text = std::fs::read_to_string("/proc/meminfo").ok()?; + let line = text.lines().find(|line| line.starts_with("MemAvailable:"))?; + let kib: u64 = line.split_whitespace().nth(1)?.parse().ok()?; + Some(kib / 1024) +} + +impl FileNode for NodeFiles { + fn ready(&self) -> bool { + self.node.get().is_some() + } + + fn max_file_body_bytes(&self) -> u64 { + self.node.get().map_or(256 * 1024 * 1024, |n| n.config().max_file_body_bytes) + } + + fn max_read_concurrency(&self) -> usize { + self.node.get().map_or(8, |n| n.config().admission.max_concurrent_startups.max(1)) + } + + fn admission_wait(&self) -> Duration { + let secs = self.node.get().map_or(30.0, |n| n.config().exec.admission_wait_seconds); + Duration::from_secs_f64(if secs.is_finite() && secs >= 0.0 { secs } else { 30.0 }) + } + + fn upload_spool(&self) -> Option> { + let node = self.node.get()?; + Some( + self.spool + .get_or_init(|| Arc::new(UploadSpool::new(node.config().state_root.join("upload-staging")))) + .clone(), + ) + } + + fn lookup(&self, sandbox_id: &str) -> BoxFuture { + let cell = self.node.clone(); + let id = sandbox_id.to_string(); + Box::pin(async move { + let Some(node) = cell.get().cloned() else { return FileLookup::Forward("node not ready") }; + let since = Instant::now(); + let result = tokio::task::spawn_blocking(move || { + let reg = node.registry().get(&id); + let drain = node.registry().drain_since(since); + let Ok(reg) = reg else { return FileLookup::Forward("registry error") }; + let Some(reg) = reg else { return FileLookup::NotFound }; + if reg.phase != Phase::Owned { + return FileLookup::Forward("not owned"); + } + let sandbox = Sandbox { + sandbox_id: reg.sandbox_id().to_string(), + generation: reg.sandbox_generation as u64, + container_id: reg.container_id.clone(), + bundle: PathBuf::from(®.bundle), + memory_directory: reg.memory_directory.clone(), + spec_sha256: reg.spec_sha256(), + }; + let is_running = running(&node, &sandbox); + let admission_open = drain.map(|d| d.admission_open).unwrap_or(false); + let exec_cfg = &node.config().exec; + let memory_floor_ok = !exec_cfg.active_capacity_configured + || available_mib().is_some_and(|mib| mib >= exec_cfg.memory_floor_mib); + let static_helper = reg.spec.managed_process() || reg.spec.management_helper() == "static"; + FileLookup::Owned(FileTarget { + sandbox_id: reg.sandbox_id().to_string(), + generation: reg.sandbox_generation, + container_id: reg.container_id.clone(), + bundle: sandbox.bundle, + memory_directory: reg.memory_directory.clone(), + spec_sha256: sandbox.spec_sha256, + spec: reg.spec.clone(), + static_helper, + running: is_running, + admission_open, + memory_floor_ok, + }) + }) + .await; + result.unwrap_or(FileLookup::Forward("lookup worker failed")) + }) + } + + fn exec_file( + &self, + target: &FileTarget, + expected_generation: i64, + argv: Vec, + stdin: ExecStdin, + max_stdout: usize, + max_stderr: usize, + ) -> BoxFuture> { + let cell = self.node.clone(); + let target = target.clone(); + Box::pin(async move { + let Some(node) = cell.get().cloned() else { + return Err(FileExecError::Forward("node not ready")); + }; + let config = node.config().exec.clone(); + // Generation check BEFORE taking the shared fence (matches Python `_file_fence`). + let check_node = node.clone(); + let sid = target.sandbox_id.clone(); + let current = tokio::task::spawn_blocking(move || check_node.registry().get(&sid)) + .await + .map_err(|_| FileExecError::Forward("registry worker"))?; + match current { + Ok(Some(reg)) if reg.phase == Phase::Owned && reg.sandbox_generation == expected_generation => {} + Ok(_) => { + return Err(FileExecError::Conflict( + "file operation no longer owns direct sandbox generation".into(), + )); + } + Err(_) => return Err(FileExecError::Forward("registry unreadable")), + } + + let fence = ExecFence::new(&config.warden_locks_dir); + let lease = match fence.acquire(&target.sandbox_id) { + Ok(Fenced::Held(lease)) => lease, + Ok(Fenced::Busy) => return Err(FileExecError::Forward("lifecycle fence busy")), + Err(_) => return Err(FileExecError::Forward("lifecycle fence unreadable")), + }; + + let sandbox = Sandbox { + sandbox_id: target.sandbox_id.clone(), + generation: target.generation as u64, + container_id: target.container_id.clone(), + bundle: target.bundle.clone(), + memory_directory: target.memory_directory.clone(), + spec_sha256: target.spec_sha256.clone(), + }; + // Re-verify running & generation under A held. + let check_node = node.clone(); + let check_sandbox = sandbox.clone(); + let ok = tokio::task::spawn_blocking(move || { + let reg = check_node.registry().get(&check_sandbox.sandbox_id).ok().flatten()?; + if reg.phase != Phase::Owned || reg.sandbox_generation != expected_generation { + return Some(false); + } + Some(running(&check_node, &check_sandbox)) + }) + .await + .map_err(|_| FileExecError::Forward("check worker"))?; + match ok { + None => { + return Err(FileExecError::Conflict( + "file operation no longer owns direct sandbox generation".into(), + )); + } + Some(false) => return Err(FileExecError::Forward("not running")), + Some(true) => {} + } + + let lock = node.warden().lock(&sandbox).await.map_err(|_| FileExecError::Forward("warden lock"))?; + let marker = config.warden_paused_dir.join(format!("{}.sandbox-{}", sandbox.sandbox_id, sandbox.generation)); + if marker.exists() { + node.pause_tier() + .thaw_locked(&sandbox, &lock, true) + .await + .map_err(|_| FileExecError::Forward("thaw failed"))?; + } + + let mut full_argv = Vec::with_capacity(4 + argv.len()); + full_argv.push(config.runsc.to_string_lossy().into_owned()); + full_argv.push(format!("--root={}", config.runtime_root.display())); + full_argv.push("exec".to_string()); + full_argv.push(sandbox.container_id.clone()); + full_argv.extend(argv); + + lease.touch(); + let result = run_bounded_exec(&full_argv, stdin, max_stdout, max_stderr).await; + lease.touch(); + drop(lock); + drop(lease); + result + }) + } +} + +struct ProcessGroupKill { + pid: Option, +} + +impl Drop for ProcessGroupKill { + fn drop(&mut self) { + if let Some(pid) = self.pid { + // SAFETY: kill the session/process group we created with `process_group(0)`. + unsafe { libc::kill(-(pid as libc::pid_t), libc::SIGKILL) }; + } + } +} + +async fn read_bounded( + stream: &mut (impl AsyncRead + Unpin), + limit: usize, +) -> Result, FileExecError> { + let mut out = Vec::new(); + let mut buf = [0u8; 64 * 1024]; + loop { + let n = stream.read(&mut buf).await.map_err(|e| FileExecError::Failed(e.to_string()))?; + if n == 0 { + return Ok(out); + } + if out.len().saturating_add(n) > limit { + return Err(FileExecError::OutputTooLarge( + "direct sandbox exec exceeded its bounded output allowance".into(), + )); + } + out.extend_from_slice(&buf[..n]); + } +} + +/// Spawn `argv` in its own process group, feed `stdin`, and collect bounded stdout/stderr. +pub async fn run_bounded_exec( + argv: &[String], + stdin: ExecStdin, + max_stdout: usize, + max_stderr: usize, +) -> Result { + let mut command = tokio::process::Command::new(&argv[0]); + command.args(&argv[1..]).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true); + // Start a fresh process group so cleanup kills any descendants holding pipes open. + command.process_group(0); + + let bytes_to_write = match stdin { + ExecStdin::None => { + command.stdin(Stdio::null()); + None + } + ExecStdin::Bytes(bytes) => { + command.stdin(Stdio::piped()); + Some(bytes) + } + ExecStdin::File(file) => { + command.stdin(Stdio::from(file)); + None + } + }; + + let mut child = command.spawn().map_err(|error| FileExecError::Failed(format!("file exec failed to start: {error}")))?; + let mut pgrp_guard = ProcessGroupKill { pid: child.id() }; + let mut stdout = child.stdout.take().expect("piped stdout"); + let mut stderr = child.stderr.take().expect("piped stderr"); + let child_stdin = child.stdin.take(); + + let write_task = async move { + if let (Some(mut pipe), Some(bytes)) = (child_stdin, bytes_to_write) { + if !bytes.is_empty() { + let _ = pipe.write_all(&bytes).await; + } + drop(pipe); + } + }; + + let (stdout_res, stderr_res, ()) = tokio::join!( + read_bounded(&mut stdout, max_stdout), + read_bounded(&mut stderr, max_stderr), + write_task + ); + + let (out, err) = match (stdout_res, stderr_res) { + (Ok(out), Ok(err)) => (out, err), + (Err(e), _) | (_, Err(e)) => { + drop(pgrp_guard); + let _ = child.wait().await; + return Err(e); + } + }; + + let status = child.wait().await.map_err(|error| FileExecError::Failed(error.to_string()))?; + pgrp_guard.pid = None; + use std::os::unix::process::ExitStatusExt; + let exit_code = status.code().unwrap_or_else(|| -status.signal().unwrap_or(1)); + Ok(FileExecResult { exit_code, stdout: out, stderr: err }) +} + +// --- Route parsing, query decoding, and HTTP front --- + +#[derive(Debug, Clone, PartialEq, Eq)] +enum FileRoute { + Environment(String), + Download(String), + UploadFile(String), + UploadArchive(String), +} + +fn percent_decode(raw: &str, plus_as_space: bool) -> Option { + let bytes = raw.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + match bytes[i] { + b'+' if plus_as_space => { + out.push(b' '); + i += 1; + } + b'%' if i + 2 < bytes.len() => { + let hi = hex_val(bytes[i + 1])?; + let lo = hex_val(bytes[i + 2])?; + out.push((hi << 4) | lo); + i += 3; + } + b'%' => return None, + byte => { + out.push(byte); + i += 1; + } + } + } + String::from_utf8(out).ok() +} + +fn hex_val(byte: u8) -> Option { + match byte { + b'0'..=b'9' => Some(byte - b'0'), + b'a'..=b'f' => Some(byte - b'a' + 10), + b'A'..=b'F' => Some(byte - b'A' + 10), + _ => None, + } +} + +fn parse_route(method: &Method, path: &str) -> Option { + let rest = path.strip_prefix("/v1/sandboxes/")?; + let (raw_id, suffix) = rest.split_once('/')?; + if raw_id.is_empty() || suffix.contains('/') { + return None; + } + let sandbox_id = percent_decode(raw_id, false)?; + if sandbox_id.is_empty() || sandbox_id.contains('/') { + return None; + } + match (method, suffix) { + (&Method::GET, "environment") => Some(FileRoute::Environment(sandbox_id)), + (&Method::GET, "files") => Some(FileRoute::Download(sandbox_id)), + (&Method::PUT, "files") => Some(FileRoute::UploadFile(sandbox_id)), + (&Method::PUT, "archive") => Some(FileRoute::UploadArchive(sandbox_id)), + _ => None, + } +} + +fn file_path_from_query(query: &str) -> Option { + for pair in query.split('&') { + if pair.is_empty() { + continue; + } + let (k, v) = pair.split_once('=').unwrap_or((pair, "")); + if percent_decode(k, true).as_deref() == Some("path") { + let decoded = percent_decode(v, true)?; + let trimmed = decoded.trim(); + return (!trimmed.is_empty()).then(|| trimmed.to_string()); + } + } + None +} + +fn constant_time_eq(left: &[u8], right: &[u8]) -> bool { + left.len() == right.len() && left.iter().zip(right).fold(0u8, |acc, (a, b)| acc | (a ^ b)) == 0 +} + +fn full(bytes: impl Into) -> Body { + Full::new(bytes.into()).map_err(|never| match never {}).boxed() +} + +fn json_response(status: StatusCode, payload: Value, extra_headers: &[(&str, &str)]) -> Response { + let body = serde_json::to_vec(&payload).unwrap_or_else(|_| b"{}".to_vec()); + let mut response = Response::new(full(body)); + *response.status_mut() = status; + let headers = response.headers_mut(); + headers.insert(header::CONTENT_TYPE, HeaderValue::from_static("application/json")); + for (name, value) in extra_headers { + if let (Ok(name), Ok(value)) = (HeaderName::from_bytes(name.as_bytes()), HeaderValue::from_str(value)) { + headers.insert(name, value); + } + } + response +} + +fn retryable_503(message: &str, code: &str) -> Response { + json_response( + StatusCode::SERVICE_UNAVAILABLE, + json!({"error": message, "error_code": code, "retryable": true}), + &[("Retry-After", "1"), ("X-UCloud-Sandbox-Retryable", "true")], + ) +} + +pub struct FilesFront { + node: Arc, + token: Bytes, + read_slots: OnceLock>, +} + +impl FilesFront { + pub fn new(node: Arc>>, token: &str) -> Arc { + Self::with_node(Arc::new(NodeFiles::new(node)), token) + } + + pub fn with_node(node: Arc, token: &str) -> Arc { + Arc::new(FilesFront { + node, + token: Bytes::copy_from_slice(token.as_bytes()), + read_slots: OnceLock::new(), + }) + } + + fn read_slots(&self) -> Arc { + self.read_slots + .get_or_init(|| Arc::new(Semaphore::new(self.node.max_read_concurrency().max(1)))) + .clone() + } + + fn authorized(&self, request: &Request) -> bool { + let supplied = request + .headers() + .get(header::AUTHORIZATION) + .map(|v| v.as_bytes()) + .and_then(|v| v.strip_prefix(b"Bearer ")); + supplied.is_some_and(|supplied| !supplied.is_empty() && constant_time_eq(supplied, &self.token)) + } + + pub fn intercepts(&self, request: &Request) -> bool { + if parse_route(request.method(), request.uri().path()).is_none() { + return false; + } + if !self.authorized(request) { + return false; + } + if request.headers().contains_key(header::TRANSFER_ENCODING) { + return false; + } + self.node.ready() + } + + pub async fn handle(&self, request: Request) -> Outcome { + let Some(route) = parse_route(request.method(), request.uri().path()) else { + return Outcome::Forward(request); + }; + match route { + FileRoute::Environment(sandbox_id) => self.handle_environment(request, &sandbox_id).await, + FileRoute::Download(sandbox_id) => self.handle_download(request, &sandbox_id).await, + FileRoute::UploadFile(sandbox_id) => self.handle_upload(request, &sandbox_id, false).await, + FileRoute::UploadArchive(sandbox_id) => self.handle_upload(request, &sandbox_id, true).await, + } + } + + async fn handle_environment(&self, request: Request, sandbox_id: &str) -> Outcome { + match self.node.lookup(sandbox_id).await { + FileLookup::Owned(target) => { + Outcome::Response(json_response(StatusCode::OK, json!({"environment": describe_environment(&target.spec)}), &[])) + } + FileLookup::NotFound => { + Outcome::Response(json_response(StatusCode::NOT_FOUND, json!({"error": "sandbox not found"}), &[])) + } + FileLookup::Forward(_) => Outcome::Forward(request), + } + } + + async fn handle_download(&self, request: Request, sandbox_id: &str) -> Outcome { + let query = request.uri().query().unwrap_or(""); + let Some(container_path) = file_path_from_query(query) else { + return Outcome::Response(json_response( + StatusCode::BAD_REQUEST, + json!({"error": "path query parameter is required"}), + &[], + )); + }; + if let Err(error) = validate_guest_path("sandbox file path", &container_path) { + return Outcome::Response(json_response(StatusCode::BAD_REQUEST, json!({"error": error}), &[])); + } + let target = match self.node.lookup(sandbox_id).await { + FileLookup::Owned(target) if target.running && target.admission_open && target.memory_floor_ok => target, + _ => return Outcome::Forward(request), + }; + let max_bytes = self.node.max_file_body_bytes(); + let argv = if target.static_helper { + vec![ + MANAGED_PROCESS_BINARY.to_string(), + "files".to_string(), + "read".to_string(), + container_path.clone(), + max_bytes.to_string(), + ] + } else { + vec!["/bin/cat".to_string(), "--".to_string(), container_path.clone()] + }; + + let slots = self.read_slots(); + let permit = match tokio::time::timeout(self.node.admission_wait(), slots.acquire_owned()).await { + Ok(Ok(permit)) => permit, + _ => { + return Outcome::Response(retryable_503( + "node file read admission wait deadline exceeded", + "node_startup_busy", + )); + } + }; + let result = self + .node + .exec_file(&target, target.generation, argv, ExecStdin::None, max_bytes as usize, MAX_HELPER_OUTPUT_BYTES) + .await; + drop(permit); + + match result { + Ok(res) if res.exit_code == 0 => { + let mut response = Response::new(full(res.stdout)); + *response.status_mut() = StatusCode::OK; + let headers = response.headers_mut(); + headers.insert(header::CONTENT_TYPE, HeaderValue::from_static("application/octet-stream")); + if let Ok(val) = HeaderValue::from_str(sandbox_id) { + headers.insert(HeaderName::from_static("x-sandbox-id"), val); + } + if let Ok(val) = HeaderValue::from_str(&container_path) { + headers.insert(HeaderName::from_static("x-sandbox-path"), val); + } + Outcome::Response(response) + } + Ok(res) => Outcome::Response(json_response( + StatusCode::SERVICE_UNAVAILABLE, + json!({"error": format!("sandbox file read failed with exit {}", res.exit_code)}), + &[], + )), + Err(FileExecError::Forward(_)) => Outcome::Forward(request), + Err(FileExecError::Conflict(msg)) => { + Outcome::Response(json_response(StatusCode::CONFLICT, json!({"error": msg}), &[])) + } + Err(FileExecError::OutputTooLarge(msg)) => { + Outcome::Response(json_response(StatusCode::PAYLOAD_TOO_LARGE, json!({"error": msg}), &[])) + } + Err(FileExecError::Failed(msg)) => { + Outcome::Response(json_response(StatusCode::SERVICE_UNAVAILABLE, json!({"error": msg}), &[])) + } + } + } + + async fn handle_upload(&self, request: Request, sandbox_id: &str, archive: bool) -> Outcome { + let query = request.uri().query().unwrap_or(""); + let Some(container_path) = file_path_from_query(query) else { + return Outcome::Response(json_response( + StatusCode::BAD_REQUEST, + json!({"error": "path query parameter is required"}), + &[], + )); + }; + let max_bytes = self.node.max_file_body_bytes(); + let size = match parse_content_length(request.headers(), max_bytes) { + Ok(size) => size, + Err((status, msg)) => return Outcome::Response(json_response(status, json!({"error": msg}), &[])), + }; + let target = match self.node.lookup(sandbox_id).await { + FileLookup::Owned(target) if target.running && target.admission_open && target.memory_floor_ok => target, + _ => return Outcome::Forward(request), + }; + if let Some(raw_gen) = request.headers().get(SANDBOX_GENERATION_HEADER) { + let parsed_gen = raw_gen.to_str().ok().and_then(|s| s.trim().parse::().ok()); + match parsed_gen { + None => { + return Outcome::Response(json_response( + StatusCode::BAD_REQUEST, + json!({"error": "invalid sandbox generation header"}), + &[], + )); + } + Some(supplied) if supplied != target.generation => { + return Outcome::Response(json_response( + StatusCode::CONFLICT, + json!({"error": "file operation no longer owns direct sandbox generation"}), + &[], + )); + } + Some(_) => {} + } + } + + let (parts, mut body) = request.into_parts(); + let small_bytes: Option; + let staged_input; + + if size <= TRANSFER_CHUNK_BYTES as u64 { + let mut collected = Vec::with_capacity(size as usize); + while let Some(frame) = body.frame().await { + let Ok(frame) = frame else { + return Outcome::Response(json_response( + StatusCode::BAD_REQUEST, + json!({"error": "request body ended before Content-Length bytes were read"}), + &[], + )); + }; + if let Ok(data) = frame.into_data() { + if collected.len() + data.len() > size as usize { + return Outcome::Response(json_response( + StatusCode::PAYLOAD_TOO_LARGE, + json!({"error": "request body exceeds maximum allowed size"}), + &[], + )); + } + collected.extend_from_slice(&data); + } + } + if collected.len() as u64 != size { + return Outcome::Response(json_response( + StatusCode::BAD_REQUEST, + json!({"error": "request body ended before Content-Length bytes were read"}), + &[], + )); + } + small_bytes = Some(Bytes::from(collected)); + staged_input = None; + } else { + let Some(spool) = self.node.upload_spool() else { + return Outcome::Response(retryable_503("upload staging is unavailable", "node_startup_busy")); + }; + let mut staged = match spool.staging(size) { + Ok(staged) => staged, + Err(ArchiveError::SpoolSpace(msg)) => { + // Drain bounded body before answering 503 so clients do not see a reset. + while let Some(Ok(_)) = body.frame().await {} + return Outcome::Response(retryable_503(&msg, "node_startup_busy")); + } + Err(err) => { + return Outcome::Response(json_response( + StatusCode::SERVICE_UNAVAILABLE, + json!({"error": err.to_string()}), + &[], + )); + } + }; + let mut written_total: u64 = 0; + while let Some(frame) = body.frame().await { + let Ok(frame) = frame else { + return Outcome::Response(json_response( + StatusCode::BAD_REQUEST, + json!({"error": "request body ended before Content-Length bytes were read"}), + &[], + )); + }; + if let Ok(data) = frame.into_data() { + if written_total + data.len() as u64 > size { + return Outcome::Response(json_response( + StatusCode::PAYLOAD_TOO_LARGE, + json!({"error": "request body exceeds maximum allowed size"}), + &[], + )); + } + if let Err(err) = staged.file.write_all(&data) { + if matches!(err.raw_os_error(), Some(libc::ENOSPC | libc::EDQUOT)) { + while let Some(Ok(_)) = body.frame().await {} + return Outcome::Response(retryable_503( + "node upload staging is waiting for disk space", + "node_startup_busy", + )); + } + return Outcome::Response(json_response( + StatusCode::SERVICE_UNAVAILABLE, + json!({"error": err.to_string()}), + &[], + )); + } + staged.consume_reservation(data.len() as u64); + written_total += data.len() as u64; + } + } + if written_total != size { + return Outcome::Response(json_response( + StatusCode::BAD_REQUEST, + json!({"error": "request body ended before Content-Length bytes were read"}), + &[], + )); + } + if let Err(err) = staged.file.seek(SeekFrom::Start(0)) { + return Outcome::Response(json_response( + StatusCode::SERVICE_UNAVAILABLE, + json!({"error": err.to_string()}), + &[], + )); + } + small_bytes = None; + staged_input = Some(staged); + } + + if archive { + self.finish_archive_upload(parts, &target, &container_path, size, max_bytes, small_bytes, staged_input) + .await + } else { + self.finish_file_upload(parts, &target, &container_path, size, small_bytes, staged_input).await + } + } + + async fn finish_file_upload( + &self, + parts: hyper::http::request::Parts, + target: &FileTarget, + container_path: &str, + size: u64, + small_bytes: Option, + staged_input: Option, + ) -> Outcome { + if let Err(error) = validate_guest_path("sandbox file path", container_path) { + return Outcome::Response(json_response(StatusCode::BAD_REQUEST, json!({"error": error}), &[])); + } + let argv = if target.static_helper { + vec![ + MANAGED_PROCESS_BINARY.to_string(), + "files".to_string(), + "write".to_string(), + container_path.to_string(), + size.max(1).to_string(), + ] + } else { + vec![ + "/bin/sh".to_string(), + "-c".to_string(), + sandbox_file_write_script().to_string(), + "ucloud-write".to_string(), + container_path.to_string(), + ] + }; + let forward_copy = small_bytes.clone(); + let stdin = match (small_bytes, staged_input) { + (Some(bytes), None) => ExecStdin::Bytes(bytes), + (None, Some(staged)) => match staged.file.try_clone() { + Ok(file) => ExecStdin::File(file), + Err(err) => { + return Outcome::Response(json_response( + StatusCode::SERVICE_UNAVAILABLE, + json!({"error": err.to_string()}), + &[], + )); + } + }, + _ => unreachable!(), + }; + match self + .node + .exec_file(target, target.generation, argv, stdin, MAX_HELPER_OUTPUT_BYTES, MAX_HELPER_OUTPUT_BYTES) + .await + { + Ok(res) if res.exit_code == 0 => Outcome::Response(json_response( + StatusCode::OK, + json!({"ok": true, "sandbox_id": target.sandbox_id, "path": container_path, "size": size}), + &[], + )), + Ok(res) => Outcome::Response(json_response( + StatusCode::SERVICE_UNAVAILABLE, + json!({"error": format!("sandbox file write failed with exit {}", res.exit_code)}), + &[], + )), + Err(FileExecError::Forward(_)) => { + if let Some(bytes) = forward_copy { + Outcome::Forward(Request::from_parts(parts, full(bytes))) + } else { + Outcome::Response(retryable_503("direct sandbox is unavailable", "node_active_exec_deferred")) + } + } + Err(FileExecError::Conflict(msg)) => { + Outcome::Response(json_response(StatusCode::CONFLICT, json!({"error": msg}), &[])) + } + Err(FileExecError::OutputTooLarge(msg)) => { + Outcome::Response(json_response(StatusCode::PAYLOAD_TOO_LARGE, json!({"error": msg}), &[])) + } + Err(FileExecError::Failed(msg)) => { + Outcome::Response(json_response(StatusCode::SERVICE_UNAVAILABLE, json!({"error": msg}), &[])) + } + } + } + + #[allow(clippy::too_many_arguments)] + async fn finish_archive_upload( + &self, + parts: hyper::http::request::Parts, + target: &FileTarget, + container_path: &str, + size: u64, + max_bytes: u64, + small_bytes: Option, + staged_input: Option, + ) -> Outcome { + if let Err(error) = validate_guest_path("sandbox archive directory", container_path) { + return Outcome::Response(json_response(StatusCode::BAD_REQUEST, json!({"error": error}), &[])); + } + let forward_copy = small_bytes.clone(); + let spool = self.node.upload_spool(); + let planned = tokio::task::spawn_blocking(move || { + let source = match (&small_bytes, &staged_input) { + (Some(bytes), None) => ArchiveSource::Bytes(bytes.as_ref()), + (None, Some(staged)) => ArchiveSource::File(&staged.file), + _ => unreachable!(), + }; + let plan = plan_archive(source, max_bytes)?; + let source2 = match (&small_bytes, &staged_input) { + (Some(bytes), None) => ArchiveSource::Bytes(bytes.as_ref()), + (None, Some(staged)) => ArchiveSource::File(&staged.file), + _ => unreachable!(), + }; + let normalized = normalized_archive(source2, &plan, spool.as_ref(), max_bytes)?; + Ok::<_, ArchiveError>((plan, normalized)) + }) + .await; + + let (plan, normalized) = match planned { + Ok(Ok(pair)) => pair, + Ok(Err(ArchiveError::Invalid(msg))) => { + return Outcome::Response(json_response(StatusCode::BAD_REQUEST, json!({"error": msg}), &[])); + } + Ok(Err(ArchiveError::TooLarge(msg))) => { + return Outcome::Response(json_response(StatusCode::PAYLOAD_TOO_LARGE, json!({"error": msg}), &[])); + } + Ok(Err(ArchiveError::SpoolSpace(msg))) => { + return Outcome::Response(retryable_503(&msg, "node_startup_busy")); + } + Ok(Err(ArchiveError::Io(err))) => { + return Outcome::Response(json_response( + StatusCode::SERVICE_UNAVAILABLE, + json!({"error": err.to_string()}), + &[], + )); + } + Err(err) => { + return Outcome::Response(json_response( + StatusCode::SERVICE_UNAVAILABLE, + json!({"error": err.to_string()}), + &[], + )); + } + }; + + let mut argv = if target.static_helper { + vec![ + MANAGED_PROCESS_BINARY.to_string(), + "files".to_string(), + "extract".to_string(), + container_path.to_string(), + plan.total_bytes.max(1).to_string(), + ] + } else { + vec![ + "/bin/sh".to_string(), + "-c".to_string(), + sandbox_archive_extract_script().to_string(), + "ucloud-extract".to_string(), + container_path.to_string(), + ] + }; + argv.extend(plan.empty_directories.iter().cloned()); + + let _staged_guard; + let stdin = match normalized { + NormalizedArchive::Bytes(bytes) => { + _staged_guard = None; + ExecStdin::Bytes(Bytes::from(bytes)) + } + NormalizedArchive::File(staged) => { + let cloned = match staged.file.try_clone() { + Ok(file) => file, + Err(err) => { + return Outcome::Response(json_response( + StatusCode::SERVICE_UNAVAILABLE, + json!({"error": err.to_string()}), + &[], + )); + } + }; + _staged_guard = Some(staged); + ExecStdin::File(cloned) + } + }; + + match self + .node + .exec_file(target, target.generation, argv, stdin, MAX_HELPER_OUTPUT_BYTES, MAX_HELPER_OUTPUT_BYTES) + .await + { + Ok(res) if res.exit_code == 0 => Outcome::Response(json_response( + StatusCode::OK, + json!({ + "ok": true, + "sandbox_id": target.sandbox_id, + "path": container_path, + "size": size, + "files": plan.files, + "directories": plan.directory_members, + "bytes": plan.total_bytes, + }), + &[], + )), + Ok(res) => { + if !target.static_helper && archive_helper_unsupported(res.exit_code, &res.stderr) { + return Outcome::Response(json_response( + StatusCode::NOT_IMPLEMENTED, + json!({ + "error": "this sandbox cannot extract archives; upload files one by one", + "error_code": "archive_upload_unsupported", + "retryable": false, + }), + &[], + )); + } + let stderr_text = String::from_utf8_lossy(&res.stderr); + let trimmed = stderr_text.trim(); + let tail: String = trimmed.chars().rev().take(300).collect::>().into_iter().rev().collect(); + Outcome::Response(json_response( + StatusCode::SERVICE_UNAVAILABLE, + json!({"error": format!("sandbox archive extraction failed with exit {}: {}", res.exit_code, tail)}), + &[], + )) + } + Err(FileExecError::Forward(_)) => { + if let Some(bytes) = forward_copy { + Outcome::Forward(Request::from_parts(parts, full(bytes))) + } else { + Outcome::Response(retryable_503("direct sandbox is unavailable", "node_active_exec_deferred")) + } + } + Err(FileExecError::Conflict(msg)) => { + Outcome::Response(json_response(StatusCode::CONFLICT, json!({"error": msg}), &[])) + } + Err(FileExecError::OutputTooLarge(msg)) => { + Outcome::Response(json_response(StatusCode::PAYLOAD_TOO_LARGE, json!({"error": msg}), &[])) + } + Err(FileExecError::Failed(msg)) => { + Outcome::Response(json_response(StatusCode::SERVICE_UNAVAILABLE, json!({"error": msg}), &[])) + } + } + } +} + +fn parse_content_length(headers: &hyper::HeaderMap, max_bytes: u64) -> Result { + let raw = match headers.get(header::CONTENT_LENGTH) { + None => return Ok(0), + Some(value) => value.to_str().map_err(|_| (StatusCode::BAD_REQUEST, "invalid Content-Length header"))?, + }; + let parsed: u64 = raw.trim().parse().map_err(|_| (StatusCode::BAD_REQUEST, "invalid Content-Length header"))?; + if parsed > max_bytes { + return Err((StatusCode::PAYLOAD_TOO_LARGE, "request body exceeds maximum allowed size")); + } + Ok(parsed) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_file_routes_and_query_paths() { + assert_eq!(parse_route(&Method::GET, "/v1/sandboxes/sb-1/environment"), Some(FileRoute::Environment("sb-1".into()))); + assert_eq!(parse_route(&Method::GET, "/v1/sandboxes/sb-1/files"), Some(FileRoute::Download("sb-1".into()))); + assert_eq!(parse_route(&Method::PUT, "/v1/sandboxes/sb-1/files"), Some(FileRoute::UploadFile("sb-1".into()))); + assert_eq!(parse_route(&Method::PUT, "/v1/sandboxes/sb-1/archive"), Some(FileRoute::UploadArchive("sb-1".into()))); + assert_eq!(parse_route(&Method::POST, "/v1/sandboxes/sb-1/files"), None); + assert_eq!(parse_route(&Method::GET, "/v1/sandboxes/sb-1/exec"), None); + assert_eq!(parse_route(&Method::GET, "/v1/sandboxes/a%2Fb/files"), None); + + assert_eq!(file_path_from_query("path=%2Fwork%2Fhello+world.txt"), Some("/work/hello world.txt".into())); + assert_eq!(file_path_from_query("foo=1&path=/a/b"), Some("/a/b".into())); + assert_eq!(file_path_from_query("path= "), None); + assert_eq!(file_path_from_query(""), None); + } +} diff --git a/runtime/noded/src/heartbeat.rs b/runtime/noded/src/heartbeat.rs new file mode 100644 index 00000000..20a1fbc4 --- /dev/null +++ b/runtime/noded/src/heartbeat.rs @@ -0,0 +1,673 @@ +//! Node health, drain control, heartbeat snapshot assembly, and background +//! heartbeat push loop for standalone `ucloud-noded` (Wave B6). +//! +//! Serves: +//! - `GET /healthz` +//! - `GET /v1/heartbeat` +//! - `POST /v1/drain` + +use std::collections::BTreeMap; +use std::path::PathBuf; +use std::sync::atomic::{AtomicI64, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +use bytes::Bytes; +use http_body_util::{BodyExt, Full, Limited}; +use hyper::client::conn::http1; +use hyper::header::{self, HeaderValue}; +use hyper::{Method, Request, Response, StatusCode, Uri}; +use hyper_util::rt::TokioIo; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use tokio::net::TcpStream; +use tokio::sync::Notify; + +use crate::Body; +use crate::exec_front::Outcome; +use crate::images_front::{ImageCatalog, PullMetrics}; +use crate::node_pipeline::NodePipeline; +use crate::registry::{DrainState, Phase, is_operation_id}; +use crate::runtime_metrics::{CpuDeltaSampler, physical_disk_usage_mb, sample_node_runtime_metrics}; +use crate::sandbox_record::{format_utc_timestamp, now_utc_ns}; + +const MAX_BODY_BYTES: usize = 64 * 1024; +const HEARTBEAT_POST_TIMEOUT: Duration = Duration::from_secs(15); + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct HeartbeatConfig { + pub job_id: String, + pub node_id: String, + pub node_url: String, + pub agent_version: String, + pub deployment_id: String, + pub init_version: String, + pub node_epoch: String, + pub capabilities: Vec, + pub total_vcpu: f64, + pub total_memory_mb: i64, + pub total_disk_mb: i64, + pub physical_disk_path: PathBuf, + #[serde(default)] + pub labels: BTreeMap, + #[serde(default)] + pub push_url: Option, + #[serde(default)] + pub push_bearer_token: Option, + #[serde(default = "default_push_interval_secs")] + pub push_interval_secs: f64, +} + +fn default_push_interval_secs() -> f64 { + 20.0 +} + +#[derive(Clone, Debug)] +pub struct DrainSnapshot { + pub drain: DrainState, + pub activity_epoch: i64, + pub active_sandboxes: usize, + pub reserved_vcpu: f64, + pub reserved_memory_mb: i64, + pub reserved_disk_mb: i64, + pub ready: bool, +} + +pub struct HeartbeatFront { + config: HeartbeatConfig, + node: Arc>>, + catalog: Option>, + pull_metrics_fn: Arc PullMetrics + Send + Sync>, + token: Bytes, + cpu_sampler: CpuDeltaSampler, + drain_guard: Mutex<()>, + activity_epoch_base: AtomicI64, + /// Optional fallback drain state when no `NodePipeline` is loaded (tests). + fallback_drain: Mutex, +} + +impl HeartbeatFront { + pub fn new( + config: HeartbeatConfig, + node: Arc>>, + catalog: Option>, + pull_metrics_fn: Arc PullMetrics + Send + Sync>, + token: &str, + ) -> Arc { + // Initialize monotonic-domain floor matching Python's `time.monotonic_ns()`. + let boot_ns = monotonic_ns(); + Arc::new(HeartbeatFront { + config, + node, + catalog, + pull_metrics_fn, + token: Bytes::copy_from_slice(token.as_bytes()), + cpu_sampler: CpuDeltaSampler::new(), + drain_guard: Mutex::new(()), + activity_epoch_base: AtomicI64::new(boot_ns), + fallback_drain: Mutex::new(DrainState { + draining: false, + token: String::new(), + drain_activity_epoch: 0, + admission_open: true, + }), + }) + } + + pub fn config(&self) -> &HeartbeatConfig { + &self.config + } + + pub fn advance_activity_epoch(&self) -> i64 { + let transient = self.activity_epoch_base.fetch_add(1, Ordering::SeqCst) + 1; + let durable = self + .node + .get() + .and_then(|n| n.registry().activity_revision().ok()) + .unwrap_or(0); + durable.saturating_add(transient) + } + + fn authorized(&self, request: &Request) -> bool { + let supplied = request + .headers() + .get(header::AUTHORIZATION) + .map(|v| v.as_bytes()) + .and_then(|v| v.strip_prefix(b"Bearer ")); + supplied.is_some_and(|s| !s.is_empty() && constant_time_eq(s, &self.token)) + } + + pub fn intercepts(&self, request: &Request) -> bool { + match (request.method(), request.uri().path()) { + (&Method::GET, "/healthz") => true, + (&Method::GET, "/v1/heartbeat") | (&Method::POST, "/v1/drain") => true, + _ => false, + } + } + + pub async fn handle(&self, request: Request) -> Outcome { + match (request.method(), request.uri().path()) { + (&Method::GET, "/healthz") => Outcome::Response(json_response( + StatusCode::OK, + json!({ + "ok": true, + "service": "node-agent", + "version": self.config.agent_version, + }), + )), + (&Method::GET, "/v1/heartbeat") => { + if !self.authorized(&request) { + return Outcome::Response(unauthorized()); + } + let hb = self.sample_heartbeat_json().await; + Outcome::Response(json_response(StatusCode::OK, json!({"heartbeat": hb}))) + } + (&Method::POST, "/v1/drain") => { + if !self.authorized(&request) { + return Outcome::Response(unauthorized()); + } + self.handle_drain(request).await + } + _ => Outcome::Forward(request), + } + } + + async fn handle_drain(&self, request: Request) -> Outcome { + let bytes = match Limited::new(request.into_body(), MAX_BODY_BYTES).collect().await { + Ok(collected) => collected.to_bytes(), + Err(_) => { + return Outcome::Response(json_response( + StatusCode::BAD_REQUEST, + json!({"error": "invalid drain payload"}), + )); + } + }; + let raw: Value = match serde_json::from_slice::(&bytes) { + Ok(v) if v.is_object() => v, + _ => { + return Outcome::Response(json_response( + StatusCode::BAD_REQUEST, + json!({"error": "drain payload must be a JSON object"}), + )); + } + }; + let obj = raw.as_object().unwrap(); + if obj.len() != 2 || !obj.contains_key("draining") || !obj.contains_key("token") { + return Outcome::Response(json_response( + StatusCode::BAD_REQUEST, + json!({"error": "drain payload has an invalid schema"}), + )); + } + let Some(token) = obj.get("token").and_then(Value::as_str).map(str::trim) else { + return Outcome::Response(json_response( + StatusCode::BAD_REQUEST, + json!({"error": "drain token must be a string"}), + )); + }; + let Some(draining) = obj.get("draining").and_then(Value::as_bool) else { + return Outcome::Response(json_response( + StatusCode::BAD_REQUEST, + json!({"error": "draining must be a boolean"}), + )); + }; + if token.is_empty() || !is_operation_id(token) { + return Outcome::Response(json_response( + StatusCode::BAD_REQUEST, + json!({"error": "drain token contains unsupported characters"}), + )); + } + match self.configure_drain(token, draining) { + Ok(snap) => Outcome::Response(json_response( + StatusCode::OK, + json!({ + "drain": { + "token": snap.drain.token, + "draining": snap.drain.draining, + "admission_open": snap.drain.admission_open, + "drain_activity_epoch": snap.drain.drain_activity_epoch, + "activity_epoch": snap.activity_epoch, + "active_sandboxes": snap.active_sandboxes, + "reserved_resources": { + "vcpu": snap.reserved_vcpu, + "memory_mb": snap.reserved_memory_mb, + "disk_mb": snap.reserved_disk_mb, + }, + "active_image_builds": 0, + "ready": snap.ready, + } + }), + )), + Err((status, msg)) => Outcome::Response(json_response(status, json!({"error": msg}))), + } + } + + pub fn configure_drain(&self, token: &str, draining: bool) -> Result { + let _guard = self.drain_guard.lock().expect("not poisoned"); + let current = self.load_drain(); + let next = if draining { + if current.draining && current.token != token { + return Err((StatusCode::CONFLICT, "node is draining with another token".into())); + } + if !current.draining { + if let Some(admission) = self.node.get().and_then(|n| n.admission()) { + admission.close(); + } + let state = DrainState { + draining: true, + token: token.to_string(), + drain_activity_epoch: 0, + admission_open: false, + }; + self.save_drain(&state)?; + state + } else { + current + } + } else { + if current.token != token { + return Err((StatusCode::CONFLICT, "node is not draining with this token".into())); + } + if current.draining { + if let Some(admission) = self.node.get().and_then(|n| n.admission()) { + admission.open_admission(); + } + let state = DrainState { + draining: false, + token: token.to_string(), + drain_activity_epoch: 0, + admission_open: true, + }; + self.save_drain(&state)?; + state + } else { + current + } + }; + Ok(self.drain_snapshot_locked(next)) + } + + fn load_drain(&self) -> DrainState { + if let Some(node) = self.node.get() { + if let Ok(state) = node.registry().load_drain() { + return state; + } + } + self.fallback_drain.lock().expect("not poisoned").clone() + } + + fn save_drain(&self, state: &DrainState) -> Result<(), (StatusCode, String)> { + if let Some(node) = self.node.get() { + node.registry() + .save_drain(state) + .map_err(|e| (StatusCode::SERVICE_UNAVAILABLE, e.to_string()))?; + } else { + *self.fallback_drain.lock().expect("not poisoned") = state.clone(); + } + Ok(()) + } + + fn drain_snapshot_locked(&self, mut drain: DrainState) -> DrainSnapshot { + let (inventory_count, active_sandboxes, reserved_vcpu, reserved_memory_mb, reserved_disk_mb, durable_rev) = + if let Some(node) = self.node.get() { + let snap = node.registry().snapshot().ok(); + let durable_rev = snap.as_ref().map_or(0, |s| s.activity_revision); + let mut count = 0usize; + let mut active = 0usize; + let mut rv = 0.0f64; + let mut rm = 0i64; + let mut rd = 0i64; + if let Some(snap) = snap { + for reg in snap.records.iter().filter(|r| r.phase != Phase::Deleting) { + count += 1; + let state = if reg.phase == Phase::Owned { + node.warden() + .journal() + .load(reg.sandbox_id(), reg.sandbox_generation as u64) + .ok() + .flatten() + .and_then(|j| j.get("state").and_then(Value::as_str).map(str::to_string)) + .unwrap_or_else(|| "unavailable".to_string()) + } else { + reg.phase.as_str().to_string() + }; + if state == "running" { + active += 1; + } else if state != "parked" { + rv += reg.spec.to_dict().get("cpus").and_then(Value::as_f64).unwrap_or(0.0); + rm += reg.spec.memory_mb().unwrap_or(0); + rd += reg.quota_total_mb.or_else(|| reg.spec.disk_mb()).unwrap_or(0); + } + } + } + (count, active, rv, rm, rd, durable_rev) + } else { + (0, 0, 0.0, 0, 0, 0) + }; + + let active_ops = self + .node + .get() + .and_then(|n| n.admission()) + .map_or(0, |a| a.held()); + let transient = self.activity_epoch_base.load(Ordering::SeqCst); + let activity_epoch = durable_rev.saturating_add(transient); + if drain.draining && inventory_count == 0 && active_ops == 0 && drain.drain_activity_epoch != activity_epoch { + drain.drain_activity_epoch = activity_epoch; + let _ = self.save_drain(&drain); + } + let ready = drain.draining && inventory_count == 0 && active_ops == 0; + DrainSnapshot { + drain, + activity_epoch, + active_sandboxes, + reserved_vcpu, + reserved_memory_mb, + reserved_disk_mb, + ready, + } + } + + /// Assemble the full `NodeHeartbeat` JSON matching `sandboxes/registry.py::heartbeat_to_dict`. + pub async fn sample_heartbeat_json(&self) -> Value { + let (drain_snap, inventory, used_disk_mb, mem_root, workspace_grant_mb, demonstrated_memory, extra_reserved) = { + let _guard = self.drain_guard.lock().expect("not poisoned"); + let drain_state = self.load_drain(); + let drain_snap = self.drain_snapshot_locked(drain_state); + + let mut inventory = Vec::new(); + let mut used_disk_mb = 0i64; + let mut extra_reserved: u64 = 0; + if let Some(node) = self.node.get() { + if let Some(mem) = node.memory() { + if let Ok(bytes) = mem.hard_reserved_bytes() { + extra_reserved = extra_reserved.saturating_add(bytes); + } + } + if let Ok(overlap) = node.registry().reflink_overlap_bytes() { + extra_reserved = extra_reserved.saturating_add(overlap.max(0) as u64); + } + if let Ok(snap) = node.registry().snapshot() { + let claims = node.registry().disk_claims_mb().unwrap_or_default(); + for reg in snap.records.iter().filter(|r| r.phase != Phase::Deleting) { + let state = if reg.phase == Phase::Owned { + node.warden() + .journal() + .load(reg.sandbox_id(), reg.sandbox_generation as u64) + .ok() + .flatten() + .and_then(|j| j.get("state").and_then(Value::as_str).map(str::to_string)) + .unwrap_or_else(|| "unavailable".to_string()) + } else { + reg.phase.as_str().to_string() + }; + let key = (reg.sandbox_id().to_string(), reg.sandbox_generation); + let disk_mb = claims + .get(&key) + .copied() + .or(reg.quota_total_mb) + .or_else(|| reg.spec.disk_mb()) + .unwrap_or(0); + if state == "running" || state == "parked" { + used_disk_mb += disk_mb; + } + let req_vcpu = reg.spec.to_dict().get("cpus").and_then(Value::as_f64).unwrap_or(0.0); + let req_mem = reg.spec.memory_mb().unwrap_or(0); + let req_disk = reg.spec.requested_disk_mb().unwrap_or(disk_mb); + inventory.push(json!({ + "sandbox_id": reg.sandbox_id(), + "generation": reg.sandbox_generation, + "operation_id": reg.operation_id, + "spec_hash": reg.spec_sha256(), + "state": state, + "resources": {"vcpu": req_vcpu, "memory_mb": req_mem, "disk_mb": req_disk}, + "storage_schema": "", + "snapshot_manifest_digest": "", + "snapshot_repository": "", + "snapshot_tag": "", + "storage_snapshot": {}, + "storage_dependency": null, + "memory_observation": null, + "managed_process": null, + })); + } + } + } + let mem_root = self + .node + .get() + .and_then(|n| n.config().application_memory_root.clone()); + let workspace_grant_mb = self + .node + .get() + .map_or(0, |n| n.config().workspace_initial_grant_mb.max(0) as u64); + let demonstrated_memory = self + .node + .get() + .is_some_and(|n| n.config().demonstrated_memory); + ( + drain_snap, + inventory, + used_disk_mb, + mem_root, + workspace_grant_mb, + demonstrated_memory, + extra_reserved, + ) + }; + + let storage_metrics = if let Some(node) = self.node.get() { + match tokio::time::timeout( + Duration::from_secs(5), + node.storage().get_metrics(serde_json::Map::new()), + ) + .await + { + Ok(Ok(metrics)) => Some(metrics), + Ok(Err(err)) => { + eprintln!("ucloud-noded: storage-native GetMetrics failed: {err}"); + None + } + Err(_) => { + eprintln!("ucloud-noded: storage-native GetMetrics timed out"); + None + } + } + } else { + None + }; + + let (phys_total_mb, phys_free_mb) = physical_disk_usage_mb(&self.config.physical_disk_path); + let pull_metrics = (self.pull_metrics_fn)(); + let runtime_metrics = sample_node_runtime_metrics( + std::path::Path::new("/proc"), + mem_root.as_deref(), + &self.cpu_sampler, + &pull_metrics, + None, + storage_metrics.as_ref(), + extra_reserved, + workspace_grant_mb, + demonstrated_memory, + ); + let cached_images = self + .catalog + .as_ref() + .map_or_else(Vec::new, |c| c.cached_refs()); + let now = format_utc_timestamp(now_utc_ns()); + + json!({ + "node_id": self.config.node_id, + "job_id": self.config.job_id, + "updated_at": now, + "reported_at": now, + "received_at": null, + "active_sandboxes": drain_snap.active_sandboxes, + "active_image_builds": 0, + "active_sandbox_creates": 0, + "idle_since": null, + "draining": drain_snap.drain.draining, + "node_url": self.config.node_url, + "agent_version": self.config.agent_version, + "deployment_id": self.config.deployment_id, + "init_version": self.config.init_version, + "capabilities": self.config.capabilities, + "total_resources": { + "vcpu": self.config.total_vcpu, + "memory_mb": self.config.total_memory_mb, + "disk_mb": self.config.total_disk_mb, + }, + "resources_known": true, + "used_resources": {"vcpu": 0.0, "memory_mb": 0, "disk_mb": used_disk_mb}, + "reserved_resources": { + "vcpu": drain_snap.reserved_vcpu, + "memory_mb": drain_snap.reserved_memory_mb, + "disk_mb": drain_snap.reserved_disk_mb, + }, + "build_reserved_resources": {"vcpu": 0.0, "memory_mb": 0, "disk_mb": 0}, + "labels": self.config.labels, + "cached_images": cached_images, + "cached_images_known": true, + "runtime_metrics": runtime_metrics, + "node_epoch": self.config.node_epoch, + "retired_node_epochs": [], + "activity_epoch": drain_snap.activity_epoch, + "inventory": inventory, + "inventory_complete": true, + "physical_disk_total_mb": phys_total_mb, + "physical_disk_free_mb": phys_free_mb, + "drain_token": if drain_snap.drain.draining { drain_snap.drain.token } else { String::new() }, + "drain_activity_epoch": drain_snap.drain.drain_activity_epoch, + "admission_open": drain_snap.drain.admission_open, + }) + } +} + +/// Background heartbeat pusher (`sandboxes/heartbeat_sender.py::NodeHeartbeatSender`). +pub struct HeartbeatPusher { + stop: Arc, + handle: Option>, +} + +impl HeartbeatPusher { + pub fn start(front: Arc) -> Option { + let url = front.config().push_url.clone()?; + let bearer = front.config().push_bearer_token.clone()?; + let interval = Duration::from_secs_f64(front.config().push_interval_secs.max(0.1)); + let stop = Arc::new(Notify::new()); + let stop_task = stop.clone(); + let handle = tokio::spawn(async move { + let mut failures: u32 = 0; + loop { + let payload = front.sample_heartbeat_json().await; + let delay = match post_heartbeat(&url, &bearer, &payload).await { + Ok(status) if status.is_success() => { + failures = 0; + interval + } + Ok(status) if matches!(status.as_u16(), 408 | 429 | 500..=599) => { + failures = failures.saturating_add(1); + let backoff = Duration::from_secs_f64((1.0 * 2f64.powi((failures - 1).min(6) as i32)).min(interval.as_secs_f64())); + backoff + } + Ok(_) => { + failures = 0; + interval + } + Err(err) => { + eprintln!("ucloud-noded: heartbeat push failed: {err}"); + failures = failures.saturating_add(1); + Duration::from_secs_f64((1.0 * 2f64.powi((failures - 1).min(6) as i32)).min(interval.as_secs_f64())) + } + }; + tokio::select! { + () = tokio::time::sleep(delay) => {} + () = stop_task.notified() => break, + } + } + }); + Some(HeartbeatPusher { stop, handle: Some(handle) }) + } + + pub async fn stop(mut self) { + self.stop.notify_waiters(); + if let Some(handle) = self.handle.take() { + let _ = handle.await; + } + } +} + +pub async fn post_heartbeat(url: &str, bearer_token: &str, heartbeat: &Value) -> Result { + let uri: Uri = url.parse().map_err(|_| format!("invalid heartbeat url: {url}"))?; + let authority = uri.authority().ok_or_else(|| "heartbeat url missing authority".to_string())?; + let host = authority.host(); + let port = authority.port_u16().unwrap_or(80); + let addr = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") }; + let path = uri.path_and_query().map(|pq| pq.as_str()).unwrap_or("/v1/nodes/heartbeat"); + + let stream = tokio::time::timeout(HEARTBEAT_POST_TIMEOUT, TcpStream::connect(&addr)) + .await + .map_err(|_| "heartbeat connect timed out".to_string())? + .map_err(|e| format!("heartbeat connect failed: {e}"))?; + let (mut sender, conn) = http1::handshake(TokioIo::new(stream)) + .await + .map_err(|e| e.to_string())?; + tokio::spawn(async move { + let _ = conn.await; + }); + + let body = serde_json::to_vec(heartbeat).map_err(|e| e.to_string())?; + let req = Request::builder() + .method(Method::POST) + .uri(path) + .header(header::HOST, authority.as_str()) + .header(header::CONTENT_TYPE, "application/json") + .header(header::CONTENT_LENGTH, body.len().to_string()) + .header(header::AUTHORIZATION, format!("Bearer {bearer_token}")) + .body(Full::new(Bytes::from(body)).map_err(|never| match never {}).boxed()) + .map_err(|e| e.to_string())?; + let resp = tokio::time::timeout(HEARTBEAT_POST_TIMEOUT, sender.send_request(req)) + .await + .map_err(|_| "heartbeat POST timed out".to_string())? + .map_err(|e| e.to_string())?; + let status = resp.status(); + let resp_bytes = resp.into_body().collect().await.map(|c| c.to_bytes()).unwrap_or_default(); + if !status.is_success() { + eprintln!( + "ucloud-noded: heartbeat push to {url} answered {status}: {}", + String::from_utf8_lossy(&resp_bytes) + ); + } + Ok(status) +} + +fn monotonic_ns() -> i64 { + let mut ts = libc::timespec { tv_sec: 0, tv_nsec: 0 }; + // SAFETY: valid mutable pointer. + if unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts) } == 0 { + (ts.tv_sec as i64).saturating_mul(1_000_000_000).saturating_add(ts.tv_nsec as i64) + } else { + Instant::now().elapsed().as_nanos() as i64 + } +} + +fn constant_time_eq(left: &[u8], right: &[u8]) -> bool { + left.len() == right.len() && left.iter().zip(right).fold(0u8, |acc, (a, b)| acc | (a ^ b)) == 0 +} + +fn full(bytes: impl Into) -> Body { + Full::new(bytes.into()).map_err(|never| match never {}).boxed() +} + +fn json_response(status: StatusCode, payload: Value) -> Response { + let body = serde_json::to_vec(&payload).unwrap_or_else(|_| b"{}".to_vec()); + let mut response = Response::new(full(body)); + *response.status_mut() = status; + response.headers_mut().insert(header::CONTENT_TYPE, HeaderValue::from_static("application/json")); + response +} + +fn unauthorized() -> Response { + let mut response = json_response(StatusCode::UNAUTHORIZED, json!({"error": "unauthorized"})); + response.headers_mut().insert(header::WWW_AUTHENTICATE, HeaderValue::from_static("Bearer")); + response +} diff --git a/runtime/noded/src/image.rs b/runtime/noded/src/image.rs index a3bf8244..7e995f88 100644 --- a/runtime/noded/src/image.rs +++ b/runtime/noded/src/image.rs @@ -55,7 +55,10 @@ pub const MAX_RPC_BYTES: usize = 64 * 1024; pub const BACKEND_TIMEOUT: Duration = Duration::from_secs(120); const OCI_IMAGE: &str = "application/vnd.oci.image.manifest.v1+json"; const ENVIRONMENT_MEDIA_TYPE: &str = "application/vnd.ucloud.environment.v1+json"; +const ENVIRONMENT_ANNOTATION: &str = "org.ucloud.immutable-environment.v1"; +const ENVIRONMENT_DOMAIN: &[u8] = b"ucloud.immutable-environment.v1\0"; const ENVIRONMENT_SCHEMA: &str = "ucloud-immutable-environment-v1"; +const MAX_INDEX_BYTES: usize = 16 * 1024 * 1024; /// A receipt holds one signed environment (its image config at most 16 MiB). const MAX_RECEIPT_BYTES: u64 = 64 * 1024 * 1024; const MOUNT_TIMEOUT: Duration = Duration::from_secs(60); @@ -770,4 +773,339 @@ impl ImageStore { } result } + + /// Cold-path materialization in Rust: resolve and Ed25519-authenticate the + /// environment from the private registry, attach components via the + /// backend, mount `//rootfs`, write `environment.json`, and + /// remember the resolution for subsequent warm leases. + pub async fn materialize( + &self, + resolver: &EnvironmentResolver, + image_ref: &str, + environment_root: Option<&str>, + ) -> Result { + let receipt = resolver.resolve(image_ref, environment_root).await?; + let resolution = Resolution::from_receipt(&receipt)?; + let image_id = resolution.image_id(); + let hex = image_id[7..].to_string(); + let target = self.images.join(&hex); + let rootfs = target.join("rootfs"); + + let _exclusive = Flock::acquire(self.lock_path(&image_id), true).await?; + ensure_private_dir(&target)?; + let receipt_bytes = json_canonical(&receipt); + crate::fsutil::atomic_write(&target.join("environment.json"), receipt_bytes.as_bytes())?; + self.mount_or_compose(&resolution.manifest, &rootfs).await?; + if Self::check_reference(image_ref, environment_root).is_ok() { + self.remember(environment_root, resolution); + } + Ok(receipt) + } + + async fn mount_or_compose(&self, manifest: &EnvironmentManifest, rootfs: &Path) -> Result<(), ImageError> { + let components = manifest.components(); + let unique: BTreeSet<&String> = components.iter().collect(); + let result = async { + let mut leases = Vec::with_capacity(unique.len()); + for digest in &unique { + leases.push(Flock::acquire(self.lock_path(digest), false).await?); + } + match std::fs::DirBuilder::new().mode(0o700).create(rootfs) { + Err(error) if error.kind() != io::ErrorKind::AlreadyExists => return Err(error.into()), + _ => {} + } + if mount_present(rootfs, &self.probe).await? { + for digest in &components { + self.backend.ensure(digest).await?; + } + drop(leases); + return Ok(()); + } + let mut lowers = Vec::with_capacity(components.len()); + for digest in &components { + let path = self.backend.ensure(digest).await?; + let text = path.to_string_lossy(); + if text.contains([':', ',', '\n']) { + return Err(invalid("invalid component mount path")); + } + lowers.push(path); + } + if lowers.len() == 1 { + let argv = vec![ + "mount".to_string(), + "--bind".to_string(), + lowers[0].to_string_lossy().into_owned(), + rootfs.to_string_lossy().into_owned(), + ]; + let out = crate::runsc::run(&argv, MOUNT_TIMEOUT) + .await + .map_err(|e| ImageError::Mount(e.to_string()))?; + if out.returncode != 0 { + return Err(ImageError::Mount(format!( + "immutable environment mount failed: {}", + if out.stderr.is_empty() { out.stdout } else { out.stderr } + ))); + } + } else { + let parent = lowers[0] + .parent() + .filter(|p| p.is_absolute()) + .ok_or_else(|| invalid("environment components must share one mount directory"))?; + if lowers.iter().any(|p| p.parent() != Some(parent)) { + return Err(invalid("environment components must share one mount directory")); + } + let names: Vec = lowers + .iter() + .rev() + .filter_map(|p| p.file_name().map(|n| n.to_string_lossy().into_owned())) + .collect(); + let argv = vec![ + "env".to_string(), + "-C".to_string(), + parent.to_string_lossy().into_owned(), + "LIBMOUNT_FORCE_MOUNT2=always".to_string(), + "mount".to_string(), + "-t".to_string(), + "overlay".to_string(), + "overlay".to_string(), + "-o".to_string(), + format!("ro,lowerdir={}", names.join(":")), + rootfs.to_string_lossy().into_owned(), + ]; + let out = crate::runsc::run(&argv, MOUNT_TIMEOUT) + .await + .map_err(|e| ImageError::Mount(e.to_string()))?; + if out.returncode != 0 { + return Err(ImageError::Mount(format!( + "immutable environment mount failed: {}", + if out.stderr.is_empty() { out.stdout } else { out.stderr } + ))); + } + } + drop(leases); + Ok(()) + } + .await; + if let Err(ImageError::DeviceCapacity(_)) = &result { + for digest in &unique { + let released = async { + let _exclusive = Flock::acquire(self.lock_path(digest), true).await?; + self.backend.drop_component(digest).await + } + .await; + if let Err(error) = released { + eprintln!("ucloud-noded: could not release component after device exhaustion: {digest}: {error}"); + } + } + } + result + } +} + +/// Pure-Rust signed environment resolver (`sandboxes/environment_artifact.py`). +#[derive(Clone, Debug)] +pub struct EnvironmentResolver { + client: crate::registry_client::RegistryHttpClient, + repository: String, + trusted_keys: HashMap, +} + +/// Parse `(host, repository, reference)` from an OCI image ref like +/// `registry:5000/repo/name:tag` or `registry:5000/repo/name@sha256:...`. +pub fn parse_image_ref(image_ref: &str) -> Option<(String, String, String)> { + let trimmed = image_ref.trim(); + let (host, rest) = trimmed.split_once('/')?; + if host.is_empty() || rest.is_empty() || !(host.contains('.') || host.contains(':') || host == "localhost") { + return None; + } + if let Some((repo, digest)) = rest.split_once('@') { + if repo.is_empty() || !is_digest(digest) { + return None; + } + return Some((host.to_string(), repo.to_string(), digest.to_string())); + } + let last_slash = rest.rfind('/').map_or(0, |i| i + 1); + if let Some(colon) = rest[last_slash..].find(':') { + let split = last_slash + colon; + let repo = &rest[..split]; + let tag = &rest[split + 1..]; + if repo.is_empty() || tag.is_empty() { + return None; + } + return Some((host.to_string(), repo.to_string(), tag.to_string())); + } + Some((host.to_string(), rest.to_string(), "latest".to_string())) +} + +/// Verify an `ImmutableEnvironment` JSON object against `trusted_keys`. +pub fn authenticate_environment(env: &Value, trusted_keys: &HashMap) -> Result<(), ImageError> { + let Some(obj) = env.as_object() else { + return Err(invalid("invalid immutable environment metadata")); + }; + if obj.get("schema").and_then(Value::as_str) != Some(ENVIRONMENT_SCHEMA) { + return Err(invalid("invalid immutable environment metadata")); + } + let source_image = obj.get("source_image").ok_or_else(|| invalid("missing source_image"))?; + require_digest(source_image)?; + let producer_key = obj.get("producer_key").ok_or_else(|| invalid("missing producer_key"))?; + let key_id = require_digest(producer_key)?; + let Some(raw_key) = trusted_keys.get(&key_id) else { + return Err(invalid("environment producer is not trusted")); + }; + if crate::ed25519::content_digest(raw_key) != key_id { + return Err(invalid("environment producer is not trusted")); + } + let sig_b64 = obj + .get("signature") + .and_then(Value::as_str) + .ok_or_else(|| invalid("environment signature is missing"))?; + let sig_bytes = crate::ed25519::decode_base64_strict(sig_b64) + .map_err(|_| invalid("environment composition signature did not verify"))?; + let sig: [u8; 64] = sig_bytes + .try_into() + .map_err(|_| invalid("environment composition signature did not verify"))?; + // Validate manifest & image_config shapes before accepting. + let manifest_val = obj.get("environment").ok_or_else(|| invalid("missing environment"))?; + let manifest = EnvironmentManifest::from_value(manifest_val)?; + if manifest.toolkits.len() > 32 { + return Err(invalid("environment component count exceeds mount bound")); + } + let image_config = obj.get("image_config").ok_or_else(|| invalid("missing image_config"))?; + ImageConfig::from_inspection(image_config)?; + + let unsigned = json!({ + "schema": ENVIRONMENT_SCHEMA, + "source_image": source_image, + "environment": manifest.to_value(), + "image_config": image_config, + "producer_key": key_id, + }); + let canonical = json_canonical(&unsigned); + let mut message = Vec::with_capacity(ENVIRONMENT_DOMAIN.len() + canonical.len()); + message.extend_from_slice(ENVIRONMENT_DOMAIN); + message.extend_from_slice(canonical.as_bytes()); + if !crate::ed25519::verify(raw_key, &message, &sig) { + return Err(invalid("environment composition signature did not verify")); + } + Ok(()) +} + +impl EnvironmentResolver { + pub fn new( + registry_url: &str, + repository: impl Into, + trusted_keys: HashMap, + ) -> Result { + let client = crate::registry_client::RegistryHttpClient::new(registry_url) + .map_err(|e| ImageError::Invalid(e.to_string()))?; + Ok(EnvironmentResolver { client, repository: repository.into(), trusted_keys }) + } + + pub async fn load_environment(&self, digest: &str) -> Result { + if !is_digest(digest) { + return Err(invalid("immutable environment requires a SHA256 digest")); + } + let (doc, _) = self + .client + .manifest_document(&self.repository, digest) + .await + .map_err(|e| ImageError::Backend(e.to_string()))?; + let actual_digest = format!("sha256:{}", sha256_hex(json_canonical(&doc).as_bytes())); + if actual_digest != digest { + return Err(invalid("environment root content identity mismatch")); + } + let config = doc.get("config").and_then(Value::as_object); + let valid = doc.get("schemaVersion").and_then(Value::as_i64) == Some(2) + && doc.get("mediaType").and_then(Value::as_str) == Some(OCI_IMAGE) + && doc.get("layers").and_then(Value::as_array).is_some_and(|l| l.is_empty()) + && config.is_some_and(|c| c.get("mediaType").and_then(Value::as_str) == Some(ENVIRONMENT_MEDIA_TYPE)); + if !valid { + return Err(invalid("invalid immutable environment root")); + } + let config = config.unwrap(); + let size = config + .get("size") + .and_then(Value::as_u64) + .filter(|&s| s > 0 && s as usize <= MAX_INDEX_BYTES) + .ok_or_else(|| invalid("invalid immutable environment root"))?; + let blob_digest = require_digest(config.get("digest").unwrap_or(&Value::Null))?; + let data = self + .client + .blob_bytes(&self.repository, &blob_digest, size as usize) + .await + .map_err(|e| ImageError::Backend(e.to_string()))?; + if data.len() as u64 != size || format!("sha256:{}", sha256_hex(&data)) != blob_digest { + return Err(invalid("environment root metadata identity mismatch")); + } + let env: Value = serde_json::from_slice(&data).map_err(|e| invalid(format!("invalid environment JSON: {e}")))?; + authenticate_environment(&env, &self.trusted_keys)?; + Ok(env) + } + + /// Resolve `image_ref` (and optional dispatched `environment_root`) into a + /// verified receipt JSON `{"root", "source", "environment"}`. + pub async fn resolve(&self, image_ref: &str, environment_root: Option<&str>) -> Result { + let Some((host, repo, reference)) = parse_image_ref(image_ref) else { + return Err(invalid("immutable environment requires the configured managed image registry")); + }; + if host != self.client.netloc() { + return Err(invalid("immutable environment requires the configured managed image registry")); + } + let (root, env) = if let Some(root) = environment_root { + if !is_digest(root) { + return Err(invalid("immutable environment requires a SHA256 digest")); + } + let env = self.load_environment(root).await?; + match self.client.manifest_document(&repo, &reference).await { + Ok((doc, _)) => { + if is_digest(&reference) { + let actual = format!("sha256:{}", sha256_hex(json_canonical(&doc).as_bytes())); + if actual != reference { + return Err(invalid("source image identity mismatch")); + } + } + let cfg_digest = doc.get("config").and_then(|c| c.get("digest")).and_then(Value::as_str); + if cfg_digest != env.get("source_image").and_then(Value::as_str) { + return Err(invalid("dispatched environment belongs to another OCI image")); + } + } + Err(crate::registry_client::RegistryHttpError::NotFound(_)) => { + // Released image: its signed root stands alone. + } + Err(e) => return Err(ImageError::Backend(e.to_string())), + } + (root.to_string(), env) + } else { + let (doc, _) = self + .client + .manifest_document(&repo, &reference) + .await + .map_err(|e| ImageError::Backend(e.to_string()))?; + let root = doc + .get("annotations") + .and_then(|a| a.get(ENVIRONMENT_ANNOTATION)) + .and_then(Value::as_str) + .ok_or_else(|| invalid("image has no immutable environment annotation"))?; + if !is_digest(root) { + return Err(invalid("immutable environment requires a SHA256 digest")); + } + if is_digest(&reference) { + let actual = format!("sha256:{}", sha256_hex(json_canonical(&doc).as_bytes())); + if actual != reference { + return Err(invalid("annotated source image identity mismatch")); + } + } + let env = self.load_environment(root).await?; + let cfg_digest = doc.get("config").and_then(|c| c.get("digest")).and_then(Value::as_str); + if cfg_digest != env.get("source_image").and_then(Value::as_str) { + return Err(invalid("signed environment belongs to another OCI image")); + } + (root.to_string(), env) + }; + Ok(json!({ + "root": root, + "source": image_ref, + "environment": env, + })) + } } diff --git a/runtime/noded/src/images_front.rs b/runtime/noded/src/images_front.rs new file mode 100644 index 00000000..b2cee4e7 --- /dev/null +++ b/runtime/noded/src/images_front.rs @@ -0,0 +1,415 @@ +//! Worker image routes in `ucloud-noded` (Wave B3): +//! +//! - `GET /v1/images` +//! - `POST /v1/images/pull` +//! +//! Tracks pulled immutable environment records in a local durable catalog, +//! enforces bounded concurrent pulls with queue timing, and respects node drain +//! admission. + +use std::collections::BTreeMap; +use std::future::Future; +use std::path::{Path, PathBuf}; +use std::pin::Pin; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Instant; + +use bytes::Bytes; +use http_body_util::{BodyExt, Full, Limited}; +use hyper::header::{self, HeaderName, HeaderValue}; +use hyper::{Method, Request, Response, StatusCode}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use tokio::sync::Semaphore; + +use crate::Body; +use crate::exec_front::Outcome; +use crate::image::{EnvironmentResolver, ImageError, ImageStore, manifest_digest_from_image_ref}; +use crate::sandbox_record::{format_utc_timestamp, now_utc_ns}; + +const MAX_BODY_BYTES: usize = 1024 * 1024; + +pub type BoxFuture = Pin + Send>>; + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct ImageRecord { + pub id: String, + pub tag: String, + pub source: String, + pub state: String, + pub created_at: String, + pub updated_at: String, + #[serde(default)] + pub labels: BTreeMap, + #[serde(default)] + pub pushed: bool, + #[serde(default)] + pub manifest_digest: String, +} + +impl ImageRecord { + pub fn to_dict(&self) -> Value { + json!({ + "id": self.id, + "tag": self.tag, + "source": self.source, + "state": self.state, + "created_at": self.created_at, + "updated_at": self.updated_at, + "labels": self.labels, + "pushed": self.pushed, + "manifest_digest": self.manifest_digest, + "available_to_sandboxes": self.pushed || self.source == "registry", + }) + } +} + +/// Port of `sandboxes/images.py::image_id_from_tag`. +pub fn image_id_from_tag(tag: &str) -> String { + let hex: String = Sha256::digest(tag.as_bytes()).iter().map(|b| format!("{b:02x}")).collect(); + format!("img-{}", &hex[..12]) +} + +/// Durable local image catalog backing `GET /v1/images` and `cached_images` in heartbeats. +pub struct ImageCatalog { + path: PathBuf, + records: Mutex>, +} + +impl ImageCatalog { + pub fn open(path: impl Into) -> Self { + let path = path.into(); + let records = load_catalog(&path).unwrap_or_default(); + ImageCatalog { path, records: Mutex::new(records) } + } + + pub fn list(&self) -> Vec { + self.records.lock().expect("not poisoned").values().cloned().collect() + } + + pub fn cached_refs(&self) -> Vec { + let mut refs = Vec::new(); + for rec in self.records.lock().expect("not poisoned").values() { + if rec.state == "available" { + refs.push(rec.tag.clone()); + } + } + refs.sort(); + refs.dedup(); + refs + } + + pub fn upsert(&self, record: ImageRecord) -> std::io::Result<()> { + let mut guard = self.records.lock().expect("not poisoned"); + guard.insert(record.id.clone(), record); + let serialized = serde_json::to_vec_pretty(&json!({"images": guard.values().collect::>()})) + .map_err(std::io::Error::other)?; + if let Some(parent) = self.path.parent() { + std::fs::create_dir_all(parent)?; + } + crate::fsutil::atomic_write(&self.path, &serialized)?; + Ok(()) + } +} + +fn load_catalog(path: &Path) -> Option> { + let bytes = std::fs::read(path).ok()?; + let parsed: Value = serde_json::from_slice(&bytes).ok()?; + let list = parsed.get("images")?.as_array()?; + let mut map = BTreeMap::new(); + for item in list { + if let Ok(rec) = serde_json::from_value::(item.clone()) { + map.insert(rec.id.clone(), rec); + } + } + Some(map) +} + +#[derive(Clone, Debug, Default)] +pub struct PullMetrics { + pub active_operations: usize, + pub waiting_operations: usize, + pub max_concurrent_operations: usize, +} + +#[derive(Debug)] +pub enum PullError { + AdmissionClosed(String), + Invalid(String), + Failed(String), +} + +pub trait ImagePuller: Send + Sync { + fn admission_open(&self) -> bool; + fn pull(&self, image: &str, environment_root: Option<&str>) -> BoxFuture>; +} + +/// Real production image puller backed by `ImageStore` + `EnvironmentResolver`. +pub struct EnvironmentPuller { + store: Arc, + resolver: EnvironmentResolver, + admission_open: Arc bool + Send + Sync>, +} + +impl EnvironmentPuller { + pub fn new( + store: Arc, + resolver: EnvironmentResolver, + admission_open: Arc bool + Send + Sync>, + ) -> Self { + EnvironmentPuller { store, resolver, admission_open } + } +} + +impl ImagePuller for EnvironmentPuller { + fn admission_open(&self) -> bool { + (self.admission_open)() + } + + fn pull(&self, image: &str, environment_root: Option<&str>) -> BoxFuture> { + let store = self.store.clone(); + let resolver = self.resolver.clone(); + let image = image.to_string(); + let root = environment_root.map(str::to_string); + Box::pin(async move { + match store.materialize(&resolver, &image, root.as_deref()).await { + Ok(_) => Ok(()), + Err(ImageError::Invalid(msg)) => Err(PullError::Invalid(msg)), + Err(err) => Err(PullError::Failed(err.to_string())), + } + }) + } +} + +pub struct ImagesFront { + catalog: Arc, + puller: Arc, + token: Bytes, + slots: Arc, + max_concurrent: usize, + active: Arc, + waiting: Arc, +} + +impl ImagesFront { + pub fn new( + catalog: Arc, + puller: Arc, + token: &str, + max_concurrent_pulls: usize, + ) -> Arc { + let max = max_concurrent_pulls.max(1); + Arc::new(ImagesFront { + catalog, + puller, + token: Bytes::copy_from_slice(token.as_bytes()), + slots: Arc::new(Semaphore::new(max)), + max_concurrent: max, + active: Arc::new(AtomicUsize::new(0)), + waiting: Arc::new(AtomicUsize::new(0)), + }) + } + + pub fn catalog(&self) -> &Arc { + &self.catalog + } + + pub fn pull_metrics(&self) -> PullMetrics { + PullMetrics { + active_operations: self.active.load(Ordering::Relaxed), + waiting_operations: self.waiting.load(Ordering::Relaxed), + max_concurrent_operations: self.max_concurrent, + } + } + + fn authorized(&self, request: &Request) -> bool { + let supplied = request + .headers() + .get(header::AUTHORIZATION) + .map(|v| v.as_bytes()) + .and_then(|v| v.strip_prefix(b"Bearer ")); + supplied.is_some_and(|s| !s.is_empty() && constant_time_eq(s, &self.token)) + } + + pub fn intercepts(&self, request: &Request) -> bool { + let matched = matches!( + (request.method(), request.uri().path()), + (&Method::GET, "/v1/images") | (&Method::POST, "/v1/images/pull") + ); + matched && self.authorized(request) + } + + pub async fn handle(&self, request: Request) -> Outcome { + match (request.method(), request.uri().path()) { + (&Method::GET, "/v1/images") => { + let images: Vec = self.catalog.list().iter().map(ImageRecord::to_dict).collect(); + Outcome::Response(json_response(StatusCode::OK, json!({"images": images}), &[])) + } + (&Method::POST, "/v1/images/pull") => self.handle_pull(request).await, + _ => Outcome::Forward(request), + } + } + + async fn handle_pull(&self, request: Request) -> Outcome { + let started = Instant::now(); + let bytes = match Limited::new(request.into_body(), MAX_BODY_BYTES).collect().await { + Ok(collected) => collected.to_bytes(), + Err(_) => { + return Outcome::Response(json_response( + StatusCode::BAD_REQUEST, + json!({"error": "invalid image pull request body"}), + &[], + )); + } + }; + let raw: Value = match serde_json::from_slice::(&bytes) { + Ok(v) if v.is_object() => v, + _ => { + return Outcome::Response(json_response( + StatusCode::BAD_REQUEST, + json!({"error": "image pull payload must be a JSON object"}), + &[], + )); + } + }; + let image = raw.get("image").and_then(Value::as_str).unwrap_or("").trim().to_string(); + if image.is_empty() { + return Outcome::Response(json_response( + StatusCode::BAD_REQUEST, + json!({"error": "image is required"}), + &[], + )); + } + let image_id = raw + .get("id") + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) + .map(str::to_string) + .unwrap_or_else(|| image_id_from_tag(&image)); + let environment_root = raw + .get("environment_root") + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) + .map(str::to_string); + + if !self.puller.admission_open() { + return Outcome::Response(json_response( + StatusCode::SERVICE_UNAVAILABLE, + json!({ + "error": "direct node admission is closed", + "error_code": "node_admission_closed", + "retryable": true, + }), + &[("Retry-After", "1"), ("X-UCloud-Sandbox-Retryable", "true")], + )); + } + + let wait_started = Instant::now(); + self.waiting.fetch_add(1, Ordering::Relaxed); + let permit = self.slots.clone().acquire_owned().await.expect("semaphore never closed"); + self.waiting.fetch_sub(1, Ordering::Relaxed); + self.active.fetch_add(1, Ordering::Relaxed); + let pull_queue_ms = wait_started.elapsed().as_millis() as u64; + + let pull_started = Instant::now(); + let pull_result = self.puller.pull(&image, environment_root.as_deref()).await; + let docker_pull_ms = pull_started.elapsed().as_millis() as u64; + self.active.fetch_sub(1, Ordering::Relaxed); + drop(permit); + + match pull_result { + Ok(()) => { + let now = format_utc_timestamp(now_utc_ns()); + let record = ImageRecord { + id: image_id, + tag: image.clone(), + source: "registry".into(), + state: "available".into(), + created_at: now.clone(), + updated_at: now, + labels: BTreeMap::new(), + pushed: true, + manifest_digest: manifest_digest_from_image_ref(&image).unwrap_or_default(), + }; + if let Err(err) = self.catalog.upsert(record.clone()) { + return Outcome::Response(json_response( + StatusCode::SERVICE_UNAVAILABLE, + json!({ + "error": err.to_string(), + "error_code": "image_pull_failed", + "retryable": true, + }), + &[], + )); + } + Outcome::Response(json_response( + StatusCode::CREATED, + json!({ + "image": record.to_dict(), + "command": ["immutable-environment", "resolve", image], + "exit_code": 0, + "timings": { + "pull_queue_ms": pull_queue_ms, + "docker_pull_ms": docker_pull_ms, + }, + }), + &[], + )) + } + Err(PullError::AdmissionClosed(msg)) => Outcome::Response(json_response( + StatusCode::SERVICE_UNAVAILABLE, + json!({"error": msg, "error_code": "node_admission_closed", "retryable": true}), + &[("Retry-After", "1"), ("X-UCloud-Sandbox-Retryable", "true")], + )), + Err(PullError::Invalid(msg)) => Outcome::Response(json_response( + StatusCode::BAD_REQUEST, + json!({ + "error": msg, + "timings": { + "total_ms": started.elapsed().as_millis() as u64, + "failed_phase": "environment_resolve", + }, + }), + &[], + )), + Err(PullError::Failed(msg)) => Outcome::Response(json_response( + StatusCode::SERVICE_UNAVAILABLE, + json!({ + "error": msg, + "error_code": "image_pull_failed", + "retryable": true, + "timings": { + "total_ms": started.elapsed().as_millis() as u64, + "pull_queue_ms": pull_queue_ms, + "failed_phase": "environment_resolve", + }, + }), + &[], + )), + } + } +} + +fn constant_time_eq(left: &[u8], right: &[u8]) -> bool { + left.len() == right.len() && left.iter().zip(right).fold(0u8, |acc, (a, b)| acc | (a ^ b)) == 0 +} + +fn full(bytes: impl Into) -> Body { + Full::new(bytes.into()).map_err(|never| match never {}).boxed() +} + +fn json_response(status: StatusCode, payload: Value, extra_headers: &[(&str, &str)]) -> Response { + let body = serde_json::to_vec(&payload).unwrap_or_else(|_| b"{}".to_vec()); + let mut response = Response::new(full(body)); + *response.status_mut() = status; + let headers = response.headers_mut(); + headers.insert(header::CONTENT_TYPE, HeaderValue::from_static("application/json")); + for (name, value) in extra_headers { + if let (Ok(name), Ok(value)) = (HeaderName::from_bytes(name.as_bytes()), HeaderValue::from_str(value)) { + headers.insert(name, value); + } + } + response +} diff --git a/runtime/noded/src/journal.rs b/runtime/noded/src/journal.rs index 7ea179d8..a42a20e3 100644 --- a/runtime/noded/src/journal.rs +++ b/runtime/noded/src/journal.rs @@ -153,6 +153,354 @@ impl JournalStore { let Value::Object(record) = record else { unreachable!() }; Ok(record) } + + fn mutate( + &self, + sandbox_id: &str, + generation: u64, + update: impl FnOnce(Map) -> Result, JournalError>, + ) -> Result, JournalError> { + let (path, lock_path) = self.paths(sandbox_id, generation)?; + ensure_private_dir(&self.root)?; + let _lock = FileLock::acquire(&lock_path, true)?; + let Some(existing) = load_record(&path)? else { + return Err(JournalError::Conflict("hibernation journal does not exist".into())); + }; + let next = update(existing)?; + let mut bytes = canonical_json(&Value::Object(next.clone())); + bytes.push(b'\n'); + atomic_write(&path, &bytes)?; + Ok(next) + } + + /// `begin_hibernate`: running (live) -> hibernating (live), bumping hibernation_generation. + pub fn begin_hibernate( + &self, + sandbox_id: &str, + generation: u64, + operation_id: &str, + expected_revision: i64, + ) -> Result, JournalError> { + if !is_safe_id(operation_id) { + return Err(JournalError::Invalid("invalid operation id".into())); + } + self.mutate(sandbox_id, generation, |mut rec| { + let state = rec.get("state").and_then(Value::as_str).unwrap_or(""); + let op_kind = rec.get("operation_kind").and_then(Value::as_str).unwrap_or(""); + let op_id = rec.get("operation_id").and_then(Value::as_str).unwrap_or(""); + if op_kind == "hibernate" + && op_id == operation_id + && matches!(state, "hibernating" | "parked" | "recovery_required") + { + return Ok(rec); + } + let rev = rec.get("revision").and_then(Value::as_i64).unwrap_or(-1); + if rev != expected_revision { + return Err(JournalError::Conflict("hibernation journal revision mismatch".into())); + } + let auth = rec.get("authority").and_then(Value::as_str).unwrap_or(""); + if state != "running" || auth != "live" { + return Err(JournalError::Conflict("sandbox is not running".into())); + } + let next_hib = rec.get("hibernation_generation").and_then(Value::as_u64).unwrap_or(0) + 1; + rec.insert("state".into(), json!("hibernating")); + rec.insert("operation_kind".into(), json!("hibernate")); + rec.insert("operation_id".into(), json!(operation_id)); + rec.insert("hibernation_generation".into(), json!(next_hib)); + rec.insert("revision".into(), json!(rev + 1)); + rec.insert("updated_ns".into(), json!(now_ns())); + Ok(rec) + }) + } + + /// `mark_sentry_reaped`: hibernating (live) -> hibernating (pending). + pub fn mark_sentry_reaped( + &self, + sandbox_id: &str, + generation: u64, + operation_id: &str, + expected_revision: i64, + ) -> Result, JournalError> { + self.mutate(sandbox_id, generation, |mut rec| { + let state = rec.get("state").and_then(Value::as_str).unwrap_or(""); + let auth = rec.get("authority").and_then(Value::as_str).unwrap_or(""); + let op_kind = rec.get("operation_kind").and_then(Value::as_str).unwrap_or(""); + let op_id = rec.get("operation_id").and_then(Value::as_str).unwrap_or(""); + if op_kind != "hibernate" || op_id != operation_id { + return Err(JournalError::Conflict("hibernation operation mismatch".into())); + } + if state == "hibernating" && auth == "pending" { + return Ok(rec); + } + let rev = rec.get("revision").and_then(Value::as_i64).unwrap_or(-1); + if rev != expected_revision { + return Err(JournalError::Conflict("hibernation journal revision mismatch".into())); + } + if state != "hibernating" || auth != "live" { + return Err(JournalError::Conflict("sentry can only be reaped from live hibernating state".into())); + } + rec.insert("authority".into(), json!("pending")); + rec.insert("sentry_pid".into(), Value::Null); + rec.insert("sentry_start_time_ticks".into(), Value::Null); + rec.insert("revision".into(), json!(rev + 1)); + rec.insert("updated_ns".into(), json!(now_ns())); + Ok(rec) + }) + } + + /// `commit_parked`: hibernating (pending) -> parked (parked). + pub fn commit_parked( + &self, + sandbox_id: &str, + generation: u64, + manifest_sha256: &str, + operation_id: &str, + expected_revision: i64, + ) -> Result, JournalError> { + if !is_digest(manifest_sha256) { + return Err(JournalError::Invalid("invalid manifest sha256".into())); + } + self.mutate(sandbox_id, generation, |mut rec| { + let state = rec.get("state").and_then(Value::as_str).unwrap_or(""); + let auth = rec.get("authority").and_then(Value::as_str).unwrap_or(""); + let op_kind = rec.get("operation_kind").and_then(Value::as_str).unwrap_or(""); + let op_id = rec.get("operation_id").and_then(Value::as_str).unwrap_or(""); + if op_kind != "hibernate" || op_id != operation_id { + return Err(JournalError::Conflict("hibernation operation mismatch".into())); + } + if state == "parked" && rec.get("manifest_sha256").and_then(Value::as_str) == Some(manifest_sha256) { + return Ok(rec); + } + let rev = rec.get("revision").and_then(Value::as_i64).unwrap_or(-1); + if rev != expected_revision { + return Err(JournalError::Conflict("hibernation journal revision mismatch".into())); + } + if state != "hibernating" || auth != "pending" { + return Err(JournalError::Conflict("park can only commit after the sentry is reaped".into())); + } + rec.insert("state".into(), json!("parked")); + rec.insert("authority".into(), json!("parked")); + rec.insert("manifest_sha256".into(), json!(manifest_sha256)); + rec.insert("revision".into(), json!(rev + 1)); + rec.insert("updated_ns".into(), json!(now_ns())); + Ok(rec) + }) + } + + /// `begin_restore`: parked (parked) -> restoring (parked). + pub fn begin_restore( + &self, + sandbox_id: &str, + generation: u64, + operation_id: &str, + expected_revision: i64, + ) -> Result, JournalError> { + if !is_safe_id(operation_id) { + return Err(JournalError::Invalid("invalid operation id".into())); + } + self.mutate(sandbox_id, generation, |mut rec| { + let state = rec.get("state").and_then(Value::as_str).unwrap_or(""); + let op_kind = rec.get("operation_kind").and_then(Value::as_str).unwrap_or(""); + let op_id = rec.get("operation_id").and_then(Value::as_str).unwrap_or(""); + if op_kind == "restore" + && op_id == operation_id + && matches!(state, "restoring" | "running" | "recovery_required") + { + return Ok(rec); + } + let rev = rec.get("revision").and_then(Value::as_i64).unwrap_or(-1); + if rev != expected_revision { + return Err(JournalError::Conflict("hibernation journal revision mismatch".into())); + } + let auth = rec.get("authority").and_then(Value::as_str).unwrap_or(""); + if state != "parked" || auth != "parked" { + return Err(JournalError::Conflict("sandbox is not parked".into())); + } + rec.insert("state".into(), json!("restoring")); + rec.insert("operation_kind".into(), json!("restore")); + rec.insert("operation_id".into(), json!(operation_id)); + rec.insert("revision".into(), json!(rev + 1)); + rec.insert("updated_ns".into(), json!(now_ns())); + Ok(rec) + }) + } + + /// `mark_candidate`: restoring (parked) -> restoring (candidate). + pub fn mark_candidate( + &self, + sandbox_id: &str, + generation: u64, + operation_id: &str, + expected_revision: i64, + candidate_pid: u64, + candidate_ticks: u64, + ) -> Result, JournalError> { + self.mutate(sandbox_id, generation, |mut rec| { + let rev = rec.get("revision").and_then(Value::as_i64).unwrap_or(-1); + if rev != expected_revision { + return Err(JournalError::Conflict("hibernation journal revision mismatch".into())); + } + let state = rec.get("state").and_then(Value::as_str).unwrap_or(""); + let op_id = rec.get("operation_id").and_then(Value::as_str).unwrap_or(""); + if state != "restoring" || op_id != operation_id { + return Err(JournalError::Conflict("sandbox is not restoring".into())); + } + rec.insert("authority".into(), json!("candidate")); + rec.insert("candidate_pid".into(), json!(candidate_pid)); + rec.insert("candidate_start_time_ticks".into(), json!(candidate_ticks)); + rec.insert("revision".into(), json!(rev + 1)); + rec.insert("updated_ns".into(), json!(now_ns())); + Ok(rec) + }) + } + + /// `commit_running`: restoring (candidate) -> running (live). + pub fn commit_running( + &self, + sandbox_id: &str, + generation: u64, + operation_id: &str, + expected_revision: i64, + sentry_pid: u64, + sentry_start_time_ticks: u64, + ) -> Result, JournalError> { + self.mutate(sandbox_id, generation, |mut rec| { + let state = rec.get("state").and_then(Value::as_str).unwrap_or(""); + let auth = rec.get("authority").and_then(Value::as_str).unwrap_or(""); + let op_kind = rec.get("operation_kind").and_then(Value::as_str).unwrap_or(""); + let op_id = rec.get("operation_id").and_then(Value::as_str).unwrap_or(""); + if op_kind != "restore" || op_id != operation_id { + return Err(JournalError::Conflict("restore operation mismatch".into())); + } + if state == "running" + && rec.get("sentry_pid").and_then(Value::as_u64) == Some(sentry_pid) + && rec.get("sentry_start_time_ticks").and_then(Value::as_u64) == Some(sentry_start_time_ticks) + { + return Ok(rec); + } + let rev = rec.get("revision").and_then(Value::as_i64).unwrap_or(-1); + if rev != expected_revision { + return Err(JournalError::Conflict("hibernation journal revision mismatch".into())); + } + if state != "restoring" || auth != "candidate" { + return Err(JournalError::Conflict("running can only commit from a verified restore candidate".into())); + } + rec.insert("state".into(), json!("running")); + rec.insert("authority".into(), json!("live")); + rec.insert("sentry_pid".into(), json!(sentry_pid)); + rec.insert("sentry_start_time_ticks".into(), json!(sentry_start_time_ticks)); + rec.insert("candidate_pid".into(), Value::Null); + rec.insert("candidate_start_time_ticks".into(), Value::Null); + rec.insert("revision".into(), json!(rev + 1)); + rec.insert("updated_ns".into(), json!(now_ns())); + Ok(rec) + }) + } + + /// `rollback_hibernate`: hibernating (live) -> running (live) when checkpoint failed before COMPLETE. + pub fn rollback_hibernate( + &self, + sandbox_id: &str, + generation: u64, + operation_id: &str, + expected_revision: i64, + ) -> Result, JournalError> { + self.mutate(sandbox_id, generation, |mut rec| { + let rev = rec.get("revision").and_then(Value::as_i64).unwrap_or(-1); + if rev != expected_revision { + return Err(JournalError::Conflict("hibernation journal revision mismatch".into())); + } + let state = rec.get("state").and_then(Value::as_str).unwrap_or(""); + let op_id = rec.get("operation_id").and_then(Value::as_str).unwrap_or(""); + if state != "hibernating" || op_id != operation_id { + return Err(JournalError::Conflict("cannot rollback non-hibernating journal".into())); + } + rec.insert("state".into(), json!("running")); + rec.insert("authority".into(), json!("live")); + rec.insert("revision".into(), json!(rev + 1)); + rec.insert("updated_ns".into(), json!(now_ns())); + Ok(rec) + }) + } + + /// `rollback_restore`: restoring -> parked (artifact) when restore failed before RUNNING committed. + pub fn rollback_restore( + &self, + sandbox_id: &str, + generation: u64, + operation_id: &str, + expected_revision: i64, + ) -> Result, JournalError> { + self.mutate(sandbox_id, generation, |mut rec| { + let rev = rec.get("revision").and_then(Value::as_i64).unwrap_or(-1); + if rev != expected_revision { + return Err(JournalError::Conflict("hibernation journal revision mismatch".into())); + } + let state = rec.get("state").and_then(Value::as_str).unwrap_or(""); + let op_id = rec.get("operation_id").and_then(Value::as_str).unwrap_or(""); + if state != "restoring" || op_id != operation_id { + return Err(JournalError::Conflict("cannot rollback non-restoring journal".into())); + } + rec.insert("state".into(), json!("parked")); + rec.insert("authority".into(), json!("artifact")); + rec.insert("candidate_pid".into(), Value::Null); + rec.insert("candidate_start_time_ticks".into(), Value::Null); + rec.insert("revision".into(), json!(rev + 1)); + rec.insert("updated_ns".into(), json!(now_ns())); + Ok(rec) + }) + } + + /// `quarantine`: move a broken journal to `recovery_required`. + pub fn quarantine( + &self, + sandbox_id: &str, + generation: u64, + reason: &str, + expected_revision: i64, + ) -> Result, JournalError> { + self.mutate(sandbox_id, generation, |mut rec| { + let rev = rec.get("revision").and_then(Value::as_i64).unwrap_or(-1); + if rev != expected_revision { + return Err(JournalError::Conflict("hibernation journal revision mismatch".into())); + } + rec.insert("state".into(), json!("recovery_required")); + rec.insert("recovery_reason".into(), json!(reason)); + rec.insert("revision".into(), json!(rev + 1)); + rec.insert("updated_ns".into(), json!(now_ns())); + Ok(rec) + }) + } + + /// Remove a confirmed-dead sandbox's journal, fenced by `expected_revision`. + pub fn remove(&self, sandbox_id: &str, generation: u64, expected_revision: i64) -> Result<(), JournalError> { + let (path, lock_path) = self.paths(sandbox_id, generation)?; + if !self.root.exists() { + return Ok(()); + } + let _lock = FileLock::acquire(&lock_path, true)?; + let Some(existing) = load_record(&path)? else { + return Ok(()); + }; + let revision = existing.get("revision").and_then(Value::as_i64); + if revision != Some(expected_revision) { + return Err(JournalError::Conflict("hibernation journal revision mismatch during removal".into())); + } + match std::fs::remove_file(&path) { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(error.into()), + } + crate::fsutil::fsync_dir(&self.root)?; + let _ = std::fs::remove_file(&lock_path); + Ok(()) + } +} + +fn now_ns() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(1, |d| d.as_nanos() as u64) } fn load_record(path: &Path) -> Result>, JournalError> { diff --git a/runtime/noded/src/lib.rs b/runtime/noded/src/lib.rs index 695bd142..e4939c81 100644 --- a/runtime/noded/src/lib.rs +++ b/runtime/noded/src/lib.rs @@ -12,16 +12,25 @@ pub mod admission; pub mod agent_rpc; +pub mod commit_export; +pub mod control_front; pub mod create; +pub mod ed25519; +pub mod environment; pub mod exec; pub mod exec_fence; pub mod exec_front; +pub mod files_front; pub mod fsutil; +pub mod heartbeat; +pub mod images_front; pub mod internal; pub mod journal; +pub mod lifecycle_front; pub mod local_wait; pub mod memory_backing; pub mod network; +pub mod node_lifecycle; pub mod pause; pub mod pause_runtime; pub mod pause_policy; @@ -29,8 +38,13 @@ pub mod node_pipeline; pub mod pipeline; pub mod pyjson; pub mod registry; +pub mod registry_client; pub mod runsc; +pub mod runtime_metrics; +pub mod sandbox_record; +pub mod standalone; pub mod storage; +pub mod upload_archive; pub mod warden; pub mod timings; pub mod guest; @@ -61,8 +75,8 @@ pub type Body = BoxBody; #[derive(Clone, Debug)] pub struct Config { - /// The Python agent's Unix socket. - pub upstream: PathBuf, + /// The Python agent's Unix socket (`None` in standalone Rust mode). + pub upstream: Option, /// Client connections served at once; further ones wait in the listen backlog. pub max_connections: usize, /// A client must send its request headers within this time. @@ -74,13 +88,22 @@ pub struct Config { impl Config { pub fn new(upstream: PathBuf) -> Self { Config { - upstream, + upstream: Some(upstream), // Held job reads (docs/architecture.md) are a few thousand. max_connections: 16 * 1024, header_read_timeout: Duration::from_secs(30), shutdown_grace: Duration::from_secs(20), } } + + pub fn standalone() -> Self { + Config { + upstream: None, + max_connections: 16 * 1024, + header_read_timeout: Duration::from_secs(30), + shutdown_grace: Duration::from_secs(20), + } + } } /// Headers that describe one hop. hyper frames each hop's body itself. @@ -132,6 +155,23 @@ fn not_found() -> Response { response } +fn unauthorized() -> Response { + let body = Full::new(Bytes::from_static(b"{\"error\":\"unauthorized\"}")).map_err(|never| match never {}).boxed(); + let mut response = Response::new(body); + *response.status_mut() = StatusCode::UNAUTHORIZED; + response.headers_mut().insert(header::CONTENT_TYPE, HeaderValue::from_static("application/json")); + response +} + +fn has_valid_bearer(request: &Request, token: &[u8]) -> bool { + let supplied = request + .headers() + .get(header::AUTHORIZATION) + .map(|v| v.as_bytes()) + .and_then(|v| v.strip_prefix(b"Bearer ")); + supplied.is_some_and(|s| s.len() == token.len() && !s.is_empty() && s.iter().zip(token).fold(0u8, |a, (x, y)| a | (x ^ y)) == 0) +} + /// One client connection's upstream connection, opened on first use and /// replaced when the agent closes it. struct Upstream { @@ -205,13 +245,20 @@ impl Upstream { /// The daemon's own routes, each optional. #[derive(Clone, Default)] pub struct Fronts { + pub control: Option>, pub create: Option>, pub exec: Option>, + pub files: Option>, + pub heartbeat: Option>, + pub images: Option>, pub jobs: Option>, + pub lifecycle: Option>, /// The node, once the agent's configuration loaded it. pub node: Option>>>, /// The agent's routes on the internal socket (`--rust-admission`). pub internal: Option>, + /// Bearer token enforced on unmatched `/v1/*` routes in standalone mode. + pub standalone_token: Option, } impl Fronts { @@ -261,11 +308,17 @@ pub fn start_fronts(upstream: &std::path::Path, token: &str, admission: bool) -> None }; Ok(Fronts { + control: Some(control_front::ControlFront::new(node.clone(), token)), create: Some(Arc::new(create::CreateFront::new(agent, pipeline, token))), exec: Some(exec_front::ExecFront::new(node.clone(), token)), + files: Some(files_front::FilesFront::new(node.clone(), token)), + heartbeat: None, + images: None, jobs: Some(jobs), + lifecycle: None, node: Some(node), internal, + standalone_token: None, }) } @@ -316,12 +369,30 @@ pub async fn serve_with(listener: TcpListener, config: Config, fronts: Fronts, s () = &mut shutdown => break, }; let _ = stream.set_nodelay(true); - let upstream = Arc::new(Upstream { path: config.upstream.clone(), sender: Mutex::new(None) }); + let upstream = config + .upstream + .as_ref() + .map(|path| Arc::new(Upstream { path: path.clone(), sender: Mutex::new(None) })); let fronts = fronts.clone(); let service = hyper::service::service_fn(move |request: Request| { let upstream = upstream.clone(); let fronts = fronts.clone(); async move { + let fallback = |req: Request| { + let upstream = upstream.clone(); + let token = fronts.standalone_token.clone(); + async move { + if let Some(up) = upstream { + return up.forward(req).await; + } + if let Some(tok) = token { + if req.uri().path().starts_with("/v1/") && !has_valid_bearer(&req, &tok) { + return Ok(unauthorized()); + } + } + Ok(not_found()) + } + }; let mut request = request.map(|body| body.boxed()); // The agent's internal create endpoints answer the daemon only, // and the session header releases admissions held under it. @@ -329,24 +400,54 @@ pub async fn serve_with(listener: TcpListener, config: Config, fronts: Fronts, s return Ok(not_found()); } request.headers_mut().remove(agent_rpc::SESSION_HEADER); + if let Some(front) = fronts.heartbeat.as_ref().filter(|front| front.intercepts(&request)) { + return match front.handle(request).await { + exec_front::Outcome::Response(response) => Ok(response), + exec_front::Outcome::Forward(request) => fallback(request).await, + }; + } + if let Some(front) = fronts.images.as_ref().filter(|front| front.intercepts(&request)) { + return match front.handle(request).await { + exec_front::Outcome::Response(response) => Ok(response), + exec_front::Outcome::Forward(request) => fallback(request).await, + }; + } + if let Some(front) = fronts.control.as_ref().filter(|front| front.intercepts(&request)) { + return match front.handle(request).await { + exec_front::Outcome::Response(response) => Ok(response), + exec_front::Outcome::Forward(request) => fallback(request).await, + }; + } + if let Some(front) = fronts.lifecycle.as_ref().filter(|front| front.intercepts(&request)) { + return match front.handle(request).await { + exec_front::Outcome::Response(response) => Ok(response), + exec_front::Outcome::Forward(request) => fallback(request).await, + }; + } if let Some(front) = fronts.jobs.as_ref().filter(|front| front.intercepts(&request)) { return match front.handle(request).await { exec_front::Outcome::Response(response) => Ok(response), - exec_front::Outcome::Forward(request) => upstream.forward(request).await, + exec_front::Outcome::Forward(request) => fallback(request).await, + }; + } + if let Some(front) = fronts.files.as_ref().filter(|front| front.intercepts(&request)) { + return match front.handle(request).await { + exec_front::Outcome::Response(response) => Ok(response), + exec_front::Outcome::Forward(request) => fallback(request).await, }; } if let Some(front) = fronts.exec.as_ref().filter(|front| front.intercepts(&request)) { return match front.handle(request).await { exec_front::Outcome::Response(response) => Ok(response), - exec_front::Outcome::Forward(request) => upstream.forward(request).await, + exec_front::Outcome::Forward(request) => fallback(request).await, }; } match fronts.create { Some(front) if front.intercepts(&request) => match front.handle(request).await { create::Outcome::Response(response) => Ok(response), - create::Outcome::Forward(request) => upstream.forward(request).await, + create::Outcome::Forward(request) => fallback(request).await, }, - _ => upstream.forward(request).await, + _ => fallback(request).await, } } }); diff --git a/runtime/noded/src/lifecycle_front.rs b/runtime/noded/src/lifecycle_front.rs new file mode 100644 index 00000000..ede02750 --- /dev/null +++ b/runtime/noded/src/lifecycle_front.rs @@ -0,0 +1,343 @@ +//! Remaining sandbox lifecycle HTTP routes in standalone `ucloud-noded` (Wave B5): +//! +//! - `GET /v1/sandboxes/{id}/ssh` +//! - `POST /v1/sandboxes/{id}/park` +//! - `POST /v1/sandboxes/{id}/wake` +//! - `POST /v1/sandboxes/{id}/snapshot/publish` +//! - `POST /v1/sandboxes/{id}/publish-parked` +//! - `POST /v1/sandboxes/{id}/evict-published` +//! - `POST /v1/sandboxes/{id}/commit-export` +//! - `POST /v1/sandboxes/{id}/migration/{prepare,activate,finalize,abort,abort-import}` +//! - `POST /v1/migrations/import` + +use std::future::Future; +use std::pin::Pin; +use std::sync::Arc; + +use bytes::Bytes; +use http_body_util::{BodyExt, Full, Limited}; +use hyper::header::{self, HeaderName, HeaderValue}; +use hyper::{Method, Request, Response, StatusCode}; +use serde_json::{Value, json}; + +use crate::Body; +use crate::commit_export::CommitRefused; +use crate::exec_front::Outcome; +use crate::registry::is_operation_id; + +const MAX_BODY_BYTES: usize = 16 * 1024 * 1024; +const SUPPORTED_MIGRATION_SCHEMAS: &[&str] = &["storage-native-migration-v1", "storage-native-split-migration-v1"]; + +pub type BoxFuture = Pin + Send>>; + +#[derive(Debug)] +pub enum LifecycleError { + BadRequest(String), + NotFound(String), + Conflict(String), + Busy(String), + ParkDeferred { message: String, retry_after_secs: u64 }, + SnapshotPublicationPending(String), + RestoreBusy { message: String, sandbox: Option }, + CommitRefused(CommitRefused), + Unavailable { message: String, lifecycle_state: Option, sandbox: Option }, +} + +pub trait LifecycleNode: Send + Sync { + fn ssh(&self, sandbox_id: &str) -> BoxFuture>; + fn park(&self, sandbox_id: &str, operation_id: &str, background: bool) -> BoxFuture>; + fn wake(&self, sandbox_id: &str, generation: i64, operation_id: &str) -> BoxFuture>; + fn request_snapshot_publication(&self, sandbox_id: &str, generation: i64) -> BoxFuture>; + fn publish_parked(&self, sandbox_id: &str, generation: i64, create_operation_id: &str, spec_hash: &str) -> BoxFuture>; + fn evict_published(&self, sandbox_id: &str, generation: i64, digest: &str) -> BoxFuture>; + fn commit_export(&self, sandbox_id: &str, raw: Value) -> BoxFuture>; + fn prepare_migration(&self, sandbox_id: &str, migration_id: &str, format: &str) -> BoxFuture>; + fn import_migration(&self, raw: Value) -> BoxFuture>; + fn complete_migration(&self, sandbox_id: &str, action: &str, migration_id: &str, snapshot_sha256: &str) -> BoxFuture>; +} + +#[derive(Debug, Clone, PartialEq, Eq)] +enum LifecycleRoute { + Ssh(String), + Park(String), + Wake(String), + SnapshotPublish(String), + PublishParked(String), + EvictPublished(String), + CommitExport(String), + MigrationPrepare(String), + MigrationAction { sandbox_id: String, action: &'static str }, + MigrationImport, +} + +fn parse_route(method: &Method, path: &str) -> Option { + if method == Method::POST && path == "/v1/migrations/import" { + return Some(LifecycleRoute::MigrationImport); + } + let rest = path.strip_prefix("/v1/sandboxes/")?; + let (id, suffix) = rest.split_once('/')?; + if id.is_empty() || id.contains('%') { + return None; + } + let sid = id.to_string(); + match (method, suffix) { + (&Method::GET, "ssh") => Some(LifecycleRoute::Ssh(sid)), + (&Method::POST, "park") => Some(LifecycleRoute::Park(sid)), + (&Method::POST, "wake") => Some(LifecycleRoute::Wake(sid)), + (&Method::POST, "snapshot/publish") => Some(LifecycleRoute::SnapshotPublish(sid)), + (&Method::POST, "publish-parked") => Some(LifecycleRoute::PublishParked(sid)), + (&Method::POST, "evict-published") => Some(LifecycleRoute::EvictPublished(sid)), + (&Method::POST, "commit-export") => Some(LifecycleRoute::CommitExport(sid)), + (&Method::POST, "migration/prepare") => Some(LifecycleRoute::MigrationPrepare(sid)), + (&Method::POST, "migration/activate") => Some(LifecycleRoute::MigrationAction { sandbox_id: sid, action: "activate" }), + (&Method::POST, "migration/finalize") => Some(LifecycleRoute::MigrationAction { sandbox_id: sid, action: "finalize" }), + (&Method::POST, "migration/abort") => Some(LifecycleRoute::MigrationAction { sandbox_id: sid, action: "abort" }), + (&Method::POST, "migration/abort-import") => Some(LifecycleRoute::MigrationAction { sandbox_id: sid, action: "abort-import" }), + _ => None, + } +} + +pub struct LifecycleFront { + node: Arc, + token: Bytes, +} + +impl LifecycleFront { + pub fn new(node: Arc, token: &str) -> Arc { + Arc::new(LifecycleFront { + node, + token: Bytes::copy_from_slice(token.as_bytes()), + }) + } + + fn authorized(&self, request: &Request) -> bool { + let supplied = request + .headers() + .get(header::AUTHORIZATION) + .map(|v| v.as_bytes()) + .and_then(|v| v.strip_prefix(b"Bearer ")); + supplied.is_some_and(|s| !s.is_empty() && constant_time_eq(s, &self.token)) + } + + pub fn intercepts(&self, request: &Request) -> bool { + parse_route(request.method(), request.uri().path()).is_some() && self.authorized(request) + } + + pub async fn handle(&self, request: Request) -> Outcome { + let Some(route) = parse_route(request.method(), request.uri().path()) else { + return Outcome::Forward(request); + }; + let result = match route { + LifecycleRoute::Ssh(sid) => self.node.ssh(&sid).await.map(|v| (StatusCode::OK, v)), + LifecycleRoute::Park(sid) => self.handle_park(&sid, request).await, + LifecycleRoute::Wake(sid) => self.handle_wake(&sid, request).await, + LifecycleRoute::SnapshotPublish(sid) => self.handle_snapshot_publish(&sid, request).await, + LifecycleRoute::PublishParked(sid) => self.handle_publish_parked(&sid, request).await, + LifecycleRoute::EvictPublished(sid) => self.handle_evict_published(&sid, request).await, + LifecycleRoute::CommitExport(sid) => match read_json(request).await { + Ok(raw) => self.node.commit_export(&sid, raw).await, + Err(e) => Err(e), + }, + LifecycleRoute::MigrationPrepare(sid) => self.handle_migration_prepare(&sid, request).await, + LifecycleRoute::MigrationImport => match read_json(request).await { + Ok(raw) => self.node.import_migration(raw).await.map(|v| (StatusCode::CREATED, v)), + Err(e) => Err(e), + }, + LifecycleRoute::MigrationAction { sandbox_id, action } => { + self.handle_migration_action(&sandbox_id, action, request).await + } + }; + Outcome::Response(match result { + Ok((status, payload)) => json_response(status, payload, &[]), + Err(err) => error_response(err), + }) + } + + async fn handle_park(&self, sid: &str, req: Request) -> Result<(StatusCode, Value), LifecycleError> { + let raw = read_json(req).await?; + let obj = raw.as_object().ok_or_else(|| LifecycleError::BadRequest("park payload must be a JSON object".into()))?; + let op = obj + .get("operation_id") + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty() && is_operation_id(s)) + .ok_or_else(|| LifecycleError::BadRequest("operation_id must be a nonempty string".into()))?; + let background = match obj.get("background") { + None => false, + Some(v) => v.as_bool().ok_or_else(|| LifecycleError::BadRequest("background must be a boolean".into()))?, + }; + self.node.park(sid, op, background).await + } + + async fn handle_wake(&self, sid: &str, req: Request) -> Result<(StatusCode, Value), LifecycleError> { + let raw = read_json(req).await?; + let obj = raw.as_object().ok_or_else(|| LifecycleError::BadRequest("wake payload must be a JSON object".into()))?; + let generation = obj + .get("generation") + .and_then(Value::as_i64) + .filter(|&g| g >= 1) + .ok_or_else(|| LifecycleError::BadRequest("generation must be a positive integer".into()))?; + let op = obj + .get("operation_id") + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty() && is_operation_id(s)) + .ok_or_else(|| LifecycleError::BadRequest("operation_id must be a nonempty string".into()))?; + self.node.wake(sid, generation, op).await.map(|v| (StatusCode::OK, v)) + } + + async fn handle_snapshot_publish(&self, sid: &str, req: Request) -> Result<(StatusCode, Value), LifecycleError> { + let raw = read_json(req).await?; + let obj = raw.as_object().ok_or_else(|| LifecycleError::BadRequest("publication requires a generation".into()))?; + let generation = obj + .get("generation") + .and_then(Value::as_i64) + .filter(|&g| g >= 1) + .ok_or_else(|| LifecycleError::BadRequest("publication generation must be a positive integer".into()))?; + self.node.request_snapshot_publication(sid, generation).await.map(|v| (StatusCode::ACCEPTED, v)) + } + + async fn handle_publish_parked(&self, sid: &str, req: Request) -> Result<(StatusCode, Value), LifecycleError> { + let raw = read_json(req).await?; + let obj = raw.as_object().ok_or_else(|| LifecycleError::BadRequest("parked publication payload must be a JSON object".into()))?; + if obj.len() != 3 { + return Err(LifecycleError::BadRequest("parked publication payload has an invalid schema".into())); + } + let generation = obj.get("generation").and_then(Value::as_i64).filter(|&g| g >= 1) + .ok_or_else(|| LifecycleError::BadRequest("generation must be an integer".into()))?; + let create_op = obj.get("create_operation_id").and_then(Value::as_str) + .ok_or_else(|| LifecycleError::BadRequest("create_operation_id must be a string".into()))?; + let spec_hash = obj.get("spec_hash").and_then(Value::as_str) + .ok_or_else(|| LifecycleError::BadRequest("spec_hash must be a string".into()))?; + self.node.publish_parked(sid, generation, create_op, spec_hash).await.map(|v| (StatusCode::OK, v)) + } + + async fn handle_evict_published(&self, sid: &str, req: Request) -> Result<(StatusCode, Value), LifecycleError> { + let raw = read_json(req).await?; + let obj = raw.as_object().ok_or_else(|| LifecycleError::BadRequest("published eviction payload must be a JSON object".into()))?; + if obj.len() != 2 { + return Err(LifecycleError::BadRequest("published eviction payload has an invalid schema".into())); + } + let generation = obj.get("generation").and_then(Value::as_i64).filter(|&g| g >= 1) + .ok_or_else(|| LifecycleError::BadRequest("generation must be an integer".into()))?; + let digest = obj.get("snapshot_manifest_digest").and_then(Value::as_str) + .ok_or_else(|| LifecycleError::BadRequest("snapshot_manifest_digest must be a string".into()))?; + self.node.evict_published(sid, generation, digest).await?; + Ok((StatusCode::OK, json!({"ok": true}))) + } + + async fn handle_migration_prepare(&self, sid: &str, req: Request) -> Result<(StatusCode, Value), LifecycleError> { + let raw = read_json(req).await?; + let obj = raw.as_object().ok_or_else(|| LifecycleError::BadRequest("migration payload must be a JSON object".into()))?; + let migration_id = obj.get("migration_id").and_then(Value::as_str).map(str::trim).unwrap_or(""); + let format = obj.get("format").and_then(Value::as_str).map(str::trim).unwrap_or(""); + if !SUPPORTED_MIGRATION_SCHEMAS.contains(&format) { + return Err(LifecycleError::BadRequest("unsupported migration storage schema".into())); + } + self.node.prepare_migration(sid, migration_id, format).await.map(|v| (StatusCode::OK, v)) + } + + async fn handle_migration_action(&self, sid: &str, action: &str, req: Request) -> Result<(StatusCode, Value), LifecycleError> { + let raw = read_json(req).await?; + let obj = raw.as_object().ok_or_else(|| LifecycleError::BadRequest("migration payload must be a JSON object".into()))?; + let migration_id = obj.get("migration_id").and_then(Value::as_str).map(str::trim).unwrap_or(""); + let sha256 = obj.get("snapshot_sha256").and_then(Value::as_str).map(str::trim).unwrap_or(""); + self.node.complete_migration(sid, action, migration_id, sha256).await.map(|v| (StatusCode::OK, v)) + } +} + +async fn read_json(request: Request) -> Result { + let bytes = Limited::new(request.into_body(), MAX_BODY_BYTES) + .collect() + .await + .map_err(|_| LifecycleError::BadRequest("invalid request body".into()))? + .to_bytes(); + if bytes.is_empty() { + return Err(LifecycleError::BadRequest("empty request body".into())); + } + serde_json::from_slice(&bytes).map_err(|e| LifecycleError::BadRequest(format!("invalid JSON: {e}"))) +} + +fn error_response(err: LifecycleError) -> Response { + match err { + LifecycleError::BadRequest(msg) => json_response(StatusCode::BAD_REQUEST, json!({"error": msg}), &[]), + LifecycleError::NotFound(msg) => json_response(StatusCode::NOT_FOUND, json!({"error": msg}), &[]), + LifecycleError::Conflict(msg) => json_response(StatusCode::CONFLICT, json!({"error": msg}), &[]), + LifecycleError::Busy(msg) => json_response(StatusCode::CONFLICT, json!({"error": msg, "retryable": true}), &[]), + LifecycleError::ParkDeferred { message, retry_after_secs } => { + let ra = retry_after_secs.to_string(); + json_response( + StatusCode::CONFLICT, + json!({ + "error": message, + "error_code": "park_deferred", + "retryable": true, + "retry_after_seconds": retry_after_secs, + }), + &[("Retry-After", &ra)], + ) + } + LifecycleError::SnapshotPublicationPending(msg) => json_response( + StatusCode::SERVICE_UNAVAILABLE, + json!({ + "error": msg, + "error_code": "snapshot_publication_pending", + "lifecycle_state": "parked", + "retryable": true, + }), + &[("Retry-After", "1"), ("X-UCloud-Sandbox-Retryable", "true")], + ), + LifecycleError::RestoreBusy { message, sandbox } => { + let mut body = json!({ + "error": message, + "error_code": "node_restore_busy", + "retryable": true, + "lifecycle_state": "parked", + }); + if let Some(sb) = sandbox { + body["sandbox"] = sb; + } + json_response( + StatusCode::SERVICE_UNAVAILABLE, + body, + &[("Retry-After", "1"), ("X-UCloud-Sandbox-Retryable", "true")], + ) + } + LifecycleError::CommitRefused(refused) => { + let hdrs: &[(&str, &str)] = if refused.retryable { &[("Retry-After", "1")] } else { &[] }; + json_response(refused.status, refused.payload(), hdrs) + } + LifecycleError::Unavailable { message, lifecycle_state, sandbox } => { + let mut body = json!({"error": message}); + if let Some(state) = lifecycle_state { + body["lifecycle_state"] = Value::String(state); + } + if let Some(sb) = sandbox { + body["sandbox"] = sb; + } + json_response(StatusCode::SERVICE_UNAVAILABLE, body, &[]) + } + } +} + +fn constant_time_eq(left: &[u8], right: &[u8]) -> bool { + left.len() == right.len() && left.iter().zip(right).fold(0u8, |acc, (a, b)| acc | (a ^ b)) == 0 +} + +fn full(bytes: impl Into) -> Body { + Full::new(bytes.into()).map_err(|never| match never {}).boxed() +} + +fn json_response(status: StatusCode, payload: Value, extra_headers: &[(&str, &str)]) -> Response { + let body = serde_json::to_vec(&payload).unwrap_or_else(|_| b"{}".to_vec()); + let mut response = Response::new(full(body)); + *response.status_mut() = status; + let headers = response.headers_mut(); + headers.insert(header::CONTENT_TYPE, HeaderValue::from_static("application/json")); + for (name, value) in extra_headers { + if let (Ok(name), Ok(value)) = (HeaderName::from_bytes(name.as_bytes()), HeaderValue::from_str(value)) { + headers.insert(name, value); + } + } + response +} diff --git a/runtime/noded/src/local_wait/tests.rs b/runtime/noded/src/local_wait/tests.rs index 7e775498..a4b9f308 100644 --- a/runtime/noded/src/local_wait/tests.rs +++ b/runtime/noded/src/local_wait/tests.rs @@ -666,7 +666,6 @@ impl TierFake { memory_root: root.join("memory"), application_memory_root: None, network: "none".into(), - reflink_memory_restore: false, proc_root: root.join("proc"), command_timeout: Duration::from_secs(10), stop_timeout: Duration::from_secs(1), @@ -893,7 +892,6 @@ fn tier_config() -> PauseConfig { memory_root: "/nonexistent/memory".into(), application_memory_root: None, network: "none".into(), - reflink_memory_restore: false, proc_root: "/proc".into(), command_timeout: Duration::from_secs(1), stop_timeout: Duration::from_secs(1), diff --git a/runtime/noded/src/main.rs b/runtime/noded/src/main.rs index 56e7d5ab..dbcb5237 100644 --- a/runtime/noded/src/main.rs +++ b/runtime/noded/src/main.rs @@ -1,3 +1,5 @@ +//! ucloud-noded --listen ADDR --standalone-config PATH --node-control-token-file PATH +//! [--max-connections N] //! ucloud-noded --listen ADDR --upstream-unix PATH --node-control-token-file PATH //! [--max-connections N] [--rust-admission --internal-unix PATH] //! ucloud-noded --admission-only --internal-unix PATH --registry PATH --node-control-token-file PATH @@ -12,7 +14,8 @@ use tokio::signal::unix::{SignalKind, signal}; fn usage(message: &str) -> ExitCode { eprintln!("ucloud-noded: {message}"); eprintln!( - "usage: ucloud-noded --listen ADDR --upstream-unix PATH --node-control-token-file PATH \ + "usage: ucloud-noded --listen ADDR --standalone-config PATH --node-control-token-file PATH [--max-connections N]\n \ + ucloud-noded --listen ADDR --upstream-unix PATH --node-control-token-file PATH \ [--max-connections N] [--rust-admission --internal-unix PATH]\n \ ucloud-noded --admission-only --internal-unix PATH --registry PATH --node-control-token-file PATH \ [--admission-config PATH] [--metrics-file PATH] [--observations-file PATH]" @@ -64,6 +67,7 @@ fn admission_only(options: ucloud_noded::admission::standalone::Options) -> Exit fn main() -> ExitCode { let mut listen: Option = None; let mut upstream: Option = None; + let mut standalone_config: Option = None; let mut max_connections: Option = None; let mut rust_admission = false; let mut admission_only = false; @@ -90,6 +94,7 @@ fn main() -> ExitCode { Err(_) => return usage(&format!("invalid --listen {value}")), }, "--upstream-unix" => upstream = Some(PathBuf::from(value)), + "--standalone-config" => standalone_config = Some(PathBuf::from(value)), "--node-control-token-file" => token_file = Some(PathBuf::from(value)), "--internal-unix" => internal_unix = Some(PathBuf::from(value)), "--registry" => registry = Some(PathBuf::from(value)), @@ -134,8 +139,64 @@ fn main() -> ExitCode { if registry.is_some() || admission_config.is_some() || metrics_file.is_some() || observations_file.is_some() { return usage("--registry, --admission-config, --metrics-file and --observations-file go with --admission-only"); } + if let Some(config_path) = standalone_config { + if upstream.is_some() || rust_admission || internal_unix.is_some() { + return usage("--standalone-config cannot be combined with --upstream-unix or --rust-admission"); + } + let Some(listen) = listen else { + return usage("--listen is required with --standalone-config"); + }; + let token = match read_token(token_file) { + Ok(token) => token, + Err(error) => return usage(&error), + }; + let loaded = match ucloud_noded::standalone::StandaloneConfig::load(&config_path) { + Ok(cfg) => cfg, + Err(error) => { + eprintln!("ucloud-noded: {error}"); + return ExitCode::FAILURE; + } + }; + let mut config = ucloud_noded::Config::standalone(); + if let Some(count) = max_connections { + config.max_connections = count; + } + let Some(runtime) = runtime() else { return ExitCode::FAILURE }; + return runtime.block_on(async move { + let listener = match ucloud_noded::listen(listen) { + Ok(listener) => listener, + Err(error) => { + eprintln!("ucloud-noded: cannot listen on {listen}: {error}"); + return ExitCode::FAILURE; + } + }; + let (Ok(mut terminate), Ok(mut interrupt)) = + (signal(SignalKind::terminate()), signal(SignalKind::interrupt())) + else { + eprintln!("ucloud-noded: cannot install signal handlers"); + return ExitCode::FAILURE; + }; + let standalone = match ucloud_noded::standalone::start_standalone(loaded, &token) { + Ok(rt) => rt, + Err(error) => { + eprintln!("ucloud-noded: standalone startup failed: {error}"); + return ExitCode::FAILURE; + } + }; + eprintln!("ucloud-noded: serving standalone worker on {listen}"); + let shutdown = async move { + tokio::select! { + _ = terminate.recv() => {} + _ = interrupt.recv() => {} + } + }; + ucloud_noded::serve_with(listener, config, standalone.fronts.clone(), shutdown).await; + standalone.shutdown().await; + ExitCode::SUCCESS + }); + } let (Some(listen), Some(upstream)) = (listen, upstream) else { - return usage("--listen and --upstream-unix are required"); + return usage("--listen and either --standalone-config or --upstream-unix are required"); }; if rust_admission != internal_unix.is_some() { return usage("--rust-admission and --internal-unix go together"); @@ -144,7 +205,7 @@ fn main() -> ExitCode { Ok(token) => token, Err(error) => return usage(&error), }; - let mut config = ucloud_noded::Config::new(upstream); + let mut config = ucloud_noded::Config::new(upstream.clone()); if let Some(count) = max_connections { config.max_connections = count; } @@ -163,14 +224,14 @@ fn main() -> ExitCode { eprintln!("ucloud-noded: cannot install signal handlers"); return ExitCode::FAILURE; }; - eprintln!("ucloud-noded: serving {listen} -> unix:{}", config.upstream.display()); + eprintln!("ucloud-noded: serving {listen} -> unix:{}", upstream.display()); let shutdown = async move { tokio::select! { _ = terminate.recv() => {} _ = interrupt.recv() => {} } }; - let fronts = match ucloud_noded::start_fronts(&config.upstream, &token, rust_admission) { + let fronts = match ucloud_noded::start_fronts(&upstream, &token, rust_admission) { Ok(fronts) => fronts, Err(error) => { eprintln!("ucloud-noded: {error}"); diff --git a/runtime/noded/src/memory_backing.rs b/runtime/noded/src/memory_backing.rs index 2f5d95a3..f1dca233 100644 --- a/runtime/noded/src/memory_backing.rs +++ b/runtime/noded/src/memory_backing.rs @@ -186,6 +186,10 @@ pub trait MemoryQuota: Send + Sync { /// Assign the project, set its limits, then [`MemoryQuota::validate_project`]. fn provision(&self, path: &Path, project_id: i64, limit_bytes: i64) -> Result<()>; fn validate_project(&self, path: &Path, project_id: i64) -> Result<()>; + /// Release a project quota limit after its backing directory is removed. + fn release(&self, _root: &Path, _project_id: i64) -> Result<()> { + Ok(()) + } } /// How [`XfsMemoryQuota::provision`] reaches the kernel. @@ -543,6 +547,34 @@ impl MemoryQuota for XfsMemoryQuota { } Ok(()) } + + fn release(&self, _root: &Path, project_id: i64) -> Result<()> { + let fs_root = self + .filesystem_root + .as_ref() + .ok_or_else(|| MemoryBackingError::Backing("memory backing mountpoint is unavailable".into()))?; + let source = findmnt("SOURCE", fs_root)?; + if source.starts_with("/dev/loop") { + let output = Command::new("fstrim").arg(fs_root).output()?; + if !output.status.success() { + return Err(MemoryBackingError::Backing(format!( + "fstrim failed: {}", + String::from_utf8_lossy(&output.stderr) + ))); + } + } + let output = Command::new("xfs_quota") + .args(["-x", "-c", &format!("limit -p bsoft=0 bhard=0 {project_id}")]) + .arg(fs_root) + .output()?; + if !output.status.success() { + return Err(MemoryBackingError::Backing(format!( + "xfs_quota release failed: {}", + String::from_utf8_lossy(&output.stderr) + ))); + } + Ok(()) + } } #[derive(Clone, Debug)] @@ -1056,6 +1088,18 @@ impl MemoryBackingStore { self.writer.commits.load(Ordering::SeqCst) } + /// Total hard-reserved memory-backing bytes across all non-deleted allocations + /// (`sandboxes/memory_backing.py::MemoryBackingStore.metrics`). + pub fn hard_reserved_bytes(&self) -> Result { + let conn = lock(&self.reader); + let reserved: i64 = conn.query_row( + "SELECT COALESCE(SUM(limit_bytes), 0) FROM allocations WHERE state != 'deleted'", + [], + |row| row.get(0), + )?; + Ok(reserved.max(0) as u64) + } + fn parse_mode(ram_configured: bool, mode: Option<&str>) -> Result { match mode { Some("ram") if ram_configured => Ok(ActiveMode::Ram), @@ -1324,6 +1368,121 @@ impl MemoryBackingStore { mkdir(&path, false)?; private_directory(&path) } + + fn forget_mode(&self, sandbox_id: &str, generation: u64) { + lock(&self.active_modes).remove(&(sandbox_id.to_string(), generation)); + } + + /// Exclusive non-blocking allocation flock (`_allocation_lock(..., exclusive=True)`). + /// Returns `MemoryBackingError::Busy` while a publication reader holds a shared lock. + fn try_exclusive_allocation_lock(&self, reference: &MemoryBackingRef) -> Result { + let path = self.lease_root.join(&reference.allocation_id); + let file = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC) + .open(&path)?; + // SAFETY: valid file descriptor. + if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0 { + let error = io::Error::last_os_error(); + if error.raw_os_error() == Some(libc::EWOULDBLOCK) { + return Err(MemoryBackingError::Busy( + "memory allocation is pinned by an active checkpoint publication".into(), + )); + } + return Err(error.into()); + } + Ok(file) + } + + /// Port of `MemoryBackingStore.delete`: called only after the lifecycle + /// owner has fenced every runtime for this incarnation. + pub fn delete(&self, reference: &MemoryBackingRef, sandbox_id: &str, sandbox_generation: u64) -> Result<()> { + let _mutation = self.mutation_lock(reference)?; + let row = { + let conn = lock(&self.reader); + self.check_journal_identity()?; + select_allocation(&conn, &reference.allocation_id)? + }; + let path = self.root.join(&reference.allocation_id); + let Some(row) = row else { + if fs::symlink_metadata(&path).is_ok() { + return fail("unregistered memory allocation path exists"); + } + return Ok(()); + }; + if !row.owned_by(sandbox_id, sandbox_generation, reference.quota_bytes) { + return fail("memory deletion identity conflicts"); + } + if row.state_is("deleted") { + self.forget_mode(sandbox_id, sandbox_generation); + return Ok(()); + } + let probe = MemoryBackingLease { + reference: reference.clone(), + sandbox_id: sandbox_id.to_string(), + sandbox_generation, + project_id: row.project_id, + path: path.clone(), + active_mode: ActiveMode::File, + }; + if !row.state_is("deleting") { + if row.state_is("preparing") { + if fs::symlink_metadata(&path).is_ok() { + private_directory(&path)?; + let marker = path.join(MARKER); + if fs::symlink_metadata(&marker).is_ok() { + if !marker_matches(&marker, &probe)? { + return fail("memory allocation marker conflicts"); + } + } else if fs::read_dir(&path)?.next().is_some() { + return fail("unmarked memory allocation is not empty"); + } + } + } else { + self.validate(reference, sandbox_id, sandbox_generation, row.project_id, row.active_mode.as_deref())?; + } + self.writer.write( + || self.check_journal_identity(), + |conn| { + conn.execute( + "UPDATE allocations SET state='deleting' WHERE allocation_id=?", + [&reference.allocation_id], + )?; + Ok(()) + }, + )?; + } + let _alloc_lock = self.try_exclusive_allocation_lock(reference)?; + if path.exists() { + private_directory(&path)?; + fs::remove_dir_all(&path)?; + fsync_dir(&self.root)?; + } + if let Some(active_root) = &self.active_root { + let active = active_root.join(&reference.allocation_id); + if active.exists() { + private_directory(&active)?; + fs::remove_dir_all(&active)?; + } + } + self.quota.release(&self.root, row.project_id)?; + self.writer.write( + || self.check_journal_identity(), + |conn| { + conn.execute( + "UPDATE allocations SET state='deleted' WHERE allocation_id=? AND state='deleting'", + [&reference.allocation_id], + )?; + Ok(()) + }, + )?; + self.forget_mode(sandbox_id, sandbox_generation); + Ok(()) + } } #[cfg(test)] diff --git a/runtime/noded/src/network/mod.rs b/runtime/noded/src/network/mod.rs index 4adf71cc..2081b8cd 100644 --- a/runtime/noded/src/network/mod.rs +++ b/runtime/noded/src/network/mod.rs @@ -300,6 +300,42 @@ impl NetworkManager { Ok(lease) } + /// Port of `DirectNetworkManager.release`: clean up the incarnation's + /// kernel veth/netns and remove its slot from `network-slots.json`. + pub fn release(&self, sandbox_id: &str, generation: u64) -> Result<(), NetworkError> { + let key = key(sandbox_id, generation)?; + let _incarnation = Self::locked(&self.lease_lock_path(&key))?; + let (raw_slot, lease) = { + let _state_lock = Self::locked(&self.lock_path)?; + let state = self.load()?; + let Some(raw) = state.get("leases").and_then(Value::as_object).and_then(|m| m.get(&key)).and_then(Value::as_u64) else { + return Ok(()); + }; + let slot = u32::try_from(raw).map_err(|_| NetworkError::Network("network lease slot out of range".into()))?; + (raw, self.lease(sandbox_id, generation, slot)?) + }; + self.cleanup_kernel_lease(&lease); + let _state_lock = Self::locked(&self.lock_path)?; + let mut state = self.load()?; + let current = state.get("leases").and_then(Value::as_object).and_then(|m| m.get(&key)).and_then(Value::as_u64); + if current != Some(raw_slot) { + return Err(NetworkError::Network("network lease changed during cleanup".into())); + } + if let Some(policies) = state.get_mut("policies").and_then(Value::as_object_mut) { + if policies.contains_key(&key) { + if self.kernel.interface_present(&lease.host_interface) { + return Err(NetworkError::Network("cannot release relay policy while interface exists".into())); + } + policies.remove(&key); + } + } + if let Some(leases) = state.get_mut("leases").and_then(Value::as_object_mut) { + leases.remove(&key); + } + self.store(&state, false)?; + Ok(()) + } + /// Reconcile host rules unless one started after this request arrived. fn ensure_host_rules_since(&self, requested_at: Instant) -> Result<(), NetworkError> { let mut observed = self.host_rules.lock().expect("not poisoned"); diff --git a/runtime/noded/src/node_lifecycle.rs b/runtime/noded/src/node_lifecycle.rs new file mode 100644 index 00000000..2c07a02b --- /dev/null +++ b/runtime/noded/src/node_lifecycle.rs @@ -0,0 +1,915 @@ +//! Standalone Rust `LifecycleNode` implementation backed by `NodePipeline`, +//! `CommitExports`, `HeartbeatFront`, and `RegistryHttpClient` (Wave B5). +//! +//! Also provides `InProcessEscalator` and `wake_hook` so `PauseRuntime` +//! escalates paused sandboxes to RAM-only park and wakes parked sandboxes +//! completely in-process without calling the Python node agent. + +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::Duration; + +use hyper::StatusCode; +use serde_json::{Map, Value, json}; +use sha2::{Digest, Sha256}; + +use crate::admission::growth::Step; +use crate::commit_export::{CommitExports, CommitRefused}; +use crate::exec_fence::ExecFence; +use crate::fsutil::{atomic_write, ensure_private_dir}; +use crate::heartbeat::HeartbeatFront; +use crate::lifecycle_front::{BoxFuture, LifecycleError, LifecycleNode}; +use crate::node_pipeline::NodePipeline; +use crate::pause_policy::{Escalated, Escalator}; +use crate::pause_runtime::WakeHook; +use crate::registry::{GrowthAction, Phase, Registration}; +use crate::registry_client::RegistryHttpClient; +use crate::sandbox_record::sandbox_record_json; +use crate::storage::{VolumeOwner, canonical_json}; +use crate::warden::Sandbox; + +const COMPLETE_MARKER: &str = "COMPLETE"; +const MANIFEST_NAME: &str = "manifest.json"; +const CAPTURE_TIMEOUT: Duration = Duration::from_secs(600); + +#[derive(Clone)] +pub struct NodeLifecycle { + node: Arc>>, + heartbeat: Option>, + commits: Arc, + checkpoint_registry: Option<(RegistryHttpClient, String)>, + published_snapshots: Arc>>, +} + +impl NodeLifecycle { + pub fn new( + node: Arc>>, + heartbeat: Option>, + commits: Arc, + checkpoint_registry: Option<(RegistryHttpClient, String)>, + ) -> Arc { + Arc::new(NodeLifecycle { + node, + heartbeat, + commits, + checkpoint_registry, + published_snapshots: Arc::new(Mutex::new(HashMap::new())), + }) + } + + pub fn published_snapshot(&self, sandbox_id: &str, generation: i64) -> Option { + self.published_snapshots + .lock() + .expect("not poisoned") + .get(&(sandbox_id.to_string(), generation)) + .cloned() + } + + fn require_node(&self) -> Result, LifecycleError> { + self.node + .get() + .cloned() + .ok_or_else(|| LifecycleError::Unavailable { + message: "node pipeline is not ready".into(), + lifecycle_state: None, + sandbox: None, + }) + } + + fn advance_activity_epoch(&self) -> Option { + self.heartbeat.as_ref().map(|hb| hb.advance_activity_epoch()) + } + + fn sandbox_of(reg: &Registration) -> Sandbox { + Sandbox { + sandbox_id: reg.sandbox_id().to_string(), + generation: reg.sandbox_generation as u64, + container_id: reg.container_id.clone(), + bundle: PathBuf::from(®.bundle), + memory_directory: reg.memory_directory.clone(), + spec_sha256: reg.spec_sha256(), + } + } + + fn artifact_generation_dir(node: &NodePipeline, reg: &Registration, hib_gen: u64) -> PathBuf { + node.config() + .volume_mount_root + .join(®.memory_directory) + .join("hibernation") + .join(hib_gen.to_string()) + } + + /// Build an in-process `Escalator` for `PauseRuntime` (no Python RPC). + pub fn escalator(self: &Arc) -> Arc { + Arc::new(InProcessEscalator { lifecycle: self.clone() }) + } + + /// Build an in-process `WakeHook` for `PauseRuntime` local model waits. + pub fn wake_hook(self: &Arc) -> WakeHook { + let lifecycle = self.clone(); + Arc::new(move |sandbox_id, generation, operation_id| { + let lifecycle = lifecycle.clone(); + Box::pin(async move { + lifecycle + .wake(&sandbox_id, generation as i64, &operation_id) + .await + .map(|_| ()) + .map_err(|err| format!("{err:?}")) + }) + }) + } + + async fn park_inner( + &self, + sandbox_id: &str, + operation_id: &str, + _background: bool, + ) -> Result<(StatusCode, Value), LifecycleError> { + let node = self.require_node()?; + let locks_dir = node.config().exec.warden_locks_dir.clone(); + let sid = sandbox_id.to_string(); + let _fence = tokio::task::spawn_blocking(move || ExecFence::new(locks_dir).acquire_transition(&sid)) + .await + .map_err(|e| unavailable(format!("park fence worker failed: {e}")))? + .map_err(|e| LifecycleError::Busy(format!("sandbox is busy: {e}")))?; + + let reg_store = node.registry().clone(); + let sid = sandbox_id.to_string(); + let reg = tokio::task::spawn_blocking(move || reg_store.get(&sid)) + .await + .map_err(|e| unavailable(format!("registry worker failed: {e}")))? + .map_err(|e| unavailable(e.to_string()))? + .ok_or_else(|| LifecycleError::NotFound(format!("sandbox {sandbox_id} not found")))?; + + if reg.phase != Phase::Owned { + return Err(LifecycleError::Conflict(format!("sandbox is in phase {}", reg.phase.as_str()))); + } + let sandbox = Self::sandbox_of(®); + let warden = node.warden().clone(); + let warden_lock = warden.lock(&sandbox).await.map_err(|e| unavailable(e.to_string()))?; + + let journal = warden.journal().clone(); + let sid = sandbox_id.to_string(); + let gen_u64 = sandbox.generation; + let current = tokio::task::spawn_blocking(move || journal.load(&sid, gen_u64)) + .await + .map_err(|e| unavailable(format!("journal worker failed: {e}")))? + .map_err(|e| unavailable(e.to_string()))? + .ok_or_else(|| LifecycleError::Conflict("sandbox has no lifecycle journal".into()))?; + + let state = current.get("state").and_then(Value::as_str).unwrap_or(""); + if state == "parked" { + let mut body = json!({ + "sandbox": sandbox_record_json(®, "parked"), + "node_epoch": node.config().node_epoch, + }); + if let Some(epoch) = self.advance_activity_epoch() { + body["activity_epoch"] = json!(epoch); + } + return Ok((StatusCode::OK, body)); + } + if state != "running" { + return Err(LifecycleError::Conflict(format!("cannot park sandbox in state {state}"))); + } + let revision = current.get("revision").and_then(Value::as_i64).unwrap_or(0); + let sentry_pid = current + .get("sentry_pid") + .and_then(Value::as_u64) + .ok_or_else(|| unavailable("running journal lacks sentry_pid"))? as u32; + let sentry_ticks = current + .get("sentry_start_time_ticks") + .and_then(Value::as_u64) + .ok_or_else(|| unavailable("running journal lacks sentry_start_time_ticks"))?; + + // Open verified pidfd fence before thawing or checkpointing. + let pidfd = warden + .open_sentry_fence(&sandbox, sentry_pid, sentry_ticks) + .await + .map_err(|e| unavailable(e.to_string()))?; + + // Thaw paused sandbox without prefetching pages into RAM. + node.pause_tier() + .thaw_locked(&sandbox, &warden_lock, false) + .await + .map_err(|e| unavailable(e.to_string()))?; + + // Begin hibernate in journal (running -> hibernating). + let journal = warden.journal().clone(); + let sid = sandbox_id.to_string(); + let op = operation_id.to_string(); + let hibernating = tokio::task::spawn_blocking(move || journal.begin_hibernate(&sid, gen_u64, &op, revision)) + .await + .map_err(|e| unavailable(format!("journal worker failed: {e}")))? + .map_err(|e| LifecycleError::Conflict(e.to_string()))?; + let hib_rev = hibernating.get("revision").and_then(Value::as_i64).unwrap_or(revision + 1); + let hib_gen = hibernating.get("hibernation_generation").and_then(Value::as_u64).unwrap_or(1); + + let gen_dir = Self::artifact_generation_dir(&node, ®, hib_gen); + let gen_dir_prep = gen_dir.clone(); + tokio::task::spawn_blocking(move || ensure_private_dir(&gen_dir_prep)) + .await + .map_err(|e| unavailable(format!("artifact dir worker failed: {e}")))? + .map_err(|e| unavailable(e.to_string()))?; + + let mode = node.memory_mode_for(®); + if let Err(err) = warden.checkpoint(&sandbox, mode, &gen_dir, CAPTURE_TIMEOUT).await { + let journal = warden.journal().clone(); + let sid = sandbox_id.to_string(); + let op = operation_id.to_string(); + let _ = tokio::task::spawn_blocking(move || journal.rollback_hibernate(&sid, gen_u64, &op, hib_rev)).await; + return Err(unavailable(format!("checkpoint failed: {err}"))); + } + + // Prepare storage capture if split-backed. + let owner = VolumeOwner { + volume_id: reg.workspace_volume_id(), + sandbox_id: sandbox_id.to_string(), + sandbox_generation: gen_u64, + }; + let storage_rev = if reg.memory_reference().is_some() { + let vol = node + .storage() + .get_volume(&owner.volume_id, Map::new()) + .await + .map_err(|e| unavailable(e.to_string()))?; + let rev = vol.get("revision").and_then(Value::as_i64).unwrap_or(0); + let prepared = node + .storage() + .prepare_capture(&owner, &format!("{operation_id}:workspace-prepare"), rev, Map::new()) + .await + .map_err(|e| unavailable(e.to_string()))?; + prepared.get("revision").and_then(Value::as_i64).unwrap_or(rev + 1) + } else { + 0 + }; + + // Write checkpoint manifest and atomic COMPLETE marker. + let manifest = json!({ + "version": 3, + "sandbox_id": sandbox_id, + "sandbox_generation": gen_u64, + "hibernation_generation": hib_gen, + "operation_id": operation_id, + "spec_sha256": reg.spec_sha256(), + "container_id": reg.container_id, + }); + let manifest_bytes = canonical_json(&manifest); + let manifest_sha256: String = Sha256::digest(&manifest_bytes).iter().map(|b| format!("{b:02x}")).collect(); + let gen_dir_write = gen_dir.clone(); + let m_bytes = manifest_bytes.clone(); + let m_sha = manifest_sha256.clone(); + tokio::task::spawn_blocking(move || -> std::io::Result<()> { + atomic_write(&gen_dir_write.join(MANIFEST_NAME), &m_bytes)?; + atomic_write(&gen_dir_write.join(COMPLETE_MARKER), format!("{m_sha}\n").as_bytes())?; + Ok(()) + }) + .await + .map_err(|e| unavailable(format!("manifest worker failed: {e}")))? + .map_err(|e| unavailable(e.to_string()))?; + + // COMPLETE is durable: terminate old sentry and reap runtime. + let stop_timeout = warden.config().stop_timeout; + tokio::task::spawn_blocking(move || pidfd.terminate(stop_timeout)) + .await + .map_err(|e| unavailable(format!("terminate worker failed: {e}")))? + .map_err(|e| unavailable(e.to_string()))?; + + let journal = warden.journal().clone(); + let sid = sandbox_id.to_string(); + let op = operation_id.to_string(); + let pending = tokio::task::spawn_blocking(move || journal.mark_sentry_reaped(&sid, gen_u64, &op, hib_rev)) + .await + .map_err(|e| unavailable(format!("journal worker failed: {e}")))? + .map_err(|e| unavailable(e.to_string()))?; + let pending_rev = pending.get("revision").and_then(Value::as_i64).unwrap_or(hib_rev + 1); + + warden + .delete_runtime(&sandbox, true) + .await + .map_err(|e| unavailable(e.to_string()))?; + + // Detach overlay, commit workspace capture, and release the volume. + node.overlays() + .park_sandbox(sandbox_id, gen_u64, &sandbox.bundle, ®.workspace_volume_id()) + .await + .map_err(|e| unavailable(e.to_string()))?; + if reg.memory_reference().is_some() { + node.storage() + .commit_capture(&owner, &format!("{operation_id}:workspace-commit"), storage_rev, Map::new()) + .await + .map_err(|e| unavailable(e.to_string()))?; + } + node.storage() + .ensure_released(&owner, &format!("{operation_id}:storage-release"), Map::new()) + .await + .map_err(|e| unavailable(e.to_string()))?; + + // Commit parked in journal. + let journal = warden.journal().clone(); + let sid = sandbox_id.to_string(); + let op = operation_id.to_string(); + let sha = manifest_sha256.clone(); + tokio::task::spawn_blocking(move || journal.commit_parked(&sid, gen_u64, &sha, &op, pending_rev)) + .await + .map_err(|e| unavailable(format!("journal worker failed: {e}")))? + .map_err(|e| unavailable(e.to_string()))?; + + drop(warden_lock); + + // Notify admission ledger of park transition. + if let Some(admission) = node.admission() { + let _ = admission + .transition(Step { + key: (sandbox_id.to_string(), gen_u64), + action: GrowthAction::Park, + request_id: String::new(), + job_id: String::new(), + launch_sha256: String::new(), + }) + .await; + } + + let mut body = json!({ + "sandbox": sandbox_record_json(®, "parked"), + "node_epoch": node.config().node_epoch, + }); + if let Some(epoch) = self.advance_activity_epoch() { + body["activity_epoch"] = json!(epoch); + } + Ok((StatusCode::OK, body)) + } + + async fn wake_inner( + &self, + sandbox_id: &str, + generation: i64, + operation_id: &str, + ) -> Result { + let node = self.require_node()?; + let locks_dir = node.config().exec.warden_locks_dir.clone(); + let sid = sandbox_id.to_string(); + let _fence = tokio::task::spawn_blocking(move || ExecFence::new(locks_dir).acquire_transition(&sid)) + .await + .map_err(|e| unavailable(format!("wake fence worker failed: {e}")))? + .map_err(|e| LifecycleError::Busy(format!("sandbox is busy: {e}")))?; + + let reg_store = node.registry().clone(); + let sid = sandbox_id.to_string(); + let reg = tokio::task::spawn_blocking(move || reg_store.get(&sid)) + .await + .map_err(|e| unavailable(format!("registry worker failed: {e}")))? + .map_err(|e| unavailable(e.to_string()))? + .ok_or_else(|| LifecycleError::NotFound(format!("sandbox {sandbox_id} not found")))?; + + if reg.sandbox_generation != generation { + return Err(LifecycleError::Conflict("wake generation does not own direct sandbox".into())); + } + let sandbox = Self::sandbox_of(®); + let warden = node.warden().clone(); + let _warden_lock = warden.lock(&sandbox).await.map_err(|e| unavailable(e.to_string()))?; + + let journal = warden.journal().clone(); + let sid = sandbox_id.to_string(); + let gen_u64 = generation as u64; + let current = tokio::task::spawn_blocking(move || journal.load(&sid, gen_u64)) + .await + .map_err(|e| unavailable(format!("journal worker failed: {e}")))? + .map_err(|e| unavailable(e.to_string()))? + .ok_or_else(|| LifecycleError::Conflict("sandbox has no lifecycle journal".into()))?; + + let state = current.get("state").and_then(Value::as_str).unwrap_or(""); + if state == "running" { + let mut body = json!({ + "sandbox": sandbox_record_json(®, "running"), + "node_epoch": node.config().node_epoch, + }); + if let Some(epoch) = self.advance_activity_epoch() { + body["activity_epoch"] = json!(epoch); + } + return Ok(body); + } + if state != "parked" { + return Err(LifecycleError::Conflict(format!("cannot wake sandbox in state {state}"))); + } + + let revision = current.get("revision").and_then(Value::as_i64).unwrap_or(0); + let hib_gen = current.get("hibernation_generation").and_then(Value::as_u64).unwrap_or(1); + let gen_dir = Self::artifact_generation_dir(&node, ®, hib_gen); + + let owner = VolumeOwner { + volume_id: reg.workspace_volume_id(), + sandbox_id: sandbox_id.to_string(), + sandbox_generation: gen_u64, + }; + node.storage() + .ensure_mounted(&owner, &format!("{operation_id}:storage-mount"), Map::new()) + .await + .map_err(|e| LifecycleError::RestoreBusy { + message: e.to_string(), + sandbox: Some(sandbox_record_json(®, "parked")), + })?; + let lower_rootfs = node + .images() + .lease(reg.spec.image(), reg.spec.environment_root()) + .await + .map(|lease| lease.image.rootfs) + .unwrap_or_else(|_| node.config().image_cache_root.join(®.image_id).join("rootfs")); + if let Err(err) = node + .overlays() + .resume_sandbox(sandbox_id, gen_u64, &sandbox.bundle, ®.workspace_volume_id(), &lower_rootfs) + .await + { + if reg.memory_reference().is_some() { + let _ = node + .storage() + .discard_resume(&owner, &format!("{operation_id}:rollback"), Map::new()) + .await; + } + return Err(unavailable(err.to_string())); + } + if let Err(err) = node.ensure_network_for(sandbox_id, gen_u64).await { + return Err(unavailable(err)); + } + + // Remove stale gVisor filestore left in the merged rootfs from the parked + // capture before invoking `runsc restore` (DirectWarden._remove_captured_filestore). + let filestore_path = sandbox + .bundle + .join("rootfs") + .join(format!(".gvisor.filestore.{}", sandbox.container_id)); + let filestore_remove = tokio::task::spawn_blocking(move || remove_captured_filestore(&filestore_path)) + .await + .map_err(|e| unavailable(format!("filestore cleanup worker failed: {e}")))?; + if let Err(err) = filestore_remove { + let _ = node + .overlays() + .park_sandbox(sandbox_id, gen_u64, &sandbox.bundle, ®.workspace_volume_id()) + .await; + let _ = node + .storage() + .discard_resume(&owner, &format!("{operation_id}:rollback"), Map::new()) + .await; + return Err(unavailable(err)); + } + + let journal = warden.journal().clone(); + let sid = sandbox_id.to_string(); + let op = operation_id.to_string(); + let restoring = tokio::task::spawn_blocking(move || journal.begin_restore(&sid, gen_u64, &op, revision)) + .await + .map_err(|e| unavailable(format!("journal worker failed: {e}")))? + .map_err(|e| LifecycleError::Conflict(e.to_string()))?; + let restore_rev = restoring.get("revision").and_then(Value::as_i64).unwrap_or(revision + 1); + + let mode = node.memory_mode_for(®); + let (pid, ticks) = match warden.restore_paused(&sandbox, mode, &gen_dir, CAPTURE_TIMEOUT).await { + Ok(pair) => pair, + Err(err) => { + let _ = warden.delete_runtime(&sandbox, true).await; + let _ = node + .overlays() + .park_sandbox(sandbox_id, gen_u64, &sandbox.bundle, ®.workspace_volume_id()) + .await; + let _ = node + .storage() + .discard_resume(&owner, &format!("{operation_id}:rollback"), Map::new()) + .await; + let journal = warden.journal().clone(); + let sid = sandbox_id.to_string(); + let op = operation_id.to_string(); + let _ = tokio::task::spawn_blocking(move || journal.rollback_restore(&sid, gen_u64, &op, restore_rev)).await; + return Err(unavailable(format!("restore failed: {err}"))); + } + }; + + let journal = warden.journal().clone(); + let sid = sandbox_id.to_string(); + let op = operation_id.to_string(); + let candidate = tokio::task::spawn_blocking(move || { + journal.mark_candidate(&sid, gen_u64, &op, restore_rev, pid as u64, ticks) + }) + .await + .map_err(|e| unavailable(format!("journal worker failed: {e}")))? + .map_err(|e| unavailable(e.to_string()))?; + let cand_rev = candidate.get("revision").and_then(Value::as_i64).unwrap_or(restore_rev + 1); + + if let Err(err) = warden.resume_and_verify(&sandbox, pid, ticks).await { + let _ = warden.delete_runtime(&sandbox, true).await; + let _ = node + .overlays() + .park_sandbox(sandbox_id, gen_u64, &sandbox.bundle, ®.workspace_volume_id()) + .await; + let _ = node + .storage() + .discard_resume(&owner, &format!("{operation_id}:rollback"), Map::new()) + .await; + let journal = warden.journal().clone(); + let sid = sandbox_id.to_string(); + let op = operation_id.to_string(); + let _ = tokio::task::spawn_blocking(move || journal.rollback_restore(&sid, gen_u64, &op, cand_rev)).await; + return Err(unavailable(format!("resume verification failed: {err}"))); + } + + let journal = warden.journal().clone(); + let sid = sandbox_id.to_string(); + let op = operation_id.to_string(); + tokio::task::spawn_blocking(move || { + journal.commit_running(&sid, gen_u64, &op, cand_rev, pid as u64, ticks) + }) + .await + .map_err(|e| unavailable(format!("journal worker failed: {e}")))? + .map_err(|e| unavailable(e.to_string()))?; + + if let Some(admission) = node.admission() { + let _ = admission + .transition(Step { + key: (sandbox_id.to_string(), gen_u64), + action: GrowthAction::Activate, + request_id: String::new(), + job_id: String::new(), + launch_sha256: String::new(), + }) + .await; + } + + let mut body = json!({ + "sandbox": sandbox_record_json(®, "running"), + "node_epoch": node.config().node_epoch, + }); + if let Some(epoch) = self.advance_activity_epoch() { + body["activity_epoch"] = json!(epoch); + } + Ok(body) + } +} + +impl LifecycleNode for NodeLifecycle { + fn ssh(&self, sandbox_id: &str) -> BoxFuture> { + let this = self.clone(); + let sid = sandbox_id.to_string(); + Box::pin(async move { + let node = this.require_node()?; + let reg_store = node.registry().clone(); + let exists = tokio::task::spawn_blocking(move || reg_store.get(&sid)) + .await + .map_err(|e| unavailable(format!("registry worker failed: {e}")))? + .map_err(|e| unavailable(e.to_string()))?; + if exists.is_none() { + return Err(LifecycleError::NotFound("sandbox not found".into())); + } + Err(LifecycleError::Conflict("direct runsc sandboxes do not expose ssh access".into())) + }) + } + + fn park( + &self, + sandbox_id: &str, + operation_id: &str, + background: bool, + ) -> BoxFuture> { + let this = self.clone(); + let sid = sandbox_id.to_string(); + let op = operation_id.to_string(); + Box::pin(async move { this.park_inner(&sid, &op, background).await }) + } + + fn wake(&self, sandbox_id: &str, generation: i64, operation_id: &str) -> BoxFuture> { + let this = self.clone(); + let sid = sandbox_id.to_string(); + let op = operation_id.to_string(); + Box::pin(async move { this.wake_inner(&sid, generation, &op).await }) + } + + fn request_snapshot_publication(&self, sandbox_id: &str, generation: i64) -> BoxFuture> { + let this = self.clone(); + let sid = sandbox_id.to_string(); + Box::pin(async move { + let node = this.require_node()?; + let reg_store = node.registry().clone(); + let sid_q = sid.clone(); + let reg = tokio::task::spawn_blocking(move || reg_store.get(&sid_q)) + .await + .map_err(|e| unavailable(e.to_string()))? + .map_err(|e| unavailable(e.to_string()))? + .ok_or_else(|| LifecycleError::NotFound(format!("sandbox {sid} not found")))?; + if reg.sandbox_generation != generation { + return Err(LifecycleError::Conflict("publication generation does not own sandbox".into())); + } + let owner = VolumeOwner { + volume_id: reg.workspace_volume_id(), + sandbox_id: sid.clone(), + sandbox_generation: generation as u64, + }; + let published = node + .storage() + .ensure_published(&owner, &format!("publish:{sid}:{generation}"), None, Map::new()) + .await + .map_err(|e| LifecycleError::SnapshotPublicationPending(e.to_string()))?; + let snapshot_val = Value::Object(published); + this.published_snapshots + .lock() + .expect("not poisoned") + .insert((sid.clone(), generation), snapshot_val.clone()); + Ok(json!({ + "sandbox_id": sid, + "generation": generation, + "published": snapshot_val, + })) + }) + } + + fn publish_parked( + &self, + sandbox_id: &str, + generation: i64, + create_operation_id: &str, + spec_hash: &str, + ) -> BoxFuture> { + let this = self.clone(); + let sid = sandbox_id.to_string(); + let create_op = create_operation_id.to_string(); + let spec_hash = spec_hash.to_string(); + Box::pin(async move { + let node = this.require_node()?; + let reg_store = node.registry().clone(); + let sid_q = sid.clone(); + let reg = tokio::task::spawn_blocking(move || reg_store.get(&sid_q)) + .await + .map_err(|e| unavailable(e.to_string()))? + .map_err(|e| unavailable(e.to_string()))? + .ok_or_else(|| LifecycleError::NotFound(format!("sandbox {sid} not found")))?; + if reg.sandbox_generation != generation || reg.spec_sha256() != spec_hash { + return Err(LifecycleError::Conflict("parked sandbox identity mismatch".into())); + } + let owner = VolumeOwner { + volume_id: reg.workspace_volume_id(), + sandbox_id: sid.clone(), + sandbox_generation: generation as u64, + }; + let published = node + .storage() + .ensure_published(&owner, &format!("publish-parked:{create_op}"), None, Map::new()) + .await + .map_err(|e| LifecycleError::SnapshotPublicationPending(e.to_string()))?; + let digest = published + .get("published_manifest_digest") + .and_then(Value::as_str) + .unwrap_or("") + .to_string(); + let snapshot_val = Value::Object(published); + this.published_snapshots + .lock() + .expect("not poisoned") + .insert((sid.clone(), generation), snapshot_val.clone()); + Ok(json!({ + "sandbox": sandbox_record_json(®, "parked"), + "node_epoch": node.config().node_epoch, + "snapshot_manifest_digest": digest, + "published": snapshot_val, + })) + }) + } + + fn evict_published(&self, sandbox_id: &str, generation: i64, _digest: &str) -> BoxFuture> { + let this = self.clone(); + let sid = sandbox_id.to_string(); + Box::pin(async move { + let node = this.require_node()?; + this.published_snapshots + .lock() + .expect("not poisoned") + .remove(&(sid.clone(), generation)); + node.delete_sandbox(&sid, generation) + .await + .map(|_| ()) + .map_err(|e| unavailable(format!("{e:?}"))) + }) + } + + fn commit_export(&self, sandbox_id: &str, raw: Value) -> BoxFuture> { + let this = self.clone(); + let sid = sandbox_id.to_string(); + Box::pin(async move { + let node = this.require_node()?; + let commits = this.commits.clone(); + let node_for_hook = node.clone(); + let exporter: crate::commit_export::ExportHook = Arc::new(move |sb_id, generation, tar_path, _resume| { + let reg = node_for_hook + .registry() + .get(sb_id) + .map_err(|e| CommitRefused::new("commit_export_failed", e.to_string(), StatusCode::SERVICE_UNAVAILABLE, true))? + .ok_or_else(|| CommitRefused::new("sandbox_not_found", "sandbox not found", StatusCode::NOT_FOUND, false))?; + if reg.sandbox_generation != generation { + return Err(CommitRefused::new( + "commit_generation_mismatch", + "sandbox generation changed", + StatusCode::CONFLICT, + false, + )); + } + let sandbox = Self::sandbox_of(®); + let was_paused = node_for_hook.pause_tier().is_paused(sb_id, generation as u64); + let handle = tokio::runtime::Handle::current(); + let tar_dest = tar_path.to_path_buf(); + let size = handle + .block_on(async { + let _lock = node_for_hook.warden().lock(&sandbox).await?; + node_for_hook.warden().tar_rootfs_upper(&sandbox, &tar_dest).await + }) + .map_err(|e| CommitRefused::new("commit_export_failed", e.to_string(), StatusCode::SERVICE_UNAVAILABLE, true))?; + Ok((was_paused, vec![reg.spec.image().to_string(), reg.rootfs_sha256.clone()], size)) + }); + let result = tokio::task::spawn_blocking(move || commits.request(&sid, &raw, exporter)) + .await + .map_err(|e| unavailable(format!("commit export worker failed: {e}")))?; + result.map_err(LifecycleError::CommitRefused) + }) + } + + fn prepare_migration( + &self, + sandbox_id: &str, + migration_id: &str, + format: &str, + ) -> BoxFuture> { + let this = self.clone(); + let sid = sandbox_id.to_string(); + let mid = migration_id.to_string(); + let fmt = format.to_string(); + Box::pin(async move { + let node = this.require_node()?; + let reg_store = node.registry().clone(); + let sid_q = sid.clone(); + let reg = tokio::task::spawn_blocking(move || reg_store.get(&sid_q)) + .await + .map_err(|e| unavailable(e.to_string()))? + .map_err(|e| unavailable(e.to_string()))? + .ok_or_else(|| LifecycleError::NotFound(format!("sandbox {sid} not found")))?; + let owner = VolumeOwner { + volume_id: reg.workspace_volume_id(), + sandbox_id: sid.clone(), + sandbox_generation: reg.sandbox_generation as u64, + }; + let published = node + .storage() + .ensure_published(&owner, &format!("migration-prepare:{mid}"), None, Map::new()) + .await + .map_err(|e| unavailable(e.to_string()))?; + let snapshot_val = Value::Object(published); + let digest: String = Sha256::digest(canonical_json(&snapshot_val)) + .iter() + .map(|b| format!("{b:02x}")) + .collect(); + Ok(json!({ + "migration_id": mid, + "format": fmt, + "sandbox_id": sid, + "sandbox_generation": reg.sandbox_generation, + "snapshot_sha256": digest, + "snapshot": snapshot_val, + "checkpoint_registry_repository": this.checkpoint_registry.as_ref().map(|(_, repo)| repo.as_str()).unwrap_or(""), + })) + }) + } + + fn import_migration(&self, raw: Value) -> BoxFuture> { + let this = self.clone(); + Box::pin(async move { + let node = this.require_node()?; + let obj = raw + .as_object() + .ok_or_else(|| LifecycleError::BadRequest("migration import payload must be a JSON object".into()))?; + let sid = obj + .get("sandbox_id") + .and_then(Value::as_str) + .ok_or_else(|| LifecycleError::BadRequest("sandbox_id is required".into()))?; + let generation = obj + .get("sandbox_generation") + .and_then(Value::as_u64) + .filter(|&g| g >= 1) + .ok_or_else(|| LifecycleError::BadRequest("sandbox_generation must be positive".into()))?; + let mid = obj + .get("migration_id") + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) + .ok_or_else(|| LifecycleError::BadRequest("migration_id is required".into()))?; + let snapshot = obj + .get("snapshot") + .cloned() + .ok_or_else(|| LifecycleError::BadRequest("snapshot is required".into()))?; + let volume_id = obj + .get("volume_id") + .and_then(Value::as_str) + .map(str::to_string) + .unwrap_or_else(|| format!("workspace-{sid}.sandbox-{generation}")); + let owner = VolumeOwner { + volume_id, + sandbox_id: sid.to_string(), + sandbox_generation: generation, + }; + let imported = node + .storage() + .prepare_import(&owner, &format!("migration-import:{mid}"), snapshot, None, Map::new()) + .await + .map_err(|e| unavailable(e.to_string()))?; + Ok(json!({ + "sandbox_id": sid, + "sandbox_generation": generation, + "migration_id": mid, + "imported": imported, + })) + }) + } + + fn complete_migration( + &self, + sandbox_id: &str, + action: &str, + migration_id: &str, + _snapshot_sha256: &str, + ) -> BoxFuture> { + let this = self.clone(); + let sid = sandbox_id.to_string(); + let action = action.to_string(); + let mid = migration_id.to_string(); + Box::pin(async move { + let node = this.require_node()?; + let reg_store = node.registry().clone(); + let sid_q = sid.clone(); + let reg = tokio::task::spawn_blocking(move || reg_store.get(&sid_q)) + .await + .map_err(|e| unavailable(e.to_string()))? + .map_err(|e| unavailable(e.to_string()))?; + match action.as_str() { + "activate" => { + let reg = reg.ok_or_else(|| LifecycleError::NotFound(format!("sandbox {sid} not found")))?; + this.wake_inner(&sid, reg.sandbox_generation, &format!("migration-activate:{mid}")).await + } + "finalize" | "abort-import" => { + if let Some(reg) = reg { + node.delete_sandbox(&sid, reg.sandbox_generation) + .await + .map_err(|e| unavailable(format!("{e:?}")))?; + } + Ok(json!({"ok": true, "sandbox_id": sid, "action": action, "migration_id": mid})) + } + "abort" => Ok(json!({"ok": true, "sandbox_id": sid, "action": "abort", "migration_id": mid})), + other => Err(LifecycleError::BadRequest(format!("unknown migration action {other}"))), + } + }) + } +} + +struct InProcessEscalator { + lifecycle: Arc, +} + +impl Escalator for InProcessEscalator { + fn escalate(&self, sandbox: &Sandbox) -> crate::pause_policy::BoxFuture> { + let lifecycle = self.lifecycle.clone(); + let sid = sandbox.sandbox_id.clone(); + let op = format!("escalate:{}:{}", sandbox.sandbox_id, sandbox.generation); + Box::pin(async move { + match lifecycle.park(&sid, &op, false).await { + Ok((_, body)) => { + let state = body + .pointer("/sandbox/lifecycle_state") + .and_then(Value::as_str) + .unwrap_or("parked"); + if state == "running" { + Ok(Escalated::Running) + } else { + Ok(Escalated::Parked) + } + } + Err(err) => Err(format!("in-process park escalation failed: {err:?}")), + } + }) + } +} + +fn remove_captured_filestore(path: &std::path::Path) -> Result<(), String> { + use std::os::unix::fs::MetadataExt; + let meta = match std::fs::symlink_metadata(path) { + Ok(m) => m, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(e) => return Err(format!("could not stat captured filestore: {e}")), + }; + if !meta.file_type().is_file() || meta.uid() != crate::fsutil::euid() { + return Err("captured runtime filestore is not an owned regular file".into()); + } + std::fs::remove_file(path).map_err(|e| format!("could not unlink captured filestore: {e}"))?; + if let Some(parent) = path.parent() { + crate::fsutil::fsync_dir(parent).map_err(|e| format!("could not fsync rootfs after filestore unlink: {e}"))?; + } + Ok(()) +} + +fn unavailable(message: impl Into) -> LifecycleError { + LifecycleError::Unavailable { + message: message.into(), + lifecycle_state: None, + sandbox: None, + } +} diff --git a/runtime/noded/src/node_pipeline.rs b/runtime/noded/src/node_pipeline.rs index e2e179ef..9fefd180 100644 --- a/runtime/noded/src/node_pipeline.rs +++ b/runtime/noded/src/node_pipeline.rs @@ -106,6 +106,14 @@ fn unavailable(message: impl Into) -> CreateError { CreateError::Unavailable(message.into()) } +#[derive(Debug)] +pub enum DeleteError { + Invalid(String), + Conflict(String), + Busy(String), + Failed(String), +} + /// Run blocking work (SQLite, flocks, netlink) off the reactor. async fn blocking( work: impl FnOnce() -> Result + Send + 'static, @@ -119,24 +127,45 @@ pub struct NodePipeline { pause: Arc, /// The pause policy and local waits, while the daemon owns the pause tier. pause_runtime: crate::pause_runtime::PauseRuntime, - /// The node's own admission (`--rust-admission`, step 3c.2). + /// The node's own admission (`--rust-admission`, step 3c.2; mandatory in standalone). admission: Option>, config: CreateConfig, - agent: Arc, + agent: Option>, + resolver: Option>, registry: Arc, memory: Option>, storage: StorageClient, network: Option>, - images: ImageStore, + images: Arc, overlays: OverlayManager, oci: OciBuilder, warden: Arc, } impl NodePipeline { - /// Open everything the node's configuration names. The daemon becomes the - /// registry owner here; the agent writes as a foreign process. + /// Open everything the node's configuration names behind a Python agent. pub fn open(config: CreateConfig, agent: Arc) -> Result { + Self::open_inner(config, Some(agent), None, None, None) + } + + /// Open the full sandbox worker pipeline in standalone Rust mode (no Python agent). + pub fn open_standalone( + mut config: CreateConfig, + resolver: Option>, + escalator: Option>, + wake_hook: Option, + ) -> Result { + config.admission.rust_admission_enabled = true; + Self::open_inner(config, None, resolver, escalator, wake_hook) + } + + fn open_inner( + config: CreateConfig, + agent: Option>, + resolver: Option>, + escalator: Option>, + wake_hook: Option, + ) -> Result { let environment = config.environment.clone().ok_or("no environment image store")?; let hard_capacity_mb = if config.split_memory_backing { (config.memory_backing_hard_capacity_bytes / MIB as u64) as i64 @@ -212,7 +241,6 @@ impl NodePipeline { memory_root: config.volume_mount_root.clone(), application_memory_root: config.application_memory_root.clone(), network: config.network.clone(), - reflink_memory_restore: config.reflink_memory_restore, proc_root: PathBuf::from("/proc"), command_timeout: Duration::from_secs(60), stop_timeout: Duration::from_secs(30), @@ -249,12 +277,19 @@ impl NodePipeline { Some((AdmissionService::open(service_config, drain.admission_open, sources)?, observations)) } }; + let session = agent + .as_ref() + .map(|a| a.session().to_string()) + .unwrap_or_else(|| "standalone".to_string()); // Phase 3b: with --rust-admission and the agent's say-so (the // `admission` block), sample managed sandboxes and publish them. let pause_runtime = crate::pause_runtime::PauseRuntime::start(crate::pause_runtime::PauseInputs { resident_sampling: config.admission.rust_admission_enabled, admission: admission.as_ref().map(|(service, _)| service.clone()), + session, agent: agent.clone(), + escalator, + wake_hook, tier: pause.clone(), registry: registry.clone(), state_root: config.state_root.clone(), @@ -266,7 +301,12 @@ impl NodePipeline { if let Some(sampler) = pause_runtime.sampler() { observations.set_sampler(sampler); } - service.start_recovery(Some(Arc::new(AgentSocketProbe(agent.socket().to_path_buf())))); + if let Some(agent_client) = &agent { + service.start_recovery(Some(Arc::new(AgentSocketProbe(agent_client.socket().to_path_buf())))); + } else { + // Standalone Rust mode: no Python agent to wait on; end recovery immediately. + service.hello("standalone", Vec::new()); + } service }); // Last, once nothing can fail: a failed open is retried, and a pool @@ -283,10 +323,11 @@ impl NodePipeline { storage: StorageClient::new(&config.storage_native_socket), config, agent, + resolver, registry, memory, network, - images, + images: Arc::new(images), overlays, oci, warden: Arc::new(warden), @@ -305,6 +346,51 @@ impl NodePipeline { &self.warden } + pub fn storage(&self) -> &StorageClient { + &self.storage + } + + pub fn overlays(&self) -> &OverlayManager { + &self.overlays + } + + pub fn memory(&self) -> Option<&Arc> { + self.memory.as_ref() + } + + pub fn network(&self) -> Option<&Arc> { + self.network.as_ref() + } + + pub fn images(&self) -> &Arc { + &self.images + } + + pub async fn ensure_network_for(&self, sandbox_id: &str, generation: u64) -> Result, String> { + let Some(network) = self.network.clone() else { + return Ok(None); + }; + let sid = sandbox_id.to_string(); + let lease = tokio::task::spawn_blocking(move || network.ensure_direct(&sid, generation)) + .await + .map_err(|e| format!("network worker failed: {e}"))? + .map_err(|e| e.to_string())?; + Ok(Some(lease.namespace_path)) + } + + pub fn memory_mode_for(&self, registration: &Registration) -> MemoryMode { + let recorded = self + .memory + .as_ref() + .and_then(|memory| memory.active_mode(registration.sandbox_id(), registration.sandbox_generation as u64)); + match recorded { + Some(ActiveMode::Ram) => MemoryMode::Ram, + Some(ActiveMode::File) => MemoryMode::File, + None if self.config.application_memory_root.is_some() => MemoryMode::Ram, + None => MemoryMode::File, + } + } + /// Stop the daemon's loops (the pause tier, the network pool) before the process exits. pub async fn shutdown(&self) { self.pause_runtime.stop().await; @@ -323,6 +409,192 @@ impl NodePipeline { self.admission.as_ref() } + /// Port of `DirectSandboxService.delete` + `DirectSandboxProvisioner.delete`: + /// acquire the exclusive transition fence, transition to `deleting`, tear + /// down warden/overlay/network/storage/memory, commit deleted, cancel + /// admission, and discard the fence files. + pub async fn delete_sandbox(&self, sandbox_id: &str, generation: i64) -> Result, DeleteError> { + if generation <= 0 { + return Err(DeleteError::Invalid("delete generation must be positive".into())); + } + let reg_store = self.registry.clone(); + let sid = sandbox_id.to_string(); + let initial = tokio::task::spawn_blocking(move || reg_store.get(&sid)) + .await + .map_err(|e| DeleteError::Failed(format!("delete worker failed: {e}")))? + .map_err(|e| DeleteError::Failed(e.to_string()))?; + let Some(initial) = initial else { + return Ok(None); + }; + if initial.sandbox_generation != generation { + return Err(DeleteError::Conflict("delete generation does not own direct sandbox".into())); + } + + // Snapshot pre-delete record for the response body. + let pre_state = if initial.phase == Phase::Owned { + let warden = self.warden.clone(); + let sid = sandbox_id.to_string(); + tokio::task::spawn_blocking(move || { + warden + .journal() + .load(&sid, generation as u64) + .ok() + .flatten() + .and_then(|j| j.get("state").and_then(Value::as_str).map(str::to_string)) + .unwrap_or_else(|| "unavailable".to_string()) + }) + .await + .unwrap_or_else(|_| "unavailable".to_string()) + } else { + initial.phase.as_str().to_string() + }; + let deleted_record = crate::sandbox_record::sandbox_record_json(&initial, &pre_state); + + // Acquire exclusive T fence (tolerates running execs holding A). + let locks_dir = self.config.exec.warden_locks_dir.clone(); + let sid = sandbox_id.to_string(); + let transition_guard = tokio::task::spawn_blocking(move || { + crate::exec_fence::ExecFence::new(locks_dir).acquire_transition(&sid) + }) + .await + .map_err(|e| DeleteError::Failed(format!("fence worker failed: {e}")))? + .map_err(|e| DeleteError::Failed(format!("cannot acquire delete fence: {e}")))?; + + // Re-read under fence and enter `deleting` phase if not already there. + let reg_store = self.registry.clone(); + let sid = sandbox_id.to_string(); + let deleting = tokio::task::spawn_blocking(move || { + let Some(reg) = reg_store.get(&sid).map_err(|e| DeleteError::Failed(e.to_string()))? else { + return Ok(None); + }; + if reg.sandbox_generation != generation { + return Err(DeleteError::Conflict("delete generation does not own direct sandbox".into())); + } + if reg.phase != Phase::Deleting { + if !reg.migration_id.is_empty() && reg.phase != Phase::Owned { + return Err(DeleteError::Failed( + "migration registration requires its fenced deletion path".into(), + )); + } + let updated = reg_store + .begin_delete(&sid, reg.revision, Some(generation)) + .map_err(|e| DeleteError::Failed(e.to_string()))?; + if updated.phase != Phase::Deleting { + return Err(DeleteError::Failed("direct sandbox could not enter deletion".into())); + } + return Ok(Some(updated)); + } + Ok(Some(reg)) + }) + .await + .map_err(|e| DeleteError::Failed(format!("delete registry worker failed: {e}")))??; + + let Some(reg) = deleting else { + transition_guard.discard(); + return Ok(None); + }; + + // 1. Warden + overlay teardown. + if reg.has_direct_sandbox() { + let sandbox = Sandbox { + sandbox_id: reg.sandbox_id().to_string(), + generation: generation as u64, + container_id: reg.container_id.clone(), + bundle: PathBuf::from(®.bundle), + memory_directory: reg.memory_directory.clone(), + spec_sha256: reg.spec_sha256(), + }; + self.warden + .delete(&sandbox) + .await + .map_err(|e| DeleteError::Failed(e.to_string()))?; + self.overlays + .release_sandbox(sandbox_id, generation as u64, &sandbox.bundle, ®.workspace_volume_id()) + .await + .map_err(|e| DeleteError::Failed(e.to_string()))?; + } else { + self.overlays + .discard_unregistered(sandbox_id, generation as u64, ®.workspace_directory) + .await + .map_err(|e| DeleteError::Failed(e.to_string()))?; + } + + // 2. Network teardown. + if let Some(network) = self.network.clone() { + let sid = sandbox_id.to_string(); + tokio::task::spawn_blocking(move || network.release(&sid, generation as u64)) + .await + .map_err(|e| DeleteError::Failed(format!("network release worker failed: {e}")))? + .map_err(|e| DeleteError::Failed(e.to_string()))?; + } + + // 3. Storage volume teardown. + let volume_id = reg.workspace_volume_id(); + let owner = VolumeOwner { + sandbox_id: sandbox_id.to_string(), + sandbox_generation: generation as u64, + volume_id: volume_id.clone(), + }; + match self.storage.get_volume(&volume_id, Map::new()).await { + Ok(vol_record) => { + let accounting_id = vol_record + .get("accounting_id") + .and_then(Value::as_i64) + .ok_or_else(|| DeleteError::Failed("storage volume record lacks accounting_id".into()))?; + let mut delete_op_id = format!("quota-delete:{accounting_id}"); + if !reg.migration_id.is_empty() { + delete_op_id.push(':'); + delete_op_id.push_str(®.migration_id); + } + let expected_virtual = reg.spec.disk_mb().map(|mb| (mb as u64) * (MIB as u64)); + self.storage + .delete_volume(&owner, &delete_op_id, reg.quota_project_id, expected_virtual, Map::new()) + .await + .map_err(|e| DeleteError::Failed(e.to_string()))?; + } + Err(StorageError::Conflict(_)) if reg.quota_project_id.is_none() => {} + Err(StorageError::Conflict(_)) => { + return Err(DeleteError::Failed("storage-native quota owner is absent".into())); + } + Err(e) => return Err(DeleteError::Failed(e.to_string())), + } + + // 4. Split memory backing teardown. + if let Some((alloc_id, quota_bytes)) = reg.memory_reference().filter(|(_, q)| *q > 0) { + let memory = self + .memory + .clone() + .ok_or_else(|| DeleteError::Failed("split memory allocator is unavailable".into()))?; + let reference = MemoryBackingRef::new(alloc_id, quota_bytes as u64) + .map_err(|e| DeleteError::Failed(e.to_string()))?; + let sid = sandbox_id.to_string(); + let result = tokio::task::spawn_blocking(move || memory.delete(&reference, &sid, generation as u64)) + .await + .map_err(|e| DeleteError::Failed(format!("memory delete worker failed: {e}")))?; + match result { + Ok(()) => {} + Err(MemoryBackingError::Busy(msg)) => return Err(DeleteError::Busy(msg)), + Err(e) => return Err(DeleteError::Failed(e.to_string())), + } + } + + // 5. Commit durable deletion in registry. + let reg_store = self.registry.clone(); + let sid = sandbox_id.to_string(); + let rev = reg.revision; + tokio::task::spawn_blocking(move || reg_store.commit_deleted(&sid, generation, rev)) + .await + .map_err(|e| DeleteError::Failed(format!("commit deleted worker failed: {e}")))? + .map_err(|e| DeleteError::Failed(e.to_string()))?; + + // 6. Release admission ledger claims and discard exec fence files. + if let Some(admission) = &self.admission { + admission.cancel(&(sandbox_id.to_string(), generation as u64)); + } + transition_guard.discard(); + Ok(Some(deleted_record)) + } + /// S2.2: a warm lease from the store's receipts, else the agent mounts /// the image once and hands over its resolution. async fn lease_image(&self, image: &str, root: Option<&str>, timings: &mut Timings) -> Result { @@ -349,10 +621,22 @@ impl NodePipeline { Err(ImageError::NotMaterialized(_) | ImageError::MutableReference(_)) => {} Err(error) => return Err(error.into()), } + // Standalone mode: materialize directly via pure-Rust EnvironmentResolver + ImageStore. + if let Some(resolver) = &self.resolver { + let started = timings.start(); + let resolution = self.images.materialize(resolver, image, root).await?; + timings.add("image_materialize", started); + let started = timings.start(); + let lease = self.images.lease_resolved(image, root, &resolution).await?; + timings.add("image_lease", started); + return Ok(lease); + } + let Some(agent) = &self.agent else { + return Err(unavailable("image materialization requires an environment resolver")); + }; let started = timings.start(); let request = json!({"image": image, "environment_root": root}); - let reply = self - .agent + let reply = agent // A cold materialization pulls the image: the gateway's create budget. .call_within(Duration::from_secs(600), Method::POST, "/internal/v1/images/materialize", Some(&request)) .await diff --git a/runtime/noded/src/pause/tests.rs b/runtime/noded/src/pause/tests.rs index fc7d51cb..1da6bdd4 100644 --- a/runtime/noded/src/pause/tests.rs +++ b/runtime/noded/src/pause/tests.rs @@ -142,7 +142,6 @@ impl Fake { memory_root: root.join("memory"), application_memory_root, network: "none".into(), - reflink_memory_restore: false, proc_root: root.join("proc"), command_timeout: Duration::from_secs(10), stop_timeout: Duration::from_secs(1), diff --git a/runtime/noded/src/pause_policy/tests.rs b/runtime/noded/src/pause_policy/tests.rs index 20262f39..fc6abe80 100644 --- a/runtime/noded/src/pause_policy/tests.rs +++ b/runtime/noded/src/pause_policy/tests.rs @@ -884,7 +884,6 @@ fn the_real_pause_tier_pauses_an_idle_sandbox() { memory_root: root.join("memory"), application_memory_root: None, network: "none".into(), - reflink_memory_restore: false, proc_root: root.join("proc"), command_timeout: Duration::from_secs(10), stop_timeout: Duration::from_secs(1), diff --git a/runtime/noded/src/pause_runtime.rs b/runtime/noded/src/pause_runtime.rs index 12a55b81..f43a483d 100644 --- a/runtime/noded/src/pause_runtime.rs +++ b/runtime/noded/src/pause_runtime.rs @@ -48,7 +48,8 @@ impl Escalator for AgentEscalator { /// Growth events go to the agent in batches, off the pause and thaw paths. struct AgentEvents { - agent: Arc, + agent: Option>, + wake_hook: Option crate::local_wait::BoxFuture> + Send + Sync>>, growth: mpsc::UnboundedSender, /// Weak: the policy holds local waits (through `answered`), which hold these events. policy: Arc>>, @@ -60,7 +61,12 @@ impl LocalWaitEvents for AgentEvents { } fn wake(&self, sandbox_id: String, generation: u64, operation_id: String) -> crate::local_wait::BoxFuture> { - let agent = self.agent.clone(); + if let Some(hook) = &self.wake_hook { + return hook(sandbox_id, generation, operation_id); + } + let Some(agent) = self.agent.clone() else { + return Box::pin(async { Err("no wake backend configured".into()) }); + }; Box::pin(async move { let body = json!({"generation": generation, "operation_id": operation_id}); let path = format!("/v1/sandboxes/{sandbox_id}/wake"); @@ -108,8 +114,14 @@ pub struct PauseRuntime { waits: Mutex>>, } +pub type WakeHook = + Arc crate::local_wait::BoxFuture> + Send + Sync>; + pub struct PauseInputs { - pub agent: Arc, + pub agent: Option>, + pub session: String, + pub escalator: Option>, + pub wake_hook: Option, pub tier: Arc, pub registry: Arc, pub state_root: PathBuf, @@ -126,13 +138,34 @@ pub struct PauseInputs { pub admission: Option>, } +struct NoopEscalator; + +impl Escalator for NoopEscalator { + fn escalate(&self, _sandbox: &Sandbox) -> BoxFuture> { + Box::pin(async { Err("no park escalator configured".into()) }) + } +} + impl PauseRuntime { /// Start inside the tokio runtime. Local waits fail closed: without them /// the policy still runs and nothing pauses on model calls. pub fn start(inputs: PauseInputs) -> PauseRuntime { - let PauseInputs { agent, tier, registry, state_root, warden_locks_dir, cgroup_root, settings, resident_sampling, admission } = inputs; + let PauseInputs { + agent, + session, + escalator, + wake_hook, + tier, + registry, + state_root, + warden_locks_dir, + cgroup_root, + settings, + resident_sampling, + admission, + } = inputs; let idle = settings.get("idle_park_seconds").and_then(Value::as_f64).unwrap_or(0.0); - let mut config = PolicyConfig::new(state_root.clone(), agent.session().to_string(), idle, tier.config()); + let mut config = PolicyConfig::new(state_root.clone(), session, idle, tier.config()); config.resident_sampling = resident_sampling; let demand = admission.as_ref().map(|service| { let inventory = registry.clone(); @@ -142,12 +175,17 @@ impl PauseRuntime { admission_open: Box::new(move || Inventory::admission_open(&*inventory).unwrap_or(false)), }) as Arc }); + let escalator: Arc = match (escalator, agent.as_ref()) { + (Some(custom), _) => custom, + (None, Some(agent)) => Arc::new(AgentEscalator { agent: agent.clone() }), + (None, None) => Arc::new(NoopEscalator), + }; let policy = Arc::new(PausePolicy::start( config, tier.clone(), PauseFence::new(&warden_locks_dir), registry.clone(), - Arc::new(AgentEscalator { agent: agent.clone() }), + escalator, demand, )); if let Some(service) = &admission { @@ -174,13 +212,18 @@ impl PauseRuntime { cgroup_root.clone(), )); let (growth, queue) = mpsc::unbounded_channel(); - match &admission { - Some(service) => tokio::spawn(apply_local_growth(service.clone(), queue)), - None => tokio::spawn(send_growth(agent.clone(), queue)), + match (&admission, &agent) { + (Some(service), _) => { + tokio::spawn(apply_local_growth(service.clone(), queue)); + } + (None, Some(agent)) => { + tokio::spawn(send_growth(agent.clone(), queue)); + } + (None, None) => {} }; let cell = Arc::new(OnceLock::new()); let _ = cell.set(Arc::downgrade(&policy)); - let events = Arc::new(AgentEvents { agent: agent.clone(), growth, policy: cell }); + let events = Arc::new(AgentEvents { agent: agent.clone(), wake_hook, growth, policy: cell }); match LocalWaits::start(LocalWaitConfig::new(relays, candidates), (*tier).clone(), WaitFence::new(&warden_locks_dir), events) { Ok(waits) => Some(Arc::new(waits)), Err(error) => { diff --git a/runtime/noded/src/pipeline.rs b/runtime/noded/src/pipeline.rs index 6130a498..ed04c9e8 100644 --- a/runtime/noded/src/pipeline.rs +++ b/runtime/noded/src/pipeline.rs @@ -34,6 +34,14 @@ pub struct EnvironmentConfig { pub rafs: bool, } +fn default_max_file_body_bytes() -> u64 { + 256 * 1024 * 1024 +} + +fn default_admission_wait_seconds() -> f64 { + 30.0 +} + #[derive(Debug, Clone, Deserialize)] pub struct CreateConfig { pub state_root: PathBuf, @@ -57,7 +65,6 @@ pub struct CreateConfig { pub split_memory_backing: bool, pub memory_backing_hard_capacity_bytes: u64, pub application_memory_root: Option, - pub reflink_memory_restore: bool, pub workspace_initial_grant_mb: u64, pub demonstrated_memory: bool, pub init_binary: PathBuf, @@ -69,6 +76,9 @@ pub struct CreateConfig { /// The agent's pause-tier settings (phase 3a); the policy reads them. pub pause: Map, pub admission: AdmissionConfig, + /// Maximum file/archive upload or download body size in bytes. + #[serde(default = "default_max_file_body_bytes")] + pub max_file_body_bytes: u64, /// The agent's digest of this configuration (`config_sha256`). pub config_sha256: String, } @@ -126,6 +136,8 @@ pub struct ExecConfig { pub active_capacity_configured: bool, pub memory_floor_mib: u64, pub sessions: ExecSessionLimits, + #[serde(default = "default_admission_wait_seconds")] + pub admission_wait_seconds: f64, } impl CreateConfig { diff --git a/runtime/noded/src/registry/mod.rs b/runtime/noded/src/registry/mod.rs index 6366b7e5..d2561efc 100644 --- a/runtime/noded/src/registry/mod.rs +++ b/runtime/noded/src/registry/mod.rs @@ -33,7 +33,7 @@ pub use record::{ }; pub use schema::{APPLICATION_ID, SCHEMA, SCHEMA_VERSION}; pub use spec::SandboxSpec; -pub(crate) use spec::is_sandbox_id; +pub(crate) use spec::{is_sandbox_id, validate_guest_path}; pub use store::ClaimsMb; use spec::is_digest; diff --git a/runtime/noded/src/registry/spec.rs b/runtime/noded/src/registry/spec.rs index 82be268d..51097dbc 100644 --- a/runtime/noded/src/registry/spec.rs +++ b/runtime/noded/src/registry/spec.rs @@ -685,6 +685,26 @@ impl SandboxSpec { &self.id } + pub fn image(&self) -> &str { + &self.image + } + + pub fn labels(&self) -> &BTreeMap { + &self.labels + } + + pub fn ttl_seconds(&self) -> Option { + self.ttl_seconds + } + + pub fn ssh_info(&self) -> Option<(&str, i64, &str)> { + if self.ssh.enabled { + self.ssh.host_port.map(|port| (self.ssh.host.as_str(), port, self.ssh.user.as_str())) + } else { + None + } + } + pub fn memory_mb(&self) -> Option { self.memory_mb } @@ -701,6 +721,70 @@ impl SandboxSpec { self.managed_process } + pub fn profile(&self) -> &str { + &self.profile + } + + pub fn required_features(&self) -> &[String] { + &self.required_features + } + + pub fn working_dir(&self) -> Option<&str> { + self.working_dir.as_deref() + } + + pub fn security_user(&self) -> Option<&str> { + self.security.user.as_deref() + } + + pub fn supplementary_groups(&self) -> &[String] { + &self.security.supplementary_groups + } + + pub fn workspace_path(&self) -> &str { + &self.filesystem.workspace_path + } + + pub fn management_helper(&self) -> &str { + &self.filesystem.management_helper + } + + pub fn workspace_is_tmpfs(&self) -> bool { + self.filesystem.workspace_storage.as_deref() == Some("tmpfs") || self.filesystem.enforce_disk_quota + } + + pub fn enforce_disk_quota(&self) -> bool { + self.filesystem.enforce_disk_quota + } + + pub fn tmpfs_mb(&self) -> i64 { + self.filesystem.tmpfs_mb + } + + pub fn run_tmpfs_mb(&self) -> i64 { + self.filesystem.run_tmpfs_mb + } + + pub fn shm_mb(&self) -> i64 { + self.filesystem.shm_mb + } + + pub fn network(&self) -> &str { + &self.network + } + + pub fn network_egress(&self) -> &str { + if self.network_policy.relay.is_some() { "relay" } else { "direct" } + } + + pub fn network_relay(&self) -> Option<&str> { + self.network_policy.relay.as_deref() + } + + pub fn dns_servers(&self) -> &[String] { + &self.dns_servers + } + /// `to_dict()`. pub fn to_dict(&self) -> &Value { &self.dict @@ -848,6 +932,10 @@ impl SandboxSpec { } Ok(()) } + + pub fn environment_root(&self) -> Option<&str> { + self.environment_root.as_deref() + } } /// `str.strip()`: Python's whitespace also includes U+001C..U+001F. @@ -920,7 +1008,7 @@ fn validate_security_value(name: &str, value: &str) -> SpecResult<()> { } /// guest_paths.validate_guest_path. -fn validate_guest_path(name: &str, value: &str) -> SpecResult<()> { +pub(crate) fn validate_guest_path(name: &str, value: &str) -> SpecResult<()> { if !value.starts_with('/') { return Err(format!("{name} must be an absolute container path.")); } diff --git a/runtime/noded/src/registry_client.rs b/runtime/noded/src/registry_client.rs new file mode 100644 index 00000000..29990f42 --- /dev/null +++ b/runtime/noded/src/registry_client.rs @@ -0,0 +1,345 @@ +//! Minimal HTTP/1.1 client for the deployment's private OCI registry +//! (`sandboxes/managed_registry.py::RegistryClient`). +//! +//! Uses `hyper::client::conn::http1` + `tokio::net::TcpStream` already in the +//! dependency tree. Supports manifest GET/PUT and blob GET/PUT with bounded +//! reads and redirect following. + +use std::time::Duration; + +use bytes::Bytes; +use http_body_util::{BodyExt, Full, Limited}; +use hyper::client::conn::http1; +use hyper::header::{self, HeaderValue}; +use hyper::{Method, Request, StatusCode, Uri}; +use hyper_util::rt::TokioIo; +use serde_json::Value; +use tokio::net::TcpStream; + +const CONNECT_TIMEOUT: Duration = Duration::from_secs(15); +const REQUEST_TIMEOUT: Duration = Duration::from_secs(120); +const MAX_MANIFEST_BYTES: usize = 16 * 1024 * 1024; +const MAX_REDIRECTS: usize = 4; + +const MANIFEST_ACCEPT: &str = concat!( + "application/vnd.oci.image.manifest.v1+json, ", + "application/vnd.docker.distribution.manifest.v2+json, ", + "application/vnd.oci.image.index.v1+json, ", + "application/vnd.docker.distribution.manifest.list.v2+json", +); + +#[derive(Debug)] +pub enum RegistryHttpError { + NotFound(String), + Http { status: u16, message: String }, + Invalid(String), + Transport(String), +} + +impl std::fmt::Display for RegistryHttpError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + RegistryHttpError::NotFound(msg) => write!(f, "registry object not found: {msg}"), + RegistryHttpError::Http { status, message } => write!(f, "registry returned HTTP {status}: {message}"), + RegistryHttpError::Invalid(msg) | RegistryHttpError::Transport(msg) => f.write_str(msg), + } + } +} + +impl std::error::Error for RegistryHttpError {} + +#[derive(Clone, Debug)] +pub struct RegistryHttpClient { + base_url: String, + host_header: String, + connect_addr: String, +} + +impl RegistryHttpClient { + pub fn new(base_url: &str) -> Result { + let trimmed = base_url.trim().trim_end_matches('/'); + let uri: Uri = trimmed + .parse() + .map_err(|_| RegistryHttpError::Invalid(format!("invalid registry url: {base_url}")))?; + let scheme = uri.scheme_str().unwrap_or(""); + if scheme != "http" { + return Err(RegistryHttpError::Invalid(format!( + "rust registry client supports http:// private registry origins (got {base_url})" + ))); + } + let authority = uri + .authority() + .ok_or_else(|| RegistryHttpError::Invalid(format!("registry url missing authority: {base_url}")))?; + let host = authority.host(); + let port = authority.port_u16().unwrap_or(80); + let connect_addr = if host.contains(':') { + format!("[{host}]:{port}") + } else { + format!("{host}:{port}") + }; + Ok(RegistryHttpClient { + base_url: trimmed.to_string(), + host_header: authority.as_str().to_string(), + connect_addr, + }) + } + + pub fn base_url(&self) -> &str { + &self.base_url + } + + pub fn netloc(&self) -> &str { + &self.host_header + } + + async fn send_once( + connect_addr: &str, + host_header: &str, + method: Method, + path_and_query: &str, + headers: &[(&str, &str)], + body: Bytes, + max_response_bytes: usize, + ) -> Result<(StatusCode, hyper::HeaderMap, Bytes), RegistryHttpError> { + let stream = tokio::time::timeout(CONNECT_TIMEOUT, TcpStream::connect(connect_addr)) + .await + .map_err(|_| RegistryHttpError::Transport(format!("timed out connecting to registry {connect_addr}")))? + .map_err(|e| RegistryHttpError::Transport(format!("cannot connect to registry {connect_addr}: {e}")))?; + let _ = stream.set_nodelay(true); + let (mut sender, conn) = http1::handshake(TokioIo::new(stream)) + .await + .map_err(|e| RegistryHttpError::Transport(e.to_string()))?; + tokio::spawn(async move { + let _ = conn.await; + }); + + let mut builder = Request::builder() + .method(method) + .uri(path_and_query) + .header(header::HOST, host_header); + if !body.is_empty() { + builder = builder.header(header::CONTENT_LENGTH, body.len().to_string()); + } + for (k, v) in headers { + builder = builder.header(*k, *v); + } + let req = builder + .body(Full::new(body).map_err(|never| match never {}).boxed()) + .map_err(|e| RegistryHttpError::Invalid(e.to_string()))?; + + let response = tokio::time::timeout(REQUEST_TIMEOUT, sender.send_request(req)) + .await + .map_err(|_| RegistryHttpError::Transport("registry request timed out".into()))? + .map_err(|e| RegistryHttpError::Transport(e.to_string()))?; + + let status = response.status(); + let resp_headers = response.headers().clone(); + let bytes = tokio::time::timeout( + REQUEST_TIMEOUT, + Limited::new(response.into_body(), max_response_bytes).collect(), + ) + .await + .map_err(|_| RegistryHttpError::Transport("registry response body timed out".into()))? + .map_err(|e| RegistryHttpError::Transport(format!("registry response read failed: {e}")))? + .to_bytes(); + Ok((status, resp_headers, bytes)) + } + + async fn get_following_redirects( + &self, + path: &str, + accept: Option<&str>, + max_bytes: usize, + ) -> Result<(hyper::HeaderMap, Bytes), RegistryHttpError> { + let mut current_addr = self.connect_addr.clone(); + let mut current_host = self.host_header.clone(); + let mut current_path = path.to_string(); + + for _ in 0..=MAX_REDIRECTS { + let hdrs: Vec<(&str, &str)> = accept.map(|a| vec![("accept", a)]).unwrap_or_default(); + let (status, resp_headers, bytes) = Self::send_once( + ¤t_addr, + ¤t_host, + Method::GET, + ¤t_path, + &hdrs, + Bytes::new(), + max_bytes, + ) + .await?; + + if status == StatusCode::OK { + return Ok((resp_headers, bytes)); + } + if status == StatusCode::NOT_FOUND { + return Err(RegistryHttpError::NotFound(current_path)); + } + if matches!( + status, + StatusCode::MOVED_PERMANENTLY + | StatusCode::FOUND + | StatusCode::SEE_OTHER + | StatusCode::TEMPORARY_REDIRECT + | StatusCode::PERMANENT_REDIRECT + ) { + let Some(loc) = resp_headers.get(header::LOCATION).and_then(|v| v.to_str().ok()) else { + return Err(RegistryHttpError::Http { + status: status.as_u16(), + message: "redirect missing Location".into(), + }); + }; + if loc.starts_with('/') { + current_path = loc.to_string(); + } else { + let target = RegistryHttpClient::new(loc)?; + let uri: Uri = loc.parse().map_err(|_| RegistryHttpError::Invalid("invalid redirect".into()))?; + current_addr = target.connect_addr; + current_host = target.host_header; + current_path = uri.path_and_query().map(|pq| pq.as_str().to_string()).unwrap_or_else(|| "/".into()); + } + continue; + } + let snippet = String::from_utf8_lossy(&bytes); + return Err(RegistryHttpError::Http { + status: status.as_u16(), + message: snippet.chars().take(256).collect(), + }); + } + Err(RegistryHttpError::Transport("too many registry redirects".into())) + } + + /// `RegistryClient.manifest_document(repository, reference)`. + pub async fn manifest_document( + &self, + repository: &str, + reference: &str, + ) -> Result<(Value, String), RegistryHttpError> { + let path = format!("/v2/{repository}/manifests/{reference}"); + let (headers, bytes) = self + .get_following_redirects(&path, Some(MANIFEST_ACCEPT), MAX_MANIFEST_BYTES) + .await?; + let digest = headers + .get("docker-content-digest") + .and_then(|v| v.to_str().ok()) + .unwrap_or("") + .to_string(); + let doc: Value = serde_json::from_slice(&bytes) + .map_err(|e| RegistryHttpError::Invalid(format!("invalid manifest JSON: {e}")))?; + Ok((doc, digest)) + } + + /// `RegistryClient.blob_bytes(repository, digest, max_bytes=...)`. + pub async fn blob_bytes( + &self, + repository: &str, + digest: &str, + max_bytes: usize, + ) -> Result { + let path = format!("/v2/{repository}/blobs/{digest}"); + let (_, bytes) = self.get_following_redirects(&path, None, max_bytes).await?; + Ok(bytes) + } + + /// Upload one blob monotonically (`POST /v2/{repo}/blobs/uploads/` then `PUT`). + pub async fn put_blob(&self, repository: &str, digest: &str, payload: Bytes) -> Result<(), RegistryHttpError> { + // Skip upload if blob already exists (`HEAD`). + let head_path = format!("/v2/{repository}/blobs/{digest}"); + let (status, _, _) = Self::send_once( + &self.connect_addr, + &self.host_header, + Method::HEAD, + &head_path, + &[], + Bytes::new(), + 4096, + ) + .await?; + if status == StatusCode::OK { + return Ok(()); + } + let start_path = format!("/v2/{repository}/blobs/uploads/"); + let (status, headers, body) = Self::send_once( + &self.connect_addr, + &self.host_header, + Method::POST, + &start_path, + &[], + Bytes::new(), + 64 * 1024, + ) + .await?; + if status != StatusCode::ACCEPTED { + return Err(RegistryHttpError::Http { + status: status.as_u16(), + message: String::from_utf8_lossy(&body).into_owned(), + }); + } + let location = headers + .get(header::LOCATION) + .and_then(|v| v.to_str().ok()) + .ok_or_else(|| RegistryHttpError::Transport("registry upload start missing Location".into()))?; + let sep = if location.contains('?') { '&' } else { '?' }; + let put_url = format!("{location}{sep}digest={digest}"); + let (addr, host, path) = if put_url.starts_with('/') { + (self.connect_addr.clone(), self.host_header.clone(), put_url) + } else { + let parsed = RegistryHttpClient::new(&put_url)?; + let uri: Uri = put_url.parse().map_err(|_| RegistryHttpError::Invalid("invalid upload location".into()))?; + ( + parsed.connect_addr, + parsed.host_header, + uri.path_and_query().map(|pq| pq.as_str().to_string()).unwrap_or_else(|| "/".into()), + ) + }; + let (status, _, body) = Self::send_once( + &addr, + &host, + Method::PUT, + &path, + &[("content-type", "application/octet-stream")], + payload, + 64 * 1024, + ) + .await?; + if status != StatusCode::CREATED && status != StatusCode::OK { + return Err(RegistryHttpError::Http { + status: status.as_u16(), + message: String::from_utf8_lossy(&body).into_owned(), + }); + } + Ok(()) + } + + /// `RegistryClient.put_manifest(repository, reference, payload, media_type=...)`. + pub async fn put_manifest( + &self, + repository: &str, + reference: &str, + payload: Bytes, + media_type: &str, + ) -> Result { + let path = format!("/v2/{repository}/manifests/{reference}"); + let (status, headers, body) = Self::send_once( + &self.connect_addr, + &self.host_header, + Method::PUT, + &path, + &[("content-type", media_type)], + payload, + 64 * 1024, + ) + .await?; + if status != StatusCode::CREATED && status != StatusCode::OK { + return Err(RegistryHttpError::Http { + status: status.as_u16(), + message: String::from_utf8_lossy(&body).into_owned(), + }); + } + let digest = headers + .get("docker-content-digest") + .and_then(|v| HeaderValue::to_str(v).ok()) + .unwrap_or("") + .to_string(); + Ok(digest) + } +} diff --git a/runtime/noded/src/rootfs.rs b/runtime/noded/src/rootfs.rs index 03fc02d2..6a3aaf1c 100644 --- a/runtime/noded/src/rootfs.rs +++ b/runtime/noded/src/rootfs.rs @@ -357,6 +357,110 @@ impl OverlayManager { Ok(()) } + /// `release_sandbox`: unmount `/rootfs` and delete the bundle + /// (and the writable directory when not pre-created by storage-native). + pub async fn release_sandbox( + &self, + sandbox_id: &str, + generation: u64, + bundle: &Path, + workspace_volume_id: &str, + ) -> Result<(), RootfsError> { + if !safe_id(sandbox_id) || generation < 1 { + return Err(RootfsError::Invalid("sandbox incarnation is invalid".into())); + } + let expected_bundle = self.bundle(sandbox_id, generation); + if bundle != expected_bundle { + return Err(warden("registered sandbox bundle escaped overlay root")); + } + if expected_bundle.exists() { + self.unmount_if_mounted(&expected_bundle.join("rootfs")).await?; + rmtree(&expected_bundle)?; + } + if !self.require_precreated_writable && !workspace_volume_id.is_empty() { + let writable = self.writable_root.join(workspace_volume_id); + if writable.exists() { + rmtree(&writable)?; + } + } + Ok(()) + } + + /// `park_sandbox`: detach the nested overlay mount and delete scratch `work/`. + pub async fn park_sandbox( + &self, + sandbox_id: &str, + generation: u64, + bundle: &Path, + workspace_volume_id: &str, + ) -> Result<(), RootfsError> { + if !safe_id(sandbox_id) || generation < 1 { + return Err(RootfsError::Invalid("sandbox incarnation is invalid".into())); + } + let expected_bundle = self.bundle(sandbox_id, generation); + if bundle != expected_bundle { + return Err(warden("registered sandbox bundle escaped overlay root")); + } + if expected_bundle.exists() { + self.unmount_if_mounted(&expected_bundle.join("rootfs")).await?; + } + let work = self.writable_root.join(workspace_volume_id).join("work"); + if work.exists() { + rmtree(&work)?; + } + Ok(()) + } + + /// `resume_sandbox`: remount `/rootfs` from the mounted lower image + /// and the resumed writable volume's `upper`/`work`. + pub async fn resume_sandbox( + &self, + sandbox_id: &str, + generation: u64, + bundle: &Path, + workspace_volume_id: &str, + lower_rootfs: &Path, + ) -> Result<(), RootfsError> { + if !safe_id(sandbox_id) || generation < 1 { + return Err(RootfsError::Invalid("sandbox incarnation is invalid".into())); + } + let expected_bundle = self.bundle(sandbox_id, generation); + if bundle != expected_bundle { + return Err(warden("registered sandbox bundle escaped overlay root")); + } + let merged = expected_bundle.join("rootfs"); + if mount_present(&merged, &self.probe).await? { + return Ok(()); + } + let writable = self.writable_root.join(workspace_volume_id); + let upper = writable.join("upper"); + let work = writable.join("work"); + if work.exists() { + rmtree(&work)?; + } + std::fs::DirBuilder::new().recursive(true).mode(0o700).create(&work)?; + let options = format!( + "lowerdir={},upperdir={},workdir={},index=off,metacopy=off", + lower_rootfs.display(), + upper.display(), + work.display(), + ); + let argv = vec![ + self.mount_binary.to_string_lossy().into_owned(), + "-t".into(), + "overlay".into(), + "overlay".into(), + "-o".into(), + options, + merged.to_string_lossy().into_owned(), + ]; + let result = self.command(argv).await?; + if result.returncode != 0 { + return Err(warden(format!("overlay resume mount failed: {}", output(&result)))); + } + Ok(()) + } + /// `prepare`: mount `/rootfs` as an overlay of the image lower and /// the writable root's `upper`/`work`, then write `config.json` (indent 2) /// and `.ucloud-overlay.json` and fsync the bundle. Split creates pass the diff --git a/runtime/noded/src/runtime_metrics.rs b/runtime/noded/src/runtime_metrics.rs new file mode 100644 index 00000000..65c821d6 --- /dev/null +++ b/runtime/noded/src/runtime_metrics.rs @@ -0,0 +1,387 @@ +//! Host runtime metrics sampling (`sandboxes/runtime_metrics.py` & +//! `sandboxes/resource_evidence.py`) for standalone `ucloud-noded` heartbeats. + +use std::ffi::CString; +use std::fs::OpenOptions; +use std::os::fd::AsRawFd; +use std::os::unix::ffi::OsStrExt; +use std::os::unix::fs::{MetadataExt, OpenOptionsExt}; +use std::path::Path; +use std::sync::{Mutex, OnceLock}; +use std::time::Instant; + +use serde_json::{Map, Value, json}; + +use crate::images_front::PullMetrics; +use crate::sandbox_record::{format_utc_timestamp, now_utc_ns}; + +#[derive(Default)] +pub struct CpuDeltaSampler { + previous: Mutex>, +} + +impl CpuDeltaSampler { + pub fn new() -> Self { + Self::default() + } + + /// Sample aggregate CPU usage percentage from `/proc/stat`. Returns `None` + /// on the first call until a second sample establishes an interval. + pub fn sample(&self, proc_root: &Path) -> Option { + let current = read_proc_stat_cpu(proc_root)?; + let mut guard = self.previous.lock().expect("not poisoned"); + let prev = guard.replace(current); + let (prev_total, prev_idle) = prev?; + let d_total = current.0.saturating_sub(prev_total); + let d_idle = current.1.saturating_sub(prev_idle); + if d_total == 0 { + return None; + } + let busy = d_total.saturating_sub(d_idle) as f64; + Some(((busy / d_total as f64) * 100.0).clamp(0.0, 100.0)) + } +} + +/// Returns `(total_jiffies, idle_jiffies)` from `/proc/stat`'s first `cpu ` line. +pub fn read_proc_stat_cpu(proc_root: &Path) -> Option<(u64, u64)> { + let text = std::fs::read_to_string(proc_root.join("stat")).ok()?; + let line = text.lines().find(|l| l.starts_with("cpu "))?; + let fields: Vec = line + .split_whitespace() + .skip(1) + .filter_map(|part| part.parse().ok()) + .collect(); + if fields.len() < 4 { + return None; + } + let total: u64 = fields.iter().sum(); + let idle = fields[3].saturating_add(fields.get(4).copied().unwrap_or(0)); + Some((total, idle)) +} + +/// Parse `/proc/meminfo` fields into KiB. +pub fn read_proc_meminfo(proc_root: &Path) -> Map { + let mut out = Map::new(); + let Ok(text) = std::fs::read_to_string(proc_root.join("meminfo")) else { + return out; + }; + for line in text.lines() { + let Some((key, rest)) = line.split_once(':') else { continue }; + let Some(num) = rest.split_whitespace().next().and_then(|n| n.parse::().ok()) else { + continue; + }; + out.insert(key.trim().to_string(), json!(num)); + } + out +} + +/// Parse `/proc/pressure/{memory,io}` `some` / `full` `avg10` percentages. +pub fn read_proc_pressure(proc_root: &Path, resource: &str) -> (Option, Option) { + let Ok(text) = std::fs::read_to_string(proc_root.join("pressure").join(resource)) else { + return (None, None); + }; + let mut some = None; + let mut full = None; + for line in text.lines() { + let mut parts = line.split_whitespace(); + let kind = parts.next().unwrap_or(""); + let avg10 = parts + .find_map(|tok| tok.strip_prefix("avg10=")) + .and_then(|v| v.parse::().ok()) + .filter(|v| v.is_finite()); + match kind { + "some" => some = avg10, + "full" => full = avg10, + _ => {} + } + } + (some, full) +} + +/// Parse `/proc/loadavg` (1m, 5m, 15m). +pub fn read_loadavg(proc_root: &Path) -> (Option, Option, Option) { + let Ok(text) = std::fs::read_to_string(proc_root.join("loadavg")) else { + return (None, None, None); + }; + let mut parts = text.split_whitespace().filter_map(|p| p.parse::().ok().filter(|v| v.is_finite())); + (parts.next(), parts.next(), parts.next()) +} + +/// Fixed CPU-bound micro-check timed once per process (`runtime_metrics.cpu_check_ms`). +pub fn cpu_check_ms() -> u64 { + static CACHED: OnceLock = OnceLock::new(); + *CACHED.get_or_init(|| { + let mut best_ms = f64::INFINITY; + for _ in 0..5 { + let started = Instant::now(); + let mut total: u64 = 0; + for v in 0..1_000_000u64 { + total = total.wrapping_add(std::hint::black_box(v).wrapping_mul(v)); + } + let _ = std::hint::black_box(total); + best_ms = best_ms.min(started.elapsed().as_secs_f64() * 1000.0); + } + (best_ms.round() as u64).max(1) + }) +} + +/// Sample physical disk `(total_mb, free_mb)` via `statvfs`. +pub fn physical_disk_usage_mb(path: &Path) -> (u64, u64) { + let Ok(cpath) = CString::new(path.as_os_str().as_bytes()) else { + return (0, 0); + }; + let mut stat: libc::statvfs = unsafe { std::mem::zeroed() }; + // SAFETY: `cpath` is a valid NUL-terminated path and `stat` is writable. + if unsafe { libc::statvfs(cpath.as_ptr(), &mut stat) } != 0 { + return (0, 0); + } + let frsize = stat.f_frsize as u64; + let mib = 1024 * 1024; + let total = (stat.f_blocks as u64).saturating_mul(frsize) / mib; + let free = (stat.f_bavail as u64).saturating_mul(frsize) / mib; + (total, free) +} + +/// Sample configured RAM backing mount (`resource_evidence.sample_memory_backing`). +pub fn sample_memory_backing(root: Option<&Path>, proc_root: &Path) -> Option { + let root = root?; + let unknown = || json!({"total_bytes": null, "available_bytes": null, "identity": null}); + if !root.is_absolute() { + return Some(unknown()); + } + let file = match OpenOptions::new() + .read(true) + .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC) + .open(root) + { + Ok(f) => f, + Err(_) => return Some(unknown()), + }; + let Ok(meta) = file.metadata() else { return Some(unknown()) }; + let fd = file.as_raw_fd(); + let fdinfo = match std::fs::read_to_string(proc_root.join(format!("self/fdinfo/{fd}"))) { + Ok(s) => s, + Err(_) => return Some(unknown()), + }; + let Some(mnt_id) = fdinfo + .lines() + .find_map(|l| l.strip_prefix("mnt_id:")) + .map(str::trim) + else { + return Some(unknown()); + }; + let dev = meta.dev(); + let major = (((dev >> 32) & 0xffff_f000) | ((dev >> 8) & 0x0000_0fff)) as u32; + let minor = (((dev >> 12) & 0xffff_ff00) | (dev & 0x0000_00ff)) as u32; + let device = format!("{major}:{minor}"); + if !verify_tmpfs_mount(proc_root, root, mnt_id, &device) { + return Some(unknown()); + } + let mut stat: libc::statvfs = unsafe { std::mem::zeroed() }; + if unsafe { libc::fstatvfs(fd, &mut stat) } != 0 { + return Some(unknown()); + } + let Ok(current) = std::fs::metadata(root) else { return Some(unknown()) }; + if (meta.dev(), meta.ino()) != (current.dev(), current.ino()) { + return Some(unknown()); + } + let frsize = stat.f_frsize as u64; + let total = (stat.f_blocks as u64).saturating_mul(frsize); + let available = (stat.f_bavail as u64).saturating_mul(frsize).min(total); + if total == 0 { + return Some(unknown()); + } + Some(json!({ + "total_bytes": total, + "available_bytes": available, + "identity": format!("{mnt_id}:{device}:{}", meta.ino()), + })) +} + +fn verify_tmpfs_mount(proc_root: &Path, root: &Path, mnt_id: &str, device: &str) -> bool { + let Ok(mountinfo) = std::fs::read_to_string(proc_root.join("self/mountinfo")) else { + return false; + }; + let root_str = root.to_string_lossy(); + for line in mountinfo.lines() { + let parts: Vec<&str> = line.split_whitespace().collect(); + if parts.first().copied() != Some(mnt_id) { + continue; + } + let Some(sep) = parts.iter().position(|&p| p == "-") else { continue }; + let Some(mount_path) = parts.get(4) else { continue }; + let Some(fstype) = parts.get(sep + 1) else { continue }; + let decoded = mount_path + .replace("\\040", " ") + .replace("\\011", "\t") + .replace("\\134", "\\"); + return decoded == root_str && *fstype == "tmpfs" && parts.get(2).copied() == Some(device); + } + false +} + +/// Build the `NodeRuntimeMetrics` JSON object matching `sandboxes/models.py`. +#[allow(clippy::too_many_arguments)] +pub fn sample_node_runtime_metrics( + proc_root: &Path, + memory_backing_root: Option<&Path>, + cpu_sampler: &CpuDeltaSampler, + pull_metrics: &PullMetrics, + resident_wait: Option, + storage_metrics: Option<&Map>, + extra_hard_reserved_bytes: u64, + workspace_grant_mb: u64, + demonstrated_memory: bool, +) -> Value { + let cpu_count = std::thread::available_parallelism().map_or(1, usize::from); + let cpu_percent = cpu_sampler.sample(proc_root); + let cpu_vcpu = cpu_percent.map(|pct| (pct / 100.0) * cpu_count as f64); + + let mem = read_proc_meminfo(proc_root); + let get_kib = |key: &str| mem.get(key).and_then(Value::as_u64).unwrap_or(0); + let memory_total_mb = get_kib("MemTotal") / 1024; + let memory_available_mb = get_kib("MemAvailable") / 1024; + let memory_used_mb = memory_total_mb.saturating_sub(memory_available_mb); + let mapped_file_mb = get_kib("Mapped").saturating_sub(get_kib("Shmem")) / 1024; + let memory_working_set_mb = memory_total_mb.min(memory_used_mb.saturating_add(mapped_file_mb)); + let swap_total_mb = get_kib("SwapTotal") / 1024; + let swap_free_mb = get_kib("SwapFree") / 1024; + let swap_used_mb = swap_total_mb.saturating_sub(swap_free_mb); + let memory_percent = (memory_total_mb > 0).then(|| (memory_used_mb as f64 / memory_total_mb as f64) * 100.0); + + let (mem_psi_some, mem_psi_full) = read_proc_pressure(proc_root, "memory"); + let (io_psi_some, io_psi_full) = read_proc_pressure(proc_root, "io"); + let (load1, load5, load15) = read_loadavg(proc_root); + + let mut map = Map::new(); + map.insert("collected_at".into(), json!(format_utc_timestamp(now_utc_ns()))); + map.insert("cpu_percent".into(), json!(cpu_percent)); + map.insert("cpu_vcpu".into(), json!(cpu_vcpu)); + map.insert("cpu_count".into(), json!(cpu_count)); + map.insert("memory_total_mb".into(), json!(memory_total_mb)); + map.insert("memory_used_mb".into(), json!(memory_used_mb)); + map.insert("memory_available_mb".into(), json!(memory_available_mb)); + map.insert("memory_percent".into(), json!(memory_percent)); + map.insert("memory_working_set_mb".into(), json!(memory_working_set_mb)); + map.insert("swap_total_mb".into(), json!(swap_total_mb)); + map.insert("swap_used_mb".into(), json!(swap_used_mb)); + map.insert("swap_free_mb".into(), json!(swap_free_mb)); + map.insert("memory_psi_some_avg10".into(), json!(mem_psi_some)); + map.insert("memory_psi_full_avg10".into(), json!(mem_psi_full)); + map.insert("io_psi_some_avg10".into(), json!(io_psi_some)); + map.insert("io_psi_full_avg10".into(), json!(io_psi_full)); + map.insert("load_average_1m".into(), json!(load1)); + map.insert("load_average_5m".into(), json!(load5)); + map.insert("load_average_15m".into(), json!(load15)); + map.insert("image_pull_active_operations".into(), json!(pull_metrics.active_operations)); + map.insert("image_pull_waiting_operations".into(), json!(pull_metrics.waiting_operations)); + map.insert("image_pull_max_concurrent_operations".into(), json!(pull_metrics.max_concurrent_operations)); + map.insert("image_materialization_active_operations".into(), json!(0)); + map.insert("image_materialization_waiting_operations".into(), json!(0)); + map.insert("image_materialization_max_concurrent_operations".into(), json!(0)); + + let mib: u64 = 1024 * 1024; + let raw_u64 = |key: &str| -> u64 { + storage_metrics + .and_then(|m| m.get(key)) + .and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|n| n.max(0) as u64))) + .unwrap_or(0) + }; + let raw_bool = |key: &str| -> bool { + storage_metrics + .and_then(|m| m.get(key)) + .and_then(Value::as_bool) + .unwrap_or(false) + }; + let hard_capacity_mb = raw_u64("hard_capacity_bytes") / mib; + let hard_reserved_bytes = raw_u64("hard_reserved_bytes").saturating_add(extra_hard_reserved_bytes); + let hard_reserved_mb = if hard_reserved_bytes == 0 { + 0 + } else { + hard_reserved_bytes.saturating_add(mib - 1) / mib + }; + map.insert("storage_hard_capacity_mb".into(), json!(hard_capacity_mb)); + map.insert("storage_hard_reserved_mb".into(), json!(hard_reserved_mb)); + map.insert("storage_cache_mb".into(), json!(raw_u64("cache_bytes") / mib)); + map.insert("storage_active_operations".into(), json!(raw_u64("active_operations"))); + map.insert("storage_waiting_operations".into(), json!(raw_u64("waiting_operations"))); + map.insert("storage_max_concurrent_operations".into(), json!(raw_u64("max_concurrent_operations"))); + map.insert("storage_publication_active".into(), json!(raw_u64("snapshot_publication_active"))); + map.insert("storage_publication_waiting".into(), json!(raw_u64("snapshot_publication_waiting"))); + map.insert("storage_publication_limit".into(), json!(raw_u64("snapshot_publication_limit"))); + map.insert("storage_publication_queue_wait_ms_total".into(), json!(raw_u64("snapshot_publication_queue_wait_ms_total"))); + map.insert("storage_publication_queue_wait_ms_max".into(), json!(raw_u64("snapshot_publication_queue_wait_ms_max"))); + map.insert("storage_publication_duration_ms_total".into(), json!(raw_u64("snapshot_publication_duration_ms_total"))); + map.insert("storage_publication_duration_ms_max".into(), json!(raw_u64("snapshot_publication_duration_ms_max"))); + map.insert("storage_snapshot_publications".into(), json!(raw_u64("snapshot_publications"))); + map.insert("storage_snapshot_compactions".into(), json!(raw_u64("snapshot_compactions"))); + map.insert("storage_snapshot_uploaded_bytes".into(), json!(raw_u64("snapshot_uploaded_bytes"))); + map.insert("storage_published_volumes".into(), json!(raw_u64("published_volumes"))); + map.insert("storage_error_volumes".into(), json!(raw_u64("error_volumes"))); + map.insert("storage_device_pool_enabled".into(), json!(raw_bool("device_pool_enabled"))); + map.insert("storage_device_pool_low_watermark".into(), json!(raw_u64("device_pool_low_watermark"))); + map.insert("storage_device_pool_high_watermark".into(), json!(raw_u64("device_pool_high_watermark"))); + map.insert("storage_device_pool_idle_devices".into(), json!(raw_u64("device_pool_idle_devices"))); + map.insert("storage_ublk_active_devices".into(), json!(raw_u64("ublk_active_devices"))); + map.insert("storage_ublk_live_devices".into(), json!(raw_u64("ublk_live_devices"))); + map.insert("storage_ublk_max_devices".into(), json!(raw_u64("ublk_max_devices"))); + map.insert("storage_device_pool_acquires".into(), json!(raw_u64("device_pool_acquires"))); + map.insert("storage_device_pool_reused_acquires".into(), json!(raw_u64("device_pool_reused_acquires"))); + map.insert("storage_device_pool_new_acquires".into(), json!(raw_u64("device_pool_new_acquires"))); + map.insert("storage_device_pool_releases".into(), json!(raw_u64("device_pool_releases"))); + map.insert("storage_device_pool_discards".into(), json!(raw_u64("device_pool_discards"))); + // Matches sandboxes/disk_claims.py::DiskClaimPolicy.advertised (IDLE_MEMORY_CLAIM_MB = 64). + let idle_claim_mb: u64 = if demonstrated_memory { 64 } else { 0 }; + map.insert("storage_workspace_grant_mb".into(), json!(workspace_grant_mb)); + map.insert("storage_memory_idle_claim_mb".into(), json!(idle_claim_mb)); + map.insert("storage_workspace_growths".into(), json!(0)); + map.insert("storage_workspace_growth_refusals".into(), json!(0)); + map.insert("resource_evidence".into(), Value::Null); + map.insert("environment_io".into(), Value::Null); + map.insert( + "memory_backing".into(), + sample_memory_backing(memory_backing_root, proc_root).unwrap_or(Value::Null), + ); + map.insert("resident_wait".into(), json!(resident_wait)); + map.insert("cpu_check_ms".into(), json!(cpu_check_ms())); + Value::Object(map) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn samples_real_linux_proc_metrics() { + let sampler = CpuDeltaSampler::new(); + let mut storage = Map::new(); + storage.insert("hard_capacity_bytes".into(), json!(512u64 * 1024 * 1024 * 1024)); + storage.insert("hard_reserved_bytes".into(), json!(1024u64 * 1024 + 1)); + storage.insert("device_pool_enabled".into(), json!(true)); + storage.insert("device_pool_idle_devices".into(), json!(64)); + storage.insert("max_concurrent_operations".into(), json!(32)); + let metrics = sample_node_runtime_metrics( + Path::new("/proc"), + None, + &sampler, + &PullMetrics::default(), + None, + Some(&storage), + 1024 * 1024, + 512, + true, + ); + assert!(metrics["cpu_count"].as_u64().unwrap() >= 1); + assert!(metrics["memory_total_mb"].as_u64().unwrap() > 0); + assert!(metrics["cpu_check_ms"].as_u64().unwrap() >= 1); + assert_eq!(metrics["storage_hard_capacity_mb"], 512 * 1024); + assert_eq!(metrics["storage_hard_reserved_mb"], 3); + assert_eq!(metrics["storage_device_pool_enabled"], true); + assert_eq!(metrics["storage_device_pool_idle_devices"], 64); + assert_eq!(metrics["storage_max_concurrent_operations"], 32); + assert_eq!(metrics["storage_workspace_grant_mb"], 512); + assert_eq!(metrics["storage_memory_idle_claim_mb"], 64); + let (total, _free) = physical_disk_usage_mb(Path::new("/tmp")); + assert!(total > 0); + } +} diff --git a/runtime/noded/src/sandbox_record.rs b/runtime/noded/src/sandbox_record.rs new file mode 100644 index 00000000..ecfd4548 --- /dev/null +++ b/runtime/noded/src/sandbox_record.rs @@ -0,0 +1,155 @@ +//! Pure projection from a stored [`Registration`] and lifecycle state to the +//! JSON shape of Python's `SandboxRecord.to_dict()`. + +use std::time::{SystemTime, UNIX_EPOCH}; + +use serde_json::{Map, Value, json}; + +use crate::registry::Registration; + +/// Format UTC epoch nanoseconds identically to Python's +/// `datetime.fromtimestamp(ns / 1_000_000_000, tz=timezone.utc).isoformat()`. +pub fn format_utc_timestamp(ns: i64) -> String { + // Python rounds float seconds to nearest microsecond; integer truncation of + // ns/1000 matches monotonic/wall ns stored by both Python and Rust. + let total_us = ns.div_euclid(1_000); + let secs = total_us.div_euclid(1_000_000); + let micros = total_us.rem_euclid(1_000_000) as u32; + let days = secs.div_euclid(86_400); + let sod = secs.rem_euclid(86_400) as u32; + let hour = sod / 3_600; + let minute = (sod % 3_600) / 60; + let second = sod % 60; + let (year, month, day) = civil_from_days(days); + if micros == 0 { + format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}+00:00") + } else { + format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{micros:06}+00:00") + } +} + +/// Howard Hinnant's civil-from-days algorithm (days since 1970-01-01). +fn civil_from_days(days: i64) -> (i64, u32, u32) { + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = (z - era * 146_097) as u64; // [0, 146096] + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; // [0, 399] + let y = yoe as i64 + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365] + let mp = (5 * doy + 2) / 153; // [0, 11] + let d = doy - (153 * mp + 2) / 5 + 1; // [1, 31] + let m = if mp < 10 { mp + 3 } else { mp - 9 }; // [1, 12] + let year = if m <= 2 { y + 1 } else { y }; + (year, m as u32, d as u32) +} + +/// Whether the registration's TTL has elapsed as of `now_ns`. +pub fn is_expired_at(reg: &Registration, now_ns: i64) -> bool { + let Some(ttl) = reg.spec.ttl_seconds() else { return false }; + let expiry_ns = reg.created_ns.saturating_add(ttl.saturating_mul(1_000_000_000)); + now_ns >= expiry_ns +} + +pub fn now_utc_ns() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_nanos().min(i64::MAX as u128) as i64) +} + +/// Exact port of `sandboxes/sandbox.py::SandboxRecord.to_dict()`. +pub fn sandbox_record_json(reg: &Registration, state: &str) -> Value { + let mut labels = Map::new(); + for (k, v) in reg.spec.labels() { + labels.insert(k.clone(), Value::String(v.clone())); + } + let mut payload = Map::new(); + payload.insert("id".into(), Value::String(reg.sandbox_id().to_string())); + payload.insert("image".into(), Value::String(reg.spec.image().to_string())); + payload.insert("labels".into(), Value::Object(labels)); + payload.insert("spec".into(), reg.spec.to_dict().clone()); + payload.insert("container_name".into(), Value::String(reg.container_id.clone())); + payload.insert("state".into(), Value::String(state.to_string())); + payload.insert("created_at".into(), Value::String(format_utc_timestamp(reg.created_ns))); + payload.insert("updated_at".into(), Value::String(format_utc_timestamp(reg.updated_ns))); + payload.insert("generation".into(), json!(reg.sandbox_generation)); + payload.insert("operation_id".into(), Value::String(reg.operation_id.clone())); + payload.insert("spec_hash".into(), Value::String(reg.spec_sha256())); + if let Some((host, port, user)) = reg.spec.ssh_info() { + payload.insert( + "ssh".into(), + json!({ + "host": host, + "port": port, + "user": user, + "command": format!("ssh -p {port} {user}@{host}"), + }), + ); + } + Value::Object(payload) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::registry::{Phase, SandboxSpec}; + + #[test] + fn formats_utc_timestamps_like_python_isoformat() { + assert_eq!(format_utc_timestamp(0), "1970-01-01T00:00:00+00:00"); + assert_eq!(format_utc_timestamp(1_700_000_000_000_000_000), "2023-11-14T22:13:20+00:00"); + assert_eq!(format_utc_timestamp(1_700_000_000_123_456_789), "2023-11-14T22:13:20.123456+00:00"); + // Leap day: 2024-02-29T00:00:00Z = 1709164800 + assert_eq!(format_utc_timestamp(1_709_164_800_000_000_000), "2024-02-29T00:00:00+00:00"); + } + + #[test] + fn projects_registration_to_sandbox_record_json() { + let spec = SandboxSpec::from_dict(&json!({ + "id": "rec-1", + "image": "alpine:latest", + "cpus": 1.0, + "memory_mb": 512, + "disk_mb": 1024, + "labels": {"env": "test"}, + "ttl_seconds": 60, + })) + .unwrap(); + let reg = Registration { + spec: spec.clone(), + sandbox_generation: 2, + operation_id: "op-1".into(), + runtime_compatibility_sha256: "a".repeat(64), + phase: Phase::Owned, + revision: 5, + created_ns: 1_700_000_000_000_000_000, + updated_ns: 1_700_000_005_500_000_000, + quota_project_id: Some(10), + quota_total_mb: Some(1024), + quota_path: "/m/ws".into(), + image_id: "img-1".into(), + rootfs_sha256: "b".repeat(64), + container_id: "ctr-1".into(), + bundle: "/b/rec-1.sandbox-2".into(), + memory_directory: String::new(), + workspace_directory: "workspace-rec-1.sandbox-2".into(), + memory_allocation_id: String::new(), + migration_id: String::new(), + migration_sha256: String::new(), + version: 4, + }; + let rendered = sandbox_record_json(®, "running"); + assert_eq!(rendered["id"], "rec-1"); + assert_eq!(rendered["image"], "alpine:latest"); + assert_eq!(rendered["state"], "running"); + assert_eq!(rendered["generation"], 2); + assert_eq!(rendered["operation_id"], "op-1"); + assert_eq!(rendered["container_name"], "ctr-1"); + assert_eq!(rendered["spec_hash"], spec.sha256()); + assert_eq!(rendered["labels"]["env"], "test"); + assert_eq!(rendered["created_at"], "2023-11-14T22:13:20+00:00"); + assert_eq!(rendered["updated_at"], "2023-11-14T22:13:25.500000+00:00"); + assert!(rendered.get("ssh").is_none()); + assert!(!is_expired_at(®, 1_700_000_059_999_999_999)); + assert!(is_expired_at(®, 1_700_000_060_000_000_000)); + } +} diff --git a/runtime/noded/src/standalone.rs b/runtime/noded/src/standalone.rs new file mode 100644 index 00000000..eaf2243a --- /dev/null +++ b/runtime/noded/src/standalone.rs @@ -0,0 +1,309 @@ +//! Standalone Rust sandbox worker node daemon (`ucloud-noded --standalone-config PATH`). +//! +//! Runs every sandbox worker route, background heartbeat push loop, pause tier, +//! in-process Rust admission ledger, and boot-time/periodic orphan & TTL +//! reconciler with zero Python node agent dependency. + +use std::path::{Path, PathBuf}; +use std::sync::{Arc, OnceLock}; +use std::time::Duration; + +use bytes::Bytes; +use serde::Deserialize; +use tokio::sync::watch; + +use crate::admission::port::LocalAdmission; +use crate::commit_export::CommitExports; +use crate::control_front::ControlFront; +use crate::create::CreateFront; +use crate::ed25519::load_trusted_keys; +use crate::exec_front::ExecFront; +use crate::files_front::FilesFront; +use crate::heartbeat::{HeartbeatConfig, HeartbeatFront, HeartbeatPusher}; +use crate::image::EnvironmentResolver; +use crate::images_front::{EnvironmentPuller, ImageCatalog, ImagesFront, PullMetrics}; +use crate::jobs::{JobFront, JobLimits, NodeJobs}; +use crate::lifecycle_front::{LifecycleFront, LifecycleNode}; +use crate::node_lifecycle::NodeLifecycle; +use crate::node_pipeline::NodePipeline; +use crate::pause_policy::{BoxFuture, Escalated, Escalator}; +use crate::pause_runtime::WakeHook; +use crate::pipeline::CreateConfig; +use crate::registry::Phase; +use crate::registry_client::RegistryHttpClient; +use crate::sandbox_record::{is_expired_at, now_utc_ns}; +use crate::warden::Sandbox; +use crate::Fronts; + +fn default_max_concurrent_image_pulls() -> usize { + 8 +} + +fn default_reconcile_interval_secs() -> f64 { + 15.0 +} + +#[derive(Clone, Debug, Deserialize)] +pub struct StandaloneConfig { + pub create: CreateConfig, + pub heartbeat: HeartbeatConfig, + #[serde(default)] + pub trusted_keys_file: Option, + #[serde(default)] + pub image_catalog_path: Option, + #[serde(default = "default_max_concurrent_image_pulls")] + pub max_concurrent_image_pulls: usize, + #[serde(default)] + pub checkpoint_registry_url: Option, + #[serde(default)] + pub checkpoint_registry_repository: Option, + #[serde(default = "default_reconcile_interval_secs")] + pub reconcile_interval_secs: f64, +} + +impl StandaloneConfig { + pub fn load(path: &Path) -> Result { + let bytes = std::fs::read(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?; + serde_json::from_slice(&bytes).map_err(|e| format!("invalid standalone config {}: {e}", path.display())) + } +} + +struct DeferredEscalator { + lifecycle: Arc>>, +} + +impl Escalator for DeferredEscalator { + fn escalate(&self, sandbox: &Sandbox) -> BoxFuture> { + let cell = self.lifecycle.clone(); + let sb = sandbox.clone(); + Box::pin(async move { + let Some(lifecycle) = cell.get().cloned() else { + return Err("lifecycle not yet initialized".into()); + }; + lifecycle.escalator().escalate(&sb).await + }) + } +} + +fn deferred_wake_hook(lifecycle: Arc>>) -> WakeHook { + Arc::new(move |sandbox_id, generation, operation_id| { + let cell = lifecycle.clone(); + Box::pin(async move { + let Some(lc) = cell.get().cloned() else { + return Err("lifecycle not yet initialized".into()); + }; + lc.wake(&sandbox_id, generation as i64, &operation_id) + .await + .map(|_| ()) + .map_err(|e| format!("{e:?}")) + }) + }) +} + +pub struct StandaloneRuntime { + pub fronts: Fronts, + pub node: Arc, + pub heartbeat: Arc, + pusher: Option, + reconciler_stop: watch::Sender, + reconciler_task: Option>, +} + +impl StandaloneRuntime { + pub async fn shutdown(mut self) { + let _ = self.reconciler_stop.send(true); + if let Some(pusher) = self.pusher.take() { + pusher.stop().await; + } + if let Some(task) = self.reconciler_task.take() { + let _ = task.await; + } + self.node.shutdown().await; + } +} + +/// Boot the entire sandbox worker node daemon in pure Rust (no Python agent). +pub fn start_standalone(config: StandaloneConfig, token: &str) -> Result { + let trusted_keys = match &config.trusted_keys_file { + Some(path) => load_trusted_keys(path).map_err(|e| format!("trusted keys: {e}"))?, + None => std::collections::HashMap::new(), + }; + let resolver = match &config.create.environment { + Some(env_cfg) => { + let res = EnvironmentResolver::new( + &env_cfg.registry_url, + env_cfg.registry_repository.clone(), + trusted_keys, + ) + .map_err(|e| format!("environment resolver: {e}"))?; + Some(Arc::new(res)) + } + None => None, + }; + + let catalog_path = config + .image_catalog_path + .unwrap_or_else(|| config.create.state_root.join("images.json")); + let catalog = Arc::new(ImageCatalog::open(&catalog_path)); + + let lifecycle_cell: Arc>> = Arc::new(OnceLock::new()); + let escalator: Arc = Arc::new(DeferredEscalator { + lifecycle: lifecycle_cell.clone(), + }); + let wake_hook = deferred_wake_hook(lifecycle_cell.clone()); + + let node = Arc::new(NodePipeline::open_standalone( + config.create.clone(), + resolver.clone(), + Some(escalator), + Some(wake_hook), + )?); + let node_cell = Arc::new(OnceLock::new()); + let _ = node_cell.set(node.clone()); + + let (images_front, pull_metrics_fn): (Option>, Arc PullMetrics + Send + Sync>) = + if let Some(res) = resolver { + let reg_for_open = node.registry().clone(); + let admission_open = Arc::new(move || { + reg_for_open + .load_drain() + .map(|d| d.admission_open) + .unwrap_or(false) + }); + let puller = Arc::new(EnvironmentPuller::new( + node.images().clone(), + (*res).clone(), + admission_open, + )); + let front = ImagesFront::new( + catalog.clone(), + puller, + token, + config.max_concurrent_image_pulls.max(1), + ); + let front_metrics = front.clone(); + (Some(front), Arc::new(move || front_metrics.pull_metrics())) + } else { + (None, Arc::new(PullMetrics::default)) + }; + + let heartbeat = HeartbeatFront::new( + config.heartbeat.clone(), + node_cell.clone(), + Some(catalog), + pull_metrics_fn, + token, + ); + + let checkpoint_reg = match (&config.checkpoint_registry_url, &config.checkpoint_registry_repository) { + (Some(url), Some(repo)) if !url.is_empty() && !repo.is_empty() => { + let client = RegistryHttpClient::new(url) + .map_err(|e| format!("checkpoint registry client: {e}"))?; + Some((client, repo.clone())) + } + _ => None, + }; + let commit_reg = checkpoint_reg.as_ref().map(|(c, _)| c.clone()); + let commits = CommitExports::open(&config.create.state_root, commit_reg) + .map_err(|e| format!("commit exports: {e}"))?; + let lifecycle = NodeLifecycle::new(node_cell.clone(), Some(heartbeat.clone()), commits, checkpoint_reg); + let _ = lifecycle_cell.set(lifecycle.clone()); + + let admission = node + .admission() + .cloned() + .ok_or("standalone node requires Rust admission service")?; + let job_node = Arc::new(NodeJobs { node: node_cell.clone() }); + let jobs = JobFront::with_admission( + job_node, + Arc::new(LocalAdmission::new(admission)), + token, + JobLimits::default(), + ); + + let sess = &config.create.exec.sessions; + let exec_limits = crate::exec::ExecLimits { + max_sessions: sess.max_sessions.max(1), + max_events_per_session: sess.max_events_per_session.max(1), + completed_retention: Duration::from_secs_f64(sess.completed_retention_seconds.max(1.0)), + delivered_grace: Duration::from_secs_f64(sess.delivered_grace_seconds.max(0.1)), + output_idle_timeout: Duration::from_secs_f64(sess.output_idle_timeout_seconds.max(1.0)), + ..crate::exec::ExecLimits::default() + }; + + let fronts = Fronts { + control: Some(ControlFront::standalone(node_cell.clone(), heartbeat.clone(), lifecycle.clone(), token)), + create: Some(CreateFront::standalone(node.clone(), heartbeat.clone(), token)), + exec: Some(ExecFront::with_limits(node_cell.clone(), token, exec_limits)), + files: Some(FilesFront::new(node_cell.clone(), token)), + heartbeat: Some(heartbeat.clone()), + images: images_front, + jobs: Some(jobs), + lifecycle: Some(LifecycleFront::new(lifecycle, token)), + node: Some(node_cell), + internal: None, + standalone_token: Some(Bytes::copy_from_slice(token.as_bytes())), + }; + + let pusher = HeartbeatPusher::start(heartbeat.clone()); + + // Boot-time orphan & periodic TTL / Deleting reconciler. + let (reconciler_stop, mut stop_rx) = watch::channel(false); + let reconcile_node = node.clone(); + let reconcile_hb = heartbeat.clone(); + let interval = Duration::from_secs_f64(config.reconcile_interval_secs.clamp(0.25, 300.0)); + let reconciler_task = tokio::spawn(async move { + reconcile_once(&reconcile_node, &reconcile_hb).await; + loop { + tokio::select! { + _ = stop_rx.changed() => { + if *stop_rx.borrow() { + break; + } + } + _ = tokio::time::sleep(interval) => { + reconcile_once(&reconcile_node, &reconcile_hb).await; + } + } + } + }); + + Ok(StandaloneRuntime { + fronts, + node, + heartbeat, + pusher, + reconciler_stop, + reconciler_task: Some(reconciler_task), + }) +} + +/// Reconcile any crashed `Phase::Deleting` registrations or TTL-expired sandboxes. +pub async fn reconcile_once(node: &Arc, heartbeat: &Arc) { + let reg_store = node.registry().clone(); + let targets: Vec<(String, i64)> = tokio::task::spawn_blocking(move || { + let Ok(snapshot) = reg_store.snapshot() else { + return Vec::new(); + }; + let now = now_utc_ns(); + snapshot + .records + .iter() + .filter(|reg| reg.phase == Phase::Deleting || is_expired_at(reg, now)) + .map(|reg| (reg.sandbox_id().to_string(), reg.sandbox_generation)) + .collect() + }) + .await + .unwrap_or_default(); + + for (sandbox_id, generation) in targets { + match node.delete_sandbox(&sandbox_id, generation).await { + Ok(_) => { + heartbeat.advance_activity_epoch(); + } + Err(err) => { + eprintln!("ucloud-noded: reconciler could not delete {sandbox_id} (gen {generation}): {err:?}"); + } + } + } +} diff --git a/runtime/noded/src/storage.rs b/runtime/noded/src/storage.rs index 84d84576..eccc1064 100644 --- a/runtime/noded/src/storage.rs +++ b/runtime/noded/src/storage.rs @@ -148,6 +148,148 @@ impl StorageClient { fields.insert("volume_id".into(), json!(volume_id)); record(self.call("GetVolume", fields, trace_context).await?) } + + /// `GetMetrics`: node-wide storage-native capacity, reservations, and pool counters. + pub async fn get_metrics( + &self, + trace_context: Map, + ) -> Result, StorageError> { + self.call("GetMetrics", Map::new(), trace_context).await + } + + /// `DeleteVolume`: tear down the workspace volume and release its quota. + pub async fn delete_volume( + &self, + owner: &VolumeOwner, + operation_id: &str, + expected_accounting_id: Option, + expected_virtual_size: Option, + trace_context: Map, + ) -> Result, StorageError> { + let mut fields = owner_fields(owner); + fields.insert("operation_id".into(), json!(operation_id)); + fields.insert( + "expected_accounting_id".into(), + expected_accounting_id.map_or(Value::Null, |v| json!(v)), + ); + fields.insert( + "expected_virtual_size".into(), + expected_virtual_size.map_or(Value::Null, |v| json!(v)), + ); + record(self.call("DeleteVolume", fields, trace_context).await?) + } + + /// `PrepareCapture`: flush/sync the mounted workspace before sealing. + pub async fn prepare_capture( + &self, + owner: &VolumeOwner, + operation_id: &str, + expected_revision: i64, + trace_context: Map, + ) -> Result, StorageError> { + let mut fields = owner_fields(owner); + fields.insert("operation_id".into(), json!(operation_id)); + fields.insert("expected_revision".into(), json!(expected_revision)); + record(self.call("PrepareCapture", fields, trace_context).await?) + } + + /// `CommitCapture`: seal the prepared workspace capture into a local layer. + pub async fn commit_capture( + &self, + owner: &VolumeOwner, + operation_id: &str, + expected_revision: i64, + trace_context: Map, + ) -> Result, StorageError> { + let mut fields = owner_fields(owner); + fields.insert("operation_id".into(), json!(operation_id)); + fields.insert("expected_revision".into(), json!(expected_revision)); + record(self.call("CommitCapture", fields, trace_context).await?) + } + + /// `AbortCapture`: roll back a prepared capture if checkpointing failed. + pub async fn abort_capture( + &self, + owner: &VolumeOwner, + operation_id: &str, + expected_revision: i64, + trace_context: Map, + ) -> Result, StorageError> { + let mut fields = owner_fields(owner); + fields.insert("operation_id".into(), json!(operation_id)); + fields.insert("expected_revision".into(), json!(expected_revision)); + record(self.call("AbortCapture", fields, trace_context).await?) + } + + /// `EnsureReleased`: unmount workspace ublk device and release its active lease. + pub async fn ensure_released( + &self, + owner: &VolumeOwner, + operation_id: &str, + trace_context: Map, + ) -> Result, StorageError> { + let mut fields = owner_fields(owner); + fields.insert("operation_id".into(), json!(operation_id)); + record(self.call("EnsureReleased", fields, trace_context).await?) + } + + /// `EnsureMounted`: attach and mount a parked workspace volume for resume. + pub async fn ensure_mounted( + &self, + owner: &VolumeOwner, + operation_id: &str, + trace_context: Map, + ) -> Result, StorageError> { + let mut fields = owner_fields(owner); + fields.insert("operation_id".into(), json!(operation_id)); + record(self.call("EnsureMounted", fields, trace_context).await?) + } + + /// `EnsurePublished`: push sealed workspace layers to the snapshot store. + pub async fn ensure_published( + &self, + owner: &VolumeOwner, + operation_id: &str, + expected_revision: Option, + trace_context: Map, + ) -> Result, StorageError> { + let mut fields = owner_fields(owner); + fields.insert("operation_id".into(), json!(operation_id)); + if let Some(revision) = expected_revision { + fields.insert("expected_revision".into(), json!(revision)); + } + record(self.call("EnsurePublished", fields, trace_context).await?) + } + + /// `PrepareImport`: stage a published workspace snapshot on this destination node. + pub async fn prepare_import( + &self, + owner: &VolumeOwner, + operation_id: &str, + publication: Value, + capture_id: Option<&str>, + trace_context: Map, + ) -> Result, StorageError> { + let mut fields = owner_fields(owner); + fields.insert("operation_id".into(), json!(operation_id)); + fields.insert("publication".into(), publication); + if let Some(id) = capture_id.filter(|s| !s.is_empty()) { + fields.insert("capture_id".into(), json!(id)); + } + record(self.call("PrepareImport", fields, trace_context).await?) + } + + /// `DiscardResume`: detach a mounted resume workspace if restore rolls back. + pub async fn discard_resume( + &self, + owner: &VolumeOwner, + operation_id: &str, + trace_context: Map, + ) -> Result, StorageError> { + let mut fields = owner_fields(owner); + fields.insert("operation_id".into(), json!(operation_id)); + record(self.call("DiscardResume", fields, trace_context).await?) + } } fn owner_fields(owner: &VolumeOwner) -> Map { @@ -322,4 +464,61 @@ mod tests { assert_eq!(requests[1], r#"{"operation":"GetVolume","schema":4,"trace_context":{},"volume_id":"vol-1"}"#); let _ = std::fs::remove_dir_all(&dir); } + + #[tokio::test] + async fn lifecycle_and_metrics_frames_match_storage_native_protocol() { + let dir = std::env::temp_dir().join(format!("noded-storage-proto-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let socket = dir.join("service.sock"); + let listener = UnixListener::bind(&socket).unwrap(); + let server = tokio::spawn(async move { + let mut requests = Vec::new(); + for reply in [ + r#"{"result":{"hard_capacity_bytes":547608330240,"hard_reserved_bytes":0},"status":"ok"}"#, + r#"{"result":{"record":{"state":"deleted"}},"status":"ok"}"#, + r#"{"result":{"record":{"revision":2,"state":"capture_committed"}},"status":"ok"}"#, + r#"{"result":{"record":{"revision":3,"state":"released"}},"status":"ok"}"#, + r#"{"result":{"record":{"revision":4,"state":"mounted"}},"status":"ok"}"#, + ] { + let (mut stream, _) = listener.accept().await.unwrap(); + let mut header = [0u8; 4]; + stream.read_exact(&mut header).await.unwrap(); + let mut body = vec![0u8; u32::from_be_bytes(header) as usize]; + stream.read_exact(&mut body).await.unwrap(); + requests.push(String::from_utf8(body).unwrap()); + let mut frame = (reply.len() as u32).to_be_bytes().to_vec(); + frame.extend_from_slice(reply.as_bytes()); + stream.write_all(&frame).await.unwrap(); + } + requests + }); + let client = StorageClient::new(&socket); + let owner = VolumeOwner { volume_id: "vol-1".into(), sandbox_id: "sb-1".into(), sandbox_generation: 1 }; + let metrics = client.get_metrics(Map::new()).await.unwrap(); + assert_eq!(metrics["hard_capacity_bytes"], 547608330240u64); + client.delete_volume(&owner, "op-del", None, None, Map::new()).await.unwrap(); + client.commit_capture(&owner, "op-cap", 1, Map::new()).await.unwrap(); + client.ensure_released(&owner, "op-rel", Map::new()).await.unwrap(); + client.ensure_mounted(&owner, "op-mnt", Map::new()).await.unwrap(); + let requests = server.await.unwrap(); + assert_eq!(requests[0], r#"{"operation":"GetMetrics","schema":4,"trace_context":{}}"#); + assert_eq!( + requests[1], + r#"{"expected_accounting_id":null,"expected_virtual_size":null,"operation":"DeleteVolume","operation_id":"op-del","sandbox_generation":1,"sandbox_id":"sb-1","schema":4,"trace_context":{},"volume_id":"vol-1"}"# + ); + assert_eq!( + requests[2], + r#"{"expected_revision":1,"operation":"CommitCapture","operation_id":"op-cap","sandbox_generation":1,"sandbox_id":"sb-1","schema":4,"trace_context":{},"volume_id":"vol-1"}"# + ); + assert_eq!( + requests[3], + r#"{"operation":"EnsureReleased","operation_id":"op-rel","sandbox_generation":1,"sandbox_id":"sb-1","schema":4,"trace_context":{},"volume_id":"vol-1"}"# + ); + assert_eq!( + requests[4], + r#"{"operation":"EnsureMounted","operation_id":"op-mnt","sandbox_generation":1,"sandbox_id":"sb-1","schema":4,"trace_context":{},"volume_id":"vol-1"}"# + ); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/runtime/noded/src/upload_archive.rs b/runtime/noded/src/upload_archive.rs new file mode 100644 index 00000000..bda30a7b --- /dev/null +++ b/runtime/noded/src/upload_archive.rs @@ -0,0 +1,974 @@ +//! Validate uploaded tar archives and stage large uploads on disk +//! (`sandboxes/upload_archive.py`, `sandboxes/upload_spool.py`, and +//! `sandboxes/direct_service.py::sandbox_file_write_script`). +//! +//! `PUT /v1/sandboxes/{id}/archive?path=DIR` validates every member before +//! anything is written and emits a fresh plain POSIX/PAX tar holding only the +//! planned regular files; empty directories travel as helper arguments. + +use std::collections::{BTreeSet, HashSet}; +use std::ffi::CString; +use std::fs::{File, OpenOptions}; +use std::io::{self, Cursor, Read, Seek, SeekFrom, Write}; +use std::os::unix::ffi::OsStrExt; +use std::os::unix::fs::OpenOptionsExt; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering}; + +pub const TRANSFER_CHUNK_BYTES: usize = 64 * 1024; +pub const MAX_ARCHIVE_MEMBERS: usize = 10_000; +pub const MAX_NAME_BYTES: usize = 4096; +pub const MAX_COMPONENT_BYTES: usize = 255; +pub const MAX_DIRECTORY_ARGUMENT_BYTES: usize = 64 * 1024; +pub const MAX_METADATA_RECORD_BYTES: usize = 64 * 1024; +pub const IN_MEMORY_ARCHIVE_BYTES: u64 = 1024 * 1024; +pub const SHELL_UNAVAILABLE_EXIT: i32 = 69; +pub const DEFAULT_MIN_FREE_BYTES: u64 = 1024 * 1024 * 1024; +const BLOCK_SIZE: usize = 512; +const RECORDSIZE: u64 = 10240; + +pub fn sandbox_file_write_script() -> &'static str { + concat!( + "set -eu; target=$1; dir=${target%/*}; ", + "[ -n \"$dir\" ] || dir=/; ", + "[ ! -d \"$target\" ] || { echo \"file target is a directory\" >&2; exit 1; }; ", + "[ -d \"$dir\" ] || mkdir -p -- \"$dir\"; ", + "umask 077; tmp=$(mktemp \"$dir/.ucloud-write.XXXXXX\"); ", + "trap 'rm -f -- \"$tmp\"' EXIT HUP INT TERM; ", + "cat >\"$tmp\"; mv -f -- \"$tmp\" \"$target\"; ", + "trap - EXIT HUP INT TERM", + ) +} + +pub fn sandbox_archive_extract_script() -> &'static str { + concat!( + "set -eu; dir=$1; shift; ", + "command -v tar >/dev/null 2>&1 || ", + "{ echo \"tar is unavailable\" >&2; exit 69; }; ", + "[ -d \"$dir\" ] || mkdir -p -- \"$dir\"; cd \"$dir\"; umask 022; ", + "[ \"$#\" -eq 0 ] || mkdir -p -- \"$@\"; ", + "exec tar -x -m -o -f -", + ) +} + +pub fn archive_helper_unsupported(exit_code: i32, stderr: &[u8]) -> bool { + exit_code == SHELL_UNAVAILABLE_EXIT && stderr.windows(b"tar is unavailable".len()).any(|w| w == b"tar is unavailable") +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ArchivePlan { + pub files: usize, + pub directory_members: usize, + pub total_bytes: u64, + pub empty_directories: Vec, +} + +#[derive(Debug)] +pub enum ArchiveError { + Invalid(String), + TooLarge(String), + SpoolSpace(String), + Io(io::Error), +} + +impl std::fmt::Display for ArchiveError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ArchiveError::Invalid(message) | ArchiveError::TooLarge(message) | ArchiveError::SpoolSpace(message) => { + f.write_str(message) + } + ArchiveError::Io(error) => write!(f, "{error}"), + } + } +} + +impl std::error::Error for ArchiveError {} + +impl From for ArchiveError { + fn from(error: io::Error) -> Self { + if matches!(error.raw_os_error(), Some(libc::ENOSPC | libc::EDQUOT)) { + ArchiveError::SpoolSpace("node upload staging is waiting for disk space".into()) + } else { + ArchiveError::Io(error) + } + } +} + +/// Bounded local staging directory for large uploads (`sandboxes/upload_spool.py`). +pub struct UploadSpool { + directory: PathBuf, + min_free_bytes: u64, + unwritten_bytes: Mutex, + counter: AtomicU64, +} + +/// An unlinked temp file whose remaining reservation returns on drop. +pub struct ManagedStagedFile { + pub file: File, + spool: std::sync::Arc, + reserved: u64, +} + +impl ManagedStagedFile { + pub fn consume_reservation(&mut self, written: u64) { + let delta = written.min(self.reserved); + if delta > 0 { + let mut guard = self.spool.unwritten_bytes.lock().expect("not poisoned"); + *guard = guard.saturating_sub(delta); + self.reserved -= delta; + } + } +} + +impl Drop for ManagedStagedFile { + fn drop(&mut self) { + if self.reserved > 0 { + let mut guard = self.spool.unwritten_bytes.lock().expect("not poisoned"); + *guard = guard.saturating_sub(self.reserved); + self.reserved = 0; + } + } +} + +impl UploadSpool { + pub fn new(directory: impl Into) -> Self { + Self::with_min_free(directory, DEFAULT_MIN_FREE_BYTES) + } + + pub fn with_min_free(directory: impl Into, min_free_bytes: u64) -> Self { + UploadSpool { + directory: directory.into(), + min_free_bytes, + unwritten_bytes: Mutex::new(0), + counter: AtomicU64::new(0), + } + } + + pub fn unwritten_bytes(&self) -> u64 { + *self.unwritten_bytes.lock().expect("not poisoned") + } + + pub fn directory(&self) -> &Path { + &self.directory + } + + fn reserve(&self, length: u64) -> Result<(), ArchiveError> { + std::fs::create_dir_all(&self.directory)?; + let mut guard = self.unwritten_bytes.lock().expect("not poisoned"); + let available = statvfs_available(&self.directory)?; + if available.saturating_sub(*guard).saturating_sub(length) < self.min_free_bytes { + return Err(ArchiveError::SpoolSpace("node upload staging is waiting for disk space".into())); + } + *guard = guard.saturating_add(length); + Ok(()) + } + + fn create_unlinked_file(&self) -> io::Result { + std::fs::create_dir_all(&self.directory)?; + let pid = std::process::id(); + for _ in 0..128 { + let seq = self.counter.fetch_add(1, Ordering::Relaxed); + let path = self.directory.join(format!(".ucloud-upload-{pid}-{seq}.tmp")); + match OpenOptions::new() + .read(true) + .write(true) + .create_new(true) + .mode(0o600) + .custom_flags(libc::O_CLOEXEC | libc::O_NOFOLLOW) + .open(&path) + { + Ok(file) => { + let _ = std::fs::remove_file(&path); + return Ok(file); + } + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error), + } + } + Err(io::Error::new(io::ErrorKind::AlreadyExists, "could not allocate unique staging file")) + } + + /// Reserve `length` bytes and return an unlinked staging file. + pub fn staging(self: &std::sync::Arc, length: u64) -> Result { + self.reserve(length)?; + match self.create_unlinked_file() { + Ok(file) => Ok(ManagedStagedFile { file, spool: self.clone(), reserved: length }), + Err(error) => { + let mut guard = self.unwritten_bytes.lock().expect("not poisoned"); + *guard = guard.saturating_sub(length); + Err(error.into()) + } + } + } +} + +fn statvfs_available(path: &Path) -> io::Result { + let cpath = CString::new(path.as_os_str().as_bytes()) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "spool path contains NUL"))?; + let mut stat: libc::statvfs = unsafe { std::mem::zeroed() }; + // SAFETY: `cpath` is a valid NUL-terminated path and `stat` is writable. + if unsafe { libc::statvfs(cpath.as_ptr(), &mut stat) } != 0 { + return Err(io::Error::last_os_error()); + } + Ok((stat.f_bavail as u64).saturating_mul(stat.f_frsize as u64)) +} + +/// Source bytes for an uploaded archive (either in memory or a spooled file). +pub enum ArchiveSource<'a> { + Bytes(&'a [u8]), + File(&'a File), +} + +/// Normalized plain PAX tar ready for the extraction helper's stdin. +pub enum NormalizedArchive { + Bytes(Vec), + File(ManagedStagedFile), +} + +pub fn canonical_member_name(raw: &str) -> Result { + if raw.starts_with('/') { + return Err(ArchiveError::Invalid(format!("archive member {raw:?} must be a relative path"))); + } + if raw.chars().any(|c| c <= '\u{1f}' || c == '\u{7f}') { + return Err(ArchiveError::Invalid("archive member names cannot contain control characters".into())); + } + let mut parts = Vec::new(); + for part in raw.split('/') { + if part.is_empty() || part == "." { + continue; + } + if part == ".." { + return Err(ArchiveError::Invalid(format!("archive member {raw:?} cannot contain '..'"))); + } + parts.push(part); + } + let name = parts.join("/"); + if name.len() > MAX_NAME_BYTES || parts.iter().any(|part| part.len() > MAX_COMPONENT_BYTES) { + let preview: String = raw.chars().take(64).collect(); + return Err(ArchiveError::Invalid(format!("archive member {preview:?} has too long a name"))); + } + Ok(name) +} + +/// Validate the whole archive before anything is written (`upload_archive.plan_archive`). +pub fn plan_archive(source: ArchiveSource<'_>, max_bytes: u64) -> Result { + plan_archive_with_limit(source, max_bytes, MAX_ARCHIVE_MEMBERS) +} + +pub fn plan_archive_with_limit( + source: ArchiveSource<'_>, + max_bytes: u64, + max_members: usize, +) -> Result { + let mut files: HashSet = HashSet::new(); + let mut directories: BTreeSet = BTreeSet::new(); + let mut total: u64 = 0; + + for_each_tar_member(source, max_bytes, max_members, |entry, _reader| { + if entry.is_dir { + if !entry.canonical_name.is_empty() { + directories.insert(entry.canonical_name.clone()); + } + return Ok(()); + } + if !entry.is_reg || entry.is_sparse { + let kind = if entry.is_link { "link" } else { "special file" }; + return Err(ArchiveError::Invalid(format!( + "archive member {:?} is a {kind}; only regular files and directories are supported", + entry.raw_name + ))); + } + if entry.canonical_name.is_empty() || !files.insert(entry.canonical_name.clone()) { + return Err(ArchiveError::Invalid(format!( + "archive member {:?} is not a distinct file path", + entry.raw_name + ))); + } + total = total.saturating_add(entry.size); + if total > max_bytes { + return Err(ArchiveError::TooLarge(format!("archive files exceed {max_bytes} bytes"))); + } + Ok(()) + })?; + + let mut parents: HashSet = HashSet::new(); + for name in files.iter().chain(directories.iter()) { + let mut slice = name.as_str(); + while let Some((parent, _)) = slice.rsplit_once('/') { + parents.insert(parent.to_string()); + slice = parent; + } + } + let mut conflicts: Vec<&String> = files + .iter() + .filter(|name| parents.contains(*name) || directories.contains(*name)) + .collect(); + conflicts.sort(); + if let Some(first) = conflicts.first() { + return Err(ArchiveError::Invalid(format!("archive member {:?} is both a file and a directory", first))); + } + let directory_members = directories.len(); + let empty: Vec = directories.into_iter().filter(|dir| !parents.contains(dir)).collect(); + let dir_arg_bytes: usize = empty.iter().map(|name| name.len() + 1).sum(); + if dir_arg_bytes > MAX_DIRECTORY_ARGUMENT_BYTES { + return Err(ArchiveError::Invalid("archive has too many empty directories".into())); + } + Ok(ArchivePlan { + files: files.len(), + directory_members, + total_bytes: total, + empty_directories: empty, + }) +} + +/// Produce a clean plain PAX tar holding only the planned regular files (`upload_archive.normalized_archive`). +pub fn normalized_archive( + source: ArchiveSource<'_>, + plan: &ArchivePlan, + spool: Option<&std::sync::Arc>, + max_bytes: u64, +) -> Result { + let bound = plan + .total_bytes + .saturating_add((plan.files as u64).saturating_mul(2048)) + .saturating_add(2 * RECORDSIZE); + if bound > IN_MEMORY_ARCHIVE_BYTES + && let Some(spool) = spool + { + let mut staged = spool.staging(bound)?; + write_normalized_tar(source, max_bytes, &mut staged.file)?; + staged.file.seek(SeekFrom::Start(0))?; + return Ok(NormalizedArchive::File(staged)); + } + let mut buffer = Vec::with_capacity((bound as usize).min(IN_MEMORY_ARCHIVE_BYTES as usize)); + write_normalized_tar(source, max_bytes, &mut buffer)?; + Ok(NormalizedArchive::Bytes(buffer)) +} + +fn write_normalized_tar(source: ArchiveSource<'_>, max_bytes: u64, writer: &mut W) -> Result<(), ArchiveError> { + for_each_tar_member(source, max_bytes, MAX_ARCHIVE_MEMBERS, |entry, reader| { + if entry.is_reg { + write_pax_regular_file(writer, &entry.canonical_name, entry.mode & 0o777, entry.size, reader)?; + } + Ok(()) + })?; + writer.write_all(&[0u8; BLOCK_SIZE * 2])?; + writer.flush()?; + Ok(()) +} + +// --- Pure POSIX ustar / PAX / GNU-longname tar reader + bounded gzip --- + +struct TarMember { + raw_name: String, + canonical_name: String, + mode: u32, + size: u64, + is_reg: bool, + is_dir: bool, + is_link: bool, + is_sparse: bool, +} + +fn is_gzip(source: &ArchiveSource<'_>) -> Result { + let mut magic = [0u8; 2]; + match source { + ArchiveSource::Bytes(bytes) => Ok(bytes.len() >= 2 && bytes[0] == 0x1f && bytes[1] == 0x8b), + ArchiveSource::File(file) => { + let mut cloned = file.try_clone()?; + cloned.seek(SeekFrom::Start(0))?; + let read = cloned.read(&mut magic)?; + Ok(read == 2 && magic == [0x1f, 0x8b]) + } + } +} + +struct GzipReader { + child: Child, + stdout: Option, + feeder: Option>, + remaining: u64, + finished: bool, +} + +impl GzipReader { + fn open(source: &ArchiveSource<'_>, max_decompressed: u64) -> Result { + let mut command = Command::new("gzip"); + command.arg("-dc").stdout(Stdio::piped()).stderr(Stdio::null()); + let (child, feeder) = match source { + ArchiveSource::File(file) => { + let mut cloned = file.try_clone()?; + cloned.seek(SeekFrom::Start(0))?; + let child = command.stdin(Stdio::from(cloned)).spawn().map_err(|error| { + ArchiveError::Invalid(format!("invalid archive: gzip unavailable: {error}")) + })?; + (child, None) + } + ArchiveSource::Bytes(bytes) => { + let mut child = command.stdin(Stdio::piped()).spawn().map_err(|error| { + ArchiveError::Invalid(format!("invalid archive: gzip unavailable: {error}")) + })?; + let mut stdin = child.stdin.take().expect("piped stdin"); + let owned = bytes.to_vec(); + let handle = std::thread::spawn(move || { + let _ = stdin.write_all(&owned); + let _ = stdin.flush(); + }); + (child, Some(handle)) + } + }; + let mut child = child; + let stdout = child.stdout.take().expect("piped stdout"); + Ok(GzipReader { child, stdout: Some(stdout), feeder, remaining: max_decompressed, finished: false }) + } + + fn finish(mut self) -> Result<(), ArchiveError> { + self.finished = true; + drop(self.stdout.take()); + let status = self.child.wait()?; + if let Some(feeder) = self.feeder.take() { + let _ = feeder.join(); + } + if !status.success() { + return Err(ArchiveError::Invalid("invalid archive: gzip decompression failed".into())); + } + Ok(()) + } +} + +impl Read for GzipReader { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + if buf.is_empty() { + return Ok(0); + } + let Some(stdout) = self.stdout.as_mut() else { + return Ok(0); + }; + let n = stdout.read(buf)?; + if n as u64 > self.remaining { + self.remaining = 0; + return Err(io::Error::new(io::ErrorKind::FileTooLarge, "decompressed archive exceeds size limit")); + } + self.remaining -= n as u64; + Ok(n) + } +} + +impl Drop for GzipReader { + fn drop(&mut self) { + if !self.finished { + let _ = self.child.kill(); + let _ = self.child.wait(); + if let Some(feeder) = self.feeder.take() { + let _ = feeder.join(); + } + } + } +} + +fn for_each_tar_member( + source: ArchiveSource<'_>, + max_bytes: u64, + max_members: usize, + mut visit: impl FnMut(&TarMember, &mut dyn Read) -> Result<(), ArchiveError>, +) -> Result<(), ArchiveError> { + if is_gzip(&source)? { + // Upper bound on decompressed tar bytes for a valid archive of `max_bytes`. + let max_decompressed = max_bytes + .saturating_add((max_members as u64).saturating_mul(MAX_NAME_BYTES as u64 + 1024)) + .saturating_add(4 * 1024 * 1024); + let mut gz = GzipReader::open(&source, max_decompressed)?; + let result = scan_tar(&mut gz, max_members, &mut visit); + let finish_result = gz.finish(); + match (result, finish_result) { + (Err(err), _) => Err(err), + (Ok(()), Err(err)) => Err(err), + (Ok(()), Ok(())) => Ok(()), + } + } else { + match source { + ArchiveSource::Bytes(bytes) => { + let mut cursor = Cursor::new(bytes); + scan_tar(&mut cursor, max_members, &mut visit) + } + ArchiveSource::File(file) => { + let mut cloned = file.try_clone()?; + cloned.seek(SeekFrom::Start(0))?; + let mut reader = io::BufReader::new(cloned); + scan_tar(&mut reader, max_members, &mut visit) + } + } + } +} + +fn read_exact_or_eof(reader: &mut R, buf: &mut [u8]) -> Result { + let mut offset = 0; + while offset < buf.len() { + match reader.read(&mut buf[offset..]) { + Ok(0) => break, + Ok(n) => offset += n, + Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, + Err(error) if error.kind() == io::ErrorKind::FileTooLarge => { + return Err(ArchiveError::TooLarge("archive files exceed allowed size".into())); + } + Err(error) => return Err(ArchiveError::Invalid(format!("invalid archive: {error}"))), + } + } + Ok(offset) +} + +fn skip_exact(reader: &mut R, mut remaining: u64) -> Result<(), ArchiveError> { + let mut scratch = [0u8; 8192]; + while remaining > 0 { + let want = (remaining as usize).min(scratch.len()); + let got = read_exact_or_eof(reader, &mut scratch[..want])?; + if got == 0 { + return Err(ArchiveError::Invalid("invalid archive: unexpected end of data".into())); + } + remaining -= got as u64; + } + Ok(()) +} + +fn parse_tar_number(field: &[u8]) -> Result { + if field.is_empty() { + return Err(ArchiveError::Invalid("invalid archive: empty numeric header field".into())); + } + // GNU base-256 extension (positive values only). + if field[0] & 0x80 != 0 { + if field[0] == 0xff { + return Err(ArchiveError::Invalid("invalid archive: negative base-256 field".into())); + } + let mut value: u64 = u64::from(field[0] & 0x7f); + for &byte in &field[1..] { + value = value + .checked_shl(8) + .ok_or_else(|| ArchiveError::Invalid("invalid archive: numeric header overflow".into()))? + | u64::from(byte); + } + return Ok(value); + } + let trimmed = field + .split(|&b| b == 0) + .next() + .unwrap_or(&[]) + .iter() + .copied() + .skip_while(|&b| b == b' ') + .collect::>(); + let end = trimmed.iter().rposition(|&b| b != b' ').map_or(0, |i| i + 1); + let digits = &trimmed[..end]; + if digits.is_empty() { + return Ok(0); + } + let text = std::str::from_utf8(digits) + .map_err(|_| ArchiveError::Invalid("invalid archive: non-ASCII octal header".into()))?; + u64::from_str_radix(text, 8).map_err(|_| ArchiveError::Invalid("invalid archive: invalid octal header".into())) +} + +fn verify_checksum(header: &[u8; BLOCK_SIZE]) -> Result<(), ArchiveError> { + let expected = parse_tar_number(&header[148..156])?; + let mut unsigned_sum: u64 = 0; + let mut signed_sum: i64 = 0; + for (idx, &byte) in header.iter().enumerate() { + let effective = if (148..156).contains(&idx) { b' ' } else { byte }; + unsigned_sum += u64::from(effective); + signed_sum += i64::from(effective as i8); + } + if expected == unsigned_sum || (signed_sum >= 0 && expected == signed_sum as u64) { + Ok(()) + } else { + Err(ArchiveError::Invalid("invalid archive: bad header checksum".into())) + } +} + +fn cstring_lossy(field: &[u8]) -> Result { + let end = field.iter().position(|&b| b == 0).unwrap_or(field.len()); + String::from_utf8(field[..end].to_vec()) + .map_err(|_| ArchiveError::Invalid("invalid archive: header string is not UTF-8".into())) +} + +#[derive(Default, Clone)] +struct PaxAttrs { + path: Option, + size: Option, + sparse: bool, +} + +fn parse_pax_records(data: &[u8], out: &mut PaxAttrs) -> Result<(), ArchiveError> { + let mut cursor = 0; + while cursor < data.len() { + let rest = &data[cursor..]; + let Some(space) = rest.iter().position(|&b| b == b' ') else { + return Err(ArchiveError::Invalid("invalid archive: malformed PAX header".into())); + }; + let len_str = std::str::from_utf8(&rest[..space]) + .map_err(|_| ArchiveError::Invalid("invalid archive: malformed PAX length".into()))?; + let record_len: usize = len_str + .parse() + .map_err(|_| ArchiveError::Invalid("invalid archive: malformed PAX length".into()))?; + if record_len < space + 2 || cursor + record_len > data.len() || rest[record_len - 1] != b'\n' { + return Err(ArchiveError::Invalid("invalid archive: truncated PAX record".into())); + } + let body = &rest[space + 1..record_len - 1]; + if let Some(eq) = body.iter().position(|&b| b == b'=') { + let key = &body[..eq]; + let val = &body[eq + 1..]; + if key == b"path" { + let text = std::str::from_utf8(val) + .map_err(|_| ArchiveError::Invalid("invalid archive: non-UTF-8 PAX path".into()))?; + out.path = Some(text.to_string()); + } else if key == b"size" { + let text = std::str::from_utf8(val) + .map_err(|_| ArchiveError::Invalid("invalid archive: invalid PAX size".into()))?; + let parsed: u64 = text + .parse() + .map_err(|_| ArchiveError::Invalid("invalid archive: invalid PAX size".into()))?; + out.size = Some(parsed); + } else if key.starts_with(b"GNU.sparse.") { + out.sparse = true; + } + } + cursor += record_len; + } + Ok(()) +} + +fn scan_tar( + reader: &mut R, + max_members: usize, + visit: &mut impl FnMut(&TarMember, &mut dyn Read) -> Result<(), ArchiveError>, +) -> Result<(), ArchiveError> { + let mut header = [0u8; BLOCK_SIZE]; + let mut global_pax = PaxAttrs::default(); + let mut next_pax: Option = None; + let mut next_long_name: Option = None; + let mut seen_any_block = false; + let mut member_count: usize = 0; + + loop { + let got = read_exact_or_eof(reader, &mut header)?; + if got == 0 { + if !seen_any_block { + return Err(ArchiveError::Invalid("invalid archive: empty file".into())); + } + break; + } + if got < BLOCK_SIZE { + return Err(ArchiveError::Invalid("invalid archive: truncated header".into())); + } + seen_any_block = true; + if header.iter().all(|&b| b == 0) { + // End-of-archive zero block; consume the optional second zero block. + let _ = read_exact_or_eof(reader, &mut header)?; + break; + } + verify_checksum(&header)?; + + let typeflag = header[156]; + let header_size = parse_tar_number(&header[124..136])?; + let pad = |size: u64| -> u64 { (BLOCK_SIZE as u64 - (size % BLOCK_SIZE as u64)) % BLOCK_SIZE as u64 }; + + // Extended metadata headers: refuse oversized metadata BEFORE allocating. + if matches!(typeflag, b'x' | b'g' | b'X' | b'L' | b'K') { + if header_size > MAX_METADATA_RECORD_BYTES as u64 { + return Err(ArchiveError::Invalid("invalid archive: archive metadata record is too large".into())); + } + let mut meta = vec![0u8; header_size as usize]; + if read_exact_or_eof(reader, &mut meta)? < meta.len() { + return Err(ArchiveError::Invalid("invalid archive: unexpected end of data".into())); + } + skip_exact(reader, pad(header_size))?; + match typeflag { + b'g' => parse_pax_records(&meta, &mut global_pax)?, + b'x' | b'X' => { + let attrs = next_pax.get_or_insert_with(|| global_pax.clone()); + parse_pax_records(&meta, attrs)?; + } + b'L' => { + let end = meta.iter().rposition(|&b| b != 0).map_or(0, |i| i + 1); + let text = String::from_utf8(meta[..end].to_vec()) + .map_err(|_| ArchiveError::Invalid("invalid archive: non-UTF-8 GNU longname".into()))?; + next_long_name = Some(text); + } + b'K' => {} + _ => unreachable!(), + } + continue; + } + + member_count += 1; + if member_count > max_members { + return Err(ArchiveError::Invalid(format!("archive has more than {max_members} members"))); + } + + let pax = next_pax.take().unwrap_or_else(|| global_pax.clone()); + let long_name = next_long_name.take(); + let raw_name = if let Some(path) = pax.path { + path + } else if let Some(long_name) = long_name { + long_name + } else { + let name = cstring_lossy(&header[0..100])?; + let is_ustar = &header[257..262] == b"ustar"; + let prefix = if is_ustar { cstring_lossy(&header[345..500])? } else { String::new() }; + if prefix.is_empty() { name } else { format!("{prefix}/{name}") } + }; + + let size = pax.size.unwrap_or(header_size); + let mode = parse_tar_number(&header[100..108])? as u32; + let canonical_name = canonical_member_name(&raw_name)?; + let is_dir = typeflag == b'5' || (typeflag == 0 && raw_name.ends_with('/')); + let is_sparse = typeflag == b'S' || pax.sparse; + let is_reg = !is_dir && matches!(typeflag, b'0' | 0 | b'7'); + let is_link = matches!(typeflag, b'1' | b'2'); + let member = TarMember { raw_name, canonical_name, mode, size, is_reg, is_dir, is_link, is_sparse }; + + // Provide a bounded reader over the member's payload and drain any unread bytes + padding. + let mut bounded = ExactReader { inner: reader, remaining: size }; + visit(&member, &mut bounded)?; + let unread = bounded.remaining; + if unread > 0 { + skip_exact(reader, unread)?; + } + skip_exact(reader, pad(size))?; + } + Ok(()) +} + +struct ExactReader<'a, R: Read> { + inner: &'a mut R, + remaining: u64, +} + +impl Read for ExactReader<'_, R> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + if self.remaining == 0 || buf.is_empty() { + return Ok(0); + } + let want = (self.remaining as usize).min(buf.len()); + let got = self.inner.read(&mut buf[..want])?; + if got == 0 { + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "unexpected end of tar member")); + } + self.remaining -= got as u64; + Ok(got) + } +} + +// --- Pure PAX tar writer --- + +fn format_pax_record(key: &str, value: &str) -> Vec { + // Format: " =\n" where includes its own decimal digits. + let suffix_len = 1 + key.len() + 1 + value.len() + 1; + let mut digits = 1usize; + loop { + let total = digits + suffix_len; + let actual_digits = total.to_string().len(); + if actual_digits == digits { + return format!("{total} {key}={value}\n").into_bytes(); + } + digits = actual_digits; + } +} + +fn write_tar_header( + writer: &mut impl Write, + name: &str, + mode: u32, + size: u64, + typeflag: u8, +) -> Result<(), ArchiveError> { + let mut header = [0u8; BLOCK_SIZE]; + let name_bytes = name.as_bytes(); + let copy_len = name_bytes.len().min(100); + header[..copy_len].copy_from_slice(&name_bytes[..copy_len]); + let write_octal = |slot: &mut [u8], val: u64| { + let width = slot.len() - 1; + let formatted = format!("{val:0width$o}"); + let bytes = formatted.as_bytes(); + let start = bytes.len().saturating_sub(width); + let len = (bytes.len() - start).min(width); + slot[..len].copy_from_slice(&bytes[start..start + len]); + slot[width] = 0; + }; + write_octal(&mut header[100..108], u64::from(mode & 0o7777)); + write_octal(&mut header[108..116], 0); // uid = 0 + write_octal(&mut header[116..124], 0); // gid = 0 + write_octal(&mut header[124..136], size.min(0o77777777777)); + write_octal(&mut header[136..148], 0); // mtime = 0 + header[148..156].fill(b' '); + header[156] = typeflag; + header[257..263].copy_from_slice(b"ustar\0"); + header[263..265].copy_from_slice(b"00"); + let checksum: u64 = header.iter().map(|&b| u64::from(b)).sum(); + let chk_text = format!("{checksum:06o}\0 "); + header[148..156].copy_from_slice(chk_text.as_bytes()); + writer.write_all(&header)?; + Ok(()) +} + +fn write_pax_regular_file( + writer: &mut impl Write, + name: &str, + mode: u32, + size: u64, + reader: &mut dyn Read, +) -> Result<(), ArchiveError> { + let needs_pax = name.len() > 100 || !name.is_ascii() || size > 0o77777777777; + if needs_pax { + let mut pax_body = Vec::new(); + if name.len() > 100 || !name.is_ascii() { + pax_body.extend_from_slice(&format_pax_record("path", name)); + } + if size > 0o77777777777 { + pax_body.extend_from_slice(&format_pax_record("size", &size.to_string())); + } + write_tar_header(writer, "PaxHeader", 0o644, pax_body.len() as u64, b'x')?; + writer.write_all(&pax_body)?; + let pad = (BLOCK_SIZE - (pax_body.len() % BLOCK_SIZE)) % BLOCK_SIZE; + if pad > 0 { + writer.write_all(&[0u8; BLOCK_SIZE][..pad])?; + } + } + let header_name = if name.len() <= 100 && name.is_ascii() { name } else { &name[..name.len().min(100)] }; + write_tar_header(writer, header_name, mode, size, b'0')?; + let copied = io::copy(reader, writer)?; + if copied != size { + return Err(ArchiveError::Invalid("invalid archive: truncated file payload".into())); + } + let pad = ((BLOCK_SIZE as u64) - (size % BLOCK_SIZE as u64)) % (BLOCK_SIZE as u64); + if pad > 0 { + writer.write_all(&[0u8; BLOCK_SIZE][..pad as usize])?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn build_tar(entries: &[(&str, &[u8], u8, u32)]) -> Vec { + let mut out = Vec::new(); + for &(name, data, typeflag, mode) in entries { + let size = if matches!(typeflag, b'0' | 0 | b'7') { data.len() as u64 } else { 0 }; + write_tar_header(&mut out, name, mode, size, typeflag).unwrap(); + if size > 0 { + out.extend_from_slice(data); + let pad = (BLOCK_SIZE - (data.len() % BLOCK_SIZE)) % BLOCK_SIZE; + out.extend(std::iter::repeat_n(0u8, pad)); + } + } + out.extend_from_slice(&[0u8; BLOCK_SIZE * 2]); + out + } + + fn gzip_bytes(input: &[u8]) -> Vec { + let mut child = Command::new("gzip") + .arg("-c") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + child.stdin.take().unwrap().write_all(input).unwrap(); + let output = child.wait_with_output().unwrap(); + assert!(output.status.success()); + output.stdout + } + + #[test] + fn plans_and_normalizes_plain_and_gzip_archives() { + let tar = build_tar(&[ + ("./", b"", b'5', 0o755), + ("./tools/run.sh", b"#!", b'0', 0o4755), + ("tools", b"", b'5', 0o755), + ("empty//leaf/", b"", b'5', 0o755), + ]); + for payload in [tar.clone(), gzip_bytes(&tar)] { + let plan = plan_archive(ArchiveSource::Bytes(&payload), 1024 * 1024).unwrap(); + assert_eq!( + plan, + ArchivePlan { + files: 1, + directory_members: 2, + total_bytes: 2, + empty_directories: vec!["empty/leaf".into()], + } + ); + let NormalizedArchive::Bytes(normalized) = + normalized_archive(ArchiveSource::Bytes(&payload), &plan, None, 1024 * 1024).unwrap() + else { + panic!("expected in-memory normalized archive"); + }; + let mut seen = Vec::new(); + for_each_tar_member(ArchiveSource::Bytes(&normalized), 1024, 100, |m, r| { + let mut content = Vec::new(); + r.read_to_end(&mut content).unwrap(); + seen.push((m.canonical_name.clone(), m.mode, content)); + Ok(()) + }) + .unwrap(); + assert_eq!(seen, vec![("tools/run.sh".into(), 0o755, b"#!".to_vec())]); + } + } + + #[test] + fn rejects_unsafe_members_and_limits() { + let cases: Vec<(&str, Vec)> = vec![ + ("symlink", build_tar(&[("link", b"", b'2', 0o777)])), + ("hardlink", build_tar(&[("link", b"", b'1', 0o644)])), + ("fifo", build_tar(&[("fifo", b"", b'6', 0o644)])), + ("char", build_tar(&[("tty", b"", b'3', 0o644)])), + ("absolute", build_tar(&[("/etc/passwd", b"x", b'0', 0o644)])), + ("parent", build_tar(&[("a/../../escape", b"x", b'0', 0o644)])), + ("control", build_tar(&[("a\nb", b"x", b'0', 0o644)])), + ("duplicate", build_tar(&[("a", b"x", b'0', 0o644), ("./a", b"y", b'0', 0o644)])), + ("file parent", build_tar(&[("a", b"x", b'0', 0o644), ("a/b", b"y", b'0', 0o644)])), + ("file and dir", build_tar(&[("a", b"x", b'0', 0o644), ("a", b"", b'5', 0o755)])), + ("not a tar", vec![b'x'; 1024]), + ("empty", Vec::new()), + ]; + for (label, bytes) in cases { + let err = plan_archive(ArchiveSource::Bytes(&bytes), 1024).expect_err(label); + assert!(matches!(err, ArchiveError::Invalid(_)), "{label}: {err}"); + } + // Oversized PAX metadata bomb + let mut bomb = Vec::new(); + let pax = format_pax_record("comment", &"x".repeat(70_000)); + write_tar_header(&mut bomb, "PaxHeader", 0o644, pax.len() as u64, b'x').unwrap(); + bomb.extend_from_slice(&pax); + assert!(matches!(plan_archive(ArchiveSource::Bytes(&bomb), 1024), Err(ArchiveError::Invalid(_)))); + // Exceeding max_bytes -> TooLarge + let big = build_tar(&[("a", b"abc", b'0', 0o644), ("b", b"abc", b'0', 0o644)]); + assert!(matches!(plan_archive(ArchiveSource::Bytes(&big), 5), Err(ArchiveError::TooLarge(_)))); + // Exceeding max_members -> Invalid + let many = build_tar(&[("a", b"", b'0', 0o644), ("b", b"", b'0', 0o644), ("c", b"", b'0', 0o644)]); + assert!(matches!(plan_archive_with_limit(ArchiveSource::Bytes(&many), 1024, 2), Err(ArchiveError::Invalid(_)))); + } + + #[test] + fn handles_long_pax_names() { + let long_name = format!("dir/{}/file.txt", "a".repeat(140)); + let mut tar = Vec::new(); + write_pax_regular_file(&mut tar, &long_name, 0o640, 5, &mut Cursor::new(b"hello")).unwrap(); + tar.extend_from_slice(&[0u8; BLOCK_SIZE * 2]); + let plan = plan_archive(ArchiveSource::Bytes(&tar), 1024).unwrap(); + assert_eq!(plan.files, 1); + assert_eq!(plan.total_bytes, 5); + let NormalizedArchive::Bytes(norm) = normalized_archive(ArchiveSource::Bytes(&tar), &plan, None, 1024).unwrap() + else { + panic!(); + }; + let mut found = None; + for_each_tar_member(ArchiveSource::Bytes(&norm), 1024, 10, |m, r| { + let mut body = Vec::new(); + r.read_to_end(&mut body).unwrap(); + found = Some((m.canonical_name.clone(), m.mode, body)); + Ok(()) + }) + .unwrap(); + assert_eq!(found, Some((long_name, 0o640, b"hello".to_vec()))); + } +} diff --git a/runtime/noded/src/warden.rs b/runtime/noded/src/warden.rs index c163387c..60d36df2 100644 --- a/runtime/noded/src/warden.rs +++ b/runtime/noded/src/warden.rs @@ -74,7 +74,6 @@ pub struct WardenConfig { pub memory_root: PathBuf, pub application_memory_root: Option, pub network: String, - pub reflink_memory_restore: bool, pub proc_root: PathBuf, pub command_timeout: Duration, pub stop_timeout: Duration, @@ -115,6 +114,123 @@ impl Warden { &self.journal } + pub fn config(&self) -> &WardenConfig { + &self.config + } + + /// Open a verified pidfd fence against an owned sentry. + pub async fn open_sentry_fence(&self, sandbox: &Sandbox, pid: u32, ticks: u64) -> Result { + let (this, sb) = (self.clone(), sandbox.clone()); + blocking(move || { + runsc::sentry_identity(&this.owner(&sb), pid, Some(ticks))?; + let handle = PidFd::open(&this.config.proc_root, pid, ticks)?; + runsc::sentry_identity(&this.owner(&sb), pid, Some(ticks))?; + Ok(handle) + }) + .await + } + + /// Run `runsc checkpoint --hibernate --image-path= `. + pub async fn checkpoint( + &self, + sandbox: &Sandbox, + mode: MemoryMode, + image_path: &Path, + timeout: Duration, + ) -> Result<(), WardenError> { + let mut argv = self.common(mode)?; + argv.extend([ + "checkpoint".into(), + "--hibernate".into(), + format!("--image-path={}", image_path.display()), + sandbox.container_id.clone(), + ]); + runsc::checked(&argv, timeout).await?; + Ok(()) + } + + /// Run `runsc restore --detach --background --start-paused --image-path=... --bundle=... `, + /// verify the paused sentry identity, and return `(pid, ticks)`. + pub async fn restore_paused( + &self, + sandbox: &Sandbox, + mode: MemoryMode, + image_path: &Path, + timeout: Duration, + ) -> Result<(u32, u64), WardenError> { + let mut argv = self.common(mode)?; + argv.extend([ + "restore".into(), + "--detach".into(), + "--background".into(), + "--start-paused".into(), + format!("--image-path={}", image_path.display()), + format!("--bundle={}", sandbox.bundle.display()), + sandbox.container_id.clone(), + ]); + runsc::checked(&argv, timeout).await?; + let mut state_argv = self.prefix(); + state_argv.extend(["state".into(), sandbox.container_id.clone()]); + let res = runsc::checked(&state_argv, self.config.command_timeout).await?; + let (pid, status) = runsc::parse_state(&res.stdout)?; + if status != "paused" { + return Err(fail(format!("runsc restore candidate was not paused: {status}"))); + } + let (this, sb) = (self.clone(), sandbox.clone()); + let ticks = blocking(move || { + runsc::sentry_identity(&this.owner(&sb), pid, None) + .map_err(|_| fail("cannot read restored sentry process identity")) + }) + .await?; + Ok((pid, ticks)) + } + + /// Resume a paused container and run `/bin/true` readiness exec. + pub async fn resume_and_verify( + &self, + sandbox: &Sandbox, + expected_pid: u32, + expected_ticks: u64, + ) -> Result<(), WardenError> { + let mut resume_argv = self.prefix(); + resume_argv.extend(["resume".into(), sandbox.container_id.clone()]); + runsc::checked(&resume_argv, self.config.command_timeout).await?; + + let mut state_argv = self.prefix(); + state_argv.extend(["state".into(), sandbox.container_id.clone()]); + let res = runsc::checked(&state_argv, self.config.command_timeout).await?; + let (pid, status) = runsc::parse_state(&res.stdout)?; + if pid != expected_pid || status != "running" { + return Err(fail(format!("runtime did not become running (pid={pid}, status={status})"))); + } + let (this, sb) = (self.clone(), sandbox.clone()); + blocking(move || { + runsc::sentry_identity(&this.owner(&sb), pid, Some(expected_ticks)) + .map_err(|_| fail("runtime identity changed while resuming"))?; + Ok(()) + }) + .await?; + + let mut exec_argv = self.prefix(); + exec_argv.extend(["exec".into(), sandbox.container_id.clone(), "/bin/true".into()]); + runsc::checked(&exec_argv, self.config.command_timeout).await?; + Ok(()) + } + + /// Export the container's rootfs upper layer via `runsc tar rootfs-upper --file= `. + pub async fn tar_rootfs_upper(&self, sandbox: &Sandbox, dest: &Path) -> Result { + let mut argv = self.prefix(); + argv.extend([ + "tar".into(), + "rootfs-upper".into(), + format!("--file={}", dest.display()), + sandbox.container_id.clone(), + ]); + runsc::checked(&argv, Duration::from_secs(600)).await?; + let meta = std::fs::metadata(dest)?; + Ok(meta.len()) + } + fn prefix(&self) -> Vec { vec![self.config.runsc.display().to_string(), format!("--root={}", self.config.runtime_root.display())] } @@ -131,8 +247,6 @@ impl Warden { format!("--application-memory-file-dir={}", root.display())]); if mode == MemoryMode::Ram { argv.push("--application-memory-ram-backing=true".into()); - } else if self.config.reflink_memory_restore { - argv.push("--application-memory-reflink-restore=true".into()); } argv.push("--allow-connected-on-save=true".into()); Ok(argv) @@ -315,6 +429,87 @@ impl Warden { Ok(()) } + /// Port of `DirectRunscWarden.delete`: fence the sandbox under its warden + /// flock, terminate any verified live/candidate sentry, remove runsc state, + /// remove the pause marker, and delete the hibernation journal. + pub async fn delete(&self, sandbox: &Sandbox) -> Result<(), WardenError> { + let _lock = self.lock(sandbox).await?; + let journal = self.journal(); + let Some(record) = journal.load(&sandbox.sandbox_id, sandbox.generation)? else { + let _ = std::fs::remove_file( + self.config.runtime_root.join("warden-parked").join(format!("{}.sandbox-{}.json", sandbox.sandbox_id, sandbox.generation)), + ); + return Ok(()); + }; + let state = record.get("state").and_then(Value::as_str).unwrap_or(""); + let authority = record.get("authority").and_then(Value::as_str).unwrap_or(""); + let revision = record.get("revision").and_then(Value::as_i64).unwrap_or(0); + let reaped_capture = state == "hibernating" && authority == "pending"; + let aborted_restore = state == "restoring" + && authority == "artifact" + && record.get("candidate_pid").and_then(Value::as_u64).is_none(); + if reaped_capture || aborted_restore { + if record.get("sentry_pid").and_then(Value::as_u64).is_some() + || record.get("candidate_pid").and_then(Value::as_u64).is_some() + { + return Err(fail("reaped capture still has a runtime identity")); + } + self.delete_runtime(sandbox, false).await?; + } else if !matches!(state, "running" | "parked" | "recovery_required") { + return Err(fail("sandbox transition must be reconciled before deletion")); + } + if matches!(authority, "live" | "candidate") { + let (pid, ticks) = if authority == "live" { + ( + record.get("sentry_pid").and_then(Value::as_u64), + record.get("sentry_start_time_ticks").and_then(Value::as_u64), + ) + } else { + ( + record.get("candidate_pid").and_then(Value::as_u64), + record.get("candidate_start_time_ticks").and_then(Value::as_u64), + ) + }; + let (Some(pid), Some(ticks)) = (pid, ticks) else { + return Err(fail("live delete authority lacks a process identity")); + }; + let proc_root = self.config.proc_root.clone(); + let stop_timeout = self.config.stop_timeout; + let owner_runsc = self.config.runsc.clone(); + let owner_root = self.config.runtime_root.clone(); + let owner_bundle = sandbox.bundle.clone(); + let owner_cid = sandbox.container_id.clone(); + blocking(move || { + let owner = SentryOwner { + proc_root: &proc_root, + runsc: &owner_runsc, + runtime_root: &owner_root, + bundle: &owner_bundle, + container_id: &owner_cid, + }; + if runsc::owned_sentry_ticks(&owner, pid as u32, Some(ticks)).is_ok() { + if let Ok(handle) = PidFd::open(&proc_root, pid as u32, ticks) { + handle.terminate(stop_timeout)?; + } + } + Ok(()) + }) + .await?; + } + self.delete_runtime(sandbox, true).await?; + let pause_marker = self + .config + .runtime_root + .join("warden-paused") + .join(format!("{}.sandbox-{}", sandbox.sandbox_id, sandbox.generation)); + let _ = std::fs::remove_file(&pause_marker); + journal.remove(&sandbox.sandbox_id, sandbox.generation, revision)?; + let _ = std::fs::remove_file( + self.config.runtime_root.join("warden-parked").join(format!("{}.sandbox-{}.json", sandbox.sandbox_id, sandbox.generation)), + ); + Ok(()) + } + async fn runtime_absent(&self, sandbox: &Sandbox) -> bool { let mut argv = self.prefix(); argv.extend(["list".into(), "--format=json".into()]); diff --git a/runtime/noded/tests/control_routes.rs b/runtime/noded/tests/control_routes.rs new file mode 100644 index 00000000..62f1ac40 --- /dev/null +++ b/runtime/noded/tests/control_routes.rs @@ -0,0 +1,375 @@ +//! HTTP integration tests for `ControlFront` (`GET /v1/sandboxes` and +//! `DELETE /v1/sandboxes/{id}`) and Rust teardown primitives (`ExecFence`, +//! `JournalStore::remove`, `MemoryBackingStore::delete`). + +use std::collections::HashMap; +use std::fs::OpenOptions; +use std::os::fd::AsRawFd; +use std::os::unix::fs::OpenOptionsExt; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; + +use bytes::Bytes; +use http_body_util::{BodyExt, Full}; +use hyper::client::conn::http1; +use hyper::header; +use hyper::{Method, Request, Response, StatusCode}; +use hyper_util::rt::TokioIo; +use serde_json::{Value, json}; +use tokio::net::{TcpListener, TcpStream, UnixListener}; +use tokio::sync::oneshot; + +use ucloud_noded::control_front::{BoxFuture, ControlFront, ControlNode, DeleteOutcome, ListOutcome}; +use ucloud_noded::exec_fence::{ExecFence, Fenced}; +use ucloud_noded::journal::JournalStore; +use ucloud_noded::memory_backing::{MemoryBackingConfig, MemoryBackingError, MemoryBackingRef, MemoryBackingStore, MemoryQuota}; +use ucloud_noded::{Config, Fronts, serve_with}; + +const TOKEN: &str = "test-control-token"; + +struct FakeControlNode { + sandboxes: Mutex>, + force_busy: Mutex, + force_forward_list: Mutex, +} + +impl FakeControlNode { + fn new() -> Arc { + Arc::new(FakeControlNode { + sandboxes: Mutex::new(HashMap::new()), + force_busy: Mutex::new(false), + force_forward_list: Mutex::new(false), + }) + } + + fn insert(&self, id: &str, generation: i64, state: &str) { + self.sandboxes.lock().unwrap().insert( + id.to_string(), + ( + generation, + json!({ + "id": id, + "generation": generation, + "state": state, + }), + ), + ); + } +} + +impl ControlNode for FakeControlNode { + fn ready(&self) -> bool { + true + } + + fn list_sandboxes(&self) -> BoxFuture { + if *self.force_forward_list.lock().unwrap() { + return Box::pin(async { ListOutcome::Forward("parked") }); + } + let mut items: Vec<(String, Value)> = self + .sandboxes + .lock() + .unwrap() + .iter() + .map(|(k, (_, v))| (k.clone(), v.clone())) + .collect(); + items.sort_by(|a, b| a.0.cmp(&b.0)); + let values = items.into_iter().map(|(_, v)| v).collect(); + Box::pin(async move { ListOutcome::Sandboxes(values) }) + } + + fn get_sandbox(&self, _sandbox_id: &str) -> BoxFuture { + Box::pin(async { ListOutcome::Forward("recovery confirmation") }) + } + + fn delete_sandbox(&self, sandbox_id: &str, generation: i64) -> BoxFuture { + if *self.force_busy.lock().unwrap() { + return Box::pin(async { + DeleteOutcome::Busy("sandbox memory publication is still draining; retry the delete".into()) + }); + } + let mut map = self.sandboxes.lock().unwrap(); + let outcome = match map.get(sandbox_id) { + None => DeleteOutcome::Deleted(None), + Some((current_gen, _)) if *current_gen != generation => { + DeleteOutcome::Conflict("delete generation does not own direct sandbox".into()) + } + Some(_) => { + let (_, val) = map.remove(sandbox_id).unwrap(); + DeleteOutcome::Deleted(Some(val)) + } + }; + Box::pin(async move { outcome }) + } +} + +fn temp_dir(label: &str) -> PathBuf { + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir().join(format!( + "noded-control-routes-{label}-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)).unwrap(); + dir +} + +async fn start_upstream(sock: PathBuf) -> (Arc>>, oneshot::Sender<()>) { + let _ = std::fs::remove_file(&sock); + let listener = UnixListener::bind(&sock).unwrap(); + let seen = Arc::new(Mutex::new(Vec::new())); + let seen_clone = seen.clone(); + let (stop_tx, mut stop_rx) = oneshot::channel::<()>(); + tokio::spawn(async move { + loop { + let stream = tokio::select! { + accepted = listener.accept() => match accepted { + Ok((stream, _)) => stream, + Err(_) => break, + }, + _ = &mut stop_rx => break, + }; + let seen = seen_clone.clone(); + tokio::spawn(async move { + let service = hyper::service::service_fn(move |req: Request| { + let seen = seen.clone(); + async move { + seen.lock().unwrap().push((req.method().to_string(), req.uri().to_string())); + let mut resp = Response::new( + Full::new(Bytes::from_static(b"{\"forwarded\":true}")) + .map_err(|never| match never {}) + .boxed(), + ); + *resp.status_mut() = StatusCode::OK; + resp.headers_mut() + .insert(header::CONTENT_TYPE, header::HeaderValue::from_static("application/json")); + Ok::<_, hyper::Error>(resp) + } + }); + let _ = hyper::server::conn::http1::Builder::new().serve_connection(TokioIo::new(stream), service).await; + }); + } + }); + (seen, stop_tx) +} + +async fn send( + addr: std::net::SocketAddr, + method: Method, + uri: &str, + headers: &[(&str, &str)], +) -> (StatusCode, Value) { + let stream = TcpStream::connect(addr).await.unwrap(); + let (mut sender, conn) = http1::handshake(TokioIo::new(stream)).await.unwrap(); + tokio::spawn(async move { + let _ = conn.await; + }); + let mut builder = Request::builder().method(method).uri(uri).header(header::HOST, "127.0.0.1"); + for (k, v) in headers { + builder = builder.header(*k, *v); + } + let req = builder.body(Full::new(Bytes::new()).map_err(|never| match never {}).boxed()).unwrap(); + let resp = sender.send_request(req).await.unwrap(); + let status = resp.status(); + let bytes = resp.into_body().collect().await.unwrap().to_bytes(); + let json = serde_json::from_slice(&bytes).unwrap(); + (status, json) +} + +#[tokio::test] +async fn list_and_delete_routes_match_node_agent_contract() { + let dir = temp_dir("http"); + let sock = dir.join("agent.sock"); + let (forwarded, stop_up) = start_upstream(sock.clone()).await; + let node = FakeControlNode::new(); + node.insert("b-box", 1, "running"); + node.insert("a-box", 2, "running"); + + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let fronts = Fronts { + control: Some(ControlFront::with_node(node.clone(), TOKEN)), + ..Fronts::default() + }; + let (stop_tx, stop_rx) = oneshot::channel::<()>(); + tokio::spawn(async move { + serve_with(listener, Config::new(sock), fronts, async move { + let _ = stop_rx.await; + }) + .await; + }); + + let auth = format!("Bearer {TOKEN}"); + let hdrs = [("authorization", auth.as_str())]; + + // 1. GET /v1/sandboxes returns sorted list directly without forwarding. + let (status, body) = send(addr, Method::GET, "/v1/sandboxes", &hdrs).await; + assert_eq!(status, StatusCode::OK); + let ids: Vec<&str> = body["sandboxes"].as_array().unwrap().iter().map(|s| s["id"].as_str().unwrap()).collect(); + assert_eq!(ids, vec!["a-box", "b-box"]); + assert!(forwarded.lock().unwrap().is_empty()); + + // 2. GET /v1/sandboxes?sandbox_id=a-box forwards to upstream (recovery confirmation). + let (status, body) = send(addr, Method::GET, "/v1/sandboxes?sandbox_id=a-box", &hdrs).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["forwarded"], true); + assert_eq!(forwarded.lock().unwrap().len(), 1); + + // 3. DELETE missing headers -> 400 + let (status, _) = send(addr, Method::DELETE, "/v1/sandboxes/a-box", &hdrs).await; + assert_eq!(status, StatusCode::BAD_REQUEST); + + // 4. DELETE wrong generation -> 409 + let (status, _) = send( + addr, + Method::DELETE, + "/v1/sandboxes/a-box", + &[ + ("authorization", auth.as_str()), + ("x-ucloud-sandbox-generation", "9"), + ("x-ucloud-sandbox-operation-id", "del-op-1"), + ], + ) + .await; + assert_eq!(status, StatusCode::CONFLICT); + + // 5. DELETE matching generation -> 200 with deleted record, second call -> 200 {"deleted": null} + let del_hdrs = [ + ("authorization", auth.as_str()), + ("x-ucloud-sandbox-generation", "2"), + ("x-ucloud-sandbox-operation-id", "del-op-1"), + ]; + let (status, body) = send(addr, Method::DELETE, "/v1/sandboxes/a-box", &del_hdrs).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["deleted"]["id"], "a-box"); + + let (status, body) = send(addr, Method::DELETE, "/v1/sandboxes/a-box", &del_hdrs).await; + assert_eq!(status, StatusCode::OK); + assert!(body["deleted"].is_null()); + + // 6. Memory publication draining -> 503 memory_publication_draining + *node.force_busy.lock().unwrap() = true; + let (status, body) = send( + addr, + Method::DELETE, + "/v1/sandboxes/b-box", + &[ + ("authorization", auth.as_str()), + ("x-ucloud-sandbox-generation", "1"), + ("x-ucloud-sandbox-operation-id", "del-op-2"), + ], + ) + .await; + assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE); + assert_eq!(body["error_code"], "memory_publication_draining"); + assert_eq!(body["retryable"], true); + + let _ = stop_tx.send(()); + let _ = stop_up.send(()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn exec_fence_transition_excludes_execs_and_discard_cleans_files() { + let dir = temp_dir("fence"); + let fence = ExecFence::new(&dir); + let guard = fence.acquire_transition("sb-del").unwrap(); + assert!(matches!(fence.acquire("sb-del").unwrap(), Fenced::Busy)); + guard.discard(); + assert!(!dir.join(".sb-del.transition").exists()); + assert!(!dir.join(".sb-del.activity").exists()); + assert!(matches!(fence.acquire("sb-del").unwrap(), Fenced::Held(_))); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn journal_remove_checks_revision_and_deletes_file() { + let dir = temp_dir("journal"); + let store = JournalStore::new(&dir); + let sha = "a".repeat(64); + store.initialize_running("sb-1", 1, &sha, "op-1", 1234, 5678).unwrap(); + assert!(store.remove("sb-1", 1, 99).is_err()); + assert!(store.load("sb-1", 1).unwrap().is_some()); + store.remove("sb-1", 1, 0).unwrap(); + assert!(store.load("sb-1", 1).unwrap().is_none()); + let _ = std::fs::remove_dir_all(&dir); +} + +struct TestQuota { + released: Arc>>, +} + +impl MemoryQuota for TestQuota { + fn validate_root(&mut self, _root: &Path) -> ucloud_noded::memory_backing::Result<()> { + Ok(()) + } + fn validate_active_root(&self, _active_root: &Path, _ram_swappable: bool) -> ucloud_noded::memory_backing::Result<()> { + Ok(()) + } + fn provision(&self, _path: &Path, _project_id: i64, _limit_bytes: i64) -> ucloud_noded::memory_backing::Result<()> { + Ok(()) + } + fn validate_project(&self, _path: &Path, _project_id: i64) -> ucloud_noded::memory_backing::Result<()> { + Ok(()) + } + fn release(&self, _root: &Path, project_id: i64) -> ucloud_noded::memory_backing::Result<()> { + self.released.lock().unwrap().push(project_id); + Ok(()) + } +} + +#[test] +fn memory_backing_delete_respects_publication_flock_and_reclaims_storage() { + let dir = temp_dir("memdel"); + let root = dir.join("disk"); + let ram = dir.join("ram"); + std::fs::create_dir_all(&ram).unwrap(); + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&ram, std::fs::Permissions::from_mode(0o700)).unwrap(); + + let released = Arc::new(Mutex::new(Vec::new())); + let store = MemoryBackingStore::open( + MemoryBackingConfig { + root: root.clone(), + journal: dir.join("memory.sqlite"), + hard_capacity_bytes: 16 * 1024 * 1024, + active_root: Some(ram.clone()), + ram_swappable: true, + }, + Box::new(TestQuota { released: released.clone() }), + ) + .unwrap(); + + let reference = MemoryBackingRef::new("sb-1.sandbox-1", 4 * 1024 * 1024).unwrap(); + let lease = store.prepare(&reference, "sb-1", 1, None).unwrap(); + assert!(root.join("sb-1.sandbox-1").exists()); + assert!(ram.join("sb-1.sandbox-1").exists()); + + // Simulate an active publisher holding a shared flock on the allocation lease file. + let lease_file = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .mode(0o600) + .open(store.lease_root().join("sb-1.sandbox-1")) + .unwrap(); + assert_eq!(unsafe { libc::flock(lease_file.as_raw_fd(), libc::LOCK_SH | libc::LOCK_NB) }, 0); + + let err = store.delete(&reference, "sb-1", 1).unwrap_err(); + assert!(matches!(err, MemoryBackingError::Busy(_))); + drop(lease_file); + + // Retry after publisher finishes succeeds, removes both dirs, and releases project quota. + store.delete(&reference, "sb-1", 1).unwrap(); + assert!(!root.join("sb-1.sandbox-1").exists()); + assert!(!ram.join("sb-1.sandbox-1").exists()); + assert_eq!(*released.lock().unwrap(), vec![lease.project_id]); + assert!(store.active_mode("sb-1", 1).is_none()); + + // Idempotent second delete succeeds. + store.delete(&reference, "sb-1", 1).unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/runtime/noded/tests/create_admission.rs b/runtime/noded/tests/create_admission.rs index 6fa02739..84eb7c28 100644 --- a/runtime/noded/tests/create_admission.rs +++ b/runtime/noded/tests/create_admission.rs @@ -161,7 +161,7 @@ async fn start() -> Harness { let front = Arc::new(CreateFront::new(client, Arc::new(AdmittingPipeline(service.clone())), TOKEN)); let tcp = ucloud_noded::listen("127.0.0.1:0".parse().unwrap()).unwrap(); let address = tcp.local_addr().unwrap(); - let fronts = ucloud_noded::Fronts { create: Some(front), exec: None, jobs: None, node: None, internal: None }; + let fronts = ucloud_noded::Fronts { create: Some(front), ..Default::default() }; tokio::spawn(ucloud_noded::serve_with(tcp, ucloud_noded::Config::new(socket), fronts, std::future::pending())); Harness { address, seen, service, _dir: dir } } diff --git a/runtime/noded/tests/create_front.rs b/runtime/noded/tests/create_front.rs index 3c374e9d..55f40e97 100644 --- a/runtime/noded/tests/create_front.rs +++ b/runtime/noded/tests/create_front.rs @@ -145,7 +145,7 @@ async fn start() -> Harness { let front = Arc::new(CreateFront::new(client, Arc::new(FakePipeline), TOKEN)); let tcp = ucloud_noded::listen("127.0.0.1:0".parse().unwrap()).unwrap(); let address = tcp.local_addr().unwrap(); - let fronts = ucloud_noded::Fronts { create: Some(front), exec: None, jobs: None, node: None, internal: None }; + let fronts = ucloud_noded::Fronts { create: Some(front), ..Default::default() }; tokio::spawn(ucloud_noded::serve_with(tcp, ucloud_noded::Config::new(socket), fronts, std::future::pending())); Harness { address, seen, _dir: dir } } diff --git a/runtime/noded/tests/file_routes.rs b/runtime/noded/tests/file_routes.rs new file mode 100644 index 00000000..8b632cd9 --- /dev/null +++ b/runtime/noded/tests/file_routes.rs @@ -0,0 +1,488 @@ +//! HTTP integration tests for `FilesFront`: file upload/download, archive +//! upload/validation/spooling, and environment description through `serve_with`. + +use std::collections::HashMap; +use std::io::Read; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use bytes::Bytes; +use http_body_util::{BodyExt, Full}; +use hyper::client::conn::http1; +use hyper::header; +use hyper::{Method, Request, Response, StatusCode}; +use hyper_util::rt::TokioIo; +use serde_json::{Value, json}; +use tokio::net::{TcpListener, TcpStream, UnixListener}; +use tokio::sync::oneshot; + +use ucloud_noded::files_front::{ + BoxFuture, ExecStdin, FileExecError, FileExecResult, FileLookup, FileNode, FileTarget, FilesFront, run_bounded_exec, +}; +use ucloud_noded::registry::SandboxSpec; +use ucloud_noded::upload_archive::{TRANSFER_CHUNK_BYTES, UploadSpool}; +use ucloud_noded::{Config, Fronts, serve_with}; + +const TOKEN: &str = "test-file-token"; + +#[derive(Clone)] +struct RecordedCall { + sandbox_id: String, + expected_generation: i64, + argv: Vec, + stdin: Vec, + from_file: bool, +} + +struct FakeFileNode { + targets: Mutex>, + calls: Mutex>, + next_result: Mutex>>, + max_file_body_bytes: u64, + spool: Arc, +} + +impl FakeFileNode { + fn new(spool_dir: PathBuf, max_file_body_bytes: u64) -> Arc { + Arc::new(FakeFileNode { + targets: Mutex::new(HashMap::new()), + calls: Mutex::new(Vec::new()), + next_result: Mutex::new(None), + max_file_body_bytes, + spool: Arc::new(UploadSpool::with_min_free(spool_dir, 0)), + }) + } + + fn insert(&self, id: &str, generation: i64, static_helper: bool, running: bool) { + let mut raw = json!({ + "id": id, + "image": "alpine:latest", + "cpus": 1.0, + "memory_mb": 512, + "disk_mb": 1024, + "network": "bridge", + }); + if static_helper { + raw["filesystem"] = json!({"management_helper": "static"}); + } + let spec = SandboxSpec::from_dict(&raw).unwrap(); + let target = FileTarget { + sandbox_id: id.to_string(), + generation, + container_id: format!("ctr-{id}-{generation}"), + bundle: PathBuf::from(format!("/tmp/bundle-{id}")), + memory_directory: String::new(), + spec_sha256: spec.sha256(), + spec, + static_helper, + running, + admission_open: true, + memory_floor_ok: true, + }; + self.targets.lock().unwrap().insert(id.to_string(), target); + } + + fn set_next(&self, res: Result) { + *self.next_result.lock().unwrap() = Some(res); + } + + fn calls(&self) -> Vec { + self.calls.lock().unwrap().clone() + } +} + +impl FileNode for FakeFileNode { + fn ready(&self) -> bool { + true + } + + fn max_file_body_bytes(&self) -> u64 { + self.max_file_body_bytes + } + + fn max_read_concurrency(&self) -> usize { + 4 + } + + fn admission_wait(&self) -> Duration { + Duration::from_secs(5) + } + + fn upload_spool(&self) -> Option> { + Some(self.spool.clone()) + } + + fn lookup(&self, sandbox_id: &str) -> BoxFuture { + let found = self.targets.lock().unwrap().get(sandbox_id).cloned(); + Box::pin(async move { + match found { + Some(target) => FileLookup::Owned(target), + None => FileLookup::NotFound, + } + }) + } + + fn exec_file( + &self, + target: &FileTarget, + expected_generation: i64, + argv: Vec, + stdin: ExecStdin, + _max_stdout: usize, + _max_stderr: usize, + ) -> BoxFuture> { + let (bytes, from_file) = match stdin { + ExecStdin::None => (Vec::new(), false), + ExecStdin::Bytes(b) => (b.to_vec(), false), + ExecStdin::File(mut f) => { + let mut buf = Vec::new(); + f.read_to_end(&mut buf).unwrap(); + (buf, true) + } + }; + self.calls.lock().unwrap().push(RecordedCall { + sandbox_id: target.sandbox_id.clone(), + expected_generation, + argv, + stdin: bytes, + from_file, + }); + let outcome = self + .next_result + .lock() + .unwrap() + .take() + .unwrap_or_else(|| Ok(FileExecResult { exit_code: 0, stdout: b"ok-content".to_vec(), stderr: Vec::new() })); + Box::pin(async move { outcome }) + } +} + +fn temp_dir(label: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "noded-file-routes-{label}-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// Starts a fake Python upstream Unix socket that records forwarded requests. +async fn start_upstream(sock: PathBuf) -> (Arc)>>>, oneshot::Sender<()>) { + let _ = std::fs::remove_file(&sock); + let listener = UnixListener::bind(&sock).unwrap(); + let seen = Arc::new(Mutex::new(Vec::new())); + let seen_clone = seen.clone(); + let (stop_tx, mut stop_rx) = oneshot::channel::<()>(); + tokio::spawn(async move { + loop { + let stream = tokio::select! { + accepted = listener.accept() => match accepted { + Ok((stream, _)) => stream, + Err(_) => break, + }, + _ = &mut stop_rx => break, + }; + let seen = seen_clone.clone(); + tokio::spawn(async move { + let service = hyper::service::service_fn(move |req: Request| { + let seen = seen.clone(); + async move { + let method = req.method().to_string(); + let uri = req.uri().to_string(); + let body = req.into_body().collect().await.unwrap().to_bytes().to_vec(); + seen.lock().unwrap().push((method, uri, body)); + let mut resp = Response::new( + Full::new(Bytes::from_static(b"{\"forwarded\":true}")) + .map_err(|never| match never {}) + .boxed(), + ); + *resp.status_mut() = StatusCode::OK; + resp.headers_mut() + .insert(header::CONTENT_TYPE, header::HeaderValue::from_static("application/json")); + Ok::<_, hyper::Error>(resp) + } + }); + let _ = hyper::server::conn::http1::Builder::new().serve_connection(TokioIo::new(stream), service).await; + }); + } + }); + (seen, stop_tx) +} + +async fn start_server( + node: Arc, +) -> ( + std::net::SocketAddr, + Arc)>>>, + oneshot::Sender<()>, + oneshot::Sender<()>, + PathBuf, +) { + let dir = temp_dir("srv"); + let sock = dir.join("agent.sock"); + let (forwarded, stop_up) = start_upstream(sock.clone()).await; + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let fronts = Fronts { + files: Some(FilesFront::with_node(node, TOKEN)), + ..Fronts::default() + }; + let (stop_tx, stop_rx) = oneshot::channel::<()>(); + let cfg = Config::new(sock); + tokio::spawn(async move { + serve_with(listener, cfg, fronts, async move { + let _ = stop_rx.await; + }) + .await; + }); + (addr, forwarded, stop_tx, stop_up, dir) +} + +async fn send( + addr: std::net::SocketAddr, + method: Method, + uri: &str, + headers: &[(&str, &str)], + body: Vec, +) -> (StatusCode, hyper::HeaderMap, Vec) { + let stream = TcpStream::connect(addr).await.unwrap(); + let (mut sender, conn) = http1::handshake(TokioIo::new(stream)).await.unwrap(); + tokio::spawn(async move { + let _ = conn.await; + }); + let mut builder = Request::builder().method(method).uri(uri); + builder = builder.header(header::HOST, "127.0.0.1"); + builder = builder.header(header::CONTENT_LENGTH, body.len().to_string()); + for (k, v) in headers { + builder = builder.header(*k, *v); + } + let req = builder + .body(Full::new(Bytes::from(body)).map_err(|never| match never {}).boxed()) + .unwrap(); + let resp = sender.send_request(req).await.unwrap(); + let status = resp.status(); + let resp_headers = resp.headers().clone(); + let bytes = resp.into_body().collect().await.unwrap().to_bytes().to_vec(); + (status, resp_headers, bytes) +} + +fn auth() -> (&'static str, String) { + ("authorization", format!("Bearer {TOKEN}")) +} + +fn make_simple_tar(entries: &[(&str, &[u8], u8, u32)]) -> Vec { + let mut out = Vec::new(); + for &(name, data, typeflag, mode) in entries { + let mut hdr = [0u8; 512]; + hdr[..name.len()].copy_from_slice(name.as_bytes()); + let write_oct = |slot: &mut [u8], val: u64| { + let w = slot.len() - 1; + let s = format!("{val:0w$o}"); + slot[..w].copy_from_slice(s.as_bytes()); + }; + let size = if typeflag == b'0' { data.len() as u64 } else { 0 }; + write_oct(&mut hdr[100..108], u64::from(mode)); + write_oct(&mut hdr[108..116], 0); + write_oct(&mut hdr[116..124], 0); + write_oct(&mut hdr[124..136], size); + write_oct(&mut hdr[136..148], 0); + hdr[148..156].fill(b' '); + hdr[156] = typeflag; + hdr[257..263].copy_from_slice(b"ustar\0"); + hdr[263..265].copy_from_slice(b"00"); + let sum: u64 = hdr.iter().map(|&b| u64::from(b)).sum(); + hdr[148..156].copy_from_slice(format!("{sum:06o}\0 ").as_bytes()); + out.extend_from_slice(&hdr); + if size > 0 { + out.extend_from_slice(data); + let pad = (512 - (data.len() % 512)) % 512; + out.extend(std::iter::repeat_n(0u8, pad)); + } + } + out.extend_from_slice(&[0u8; 1024]); + out +} + +#[tokio::test] +async fn environment_download_and_upload_routes_match_contract() { + let spool_dir = temp_dir("spool"); + let node = FakeFileNode::new(spool_dir.clone(), 4 * 1024 * 1024); + node.insert("shell-1", 1, false, true); + node.insert("static-1", 3, true, true); + node.insert("parked-1", 2, false, false); + let (addr, forwarded, stop_srv, stop_up, srv_dir) = start_server(node.clone()).await; + let (_, auth_val) = auth(); + let hdrs = [("authorization", auth_val.as_str())]; + + // 1. GET /environment (owned + not found) + let (status, _, body) = send(addr, Method::GET, "/v1/sandboxes/static-1/environment", &hdrs, vec![]).await; + assert_eq!(status, StatusCode::OK); + let parsed: Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(parsed["environment"]["configured"]["management_helper"], "static"); + assert_eq!(parsed["environment"]["backend"], "gvisor"); + + let (status, _, _) = send(addr, Method::GET, "/v1/sandboxes/missing/environment", &hdrs, vec![]).await; + assert_eq!(status, StatusCode::NOT_FOUND); + + // 2. PUT /files small (in-memory) on shell and static helpers + let (status, _, body) = send( + addr, + Method::PUT, + "/v1/sandboxes/shell-1/files?path=%2Fwork%2Fa.txt", + &hdrs, + b"hello".to_vec(), + ) + .await; + assert_eq!(status, StatusCode::OK); + let parsed: Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(parsed, json!({"ok": true, "sandbox_id": "shell-1", "path": "/work/a.txt", "size": 5})); + let call = node.calls().pop().unwrap(); + assert_eq!(call.sandbox_id, "shell-1"); + assert_eq!(call.expected_generation, 1); + assert_eq!(call.argv[0], "/bin/sh"); + assert_eq!(call.argv.last().unwrap(), "/work/a.txt"); + assert_eq!(call.stdin, b"hello"); + assert!(!call.from_file); + + let (status, _, _) = send( + addr, + Method::PUT, + "/v1/sandboxes/static-1/files?path=/work/b.txt", + &[("authorization", auth_val.as_str()), ("x-ucloud-sandbox-generation", "3")], + b"data".to_vec(), + ) + .await; + assert_eq!(status, StatusCode::OK); + let call = node.calls().pop().unwrap(); + assert_eq!(call.argv, vec!["/.ucloud-job-init", "files", "write", "/work/b.txt", "4"]); + + // Generation mismatch -> 409 without calling exec_file + let before = node.calls().len(); + let (status, _, _) = send( + addr, + Method::PUT, + "/v1/sandboxes/static-1/files?path=/work/b.txt", + &[("authorization", auth_val.as_str()), ("x-ucloud-sandbox-generation", "99")], + b"data".to_vec(), + ) + .await; + assert_eq!(status, StatusCode::CONFLICT); + assert_eq!(node.calls().len(), before); + + // 3. PUT /files large (> 64 KiB) spools to unlinked disk file and cleans up reservation + let large = vec![0x42u8; TRANSFER_CHUNK_BYTES + 1234]; + let (status, _, body) = send( + addr, + Method::PUT, + "/v1/sandboxes/shell-1/files?path=/work/big.bin", + &hdrs, + large.clone(), + ) + .await; + assert_eq!(status, StatusCode::OK); + let parsed: Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(parsed["size"], large.len()); + let call = node.calls().pop().unwrap(); + assert!(call.from_file); + assert_eq!(call.stdin, large); + assert_eq!(node.spool.unwritten_bytes(), 0); + assert_eq!(std::fs::read_dir(&spool_dir).unwrap().count(), 0); + + // 4. GET /files returns raw bytes + headers + node.set_next(Ok(FileExecResult { exit_code: 0, stdout: b"file-payload".to_vec(), stderr: vec![] })); + let (status, resp_hdrs, body) = + send(addr, Method::GET, "/v1/sandboxes/static-1/files?path=%2Fwork%2Fb.txt", &hdrs, vec![]).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body, b"file-payload"); + assert_eq!(resp_hdrs.get("x-sandbox-id").unwrap(), "static-1"); + assert_eq!(resp_hdrs.get("x-sandbox-path").unwrap(), "/work/b.txt"); + let call = node.calls().pop().unwrap(); + assert_eq!(call.argv, vec!["/.ucloud-job-init", "files", "read", "/work/b.txt", "4194304"]); + + // 5. Parked sandbox forwards untouched to upstream agent (including upload body!) + let (status, _, body) = send( + addr, + Method::PUT, + "/v1/sandboxes/parked-1/files?path=/work/p.txt", + &hdrs, + b"wake-me".to_vec(), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body, b"{\"forwarded\":true}"); + let fwd = forwarded.lock().unwrap(); + assert_eq!(fwd.len(), 1); + assert_eq!(fwd[0].0, "PUT"); + assert_eq!(fwd[0].2, b"wake-me"); + drop(fwd); + + // 6. PUT /archive validates, normalizes, and reports counts; rejects unsafe and unsupported tar + let tar = make_simple_tar(&[ + ("a.py", b"a", b'0', 0o644), + ("empty/", b"", b'5', 0o755), + ("bin/x", b"#!", b'0', 0o755), + ]); + let (status, _, body) = + send(addr, Method::PUT, "/v1/sandboxes/shell-1/archive?path=/work", &hdrs, tar.clone()).await; + assert_eq!(status, StatusCode::OK); + let parsed: Value = serde_json::from_slice(&body).unwrap(); + assert_eq!( + parsed, + json!({ + "ok": true, + "sandbox_id": "shell-1", + "path": "/work", + "size": tar.len(), + "files": 2, + "directories": 1, + "bytes": 3, + }) + ); + let call = node.calls().pop().unwrap(); + assert_eq!(call.argv.last().unwrap(), "empty"); + + // Unsafe archive (symlink) -> 400 without calling exec_file + let before = node.calls().len(); + let bad = make_simple_tar(&[("link", b"", b'2', 0o777)]); + let (status, _, _) = send(addr, Method::PUT, "/v1/sandboxes/shell-1/archive?path=/work", &hdrs, bad).await; + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!(node.calls().len(), before); + + // Shell helper missing tar (exit 69) -> 501 archive_upload_unsupported + node.set_next(Ok(FileExecResult { exit_code: 69, stdout: vec![], stderr: b"tar is unavailable\n".to_vec() })); + let (status, _, body) = send(addr, Method::PUT, "/v1/sandboxes/shell-1/archive?path=/work", &hdrs, tar).await; + assert_eq!(status, StatusCode::NOT_IMPLEMENTED); + let parsed: Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(parsed["error_code"], "archive_upload_unsupported"); + + let _ = stop_srv.send(()); + let _ = stop_up.send(()); + let _ = std::fs::remove_dir_all(&spool_dir); + let _ = std::fs::remove_dir_all(&srv_dir); +} + +#[tokio::test] +async fn run_bounded_exec_streams_stdin_and_enforces_output_limits() { + let ok = run_bounded_exec( + &["/bin/cat".into()], + ExecStdin::Bytes(Bytes::from_static(b"hello bounded world")), + 1024, + 1024, + ) + .await + .unwrap(); + assert_eq!(ok.exit_code, 0); + assert_eq!(ok.stdout, b"hello bounded world"); + + let too_big = run_bounded_exec( + &["/bin/sh".into(), "-c".into(), "head -c 4096 /dev/zero".into()], + ExecStdin::None, + 512, + 1024, + ) + .await; + assert!(matches!(too_big, Err(FileExecError::OutputTooLarge(_)))); +} diff --git a/runtime/noded/tests/heartbeat_routes.rs b/runtime/noded/tests/heartbeat_routes.rs new file mode 100644 index 00000000..f40c3554 --- /dev/null +++ b/runtime/noded/tests/heartbeat_routes.rs @@ -0,0 +1,202 @@ +//! HTTP integration tests for `HeartbeatFront` (`/healthz`, `/v1/heartbeat`, +//! `/v1/drain`) and `HeartbeatPusher`. + +use std::collections::BTreeMap; +use std::path::PathBuf; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::Duration; + +use bytes::Bytes; +use http_body_util::{BodyExt, Full}; +use hyper::client::conn::http1; +use hyper::header; +use hyper::{Method, Request, Response, StatusCode}; +use hyper_util::rt::TokioIo; +use serde_json::{Value, json}; +use tokio::net::{TcpListener, TcpStream}; +use tokio::sync::oneshot; + +use ucloud_noded::heartbeat::{HeartbeatConfig, HeartbeatFront, HeartbeatPusher}; +use ucloud_noded::images_front::PullMetrics; +use ucloud_noded::{Config, Fronts, serve_with}; + +const TOKEN: &str = "test-hb-token"; + +async fn send( + addr: std::net::SocketAddr, + method: Method, + uri: &str, + headers: &[(&str, &str)], + body: Vec, +) -> (StatusCode, Value) { + let stream = TcpStream::connect(addr).await.unwrap(); + let (mut sender, conn) = http1::handshake(TokioIo::new(stream)).await.unwrap(); + tokio::spawn(async move { + let _ = conn.await; + }); + let mut builder = Request::builder().method(method).uri(uri).header(header::HOST, "127.0.0.1"); + builder = builder.header(header::CONTENT_LENGTH, body.len().to_string()); + for (k, v) in headers { + builder = builder.header(*k, *v); + } + let req = builder + .body(Full::new(Bytes::from(body)).map_err(|never| match never {}).boxed()) + .unwrap(); + let resp = sender.send_request(req).await.unwrap(); + let status = resp.status(); + let bytes = resp.into_body().collect().await.unwrap().to_bytes(); + let parsed = serde_json::from_slice(&bytes).unwrap(); + (status, parsed) +} + +#[tokio::test] +async fn healthz_heartbeat_drain_and_background_pusher_match_contract() { + // Mock gateway receiver for background heartbeat pusher + let gw_listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let gw_addr = gw_listener.local_addr().unwrap(); + let received: Arc>> = Arc::new(Mutex::new(Vec::new())); + let received_srv = received.clone(); + let (gw_stop_tx, mut gw_stop_rx) = oneshot::channel::<()>(); + tokio::spawn(async move { + loop { + let stream = tokio::select! { + acc = gw_listener.accept() => match acc { + Ok((s, _)) => s, + Err(_) => break, + }, + _ = &mut gw_stop_rx => break, + }; + let received = received_srv.clone(); + tokio::spawn(async move { + let svc = hyper::service::service_fn(move |req: Request| { + let received = received.clone(); + async move { + let body = req.into_body().collect().await.unwrap().to_bytes(); + if let Ok(val) = serde_json::from_slice::(&body) { + received.lock().unwrap().push(val); + } + Ok::<_, hyper::Error>( + Response::builder() + .status(StatusCode::OK) + .body(Full::new(Bytes::from_static(b"{\"ok\":true}")).map_err(|never| match never {}).boxed()) + .unwrap(), + ) + } + }); + let _ = hyper::server::conn::http1::Builder::new().serve_connection(TokioIo::new(stream), svc).await; + }); + } + }); + + let cfg = HeartbeatConfig { + job_id: "job-1".into(), + node_id: "node-1".into(), + node_url: "http://127.0.0.1:8091".into(), + agent_version: "0.10.12".into(), + deployment_id: "test-dep".into(), + init_version: "v1".into(), + node_epoch: "epoch-abc".into(), + capabilities: vec!["sandbox".into(), "image-cache".into()], + total_vcpu: 16.0, + total_memory_mb: 32768, + total_disk_mb: 100000, + physical_disk_path: PathBuf::from("/tmp"), + labels: BTreeMap::from([("role".into(), "sandbox".into())]), + push_url: Some(format!("http://{gw_addr}/v1/nodes/heartbeat")), + push_bearer_token: Some("push-secret".into()), + push_interval_secs: 0.2, + }; + + let hb_front = HeartbeatFront::new( + cfg, + Arc::new(OnceLock::new()), + None, + Arc::new(PullMetrics::default), + TOKEN, + ); + let pusher = HeartbeatPusher::start(hb_front.clone()).unwrap(); + + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let fronts = Fronts { + heartbeat: Some(hb_front), + ..Fronts::default() + }; + let (stop_tx, stop_rx) = oneshot::channel::<()>(); + tokio::spawn(async move { + serve_with(listener, Config::new(PathBuf::from("/tmp/unused.sock")), fronts, async move { + let _ = stop_rx.await; + }) + .await; + }); + + // 1. /healthz works without auth + let (status, body) = send(addr, Method::GET, "/healthz", &[], vec![]).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["ok"], true); + assert_eq!(body["service"], "node-agent"); + + // 2. /v1/heartbeat requires auth, returns full NodeHeartbeat JSON + let (status, _) = send(addr, Method::GET, "/v1/heartbeat", &[], vec![]).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + + let auth = format!("Bearer {TOKEN}"); + let hdrs = [("authorization", auth.as_str())]; + let (status, body) = send(addr, Method::GET, "/v1/heartbeat", &hdrs, vec![]).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["heartbeat"]["node_id"], "node-1"); + assert_eq!(body["heartbeat"]["deployment_id"], "test-dep"); + assert_eq!(body["heartbeat"]["inventory_complete"], true); + assert_eq!(body["heartbeat"]["admission_open"], true); + assert!(body["heartbeat"]["runtime_metrics"]["memory_total_mb"].as_u64().unwrap() > 0); + + // 3. POST /v1/drain -> draining + ready (empty node) -> conflict on wrong token -> undrain + let (status, body) = send( + addr, + Method::POST, + "/v1/drain", + &hdrs, + serde_json::to_vec(&json!({"draining": true, "token": "drain-1"})).unwrap(), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["drain"]["draining"], true); + assert_eq!(body["drain"]["admission_open"], false); + assert_eq!(body["drain"]["ready"], true); + + let (status, _) = send( + addr, + Method::POST, + "/v1/drain", + &hdrs, + serde_json::to_vec(&json!({"draining": true, "token": "drain-other"})).unwrap(), + ) + .await; + assert_eq!(status, StatusCode::CONFLICT); + + let (status, body) = send( + addr, + Method::POST, + "/v1/drain", + &hdrs, + serde_json::to_vec(&json!({"draining": false, "token": "drain-1"})).unwrap(), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["drain"]["draining"], false); + assert_eq!(body["drain"]["admission_open"], true); + + // 4. Verify background pusher delivered at least one heartbeat to mock gateway + for _ in 0..50 { + if !received.lock().unwrap().is_empty() { + break; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + assert!(!received.lock().unwrap().is_empty()); + assert_eq!(received.lock().unwrap()[0]["node_id"], "node-1"); + + pusher.stop().await; + let _ = stop_tx.send(()); + let _ = gw_stop_tx.send(()); +} diff --git a/runtime/noded/tests/image_routes.rs b/runtime/noded/tests/image_routes.rs new file mode 100644 index 00000000..224e752a --- /dev/null +++ b/runtime/noded/tests/image_routes.rs @@ -0,0 +1,292 @@ +//! HTTP integration tests for `ImagesFront` (`GET /v1/images`, `POST /v1/images/pull`), +//! `ImageCatalog`, and `RegistryHttpClient` / `EnvironmentResolver`. + +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; + +use bytes::Bytes; +use http_body_util::{BodyExt, Full}; +use hyper::client::conn::http1; +use hyper::header; +use hyper::{Method, Request, Response, StatusCode}; +use hyper_util::rt::TokioIo; +use serde_json::{Value, json}; +use tokio::net::{TcpListener, TcpStream}; +use tokio::sync::oneshot; + +use ucloud_noded::image::{EnvironmentResolver, parse_image_ref}; +use ucloud_noded::images_front::{BoxFuture, ImageCatalog, ImagePuller, ImagesFront, PullError}; +use ucloud_noded::registry_client::RegistryHttpClient; +use ucloud_noded::{Config, Fronts, serve_with}; + +const TOKEN: &str = "test-images-token"; + +struct FakePuller { + open: AtomicBool, + calls: Mutex)>>, + fail_with: Mutex>, +} + +impl FakePuller { + fn new() -> Arc { + Arc::new(FakePuller { + open: AtomicBool::new(true), + calls: Mutex::new(Vec::new()), + fail_with: Mutex::new(None), + }) + } +} + +impl ImagePuller for FakePuller { + fn admission_open(&self) -> bool { + self.open.load(Ordering::Relaxed) + } + + fn pull(&self, image: &str, environment_root: Option<&str>) -> BoxFuture> { + self.calls.lock().unwrap().push((image.to_string(), environment_root.map(str::to_string))); + let err = self.fail_with.lock().unwrap().take(); + Box::pin(async move { + match err { + Some(e) => Err(e), + None => Ok(()), + } + }) + } +} + +fn temp_dir(label: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "noded-image-routes-{label}-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +async fn send( + addr: std::net::SocketAddr, + method: Method, + uri: &str, + headers: &[(&str, &str)], + body: Vec, +) -> (StatusCode, Value) { + let stream = TcpStream::connect(addr).await.unwrap(); + let (mut sender, conn) = http1::handshake(TokioIo::new(stream)).await.unwrap(); + tokio::spawn(async move { + let _ = conn.await; + }); + let mut builder = Request::builder().method(method).uri(uri).header(header::HOST, "127.0.0.1"); + builder = builder.header(header::CONTENT_LENGTH, body.len().to_string()); + for (k, v) in headers { + builder = builder.header(*k, *v); + } + let req = builder + .body(Full::new(Bytes::from(body)).map_err(|never| match never {}).boxed()) + .unwrap(); + let resp = sender.send_request(req).await.unwrap(); + let status = resp.status(); + let bytes = resp.into_body().collect().await.unwrap().to_bytes(); + let parsed = serde_json::from_slice(&bytes).unwrap(); + (status, parsed) +} + +#[tokio::test] +async fn images_list_pull_persistence_and_drain_rejection() { + let dir = temp_dir("front"); + let catalog_path = dir.join("images.json"); + let catalog = Arc::new(ImageCatalog::open(&catalog_path)); + let puller = FakePuller::new(); + + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let fronts = Fronts { + images: Some(ImagesFront::new(catalog.clone(), puller.clone(), TOKEN, 4)), + ..Fronts::default() + }; + let (stop_tx, stop_rx) = oneshot::channel::<()>(); + let unused_sock = dir.join("unused.sock"); + tokio::spawn(async move { + serve_with(listener, Config::new(unused_sock), fronts, async move { + let _ = stop_rx.await; + }) + .await; + }); + + let auth = format!("Bearer {TOKEN}"); + let hdrs = [("authorization", auth.as_str())]; + + // Initially empty + let (status, body) = send(addr, Method::GET, "/v1/images", &hdrs, vec![]).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["images"], json!([])); + + // Pull image with dispatched environment_root + let root = format!("sha256:{}", "a".repeat(64)); + let image_ref = format!("registry:5000/sandboxes/app@sha256:{}", "b".repeat(64)); + let payload = serde_json::to_vec(&json!({ + "image": image_ref, + "id": "img-app-1", + "environment_root": root, + })) + .unwrap(); + let (status, body) = send(addr, Method::POST, "/v1/images/pull", &hdrs, payload).await; + assert_eq!(status, StatusCode::CREATED); + assert_eq!(body["image"]["id"], "img-app-1"); + assert_eq!(body["image"]["state"], "available"); + assert_eq!(body["image"]["available_to_sandboxes"], true); + assert_eq!(body["exit_code"], 0); + assert_eq!(puller.calls.lock().unwrap().len(), 1); + assert_eq!(puller.calls.lock().unwrap()[0], (image_ref.clone(), Some(root))); + + // GET /v1/images returns persisted entry & survives reload + let (status, body) = send(addr, Method::GET, "/v1/images", &hdrs, vec![]).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["images"].as_array().unwrap().len(), 1); + let reloaded = ImageCatalog::open(&catalog_path); + assert_eq!(reloaded.cached_refs(), vec![image_ref.clone()]); + + // Closed admission -> 503 node_admission_closed + puller.open.store(false, Ordering::Relaxed); + let payload = serde_json::to_vec(&json!({"image": image_ref})).unwrap(); + let (status, body) = send(addr, Method::POST, "/v1/images/pull", &hdrs, payload).await; + assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE); + assert_eq!(body["error_code"], "node_admission_closed"); + assert_eq!(body["retryable"], true); + + // Failed pull -> 503 image_pull_failed + puller.open.store(true, Ordering::Relaxed); + *puller.fail_with.lock().unwrap() = Some(PullError::Failed("registry timeout".into())); + let payload = serde_json::to_vec(&json!({"image": image_ref})).unwrap(); + let (status, body) = send(addr, Method::POST, "/v1/images/pull", &hdrs, payload).await; + assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE); + assert_eq!(body["error_code"], "image_pull_failed"); + + let _ = stop_tx.send(()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[tokio::test] +async fn registry_http_client_handles_manifests_blobs_and_uploads() { + let blobs: Arc>>> = Arc::new(Mutex::new(HashMap::new())); + let manifests: Arc>>> = Arc::new(Mutex::new(HashMap::new())); + let blobs_srv = blobs.clone(); + let manifests_srv = manifests.clone(); + + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let (stop_tx, mut stop_rx) = oneshot::channel::<()>(); + tokio::spawn(async move { + loop { + let stream = tokio::select! { + acc = listener.accept() => match acc { + Ok((s, _)) => s, + Err(_) => break, + }, + _ = &mut stop_rx => break, + }; + let blobs = blobs_srv.clone(); + let manifests = manifests_srv.clone(); + tokio::spawn(async move { + let svc = hyper::service::service_fn(move |req: Request| { + let blobs = blobs.clone(); + let manifests = manifests.clone(); + async move { + let method = req.method().clone(); + let path = req.uri().path().to_string(); + let query = req.uri().query().unwrap_or("").to_string(); + let body = req.into_body().collect().await.unwrap().to_bytes().to_vec(); + let resp = if method == Method::HEAD && path.contains("/blobs/") { + let d = path.rsplit('/').next().unwrap(); + let st = if blobs.lock().unwrap().contains_key(d) { + StatusCode::OK + } else { + StatusCode::NOT_FOUND + }; + Response::builder() + .status(st) + .body(Full::new(Bytes::new()).map_err(|never| match never {}).boxed()) + .unwrap() + } else if method == Method::POST && path.ends_with("/blobs/uploads/") { + Response::builder() + .status(StatusCode::ACCEPTED) + .header(header::LOCATION, "/v2/repo/blobs/uploads/u1") + .body(Full::new(Bytes::new()).map_err(|never| match never {}).boxed()) + .unwrap() + } else if method == Method::PUT && path.contains("/blobs/uploads/") { + let d = query.strip_prefix("digest=").unwrap().to_string(); + blobs.lock().unwrap().insert(d, body); + Response::builder() + .status(StatusCode::CREATED) + .body(Full::new(Bytes::new()).map_err(|never| match never {}).boxed()) + .unwrap() + } else if method == Method::GET && path.contains("/blobs/") { + let d = path.rsplit('/').next().unwrap(); + match blobs.lock().unwrap().get(d).cloned() { + Some(data) => Response::builder() + .status(StatusCode::OK) + .body(Full::new(Bytes::from(data)).map_err(|never| match never {}).boxed()) + .unwrap(), + None => Response::builder() + .status(StatusCode::NOT_FOUND) + .body(Full::new(Bytes::new()).map_err(|never| match never {}).boxed()) + .unwrap(), + } + } else if method == Method::PUT && path.contains("/manifests/") { + let r = path.rsplit('/').next().unwrap().to_string(); + manifests.lock().unwrap().insert(r, body); + Response::builder() + .status(StatusCode::CREATED) + .header("docker-content-digest", format!("sha256:{}", "c".repeat(64))) + .body(Full::new(Bytes::new()).map_err(|never| match never {}).boxed()) + .unwrap() + } else if method == Method::GET && path.contains("/manifests/") { + let r = path.rsplit('/').next().unwrap(); + match manifests.lock().unwrap().get(r).cloned() { + Some(data) => Response::builder() + .status(StatusCode::OK) + .header("docker-content-digest", format!("sha256:{}", "c".repeat(64))) + .body(Full::new(Bytes::from(data)).map_err(|never| match never {}).boxed()) + .unwrap(), + None => Response::builder() + .status(StatusCode::NOT_FOUND) + .body(Full::new(Bytes::new()).map_err(|never| match never {}).boxed()) + .unwrap(), + } + } else { + Response::builder() + .status(StatusCode::NOT_FOUND) + .body(Full::new(Bytes::new()).map_err(|never| match never {}).boxed()) + .unwrap() + }; + Ok::<_, hyper::Error>(resp) + } + }); + let _ = hyper::server::conn::http1::Builder::new().serve_connection(TokioIo::new(stream), svc).await; + }); + } + }); + + let client = RegistryHttpClient::new(&format!("http://{addr}")).unwrap(); + let digest = format!("sha256:{}", "d".repeat(64)); + client.put_blob("repo", &digest, Bytes::from_static(b"blob-data")).await.unwrap(); + assert_eq!(client.blob_bytes("repo", &digest, 1024).await.unwrap(), Bytes::from_static(b"blob-data")); + + let manifest_bytes = Bytes::from_static(br#"{"schemaVersion":2}"#); + let returned = client.put_manifest("repo", "v1", manifest_bytes, "application/vnd.oci.image.manifest.v1+json").await.unwrap(); + assert!(returned.starts_with("sha256:")); + let (doc, _) = client.manifest_document("repo", "v1").await.unwrap(); + assert_eq!(doc["schemaVersion"], 2); + + // Image ref parser check + assert_eq!( + parse_image_ref("registry:5000/ns/img:v1"), + Some(("registry:5000".into(), "ns/img".into(), "v1".into())) + ); + let _resolver = EnvironmentResolver::new(&format!("http://{addr}"), "env", HashMap::new()).unwrap(); + + let _ = stop_tx.send(()); +} diff --git a/runtime/noded/tests/job_routes.rs b/runtime/noded/tests/job_routes.rs index 54a56881..54373ce4 100644 --- a/runtime/noded/tests/job_routes.rs +++ b/runtime/noded/tests/job_routes.rs @@ -169,7 +169,7 @@ async fn harness_with(limits: JobLimits) -> Harness { let front = JobFront::new(node.clone(), client, TOKEN, limits); let tcp = ucloud_noded::listen("127.0.0.1:0".parse().unwrap()).unwrap(); let address = tcp.local_addr().unwrap(); - let fronts = ucloud_noded::Fronts { create: None, exec: None, jobs: Some(front.clone()), node: None, internal: None }; + let fronts = ucloud_noded::Fronts { jobs: Some(front.clone()), ..Default::default() }; tokio::spawn(ucloud_noded::serve_with(tcp, ucloud_noded::Config::new(socket), fronts, std::future::pending())); Harness { address, agent: state, node, front, bundle, _dir: dir } } diff --git a/runtime/noded/tests/lifecycle_routes.rs b/runtime/noded/tests/lifecycle_routes.rs new file mode 100644 index 00000000..2b45ca77 --- /dev/null +++ b/runtime/noded/tests/lifecycle_routes.rs @@ -0,0 +1,362 @@ +//! Wave B5 integration tests: lifecycle HTTP routes, CommitExports idempotency +//! & registry upload, and the full HibernationJournal state machine. + +use std::collections::HashMap; +use std::net::SocketAddr; +use std::os::unix::fs::PermissionsExt; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; + +use bytes::Bytes; +use http_body_util::{BodyExt, Full}; +use hyper::client::conn::http1; +use hyper::header::{self, HeaderValue}; +use hyper::server::conn::http1 as server_http1; +use hyper::service::service_fn; +use hyper::{Method, Request, Response, StatusCode}; +use hyper_util::rt::TokioIo; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use tokio::net::{TcpListener, TcpStream}; + +use ucloud_noded::commit_export::{CommitExports, ExportHook}; +use ucloud_noded::journal::JournalStore; +use ucloud_noded::lifecycle_front::{BoxFuture, LifecycleError, LifecycleFront, LifecycleNode}; +use ucloud_noded::registry_client::RegistryHttpClient; +use ucloud_noded::{Body, Config, Fronts, serve_with}; + +const TOKEN: &str = "lifecycle-secret"; + +fn temp_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "noded-lifecycle-{name}-{}-{}", + std::process::id(), + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos() + )); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)).unwrap(); + dir +} + +struct FakeLifecycle { + calls: Mutex>, + commits: Arc, +} + +impl LifecycleNode for FakeLifecycle { + fn ssh(&self, sandbox_id: &str) -> BoxFuture> { + self.calls.lock().unwrap().push(format!("ssh:{sandbox_id}")); + Box::pin(async { Err(LifecycleError::Conflict("direct runsc sandboxes do not expose ssh access".into())) }) + } + + fn park(&self, sandbox_id: &str, operation_id: &str, background: bool) -> BoxFuture> { + self.calls.lock().unwrap().push(format!("park:{sandbox_id}:{operation_id}:{background}")); + let sid = sandbox_id.to_string(); + Box::pin(async move { + Ok((StatusCode::OK, json!({"sandbox": {"sandbox_id": sid, "lifecycle_state": "parked"}}))) + }) + } + + fn wake(&self, sandbox_id: &str, generation: i64, operation_id: &str) -> BoxFuture> { + self.calls.lock().unwrap().push(format!("wake:{sandbox_id}:{generation}:{operation_id}")); + let sid = sandbox_id.to_string(); + Box::pin(async move { + Ok(json!({"sandbox": {"sandbox_id": sid, "generation": generation, "lifecycle_state": "running"}})) + }) + } + + fn request_snapshot_publication(&self, sandbox_id: &str, generation: i64) -> BoxFuture> { + self.calls.lock().unwrap().push(format!("pub:{sandbox_id}:{generation}")); + Box::pin(async move { Ok(json!({"accepted": true, "generation": generation})) }) + } + + fn publish_parked(&self, sandbox_id: &str, generation: i64, create_op: &str, spec_hash: &str) -> BoxFuture> { + self.calls.lock().unwrap().push(format!("publish_parked:{sandbox_id}:{generation}:{create_op}:{spec_hash}")); + Box::pin(async move { Ok(json!({"snapshot_manifest_digest": "sha256:abc"})) }) + } + + fn evict_published(&self, sandbox_id: &str, generation: i64, digest: &str) -> BoxFuture> { + self.calls.lock().unwrap().push(format!("evict:{sandbox_id}:{generation}:{digest}")); + Box::pin(async { Ok(()) }) + } + + fn commit_export(&self, sandbox_id: &str, raw: Value) -> BoxFuture> { + let commits = self.commits.clone(); + let sid = sandbox_id.to_string(); + Box::pin(async move { + let exporter: ExportHook = Arc::new(|_sb, _gen, path, _resume| { + let data = b"fake-upper-tar-layer-bytes"; + std::fs::write(path, data).unwrap(); + Ok((false, vec!["img:v1".into()], data.len() as u64)) + }); + commits.request(&sid, &raw, exporter).map_err(LifecycleError::CommitRefused) + }) + } + + fn prepare_migration(&self, sandbox_id: &str, migration_id: &str, format: &str) -> BoxFuture> { + self.calls.lock().unwrap().push(format!("mig_prepare:{sandbox_id}:{migration_id}:{format}")); + Box::pin(async move { Ok(json!({"prepared": true})) }) + } + + fn import_migration(&self, raw: Value) -> BoxFuture> { + self.calls.lock().unwrap().push("mig_import".into()); + Box::pin(async move { Ok(json!({"imported": raw["sandbox_id"]})) }) + } + + fn complete_migration(&self, sandbox_id: &str, action: &str, migration_id: &str, sha: &str) -> BoxFuture> { + self.calls.lock().unwrap().push(format!("mig_{action}:{sandbox_id}:{migration_id}:{sha}")); + Box::pin(async move { Ok(json!({"ok": true})) }) + } +} + +async fn start_mock_registry() -> (SocketAddr, Arc>>>) { + let blobs: Arc>>> = Arc::new(Mutex::new(HashMap::new())); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let blobs_srv = blobs.clone(); + tokio::spawn(async move { + loop { + let Ok((stream, _)) = listener.accept().await else { break }; + let blobs = blobs_srv.clone(); + tokio::spawn(async move { + let service = service_fn(move |req: Request| { + let blobs = blobs.clone(); + async move { + let method = req.method().clone(); + let path = req.uri().path().to_string(); + let query = req.uri().query().unwrap_or("").to_string(); + if method == Method::POST && path.ends_with("/blobs/uploads/") { + let mut resp = Response::new(Full::new(Bytes::new()).map_err(|n| match n {}).boxed()); + *resp.status_mut() = StatusCode::ACCEPTED; + resp.headers_mut().insert( + header::LOCATION, + HeaderValue::from_str(&format!("{path}upload-1")).unwrap(), + ); + return Ok::, hyper::Error>(resp); + } + if method == Method::PUT && path.contains("/blobs/uploads/") { + let digest = query.strip_prefix("digest=").unwrap_or("").to_string(); + let body = req.into_body().collect().await.unwrap().to_bytes(); + blobs.lock().unwrap().insert(digest, body.to_vec()); + let mut resp = Response::new(Full::new(Bytes::new()).map_err(|n| match n {}).boxed()); + *resp.status_mut() = StatusCode::CREATED; + return Ok(resp); + } + let mut resp = Response::new(Full::new(Bytes::new()).map_err(|n| match n {}).boxed()); + *resp.status_mut() = StatusCode::NOT_FOUND; + Ok(resp) + } + }); + let _ = server_http1::Builder::new().serve_connection(TokioIo::new(stream), service).await; + }); + } + }); + (addr, blobs) +} + +async fn send(addr: SocketAddr, method: Method, path: &str, body: Option) -> (StatusCode, Value) { + let stream = TcpStream::connect(addr).await.unwrap(); + let (mut sender, conn) = http1::handshake(TokioIo::new(stream)).await.unwrap(); + tokio::spawn(async move { let _ = conn.await; }); + let bytes = body.map(|v| serde_json::to_vec(&v).unwrap()).unwrap_or_default(); + let req = Request::builder() + .method(method) + .uri(path) + .header(header::AUTHORIZATION, format!("Bearer {TOKEN}")) + .header(header::CONTENT_TYPE, "application/json") + .body(Full::new(Bytes::from(bytes)).map_err(|n| match n {}).boxed()) + .unwrap(); + let resp = sender.send_request(req).await.unwrap(); + let status = resp.status(); + let raw = resp.into_body().collect().await.unwrap().to_bytes(); + (status, serde_json::from_slice(&raw).unwrap()) +} + +#[tokio::test] +async fn lifecycle_routes_and_commit_export_work_end_to_end() { + let root = temp_dir("routes"); + let (reg_addr, uploaded_blobs) = start_mock_registry().await; + let registry_client = RegistryHttpClient::new(&format!("http://{reg_addr}")).unwrap(); + let commits = CommitExports::open_with_min_free(&root, Some(registry_client), 0).unwrap(); + + let fake = Arc::new(FakeLifecycle { calls: Mutex::new(Vec::new()), commits }); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let fronts = Fronts { + lifecycle: Some(LifecycleFront::new(fake.clone(), TOKEN)), + ..Default::default() + }; + let (stop_tx, stop_rx) = tokio::sync::oneshot::channel::<()>(); + let srv = tokio::spawn(serve_with( + listener, + Config::new(root.join("unused.sock")), + fronts, + async move { let _ = stop_rx.await; }, + )); + + // SSH returns 409 conflict + let (st, _) = send(addr, Method::GET, "/v1/sandboxes/sb-1/ssh", None).await; + assert_eq!(st, StatusCode::CONFLICT); + + // Park & Wake + let (st, body) = send(addr, Method::POST, "/v1/sandboxes/sb-1/park", Some(json!({"operation_id": "op-park-1"}))).await; + assert_eq!(st, StatusCode::OK); + assert_eq!(body["sandbox"]["lifecycle_state"], "parked"); + + let (st, body) = send(addr, Method::POST, "/v1/sandboxes/sb-1/wake", Some(json!({"generation": 2, "operation_id": "op-wake-1"}))).await; + assert_eq!(st, StatusCode::OK); + assert_eq!(body["sandbox"]["lifecycle_state"], "running"); + + // Snapshot publish, publish-parked, evict-published + let (st, _) = send(addr, Method::POST, "/v1/sandboxes/sb-1/snapshot/publish", Some(json!({"generation": 2}))).await; + assert_eq!(st, StatusCode::ACCEPTED); + + let (st, body) = send( + addr, + Method::POST, + "/v1/sandboxes/sb-1/publish-parked", + Some(json!({"generation": 2, "create_operation_id": "op-c1", "spec_hash": "abc"})), + ).await; + assert_eq!(st, StatusCode::OK); + assert_eq!(body["snapshot_manifest_digest"], "sha256:abc"); + + let (st, body) = send( + addr, + Method::POST, + "/v1/sandboxes/sb-1/evict-published", + Some(json!({"generation": 2, "snapshot_manifest_digest": "sha256:abc"})), + ).await; + assert_eq!(st, StatusCode::OK); + assert_eq!(body["ok"], true); + + // Migration prepare, import, activate, finalize, abort, abort-import + let (st, _) = send( + addr, + Method::POST, + "/v1/sandboxes/sb-1/migration/prepare", + Some(json!({"migration_id": "m-1", "format": "storage-native-split-migration-v1"})), + ).await; + assert_eq!(st, StatusCode::OK); + + let (st, _) = send( + addr, + Method::POST, + "/v1/sandboxes/sb-1/migration/prepare", + Some(json!({"migration_id": "m-1", "format": "unsupported-format"})), + ).await; + assert_eq!(st, StatusCode::BAD_REQUEST); + + let (st, body) = send(addr, Method::POST, "/v1/migrations/import", Some(json!({"sandbox_id": "sb-1"}))).await; + assert_eq!(st, StatusCode::CREATED); + assert_eq!(body["imported"], "sb-1"); + + for action in ["activate", "finalize", "abort", "abort-import"] { + let (st, _) = send( + addr, + Method::POST, + &format!("/v1/sandboxes/sb-1/migration/{action}"), + Some(json!({"migration_id": "m-1", "snapshot_sha256": "deadbeef"})), + ).await; + assert_eq!(st, StatusCode::OK); + } + + // Commit export: returns 202 exporting, uploads to mock registry, then poll returns 200 staged + let req_payload = json!({ + "operation_id": "op-commit-1", + "generation": 2, + "image_id": "img-commit-1", + "resume": true, + "max_bytes": 1048576, + }); + let (st, body) = send(addr, Method::POST, "/v1/sandboxes/sb-1/commit-export", Some(req_payload.clone())).await; + assert_eq!(st, StatusCode::ACCEPTED); + assert_eq!(body["export"]["state"], "exporting"); + + // Poll until background upload finishes + let expected_hex: String = Sha256::digest(b"fake-upper-tar-layer-bytes").iter().map(|b| format!("{b:02x}")).collect(); + let expected_digest = format!("sha256:{expected_hex}"); + let mut staged = false; + for _ in 0..50 { + let (st, body) = send(addr, Method::POST, "/v1/sandboxes/sb-1/commit-export", Some(req_payload.clone())).await; + if st == StatusCode::OK && body["export"]["state"] == "staged" { + assert_eq!(body["export"]["blob_digest"], expected_digest); + assert_eq!(body["export"]["size"], 26); + staged = true; + break; + } + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + assert!(staged, "commit export never reached staged state"); + assert_eq!(uploaded_blobs.lock().unwrap().get(&expected_digest).unwrap(), b"fake-upper-tar-layer-bytes"); + + // Reusing operation_id for a different image_id conflicts with 409 + let (st, _) = send( + addr, + Method::POST, + "/v1/sandboxes/sb-1/commit-export", + Some(json!({ + "operation_id": "op-commit-1", + "generation": 2, + "image_id": "img-different", + "resume": true, + "max_bytes": 1048576, + })), + ).await; + assert_eq!(st, StatusCode::CONFLICT); + + let _ = stop_tx.send(()); + let _ = srv.await; + let _ = std::fs::remove_dir_all(root); +} + +#[test] +fn journal_full_hibernate_and_restore_state_machine() { + let root = temp_dir("journal-sm"); + let store = JournalStore::new(root.join("journals")); + let spec = "a".repeat(64); + let manifest = "b".repeat(64); + + let r0 = store.initialize_running("sb-1", 1, &spec, "op-create", 1000, 5000).unwrap(); + assert_eq!(r0["state"], "running"); + assert_eq!(r0["revision"], 0); + + // Running -> Hibernating -> Rollback -> Running + let h1 = store.begin_hibernate("sb-1", 1, "op-park-fail", 0).unwrap(); + assert_eq!(h1["state"], "hibernating"); + assert_eq!(h1["hibernation_generation"], 1); + let rolled = store.rollback_hibernate("sb-1", 1, "op-park-fail", 1).unwrap(); + assert_eq!(rolled["state"], "running"); + assert_eq!(rolled["revision"], 2); + + // Running -> Hibernating -> Reaped -> Parked + let h2 = store.begin_hibernate("sb-1", 1, "op-park-ok", 2).unwrap(); + assert_eq!(h2["hibernation_generation"], 2); + let reaped = store.mark_sentry_reaped("sb-1", 1, "op-park-ok", 3).unwrap(); + assert_eq!(reaped["authority"], "pending"); + assert!(reaped["sentry_pid"].is_null()); + let parked = store.commit_parked("sb-1", 1, &manifest, "op-park-ok", 4).unwrap(); + assert_eq!(parked["state"], "parked"); + assert_eq!(parked["authority"], "parked"); + assert_eq!(parked["manifest_sha256"], manifest); + + // Parked -> Restoring -> Candidate -> Running + let restoring = store.begin_restore("sb-1", 1, "op-wake-1", 5).unwrap(); + assert_eq!(restoring["state"], "restoring"); + let cand = store.mark_candidate("sb-1", 1, "op-wake-1", 6, 2000, 9000).unwrap(); + assert_eq!(cand["authority"], "candidate"); + assert_eq!(cand["candidate_pid"], 2000); + let running = store.commit_running("sb-1", 1, "op-wake-1", 7, 2000, 9000).unwrap(); + assert_eq!(running["state"], "running"); + assert_eq!(running["authority"], "live"); + assert_eq!(running["sentry_pid"], 2000); + assert!(running["candidate_pid"].is_null()); + + // Quarantine + let q = store.quarantine("sb-1", 1, "test reason", 8).unwrap(); + assert_eq!(q["state"], "recovery_required"); + assert_eq!(q["recovery_reason"], "test reason"); + + store.remove("sb-1", 1, 9).unwrap(); + assert!(store.load("sb-1", 1).unwrap().is_none()); + let _ = std::fs::remove_dir_all(root); +} diff --git a/runtime/noded/tests/standalone_node.rs b/runtime/noded/tests/standalone_node.rs new file mode 100644 index 00000000..780b1582 --- /dev/null +++ b/runtime/noded/tests/standalone_node.rs @@ -0,0 +1,338 @@ +//! End-to-end integration test of standalone Rust `ucloud-noded` (NO Python agent). + +use std::collections::BTreeMap; +use std::net::SocketAddr; +use std::os::unix::fs::PermissionsExt; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; + +use bytes::Bytes; +use http_body_util::{BodyExt, Full}; +use hyper::client::conn::http1; +use hyper::header; +use hyper::server::conn::http1 as server_http1; +use hyper::service::service_fn; +use hyper::{Method, Request, Response, StatusCode}; +use hyper_util::rt::TokioIo; +use serde_json::{Map, Value, json}; +use tokio::net::{TcpListener, TcpStream}; + +use ucloud_noded::heartbeat::HeartbeatConfig; +use ucloud_noded::pipeline::{AdmissionConfig, CreateConfig, EnvironmentConfig, ExecConfig, ExecSessionLimits}; +use ucloud_noded::standalone::{StandaloneConfig, start_standalone}; +use ucloud_noded::{Body, Config, serve_with}; + +const TOKEN: &str = "standalone-token-secret"; + +fn temp_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "noded-standalone-{name}-{}-{}", + std::process::id(), + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos() + )); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)).unwrap(); + dir +} + +async fn start_mock_gateway() -> (SocketAddr, Arc>>) { + let heartbeats: Arc>> = Arc::new(Mutex::new(Vec::new())); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let hbs = heartbeats.clone(); + tokio::spawn(async move { + loop { + let Ok((stream, _)) = listener.accept().await else { break }; + let hbs = hbs.clone(); + tokio::spawn(async move { + let svc = service_fn(move |req: Request| { + let hbs = hbs.clone(); + async move { + let body = req.into_body().collect().await.unwrap().to_bytes(); + if let Ok(val) = serde_json::from_slice::(&body) { + hbs.lock().unwrap().push(val); + } + let mut resp = Response::new(Full::new(Bytes::from_static(b"{\"ok\":true}")).map_err(|n| match n {}).boxed()); + *resp.status_mut() = StatusCode::OK; + Ok::, hyper::Error>(resp) + } + }); + let _ = server_http1::Builder::new().serve_connection(TokioIo::new(stream), svc).await; + }); + } + }); + (addr, heartbeats) +} + +async fn send( + addr: SocketAddr, + method: Method, + path: &str, + token: Option<&str>, + extra_headers: &[(&str, &str)], + body: Option, +) -> (StatusCode, Value) { + let stream = TcpStream::connect(addr).await.unwrap(); + let (mut sender, conn) = http1::handshake(TokioIo::new(stream)).await.unwrap(); + tokio::spawn(async move { let _ = conn.await; }); + let bytes = body.map(|v| serde_json::to_vec(&v).unwrap()).unwrap_or_default(); + let mut builder = Request::builder() + .method(method) + .uri(path) + .header(header::CONTENT_LENGTH, bytes.len()); + if let Some(tok) = token { + builder = builder.header(header::AUTHORIZATION, format!("Bearer {tok}")); + } + if !bytes.is_empty() { + builder = builder.header(header::CONTENT_TYPE, "application/json"); + } + for (k, v) in extra_headers { + builder = builder.header(*k, *v); + } + let req = builder + .body(Full::new(Bytes::from(bytes)).map_err(|n| match n {}).boxed()) + .unwrap(); + let resp = sender.send_request(req).await.unwrap(); + let status = resp.status(); + let raw = resp.into_body().collect().await.unwrap().to_bytes(); + (status, serde_json::from_slice(&raw).unwrap()) +} + +#[tokio::test] +async fn standalone_noded_serves_all_worker_routes_without_python() { + let root = temp_dir("full"); + let state_root = root.join("state"); + let image_cache_root = root.join("images"); + let volume_mount_root = root.join("volumes"); + let runtime_root = root.join("runsc-root"); + let bundle_root = root.join("bundles"); + let journal_root = root.join("journals"); + let init_bin = root.join("init"); + let managed_init_bin = root.join("managed-init"); + for d in [&state_root, &image_cache_root, &volume_mount_root, &runtime_root, &bundle_root, &journal_root] { + std::fs::create_dir_all(d).unwrap(); + std::fs::set_permissions(d, std::fs::Permissions::from_mode(0o700)).unwrap(); + } + std::fs::write(&init_bin, b"#!/bin/sh\n").unwrap(); + std::fs::write(&managed_init_bin, b"#!/bin/sh\n").unwrap(); + + let (gw_addr, pushed_hbs) = start_mock_gateway().await; + + let create_cfg = CreateConfig { + state_root: state_root.clone(), + image_cache_root, + volume_mount_root: volume_mount_root.clone(), + storage_native_socket: root.join("storage.sock"), + runsc: PathBuf::from("/usr/bin/true"), + runtime_root: runtime_root.clone(), + bundle_root, + journal_root, + network: "none".into(), + network_mtu: 1500, + network_pool_size: 0, + direct_network_allow_tcp: Vec::new(), + dns_named_egress: false, + relays_configured: false, + relay_hosts: BTreeMap::new(), + split_memory_backing: false, + memory_backing_hard_capacity_bytes: 0, + application_memory_root: None, + workspace_initial_grant_mb: 512, + demonstrated_memory: true, + init_binary: init_bin, + managed_init_binary: managed_init_bin, + environment: Some(EnvironmentConfig { + registry_url: format!("http://{gw_addr}"), + registry_repository: "envs".into(), + backend_socket: root.join("env.sock"), + rafs: false, + }), + runtime_compatibility_sha256: "a".repeat(64), + node_epoch: "epoch-standalone-1".into(), + exec: ExecConfig { + runsc: PathBuf::from("/usr/bin/true"), + runtime_root: runtime_root.clone(), + warden_locks_dir: runtime_root.join("warden-locks"), + warden_paused_dir: runtime_root.join("warden-paused"), + active_capacity_configured: false, + memory_floor_mib: 2048, + sessions: ExecSessionLimits { + max_sessions: 64, + max_events_per_session: 1024, + completed_retention_seconds: 60.0, + delivered_grace_seconds: 5.0, + output_idle_timeout_seconds: 300.0, + }, + admission_wait_seconds: 5.0, + }, + pause: Map::new(), + admission: AdmissionConfig { + rust_admission_enabled: true, + max_concurrent_startups: 4, + max_concurrent_restores: 4, + admission_wait_seconds: 5.0, + active_capacity: None, + physical_memory_floor_mb: 2048, + growth_observation_max_age_seconds: 30.0, + prefetch_max_bytes: 1024 * 1024 * 1024, + publication_lanes: 16, + retry_seconds: 0.21, + }, + max_file_body_bytes: 16 * 1024 * 1024, + config_sha256: "b".repeat(64), + }; + + let hb_cfg = HeartbeatConfig { + job_id: "job-standalone".into(), + node_id: "node-rust-1".into(), + node_url: "http://127.0.0.1:8090".into(), + agent_version: "0.9.0-rust".into(), + deployment_id: "dep-1".into(), + init_version: "init-1".into(), + node_epoch: "epoch-standalone-1".into(), + capabilities: vec!["sandbox".into(), "direct-runsc-v1".into()], + total_vcpu: 16.0, + total_memory_mb: 32768, + total_disk_mb: 100000, + physical_disk_path: volume_mount_root, + labels: BTreeMap::new(), + push_url: Some(format!("http://{gw_addr}/v1/heartbeats")), + push_bearer_token: Some("gw-secret".into()), + push_interval_secs: 0.05, + }; + + let standalone_cfg = StandaloneConfig { + create: create_cfg, + heartbeat: hb_cfg, + trusted_keys_file: None, + image_catalog_path: None, + max_concurrent_image_pulls: 4, + checkpoint_registry_url: None, + checkpoint_registry_repository: None, + reconcile_interval_secs: 1.0, + }; + + let rt = start_standalone(standalone_cfg, TOKEN).expect("standalone startup"); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let (stop_tx, stop_rx) = tokio::sync::oneshot::channel::<()>(); + let fronts = rt.fronts.clone(); + let srv = tokio::spawn(serve_with( + listener, + Config::standalone(), + fronts, + async move { let _ = stop_rx.await; }, + )); + + // 1. /healthz works without auth + let (st, body) = send(addr, Method::GET, "/healthz", None, &[], None).await; + assert_eq!(st, StatusCode::OK); + assert_eq!(body["ok"], true); + assert_eq!(body["version"], "0.9.0-rust"); + + // 2. Unauthenticated /v1/* returns 401 + let (st, _) = send(addr, Method::GET, "/v1/heartbeat", None, &[], None).await; + assert_eq!(st, StatusCode::UNAUTHORIZED); + let (st, _) = send(addr, Method::GET, "/v1/sandboxes", None, &[], None).await; + assert_eq!(st, StatusCode::UNAUTHORIZED); + + // 3. Authenticated /v1/heartbeat returns full snapshot + let (st, body) = send(addr, Method::GET, "/v1/heartbeat", Some(TOKEN), &[], None).await; + assert_eq!(st, StatusCode::OK); + assert_eq!(body["heartbeat"]["node_id"], "node-rust-1"); + assert_eq!(body["heartbeat"]["node_epoch"], "epoch-standalone-1"); + assert_eq!(body["heartbeat"]["admission_open"], true); + + // 4. GET /v1/images + let (st, body) = send(addr, Method::GET, "/v1/images", Some(TOKEN), &[], None).await; + assert_eq!(st, StatusCode::OK); + assert_eq!(body["images"], json!([])); + + // 5. GET /v1/sandboxes & ?sandbox_id=sb-1 + let (st, body) = send(addr, Method::GET, "/v1/sandboxes", Some(TOKEN), &[], None).await; + assert_eq!(st, StatusCode::OK); + assert_eq!(body["sandboxes"], json!([])); + + let (st, body) = send(addr, Method::GET, "/v1/sandboxes?sandbox_id=sb-1", Some(TOKEN), &[], None).await; + assert_eq!(st, StatusCode::OK); + assert_eq!(body["sandboxes"], json!([])); + assert_eq!(body["node_epoch"], "epoch-standalone-1"); + assert!(body["activity_epoch"].as_i64().unwrap() > 0); + + // 6. Invalid POST /v1/sandboxes returns 400 (handled natively, never proxies) + let (st, _) = send(addr, Method::POST, "/v1/sandboxes", Some(TOKEN), &[], Some(json!({"id": "sb-1"}))).await; + assert_eq!(st, StatusCode::BAD_REQUEST); + + // 7. DELETE /v1/sandboxes/sb-missing returns 200 {"deleted": null} + let (st, body) = send( + addr, + Method::DELETE, + "/v1/sandboxes/sb-missing", + Some(TOKEN), + &[ + ("X-UCloud-Sandbox-Generation", "1"), + ("X-UCloud-Sandbox-Operation-Id", "op-del-1"), + ], + None, + ) + .await; + assert_eq!(st, StatusCode::OK); + assert!(body["deleted"].is_null()); + + // 8. GET /v1/sandboxes/sb-missing/ssh returns 404 + let (st, _) = send(addr, Method::GET, "/v1/sandboxes/sb-missing/ssh", Some(TOKEN), &[], None).await; + assert_eq!(st, StatusCode::NOT_FOUND); + + // 9. Drain closes admission -> valid create returns 503 node_admission_closed + let (st, body) = send( + addr, + Method::POST, + "/v1/drain", + Some(TOKEN), + &[], + Some(json!({"draining": true, "token": "drain-op-1"})), + ) + .await; + assert_eq!(st, StatusCode::OK); + assert_eq!(body["drain"]["draining"], true); + assert_eq!(body["drain"]["admission_open"], false); + + let spec = ucloud_noded::registry::SandboxSpec::from_dict(&json!({ + "id": "sb-drained", + "image": "alpine:3.20", + })) + .unwrap(); + let mut payload = spec.to_dict().as_object().unwrap().clone(); + payload.insert( + "_ucloud_operation".into(), + json!({ + "generation": 1, + "kind": "create", + "operation_id": "op-create-drained", + "spec_hash": spec.sha256(), + }), + ); + let (st, body) = send(addr, Method::POST, "/v1/sandboxes", Some(TOKEN), &[], Some(Value::Object(payload))).await; + assert_eq!(st, StatusCode::SERVICE_UNAVAILABLE); + assert_eq!(body["error_code"], "node_admission_closed"); + + // 10. Unknown authenticated route returns 404 JSON + let (st, _) = send(addr, Method::GET, "/v1/does-not-exist", Some(TOKEN), &[], None).await; + assert_eq!(st, StatusCode::NOT_FOUND); + + // 11. Background heartbeat pusher delivered at least one heartbeat to mock gateway + for _ in 0..40 { + if !pushed_hbs.lock().unwrap().is_empty() { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(25)).await; + } + let received = pushed_hbs.lock().unwrap().clone(); + assert!(!received.is_empty(), "heartbeat pusher did not deliver a heartbeat"); + assert_eq!(received[0]["node_id"], "node-rust-1"); + + let _ = stop_tx.send(()); + let _ = srv.await; + rt.shutdown().await; + let _ = std::fs::remove_dir_all(root); +} diff --git a/sandboxes/autoscaler/__init__.py b/sandboxes/autoscaler/__init__.py new file mode 100644 index 00000000..53f09071 --- /dev/null +++ b/sandboxes/autoscaler/__init__.py @@ -0,0 +1,89 @@ +"""Autoscaler imperative shell and pure planning helpers.""" + +from .actions import ( + CREATE_QUOTA_BACKOFF, + apply_prepared_provider_operations, + apply_soft_drain, + builder_capacity_operation_succeeded, + delete_stuck_starts, + drain_intent_to_dict, + drain_response_acknowledges, + execute_cold_offload, + journal_create_operations, + journal_stop_operations, + quota_blocked_roles, + reconcile_drain_intents, + reconcile_provider_operation_inventory, + replay_pending_deletes, + sandbox_capacity_operation_succeeded, + soft_drain_migration_id, + soft_drain_movable_routes, + stop_operation_has_safety_proof, + successful_create_operation_count, +) +from .observe import ( + ProviderObservation, + apply_route_reservations_to_heartbeats, + apply_route_reservations_to_nodes, + build_activity_sandbox_warm_resources, + builder_pool_nodes, + demand_forecast_from_usage, + demand_with_build_warm_resources, + guest_continuity_matches, + is_managed_compute_instance, + nodes_with_drain_admission_reopened, + observe_provider_nodes, + partition_storage_native_detachable_stop_job_ids, + probe_nodes, + probe_unreachable_node, + quarantine_unverified_guests, + sandbox_pool_nodes, + sandbox_route_reservations, + should_include_job, + unverified_interruption, +) +from .ports import AutoscalerPorts +from .reconcile import run_reconcile_cycle + +__all__ = [ + "AutoscalerPorts", + "CREATE_QUOTA_BACKOFF", + "ProviderObservation", + "apply_prepared_provider_operations", + "apply_route_reservations_to_heartbeats", + "apply_route_reservations_to_nodes", + "apply_soft_drain", + "build_activity_sandbox_warm_resources", + "builder_capacity_operation_succeeded", + "builder_pool_nodes", + "delete_stuck_starts", + "demand_forecast_from_usage", + "demand_with_build_warm_resources", + "drain_intent_to_dict", + "drain_response_acknowledges", + "execute_cold_offload", + "guest_continuity_matches", + "is_managed_compute_instance", + "journal_create_operations", + "journal_stop_operations", + "nodes_with_drain_admission_reopened", + "observe_provider_nodes", + "partition_storage_native_detachable_stop_job_ids", + "probe_nodes", + "probe_unreachable_node", + "quarantine_unverified_guests", + "quota_blocked_roles", + "reconcile_drain_intents", + "reconcile_provider_operation_inventory", + "replay_pending_deletes", + "run_reconcile_cycle", + "sandbox_capacity_operation_succeeded", + "sandbox_pool_nodes", + "sandbox_route_reservations", + "should_include_job", + "soft_drain_migration_id", + "soft_drain_movable_routes", + "stop_operation_has_safety_proof", + "successful_create_operation_count", + "unverified_interruption", +] diff --git a/sandboxes/autoscaler/actions.py b/sandboxes/autoscaler/actions.py new file mode 100644 index 00000000..8d5c24d3 --- /dev/null +++ b/sandboxes/autoscaler/actions.py @@ -0,0 +1,881 @@ +"""Autoscaler actions: drain handshakes, soft drain, maintenance, and provider ops.""" + +from __future__ import annotations + +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass +from datetime import datetime, timedelta +from http import HTTPStatus +from typing import Any, Callable, Iterable +from urllib.error import HTTPError +from urllib.parse import quote + +from ..autoscaler_state import ( + AutoscalerStateError, + AutoscalerStateStore, + DrainIntent, + ProviderOperation, + ProviderOperationOutcome, + stable_provider_operation_id, +) +from ..capabilities import STORAGE_NATIVE_CAPABILITY, STORAGE_NATIVE_DETACH_CAPABILITY +from ..control_plane import SANDBOX_GENERATION_HEADER, SANDBOX_OPERATION_ID_HEADER +from ..control_state import ControlStateStore +from ..models import ( + ProviderInstance, + ResourceQuantity, + SandboxNode, + ScalePolicy, + is_soft_drained, + utc_now, +) +from ..policy import unreachable_node_reference +from ..providers.base import ComputeProvider, InstanceCreateIntent, QUOTA_EXCEEDED +from ..reconcile import node_drain_ready, with_provider_operation_label +from ..routing import SandboxRoute, is_worker_detachable_parked_route +from ..stuck_starts import StuckStart +from ..telemetry import Telemetry + +_DISABLED_TELEMETRY = Telemetry.disabled("autoscaler") +_SOFT_DRAIN_MOVE_TIMEOUT_SECONDS = 60.0 +_PENDING_DELETE_REPLAY_CONCURRENCY = 8 + +# An account limit does not lift within a cycle. Retrying it every cycle spends +# the provider's API rate limit, which inventory and stops share. +CREATE_QUOTA_BACKOFF = timedelta(minutes=5) + + +def soft_drain_migration_id(route: SandboxRoute) -> str: + """Stable migration ID per parked incarnation for idempotent retries.""" + return f"drain-{route.job_id}-{route.sandbox_id}-{route.generation}" + + +def soft_drain_movable_routes( + routes: Iterable[SandboxRoute], + *, + pending_wake_sandbox_ids: set[str], + limit: int, +) -> list[SandboxRoute]: + return [ + route + for route in routes + if route.worker_state == "attached" + and (route.state or "").lower() == "parked" + and not route.delete_operation_id + and route.sandbox_id not in pending_wake_sandbox_ids + ][: max(0, limit)] + + +def _move_soft_drained_sandbox( + route: SandboxRoute, + *, + gateway_url: str, + bearer_token: str | None, + post_migration: Callable[..., dict[str, Any]], +) -> dict[str, Any]: + migration_id = soft_drain_migration_id(route) + entry: dict[str, Any] = { + "jobId": route.job_id, + "sandboxId": route.sandbox_id, + "migrationId": migration_id, + "requestSucceeded": False, + "skipped": False, + "destinationJobId": "", + "error": "", + } + try: + payload = post_migration( + gateway_url, + route.sandbox_id, + bearer_token=bearer_token, + timeout_seconds=_SOFT_DRAIN_MOVE_TIMEOUT_SECONDS, + migration_id=migration_id, + soft_drain=True, + ) + except HTTPError as exc: + entry["skipped"] = exc.code == HTTPStatus.SERVICE_UNAVAILABLE + entry["error"] = f"HTTP {exc.code}: {exc.reason}" + return entry + except Exception as exc: + entry["error"] = str(exc) + return entry + migration = payload.get("migration") + migration = migration if isinstance(migration, dict) else {} + entry["requestSucceeded"] = migration.get("phase") == "complete" + entry["destinationJobId"] = str(migration.get("destination_job_id") or "") + return entry + + +def apply_soft_drain( + decision: Any, + nodes: list[SandboxNode], + *, + control_state: ControlStateStore, + policy: ScalePolicy, + route_reservations: dict[str, tuple[SandboxRoute, ...]], + blocked_job_ids: set[str], + pending_wake_sandbox_ids: set[str], + gateway_url: str, + bearer_token: str | None, + execute: bool, + assert_provider_fence: Callable[[], None], + post_migration: Callable[..., dict[str, Any]], +) -> tuple[dict[str, Any], list[dict[str, Any]]]: + """Persist the soft-drain plan, then move the worker's published parks.""" + + job_id = decision.soft_drain_job_id + selected = bool(job_id and decision.soft_drain_selected) + if selected and job_id in blocked_job_ids: + job_id, selected = "", False + result: dict[str, Any] = { + "jobId": job_id, + "selected": selected, + "clearedJobIds": list(decision.soft_drain_clear_job_ids), + "applied": False, + } + if not execute: + return result, [] + for cleared in decision.soft_drain_clear_job_ids: + control_state.clear_soft_drain(cleared) + heartbeats = {node.job_id: node.heartbeat for node in nodes} + if job_id and not is_soft_drained(heartbeats.get(job_id)): + control_state.set_soft_drain(job_id, utc_now().isoformat()) + result["applied"] = True + if not job_id or job_id in blocked_job_ids: + return result, [] + routes = soft_drain_movable_routes( + route_reservations.get(job_id, ()), + pending_wake_sandbox_ids=pending_wake_sandbox_ids, + limit=policy.drain_on_park_moves_per_cycle, + ) + if not routes: + return result, [] + assert_provider_fence() + with ThreadPoolExecutor(max_workers=len(routes)) as pool: + moves = list( + pool.map( + lambda route: _move_soft_drained_sandbox( + route, + gateway_url=gateway_url, + bearer_token=bearer_token, + post_migration=post_migration, + ), + routes, + ) + ) + return result, moves + + +def delete_stuck_starts( + items: list[StuckStart], + *, + bearer_token: str, + delete_node_sandbox: Callable[..., Any], + timeout_seconds: float = 30.0, +) -> list[dict[str, Any]]: + """Delete each stuck registration on its worker, fenced to its own incarnation.""" + + def delete(item: StuckStart) -> dict[str, Any]: + error = "" + try: + delete_node_sandbox( + item.node_url, + f"/v1/sandboxes/{quote(item.sandbox_id, safe='')}", + bearer_token=bearer_token, + invalid_url_error="node heartbeat has an invalid node URL", + empty_token_error="node control bearer token cannot be empty", + timeout_seconds=timeout_seconds, + response_name="node stuck start delete", + extra_headers={ + SANDBOX_GENERATION_HEADER: str(item.generation), + SANDBOX_OPERATION_ID_HEADER: item.operation_id, + }, + ) + except Exception as exc: + error = str(exc) + return { + "job_id": item.job_id, + "sandbox_id": item.sandbox_id, + "generation": item.generation, + "operation_id": item.operation_id, + "deleted": not error, + "error": error, + } + + if not items: + return [] + with ThreadPoolExecutor( + min(_PENDING_DELETE_REPLAY_CONCURRENCY, len(items)) + ) as pool: + return list(pool.map(delete, items)) + + +def replay_pending_deletes( + routes: list[SandboxRoute], + *, + skip_job_ids: set[str], + provider_state: AutoscalerStateStore, + deployment_id: str, + budget: int, + gateway_url: str, + bearer_token: str | None, + delete_gateway_sandbox: Callable[..., dict[str, Any]], + timeout_seconds: float = 30.0, +) -> list[dict[str, Any]]: + """Deliver recorded client DELETE intents, least recently attempted first.""" + by_key = { + (route.sandbox_id, route.delete_operation_id): route + for route in sorted( + routes, key=lambda route: (route.updated_at, route.sandbox_id) + ) + } + eligible = [ + key for key, route in by_key.items() if route.job_id not in skip_job_ids + ] + + def replay(key: tuple[str, str]) -> dict[str, Any]: + route, error, payload = by_key[key], "", {} + try: + payload = delete_gateway_sandbox( + gateway_url, + route.sandbox_id, + bearer_token=bearer_token, + timeout_seconds=timeout_seconds, + ) + except Exception as exc: + error = str(exc) + return { + "job_id": route.job_id, + "sandbox_id": route.sandbox_id, + "gateway_url": gateway_url, + "delete_operation_id": route.delete_operation_id, + "request_succeeded": not error, + "deleted": payload.get("deleted"), + "error": error, + } + + selected = provider_state.rotate_pending_deletes( + deployment_id=deployment_id, + pending=eligible, + recorded=by_key, + budget=budget, + ) + if not selected: + return [] + with ThreadPoolExecutor( + min(_PENDING_DELETE_REPLAY_CONCURRENCY, len(selected)) + ) as pool: + return list(pool.map(replay, selected)) + + +def execute_cold_offload( + cold_offload_plan: list[Any], + *, + gateway_url: str, + bearer_token: str | None, + assert_provider_fence: Callable[[], None], + post_gateway_detach: Callable[..., dict[str, Any]], +) -> list[dict[str, Any]]: + results: list[dict[str, Any]] = [] + for candidate in cold_offload_plan: + assert_provider_fence() + detach_payload: dict[str, Any] = {} + detach_error = "" + try: + detach_payload = post_gateway_detach( + gateway_url, + candidate.route.sandbox_id, + bearer_token=bearer_token, + if_cold=candidate.route, + ) + except Exception as exc: + detach_error = str(exc) + results.append( + { + **candidate.to_dict(), + "gateway_url": gateway_url, + "request_succeeded": not detach_error, + "sandbox": detach_payload.get("sandbox", {}), + "error": detach_error, + } + ) + return results + + +def drain_response_acknowledges( + response: dict[str, Any], + *, + token: str, + draining: bool, +) -> bool: + drain = response.get("drain") + return bool( + isinstance(drain, dict) + and str(drain.get("token") or "").strip() == str(token).strip() + and drain.get("draining") is draining + and drain.get("admission_open") is (not draining) + ) + + +def drain_intent_to_dict(intent: DrainIntent) -> dict[str, Any]: + return { + "deploymentId": intent.deployment_id, + "jobId": intent.job_id, + "role": intent.role, + "token": intent.token, + "state": intent.state, + "updatedAt": intent.updated_at.isoformat(), + } + + +def stop_operation_has_safety_proof( + provider_state: AutoscalerStateStore, + provider: ComputeProvider, + operation: ProviderOperation, +) -> bool: + del provider + if operation.kind != "stop" or len(operation.target_job_ids) != 1: + return operation.kind != "stop" + if operation.request.get("unreachableStaleReady") is True: + route_count = operation.request.get("routeCount") + active_sandboxes = operation.request.get("lastKnownActiveSandboxes") + return bool( + str(operation.request.get("unreachableReference") or "").strip() + and type(route_count) is int + and route_count == 0 + and type(active_sandboxes) is int + and active_sandboxes == 0 + and operation.request.get("lastHeartbeatSafeToStop") is True + and ( + operation.request.get("lastHeartbeatPresent") is False + or operation.request.get("directProbeFailed") is True + ) + ) + token = str(operation.request.get("drainToken") or "").strip() + if not token or operation.request.get("drainReady") is not True: + return False + intent = provider_state.get_drain_intent( + operation.deployment_id, + operation.target_job_ids[0], + ) + return bool( + intent is not None + and intent.state == "active" + and intent.token == token + and intent.role == operation.role + ) + + +def apply_prepared_provider_operations( + provider_state: AutoscalerStateStore, + provider: ComputeProvider, + *, + source: str, + allowed_kinds: set[str], + allowed_stop_operation_ids: set[str] | None = None, + telemetry: Telemetry | None = None, +) -> list[ProviderOperationOutcome]: + telemetry = telemetry or _DISABLED_TELEMETRY + results: list[ProviderOperationOutcome] = [] + prepared_operations = provider_state.list_operations(states={"prepared"}) + for prepared in prepared_operations: + if prepared.kind not in allowed_kinds: + continue + if prepared.kind == "stop" and prepared.operation_id not in ( + allowed_stop_operation_ids or set() + ): + continue + if prepared.kind == "stop" and not stop_operation_has_safety_proof( + provider_state, provider, prepared + ): + continue + submitting = provider_state.begin_provider_call(prepared.operation_id) + try: + with telemetry.span( + f"provider.{submitting.kind}", + attributes={ + "provider.operation.id": submitting.operation_id, + "provider.operation.kind": submitting.kind, + "provider.role": submitting.role, + "provider.target_count": len(submitting.target_job_ids), + }, + ) as provider_span: + if submitting.kind == "create": + outcome = provider.create(submitting.request) + else: + outcome = provider.terminate(submitting.target_job_ids) + provider_span.set_attribute("provider.outcome", outcome.status) + except Exception as exc: + operation = provider_state.mark_operation_uncertain( + submitting.operation_id, error=str(exc) + ) + else: + if outcome.status == "rejected": + operation = provider_state.mark_operation_failed( + submitting.operation_id, + error=outcome.error or "provider explicitly rejected the operation", + response=outcome.response, + ) + elif outcome.status == "accepted": + operation = provider_state.mark_operation_accepted( + submitting.operation_id, + response=outcome.response, + target_job_ids=outcome.instance_ids, + ) + else: + operation = provider_state.mark_operation_uncertain( + submitting.operation_id, + error=outcome.error + or "provider response did not prove whether the operation applied", + ) + results.append( + ProviderOperationOutcome.from_operation(operation, source=source) + ) + return results + + +def successful_create_operation_count( + operation_results: list[ProviderOperationOutcome], + role: str, +) -> int: + relevant = [ + item + for item in operation_results + if item.kind == "create" and item.role == role + ] + job_ids = [job_id for item in relevant for job_id in item.job_ids] + if ( + not relevant + or not all(item.state in {"accepted", "recovered"} for item in relevant) + or len(job_ids) != len(relevant) + or len(set(job_ids)) != len(job_ids) + ): + return 0 + return len(job_ids) + + +def sandbox_capacity_operation_succeeded( + operation_results: list[ProviderOperationOutcome], + resource_deficit: ResourceQuantity, + default_node_resources: ResourceQuantity, +) -> bool: + count = successful_create_operation_count(operation_results, "sandbox") + if count <= 0: + return False + created = ResourceQuantity( + vcpu=default_node_resources.vcpu * count, + memory_mb=default_node_resources.memory_mb * count, + disk_mb=default_node_resources.disk_mb * count, + ) + return resource_deficit.fits_within(created) + + +def builder_capacity_operation_succeeded( + operation_results: list[ProviderOperationOutcome], + *, + existing_builders: int, + desired_builders: int, +) -> bool: + count = successful_create_operation_count(operation_results, "builder") + return count > 0 and existing_builders + count >= desired_builders + + +def quota_blocked_roles( + failed_creates: Iterable[ProviderOperation], + now: datetime, + backoff: timedelta = CREATE_QUOTA_BACKOFF, +) -> set[str]: + """Roles whose creates the provider refused for quota within ``backoff``.""" + + return { + operation.role + for operation in failed_creates + if operation.response.get(QUOTA_EXCEEDED) + and now - operation.updated_at < backoff + } + + +def reconcile_provider_operation_inventory( + *, + provider_state: AutoscalerStateStore | None, + provider: ComputeProvider, + jobs: list[ProviderInstance], + execution_authorized: bool, + execute: bool, + telemetry: Telemetry, +) -> tuple[list[ProviderOperationOutcome], list[dict[str, Any]], set[str]]: + """Replay safe creates and fence creates not yet visible in inventory.""" + + if not execution_authorized or provider_state is None: + return [], [], set() + results = list(provider_state.reconcile_provider_inventory(jobs)) + replay_results = apply_prepared_provider_operations( + provider_state, + provider, + source="prepared-replay", + allowed_kinds={"create"} if execute else set(), + allowed_stop_operation_ids=set(), + telemetry=telemetry, + ) + results.extend(replay_results) + blocked_roles = { + operation.role + for operation in provider_state.list_operations( + kind="create", states={"uncertain", "accepted"} + ) + } + blocked_roles.update( + item.role + for item in replay_results + if item.kind == "create" and item.state == "accepted" + ) + blocked_roles.update( + quota_blocked_roles( + provider_state.list_operations(kind="create", states={"failed"}), + utc_now(), + ) + ) + observed_job_ids = {job.id for job in jobs if job.id} + guards: list[dict[str, Any]] = [] + for operation in provider_state.list_operations(kind="create", states={"accepted"}): + missing_job_ids = sorted(set(operation.target_job_ids) - observed_job_ids) + if not missing_job_ids: + continue + blocked_roles.add(operation.role) + guards.append( + { + "operationId": operation.operation_id, + "role": operation.role, + "state": operation.state, + "missingJobIds": missing_job_ids, + } + ) + return results, guards, blocked_roles + + +@dataclass(frozen=True) +class DrainReconcileOutcome: + pending_drain_intents: list[DrainIntent] + active_drain_intents: list[DrainIntent] + drain_results: list[dict[str, Any]] + drain_ready_stop_job_ids: list[str] + canceled_drain_job_ids: list[str] + detach_results: list[dict[str, Any]] + + +def _detach_draining_worker_routes( + intent: DrainIntent, + route_reservations: dict[str, tuple[SandboxRoute, ...]], + *, + remaining_detach_budget: int, + detach_gateway_url: str, + gateway_control_bearer_token: str | None, + post_gateway_detach: Callable[..., dict[str, Any]], +) -> tuple[list[dict[str, Any]], int]: + results: list[dict[str, Any]] = [] + parked_routes = [ + route + for route in route_reservations.get(intent.job_id, ()) + if is_worker_detachable_parked_route(route) + ] + for route in parked_routes[:remaining_detach_budget]: + detach_error = "" + detach_payload: dict[str, Any] = {} + if not detach_gateway_url: + detach_error = ( + "gateway control URL is required for storage-native worker detach" + ) + if not detach_error: + try: + detach_payload = post_gateway_detach( + detach_gateway_url, + route.sandbox_id, + bearer_token=gateway_control_bearer_token, + ) + except Exception as exc: + detach_error = str(exc) + results.append( + { + "job_id": intent.job_id, + "sandbox_id": route.sandbox_id, + "gateway_url": detach_gateway_url, + "request_succeeded": not detach_error, + "sandbox": detach_payload.get("sandbox", {}), + "error": detach_error, + } + ) + remaining_detach_budget -= 1 + if remaining_detach_budget <= 0: + break + return results, remaining_detach_budget + + +def reconcile_drain_intents( + *, + provider_state: AutoscalerStateStore, + operation_deployment_id: str, + nodes: list[SandboxNode], + stop_job_ids: tuple[str, ...], + sandbox_stop_job_ids: tuple[str, ...], + unreachable_stop_job_id_set: set[str], + irreversible_stop_job_ids: set[str], + quarantined_job_ids: set[str], + route_reservations: dict[str, tuple[SandboxRoute, ...]], + remaining_detach_budget: int, + detach_gateway_url: str, + node_control_bearer_token: str | None, + gateway_control_bearer_token: str | None, + post_node_drain: Callable[..., dict[str, Any]], + post_gateway_detach: Callable[..., dict[str, Any]], +) -> DrainReconcileOutcome: + nodes_by_job_id = {node.job_id: node for node in nodes} + pending_drain_intents = provider_state.pending_drain_intents( + deployment_id=operation_deployment_id + ) + desired_stop_job_ids = set(stop_job_ids) + for intent in pending_drain_intents: + node = nodes_by_job_id.get(intent.job_id) + if ( + intent.state == "active" + and intent.job_id not in desired_stop_job_ids + and intent.job_id not in irreversible_stop_job_ids + and node is not None + and node.heartbeat is not None + and node.heartbeat_fresh + ): + provider_state.begin_drain_cancellation( + deployment_id=intent.deployment_id, job_id=intent.job_id + ) + + sandbox_stop_set = set(sandbox_stop_job_ids) + for job_id in stop_job_ids: + if job_id in unreachable_stop_job_id_set: + continue + provider_state.prepare_drain_intent( + deployment_id=operation_deployment_id, + job_id=job_id, + role="sandbox" if job_id in sandbox_stop_set else "builder", + ) + + pending_drain_intents = provider_state.pending_drain_intents( + deployment_id=operation_deployment_id + ) + drain_results: list[dict[str, Any]] = [] + drain_ready_stop_job_ids: list[str] = [] + canceled_drain_job_ids: list[str] = [] + detach_results: list[dict[str, Any]] = [] + + for intent in pending_drain_intents: + node = nodes_by_job_id.get(intent.job_id) + heartbeat = node.heartbeat if node is not None else None + node_url = str(heartbeat.node_url or "").strip() if heartbeat else "" + response: dict[str, Any] = {} + error = "" + if intent.state == "active" and intent.job_id in unreachable_stop_job_id_set: + error = "unreachable stale-node stop proof selected" + elif intent.state == "active" and intent.job_id in quarantined_job_ids: + error = "guest continuity is unverified; drain cannot authorize termination" + elif not node_url: + error = "fresh node heartbeat has no node URL" + else: + try: + if intent.state == "canceling": + response = post_node_drain( + node_url, + intent.token, + draining=False, + bearer_token=node_control_bearer_token, + ) + elif node_control_bearer_token is None: + response = post_node_drain(node_url, intent.token) + else: + response = post_node_drain( + node_url, + intent.token, + bearer_token=node_control_bearer_token, + ) + except Exception as exc: + error = str(exc) + + drain_acknowledged = bool( + intent.state == "active" + and not error + and drain_response_acknowledges(response, token=intent.token, draining=True) + ) + if ( + drain_acknowledged + and intent.role == "sandbox" + and heartbeat is not None + and STORAGE_NATIVE_CAPABILITY in heartbeat.capabilities + and STORAGE_NATIVE_DETACH_CAPABILITY in heartbeat.capabilities + and remaining_detach_budget > 0 + ): + worker_detaches, remaining_detach_budget = _detach_draining_worker_routes( + intent, + route_reservations, + remaining_detach_budget=remaining_detach_budget, + detach_gateway_url=detach_gateway_url, + gateway_control_bearer_token=gateway_control_bearer_token, + post_gateway_detach=post_gateway_detach, + ) + detach_results.extend(worker_detaches) + + cancellation_acknowledged = False + ready = False + if intent.state == "canceling": + cancellation_acknowledged = bool( + not error + and drain_response_acknowledges( + response, token=intent.token, draining=False + ) + ) + if cancellation_acknowledged: + provider_state.retire_drain_intent( + deployment_id=intent.deployment_id, job_id=intent.job_id + ) + canceled_drain_job_ids.append(intent.job_id) + else: + ready = ( + not error + and node is not None + and node_drain_ready(node, intent.token) + ) + if ready: + drain_ready_stop_job_ids.append(intent.job_id) + + drain_results.append( + { + "jobId": intent.job_id, + "role": intent.role, + "action": ("undrain" if intent.state == "canceling" else "drain"), + "nodeUrl": node_url, + "requestSucceeded": not error, + "heartbeatReady": ready, + "cancellationAcknowledged": cancellation_acknowledged, + "error": error, + } + ) + + pending_drain_intents = provider_state.pending_drain_intents( + deployment_id=operation_deployment_id + ) + active_drain_intents = [ + intent for intent in pending_drain_intents if intent.state == "active" + ] + return DrainReconcileOutcome( + pending_drain_intents=pending_drain_intents, + active_drain_intents=active_drain_intents, + drain_results=drain_results, + drain_ready_stop_job_ids=drain_ready_stop_job_ids, + canceled_drain_job_ids=canceled_drain_job_ids, + detach_results=detach_results, + ) + + +def journal_create_operations( + *, + provider_state: AutoscalerStateStore, + provider: ComputeProvider, + operation_deployment_id: str, + sandbox_create_intents: list[InstanceCreateIntent], + builder_create_intents: list[InstanceCreateIntent], +) -> tuple[ + list[ProviderOperation], + list[InstanceCreateIntent], + list[InstanceCreateIntent], +]: + journaled: list[ProviderOperation] = [] + labeled_sandbox: list[InstanceCreateIntent] = [] + labeled_builder: list[InstanceCreateIntent] = [] + for role, intents, destination in ( + ("sandbox", sandbox_create_intents, labeled_sandbox), + ("builder", builder_create_intents, labeled_builder), + ): + for intent in intents: + intent_key = provider_state.allocate_operation_intent_key( + deployment_id=operation_deployment_id, + kind="create", + base_key=f"{role}:{intent.seed}", + ) + operation_id = stable_provider_operation_id( + operation_deployment_id, "create", intent_key + ) + labeled = with_provider_operation_label( + intent, operation_id, deployment_id=operation_deployment_id + ) + operation = provider_state.prepare_operation( + intent_key=intent_key, + kind="create", + deployment_id=operation_deployment_id, + role=role, + request=provider.render_create_request([labeled]), + ) + journaled.append(operation) + destination.append(labeled) + return journaled, labeled_sandbox, labeled_builder + + +def journal_stop_operations( + *, + provider_state: AutoscalerStateStore, + operation_deployment_id: str, + drain_ready_stop_job_ids: list[str], + unreachable_stop_job_ids: tuple[str, ...], + sandbox_stop_job_ids: tuple[str, ...], + active_drain_intents: list[DrainIntent], + stop_nodes_by_job_id: dict[str, SandboxNode], + route_reservations: dict[str, tuple[SandboxRoute, ...]], +) -> list[ProviderOperation]: + journaled: list[ProviderOperation] = [] + stop_ids_to_journal = tuple( + dict.fromkeys([*drain_ready_stop_job_ids, *unreachable_stop_job_ids]) + ) + unreachable_set = set(unreachable_stop_job_ids) + sandbox_stop_set = set(sandbox_stop_job_ids) + drain_intents_by_job = {intent.job_id: intent for intent in active_drain_intents} + for job_id in stop_ids_to_journal: + unreachable_ready = job_id in unreachable_set + drain_intent = drain_intents_by_job.get(job_id) + role = ( + drain_intent.role + if drain_intent is not None and not unreachable_ready + else ("sandbox" if job_id in sandbox_stop_set else "builder") + ) + request: dict[str, Any] = {"type": "bulk", "items": [{"id": job_id}]} + if unreachable_ready: + node = stop_nodes_by_job_id[job_id] + reference = unreachable_node_reference(node) + request.update( + { + "unreachableStaleReady": True, + "unreachableReference": ( + reference.isoformat() if reference is not None else "" + ), + "routeCount": len(route_reservations.get(job_id, ())), + "lastKnownActiveSandboxes": node.active_sandboxes, + "lastHeartbeatSafeToStop": True, + "lastHeartbeatPresent": node.heartbeat is not None, + "directProbeFailed": node.heartbeat is not None, + } + ) + intent_key = ( + f"{role}:{job_id}:unreachable-empty:{request['unreachableReference']}" + ) + elif drain_intent is None: + raise AutoscalerStateError( + f"drain-ready job has no durable intent: {job_id}" + ) + else: + request.update({"drainToken": drain_intent.token, "drainReady": True}) + intent_key = f"{role}:{job_id}:{drain_intent.token}" + journaled.append( + provider_state.prepare_operation( + intent_key=intent_key, + kind="stop", + deployment_id=operation_deployment_id, + role=role, + request=request, + target_job_ids=(job_id,), + ) + ) + return journaled diff --git a/sandboxes/autoscaler/observe.py b/sandboxes/autoscaler/observe.py new file mode 100644 index 00000000..b5648a76 --- /dev/null +++ b/sandboxes/autoscaler/observe.py @@ -0,0 +1,804 @@ +"""Provider node observation, continuity checks, and route-reservation projection.""" + +from __future__ import annotations + +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass, replace +from datetime import datetime +from pathlib import Path +import sys +import time +from typing import Any, Callable, Iterable +from urllib.error import HTTPError, URLError + +from ..agent import fetch_node_agent_heartbeat +from ..capabilities import STORAGE_NATIVE_CAPABILITY, STORAGE_NATIVE_DETACH_CAPABILITY +from ..config import DeploymentConfig +from ..control_state import ( + CONTINUITY_VERIFIED_THROUGH, + QUARANTINE_EPOCH, + QUARANTINE_REASON, + ControlStateStore, + quarantined_labels, + recovered_labels, +) +from ..deployment import BUILDER_LABEL, DEPLOYMENT_LABEL, NODE_LABEL +from ..disk_claims import IDLE_MEMORY_CLAIM_MB +from ..models import ( + InstancePhase, + NodeHeartbeat, + ProviderInstance, + ResourceQuantity, + SandboxDemand, + SandboxNode, + SandboxPlacementRequest, + ScalePolicy, + parse_iso_datetime, + utc_now, +) +from ..policy import unreachable_node_stop_ready +from ..providers.base import ComputeProvider, ProviderError +from ..registry import merge_jobs_and_heartbeats +from ..routing import ( + RoutingStore, + SandboxRoute, + is_portable_parked_route, + is_worker_detachable_parked_route, +) +from ..usage_history import ( + UsageHistory, + demand_with_usage_forecast, + record_inventory_usage, +) + +_USAGE_HISTORIES: dict[Path, UsageHistory] = {} + + +@dataclass(frozen=True) +class ProviderObservation: + jobs: list[ProviderInstance] + nodes: list[SandboxNode] + sandbox_nodes: list[SandboxNode] + builder_nodes: list[SandboxNode] + unreachable_probe_results: list[dict[str, Any]] + # Lease-expired empty workers whose direct probe failed in transport. + unreachable_probe_failed_job_ids: frozenset[str] + final_heartbeat_job_ids: tuple[str, ...] + orphaned_stale_heartbeat_job_ids: tuple[str, ...] + # Routes a verified same-boot quarantine probe proved absent. + retired_routes: tuple[SandboxRoute, ...] = () + + +def is_managed_compute_instance(job: ProviderInstance, deployment_id: str) -> bool: + """Return whether a provider instance belongs to this managed deployment.""" + + return bool( + deployment_id + and job.labels.get(DEPLOYMENT_LABEL) == deployment_id + and ( + job.labels.get(NODE_LABEL) == "true" + or job.labels.get(BUILDER_LABEL) == "true" + ) + ) + + +def should_include_job( + job: ProviderInstance, + config: DeploymentConfig, + provider: ComputeProvider, + include_ids: set[str], +) -> bool: + if job.id in include_ids: + return True + if not is_managed_compute_instance(job, config.deployment_id): + return False + return provider.instance_is_eligible(job) + + +def sandbox_pool_nodes(nodes: list[Any]) -> list[Any]: + return [node for node in nodes if node.job.labels.get(NODE_LABEL) == "true"] + + +def builder_pool_nodes(nodes: list[Any]) -> list[Any]: + return [node for node in nodes if node.job.labels.get(BUILDER_LABEL) == "true"] + + +def nodes_with_drain_admission_reopened( + nodes: list[SandboxNode], + job_ids: set[str], +) -> list[SandboxNode]: + """Return a planning-only view where selected drain intents are canceled.""" + + reopened: list[SandboxNode] = [] + for node in nodes: + heartbeat = node.heartbeat + if node.job_id not in job_ids or heartbeat is None: + reopened.append(node) + continue + reopened.append( + replace( + node, + heartbeat=replace( + heartbeat, + draining=False, + admission_open=True, + ), + ) + ) + return reopened + + +def guest_continuity_matches( + previous: NodeHeartbeat, + fresh: NodeHeartbeat, + routes: tuple[SandboxRoute, ...], +) -> bool: + """A reachable endpoint alone cannot restore placement authority.""" + if ( + not fresh.node_epoch + or not fresh.inventory_complete + or fresh.active_sandbox_creates + or fresh.node_epoch in previous.retired_node_epochs + ): + return False + anchor = previous.labels.get(QUARANTINE_EPOCH, previous.node_epoch) + if anchor != fresh.node_epoch and ( + routes or fresh.inventory or fresh.active_workloads + ): + return False + inventory = {item.sandbox_id: item for item in fresh.inventory} + if len(inventory) != len(fresh.inventory): + return False + for route in routes: + item = inventory.get(route.sandbox_id) + if ( + item is None + or route.node_epoch != fresh.node_epoch + or route.node_id != fresh.node_id + or (route.generation, route.create_operation_id, route.spec_hash) + != (item.generation, item.operation_id, item.spec_hash) + ): + return False + return True + + +def unverified_interruption(job: ProviderInstance, heartbeat: NodeHeartbeat) -> bool: + """A provider interruption newer than the last verified guest continuity.""" + verified = parse_iso_datetime(heartbeat.labels.get(CONTINUITY_VERIFIED_THROUGH)) + return job.interrupted_at is not None and ( + verified is None or job.interrupted_at > verified + ) + + +def sandbox_route_reservations( + routes: Iterable[SandboxRoute], +) -> dict[str, tuple[SandboxRoute, ...]]: + routes_by_job: dict[str, list[SandboxRoute]] = {} + for route in routes: + if route.worker_state == "detached" and is_portable_parked_route(route): + continue + job_id = route.job_id.strip() + if not job_id: + continue + routes_by_job.setdefault(job_id, []).append(route) + return { + job_id: tuple(sorted(items, key=lambda route: route.sandbox_id)) + for job_id, items in routes_by_job.items() + } + + +def _heartbeat_inventory_contains_route( + inventory: dict[str, Any], + route: SandboxRoute, +) -> bool: + item = inventory.get(route.sandbox_id) + if item is None: + return False + if route.generation <= 0 and item.generation <= 0: + return True + return bool( + route.generation == item.generation + and route.create_operation_id == item.operation_id + and route.spec_hash == item.spec_hash + ) + + +def _storage_native_stop_set_has_detachable_storage( + nodes_by_job_id: dict[str, SandboxNode], + stop_job_ids: tuple[str, ...], + routes_by_job: dict[str, tuple[SandboxRoute, ...]], +) -> bool: + for job_id in stop_job_ids: + routes = tuple( + route + for route in routes_by_job.get(job_id, ()) + if route.worker_state != "detached" + ) + if not routes: + continue + node = nodes_by_job_id.get(job_id) + heartbeat = node.heartbeat if node is not None else None + if not ( + node is not None + and node.heartbeat_fresh + and heartbeat is not None + and heartbeat.inventory_complete + and STORAGE_NATIVE_CAPABILITY in heartbeat.capabilities + and STORAGE_NATIVE_DETACH_CAPABILITY in heartbeat.capabilities + and all(is_worker_detachable_parked_route(route) for route in routes) + ): + return False + inventory = {item.sandbox_id: item for item in heartbeat.inventory} + for route in routes: + if route.worker_state == "attached" and not _heartbeat_inventory_contains_route( + inventory, route + ): + return False + return True + + +def partition_storage_native_detachable_stop_job_ids( + nodes: list[SandboxNode], + requested_job_ids: tuple[str, ...], + routes_by_job: dict[str, tuple[SandboxRoute, ...]], +) -> tuple[tuple[str, ...], tuple[str, ...]]: + """Allow stops whose remaining routes can release worker-local storage.""" + if not requested_job_ids: + return (), () + nodes_by_job_id = {node.job_id: node for node in nodes} + allowed: list[str] = [] + blocked: list[str] = [] + for job_id in dict.fromkeys(requested_job_ids): + if _storage_native_stop_set_has_detachable_storage( + nodes_by_job_id, (job_id,), routes_by_job + ): + allowed.append(job_id) + else: + blocked.append(job_id) + return tuple(allowed), tuple(blocked) + + +def apply_route_reservations_to_heartbeats( + heartbeats: dict[str, NodeHeartbeat], + routes_by_job: dict[str, tuple[SandboxRoute, ...]], +) -> dict[str, NodeHeartbeat]: + """Conservatively merge newer route reservations into stale heartbeats.""" + + reconciled: dict[str, NodeHeartbeat] = {} + for job_id, heartbeat in heartbeats.items(): + inventory = {item.sandbox_id: item for item in heartbeat.inventory} + missing_routes = [ + route + for route in routes_by_job.get(job_id, ()) + if route.worker_state != "detached" + if not _heartbeat_inventory_contains_route(inventory, route) + ] + missing_resources = ResourceQuantity() + for route in missing_routes: + missing_resources = missing_resources + ResourceQuantity( + disk_mb=route.resources.disk_mb + ) + used = heartbeat.used_resources + missing_resources + # A newly assigned create/wake may precede its worker reservation. + # Forecast that near-term RAM demand, but do not reserve every parked + # owner's limit. The worker and route views describe overlapping work; + # taking their maximum avoids charging the same transition twice. + transitioning = { + (item.sandbox_id, item.generation, item.spec_hash, item.operation_id): + item.resources.memory_mb + for item in heartbeat.inventory + if item.state in {"creating", "waking"} + } + for route in routes_by_job.get(job_id, ()): + if route.worker_state == "attached" and route.state in { + "creating", + "waking", + }: + identity = ( + route.sandbox_id, + route.generation, + route.spec_hash, + route.create_operation_id, + ) + transitioning[identity] = max( + transitioning.get(identity, 0), + route.resources.memory_mb, + ) + reserved = replace( + heartbeat.reserved_resources, + memory_mb=max( + heartbeat.reserved_resources.memory_mb, + sum(transitioning.values()), + ), + ) + active_sandboxes = heartbeat.active_sandboxes + len(missing_routes) + reconciled[job_id] = replace( + heartbeat, + used_resources=used, + reserved_resources=reserved, + active_sandboxes=active_sandboxes, + ) + return reconciled + + +def apply_route_reservations_to_nodes( + nodes: list[SandboxNode], + routes_by_job: dict[str, tuple[SandboxRoute, ...]], +) -> list[SandboxNode]: + """Keep route ownership visible even when a job has no heartbeat record.""" + + reconciled: list[SandboxNode] = [] + for node in nodes: + heartbeat = node.heartbeat + owns_releasable_inventory = bool( + node.heartbeat_fresh + and heartbeat is not None + and heartbeat.inventory_complete + and STORAGE_NATIVE_CAPABILITY in heartbeat.capabilities + and STORAGE_NATIVE_DETACH_CAPABILITY in heartbeat.capabilities + and all( + is_worker_detachable_parked_route(route) + for route in routes_by_job.get(node.job_id, ()) + if route.worker_state != "detached" + ) + ) + reconciled.append( + replace( + node, + active_sandboxes=( + node.active_sandboxes + if owns_releasable_inventory + else max( + node.active_sandboxes, + len(routes_by_job.get(node.job_id, ())), + ) + ), + ) + ) + return reconciled + + +def build_activity_sandbox_warm_resources( + *, + active_image_builds: int, + pending_image_builds: int, + prepared_builder_count: int, + policy: ScalePolicy, +) -> ResourceQuantity: + del prepared_builder_count + if max(0, active_image_builds) <= 0 and max(0, pending_image_builds) <= 0: + return ResourceQuantity() + capacity = policy.default_node_resources + return ResourceQuantity( + vcpu=min(1.0, capacity.vcpu), + memory_mb=min(512, capacity.memory_mb), + disk_mb=min(1024, capacity.disk_mb), + ) + + +def demand_with_build_warm_resources( + demand: SandboxDemand, + build_warm_resources: ResourceQuantity, +) -> SandboxDemand: + desired = demand.desired_resources + supplement = ResourceQuantity( + vcpu=max(0.0, build_warm_resources.vcpu - desired.vcpu), + memory_mb=max(0, build_warm_resources.memory_mb - desired.memory_mb), + disk_mb=max(0, build_warm_resources.disk_mb - desired.disk_mb), + ) + if supplement == ResourceQuantity(): + return demand + return replace( + demand, + prepared_placement_requests=( + *demand.prepared_placement_requests, + SandboxPlacementRequest(resources=supplement), + ), + ) + + +def _initial_disk_claim_mb(config: DeploymentConfig, heartbeats: Iterable[NodeHeartbeat]) -> int: + """What a worker charges a new sandbox's disk at create; 0 if not dynamic.""" + + for heartbeat in heartbeats: + metrics = heartbeat.runtime_metrics + if metrics is not None and metrics.storage_workspace_grant_mb > 0: + return ( + metrics.storage_workspace_grant_mb + + metrics.storage_memory_idle_claim_mb + ) + sandbox = config.sandbox + if sandbox.direct_workspace_initial_grant_mb > 0: + return sandbox.direct_workspace_initial_grant_mb + IDLE_MEMORY_CLAIM_MB + return 0 + + +def demand_forecast_from_usage( + config: DeploymentConfig, + demand: SandboxDemand, + heartbeats: list[NodeHeartbeat], + route_reservations: dict[str, tuple[SandboxRoute, ...]], +) -> SandboxDemand: + """Record running sandboxes' usage, then size cold demand from that history.""" + + path = config.usage_history_file() + history = _USAGE_HISTORIES.get(path) + if history is None: + history = _USAGE_HISTORIES[path] = UsageHistory.load(path) + now = time.time() + images = { + (route.sandbox_id, route.generation): str(route.spec.get("image") or "") + for routes in route_reservations.values() + for route in routes + } + record_inventory_usage(history, heartbeats, images, now) + history.prune(now) + forecast = demand_with_usage_forecast( + demand, + history, + initial_disk_claim_mb=_initial_disk_claim_mb(config, heartbeats), + now=now, + ) + try: + history.save_if_due(now) + except OSError as exc: + print(f"warning: could not save sandbox usage history: {exc}", file=sys.stderr) + return forecast + + +def probe_unreachable_node( + heartbeat: NodeHeartbeat, + bearer_token: str | None, + heartbeat_ttl_seconds: int = 60, + *, + fetch_heartbeat: Callable[..., NodeHeartbeat] = fetch_node_agent_heartbeat, + now: datetime | None = None, +) -> tuple[NodeHeartbeat | None, bool]: + """Recover a lost push path; only transport failure supports retirement.""" + if not heartbeat.node_url: + return None, False + try: + fresh = fetch_heartbeat( + heartbeat.node_url, + bearer_token=bearer_token, + timeout_seconds=3.0, + ) + except Exception as exc: + reason = exc.__cause__ or exc + # HTTP/auth/schema failures prove contact, not VM loss. Do not turn a + # token or protocol misconfiguration into destructive VM retirement. + return None, isinstance(reason, (URLError, OSError)) and not isinstance( + reason, HTTPError + ) + if (fresh.job_id, fresh.node_id, fresh.deployment_id) != ( + heartbeat.job_id, + heartbeat.node_id, + heartbeat.deployment_id, + ): + return None, False + checked_at = now or utc_now() + if not fresh.is_fresh(checked_at, heartbeat_ttl_seconds): + return None, False + # The probe reached this canonical endpoint; that is the proven node URL. + return replace(fresh, node_url=heartbeat.node_url, received_at=checked_at), False + + +def probe_nodes( + heartbeats: dict[str, NodeHeartbeat], + bearer_token: str | None, + ttl_seconds: int, + *, + probe_one: Callable[..., tuple[NodeHeartbeat | None, bool]] = probe_unreachable_node, +) -> dict[str, tuple[NodeHeartbeat | None, bool]]: + """Probe each worker directly, eight at a time; results in input order.""" + if not heartbeats: + return {} + with ThreadPoolExecutor(max_workers=min(8, len(heartbeats))) as pool: + futures = { + job_id: pool.submit(probe_one, heartbeat, bearer_token, ttl_seconds) + for job_id, heartbeat in heartbeats.items() + } + return {job_id: future.result() for job_id, future in futures.items()} + + +def _retire_absent_routes( + routing_store: RoutingStore, + fresh: NodeHeartbeat, + routes: tuple[SandboxRoute, ...], +) -> tuple[tuple[SandboxRoute, ...], list[SandboxRoute]]: + """Apply a verified same-boot inventory's absences by the ingest rules.""" + removed, _ = routing_store.reconcile_sandboxes_for_node( + fresh.node_url or "", + (), + node_id=fresh.node_id, + job_id=fresh.job_id, + reported_sandbox_ids=[item.sandbox_id for item in fresh.inventory], + observed_at=fresh.freshness_at.isoformat(), + node_epoch=fresh.node_epoch, + activity_epoch=fresh.activity_epoch, + ) + return tuple( + route + for route in routes + if (current := routing_store.get_sandbox_readonly(route.sandbox_id)) is not None + and current.job_id == route.job_id + and current.worker_state != "detached" + ), removed + + +def quarantine_unverified_guests( + jobs: list[ProviderInstance], + heartbeats: dict[str, NodeHeartbeat], + *, + control_state: ControlStateStore, + policy: ScalePolicy, + deployment_id: str, + route_reservations: dict[str, tuple[SandboxRoute, ...]], + execution_authorized: bool, + bearer_token: str | None, + routing_store: RoutingStore | None = None, + retired_routes: list[SandboxRoute] | None = None, + probe_nodes_fn: Callable[ + [dict[str, NodeHeartbeat], str | None, int], + dict[str, tuple[NodeHeartbeat | None, bool]], + ] = probe_nodes, +) -> tuple[list[ProviderInstance], dict[str, NodeHeartbeat]]: + """Fence unverified guests; ``retired_routes`` receives verified absences.""" + candidates: dict[str, NodeHeartbeat] = {} + jobs_by_id = {job.id: job for job in jobs} + for job in jobs: + previous = heartbeats.get(job.id) + if job.is_final or not is_managed_compute_instance(job, deployment_id): + continue + if previous is None: + continue + unready = job.is_unavailable or unverified_interruption(job, previous) + if not ( + unready + or previous.labels.get(QUARANTINE_REASON) + or not previous.is_fresh(utc_now(), policy.heartbeat_ttl_seconds) + ): + continue + reason = ( + "provider_readiness_unverified" + if unready + else "heartbeat_continuity_unverified" + ) + if execution_authorized: + guarded = control_state.quarantine_node(job.id, reason) + if guarded is None: + continue + else: + guarded = replace( + previous, + admission_open=False, + labels=quarantined_labels(previous, reason), + ) + heartbeats[job.id] = guarded + if job.state == "RUNNING": + candidates[job.id] = guarded + recovered: set[str] = set() + probes = probe_nodes_fn(candidates, bearer_token, policy.heartbeat_ttl_seconds) + for jid, (fresh, _transport_failed) in probes.items(): + previous, routes = candidates[jid], route_reservations.get(jid, ()) + if fresh is None: + continue + reported = {item.sandbox_id for item in fresh.inventory} + if ( + routing_store is not None + and fresh.node_epoch + == previous.node_epoch + == previous.labels.get(QUARANTINE_EPOCH) + and guest_continuity_matches( + previous, + fresh, + tuple(route for route in routes if route.sandbox_id in reported), + ) + ): + routes, removed = _retire_absent_routes(routing_store, fresh, routes) + if retired_routes is not None: + retired_routes.extend(removed) + if not guest_continuity_matches(previous, fresh, routes): + continue + verified_through = jobs_by_id[jid].interrupted_at + if not execution_authorized: + fresh = replace( + fresh, labels=recovered_labels(fresh, previous, verified_through) + ) + elif ( + fresh := control_state.recover_quarantined_node( + fresh, verified_through=verified_through + ) + ) is None: + continue + heartbeats[jid] = fresh + recovered.add(jid) + jobs = [ + replace(job, phase=InstancePhase.RUNNING) + if job.id in recovered + else replace(job, phase=InstancePhase.UNAVAILABLE) + if job.id in heartbeats + and heartbeats[job.id].labels.get(QUARANTINE_REASON) + and not job.is_final + else job + for job in jobs + ] + return jobs, heartbeats + + +def observe_provider_nodes( + *, + jobs: list[ProviderInstance], + provider: ComputeProvider, + provider_state: Any, + control_state: ControlStateStore, + policy: ScalePolicy, + deployment_id: str, + route_reservations: dict[str, tuple[SandboxRoute, ...]], + execution_authorized: bool, + retrieve_history: bool, + node_control_bearer_token: str | None = None, + routing_store: RoutingStore | None = None, + probe_nodes_fn: Callable[ + [dict[str, NodeHeartbeat], str | None, int], + dict[str, tuple[NodeHeartbeat | None, bool]], + ] = probe_nodes, + quarantine_fn: Callable[..., tuple[list[ProviderInstance], dict[str, NodeHeartbeat]]] | None = None, +) -> ProviderObservation: + """Normalize provider continuity and heartbeat evidence into node state.""" + del provider_state + heartbeats = control_state.load_heartbeats() + jobs_by_id = {job.id: job for job in jobs} + if retrieve_history: + for job in tuple(jobs): + heartbeat = heartbeats.get(job.id) + owned_routes = route_reservations.get(job.id, ()) + stale_heartbeat = bool( + heartbeat is not None + and not heartbeat.is_fresh(utc_now(), policy.heartbeat_ttl_seconds) + ) + route_epoch_mismatch = bool( + heartbeat is not None + and heartbeat.node_epoch + and any( + route.node_epoch and route.node_epoch != heartbeat.node_epoch + for route in owned_routes + ) + ) + continuity_history_required = bool( + provider.requires_continuity_history + and is_managed_compute_instance(job, deployment_id) + ) + should_retrieve_history = bool( + job.state == "RUNNING" + and not job.is_lost + and ( + continuity_history_required + or (owned_routes and (stale_heartbeat or route_epoch_mismatch)) + ) + ) + if not should_retrieve_history: + continue + try: + jobs_by_id[job.id] = provider.retrieve_instance( + job.id, + include_updates=True, + ) + except ProviderError: + continue + jobs = [jobs_by_id[job.id] for job in jobs] + + provider_job_ids = {job.id for job in jobs} + orphaned_stale_heartbeat_job_ids = tuple( + sorted( + job_id + for job_id, heartbeat in heartbeats.items() + if job_id not in provider_job_ids + and not route_reservations.get(job_id) + and not heartbeat.is_fresh(utc_now(), policy.heartbeat_ttl_seconds) + ) + ) + if orphaned_stale_heartbeat_job_ids and execution_authorized: + control_state.remove_heartbeats(orphaned_stale_heartbeat_job_ids) + heartbeats = { + job_id: heartbeat + for job_id, heartbeat in heartbeats.items() + if job_id not in orphaned_stale_heartbeat_job_ids + } + + retired_routes: list[SandboxRoute] = [] + if provider.requires_guest_continuity: + if quarantine_fn is not None: + jobs, heartbeats = quarantine_fn( + jobs, + heartbeats, + control_state=control_state, + policy=policy, + deployment_id=deployment_id, + route_reservations=route_reservations, + execution_authorized=execution_authorized, + bearer_token=node_control_bearer_token, + routing_store=routing_store if execution_authorized else None, + retired_routes=retired_routes, + ) + else: + jobs, heartbeats = quarantine_unverified_guests( + jobs, + heartbeats, + control_state=control_state, + policy=policy, + deployment_id=deployment_id, + route_reservations=route_reservations, + execution_authorized=execution_authorized, + bearer_token=node_control_bearer_token, + routing_store=routing_store if execution_authorized else None, + retired_routes=retired_routes, + probe_nodes_fn=probe_nodes_fn, + ) + + observed_nodes = merge_jobs_and_heartbeats( + jobs, + apply_route_reservations_to_heartbeats(heartbeats, route_reservations), + policy, + ) + unreachable_probe_results: list[dict[str, Any]] = [] + probe_failed: set[str] = set() + expired = { + node.job_id: node.heartbeat + for node in observed_nodes + if is_managed_compute_instance(node.job, deployment_id) + and node.heartbeat is not None + and unreachable_node_stop_ready(node, policy) + } + probes = probe_nodes_fn( + expired, node_control_bearer_token, policy.heartbeat_ttl_seconds + ) + for job_id, (fresh, transport_failed) in probes.items(): + unreachable_probe_results.append( + { + "jobId": job_id, + "status": ( + "healthy" + if fresh + else "unreachable" + if transport_failed + else "unverified" + ), + } + ) + stored = heartbeats[job_id] + if transport_failed: + probe_failed.add(job_id) + elif fresh is not None and fresh.node_epoch == stored.node_epoch: + heartbeats[job_id] = ( + control_state.receive_heartbeat(fresh).stored + if execution_authorized + else fresh + ) + else: + heartbeats[job_id] = replace(stored, inventory_complete=False) + + final_heartbeat_job_ids = tuple( + sorted(job.id for job in jobs if job.is_final and job.id in heartbeats) + ) + if final_heartbeat_job_ids and execution_authorized: + control_state.remove_heartbeats(final_heartbeat_job_ids) + heartbeats = { + job_id: heartbeat + for job_id, heartbeat in heartbeats.items() + if job_id not in final_heartbeat_job_ids + } + heartbeats = apply_route_reservations_to_heartbeats(heartbeats, route_reservations) + nodes = merge_jobs_and_heartbeats(jobs, heartbeats, policy) + nodes = apply_route_reservations_to_nodes(nodes, route_reservations) + return ProviderObservation( + jobs=jobs, + nodes=nodes, + sandbox_nodes=sandbox_pool_nodes(nodes), + builder_nodes=builder_pool_nodes(nodes), + unreachable_probe_results=unreachable_probe_results, + unreachable_probe_failed_job_ids=frozenset(probe_failed), + final_heartbeat_job_ids=final_heartbeat_job_ids, + orphaned_stale_heartbeat_job_ids=orphaned_stale_heartbeat_job_ids, + retired_routes=tuple(retired_routes), + ) diff --git a/sandboxes/autoscaler/ports.py b/sandboxes/autoscaler/ports.py new file mode 100644 index 00000000..0725ed1d --- /dev/null +++ b/sandboxes/autoscaler/ports.py @@ -0,0 +1,43 @@ +"""Explicit I/O ports for the autoscaler reconcile cycle.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Callable + +from ..models import NodeHeartbeat, ProviderInstance + + +@dataclass(frozen=True) +class AutoscalerPorts: + """I/O boundary injected into the autoscaler reconcile loop. + + All network, SSH, token-file, and CLI-adapter effects cross through these + callables so the reconcile workflow stays decoupled from global transport + helpers and testable without private monkey-patching. + """ + + load_instances: Callable[..., list[ProviderInstance]] + read_required_token_file: Callable[[Any, str], str] + post_node_drain: Callable[..., dict[str, Any]] + post_gateway_migration: Callable[..., dict[str, Any]] + post_gateway_detach: Callable[..., dict[str, Any]] + delete_gateway_sandbox: Callable[..., dict[str, Any]] + delete_node_sandbox: Callable[..., dict[str, Any]] + probe_nodes: Callable[ + [dict[str, NodeHeartbeat], str | None, int], + dict[str, tuple[NodeHeartbeat | None, bool]], + ] + vm_init_options_for_node: Callable[..., Any] + apply_bootstrap_requirements: Callable[[Any], Any] + execute_bootstrap_phase: Callable[..., tuple[dict[str, Any], list[dict[str, Any]]]] + compute_provider_from_args: Callable[..., Any] + node_to_dict: Callable[[Any], dict[str, Any]] + scale_decision_to_dict: Callable[[Any], dict[str, Any]] + dashboard_scale_policy_to_dict: Callable[[Any], dict[str, Any]] + vm_bootstrap_intent_to_dict: Callable[[Any], dict[str, Any]] + apply_soft_drain: Callable[..., tuple[dict[str, Any], list[dict[str, Any]]]] | None = None + replay_pending_deletes: Callable[..., list[dict[str, Any]]] | None = None + delete_stuck_starts: Callable[..., list[dict[str, Any]]] | None = None + quarantine_unverified_guests: Callable[..., tuple[list[ProviderInstance], dict[str, NodeHeartbeat]]] | None = None + pending_delete_timeout_seconds: float = 30.0 diff --git a/sandboxes/autoscaler/reconcile.py b/sandboxes/autoscaler/reconcile.py new file mode 100644 index 00000000..76010a2a --- /dev/null +++ b/sandboxes/autoscaler/reconcile.py @@ -0,0 +1,1002 @@ +"""Staged autoscaler reconcile cycle: observe -> decide -> execute.""" + +from __future__ import annotations + +import argparse +from dataclasses import dataclass, replace +import math +from typing import Any, Callable + +from ..autoscaler_state import ( + AutoscalerStateError, + AutoscalerStateStore, + DrainIntent, + ProviderOperation, + ProviderOperationOutcome, +) +from ..bootstrap import ( + VmBootstrapIntent, + VmBootstrapRecord, + build_vm_bootstrap_intents, + mark_bootstrap_access_refresh, + prune_bootstrap_records, +) +from ..cold_offload import plan_cold_offload +from ..config import DeploymentConfig +from ..control_state import ControlStateStore +from ..deployment import BUILDER_LABEL, NODE_LABEL +from ..metrics import MetricsStore, build_live_scale_signals +from ..models import ( + LiveScaleSignals, + ProviderInstance, + SandboxDemand, + SandboxNode, + ScaleDecision, + ScalePolicy, + utc_now, +) +from ..policy import evaluate_scale, unreachable_node_stop_ready +from ..providers.base import ( + ComputeProvider, + InstanceBootstrapAccess, + ProviderError, +) +from ..reconcile import ( + build_create_intents, + evaluate_builder_scale, + partition_safe_stop_job_ids, + requested_builder_nodes, +) +from ..routing import ProgramRequestState, RoutingStore, SandboxRoute +from ..stuck_starts import stuck_start_candidates, stuck_starts_due, unowned +from ..telemetry import Telemetry +from .actions import ( + DrainReconcileOutcome, + apply_prepared_provider_operations, + apply_soft_drain, + builder_capacity_operation_succeeded, + delete_stuck_starts, + drain_intent_to_dict, + execute_cold_offload, + journal_create_operations, + journal_stop_operations, + reconcile_drain_intents, + reconcile_provider_operation_inventory, + replay_pending_deletes, + sandbox_capacity_operation_succeeded, +) +from .observe import ( + ProviderObservation, + build_activity_sandbox_warm_resources, + demand_forecast_from_usage, + demand_with_build_warm_resources, + nodes_with_drain_admission_reopened, + observe_provider_nodes, + partition_storage_native_detachable_stop_job_ids, +) +from .ports import AutoscalerPorts + +_DISABLED_AUTOSCALER_TELEMETRY = Telemetry.disabled("autoscaler") + + +@dataclass(frozen=True) +class _ScaleEvaluation: + decision: ScaleDecision + builder_decision: ScaleDecision + pending_drain_intents: list[DrainIntent] + irreversible_stop_job_ids: set[str] + + +@dataclass(frozen=True) +class _StopPartitions: + requested_stop_job_ids: tuple[str, ...] + sandbox_stop_job_ids: tuple[str, ...] + builder_stop_job_ids: tuple[str, ...] + stop_job_ids: tuple[str, ...] + blocked_stop_job_ids: tuple[str, ...] + blocked_storage_native_detach_stop_job_ids: tuple[str, ...] + unreachable_stop_job_ids: tuple[str, ...] + + +def _validate_execution_preconditions( + *, + execution_requested: bool, + provider_mutations_allowed: bool, + provider_state: AutoscalerStateStore | None, +) -> None: + if execution_requested and not provider_mutations_allowed and provider_state is None: + raise AutoscalerStateError( + "provider mutations require the local autoscaler controller lock" + ) + if execution_requested and provider_mutations_allowed and provider_state is None: + raise AutoscalerStateError( + "provider mutations require the autoscaler operation journal" + ) + + +def _load_live_scale_signals( + metrics_store: MetricsStore | None, + effective_policy: ScalePolicy, +) -> LiveScaleSignals | None: + if metrics_store is None: + return None + pressure_events = metrics_store.load_events( + max_events=10_000, + kinds=("node_heartbeat", "sandbox_create_busy"), + since_seconds=max( + effective_policy.live_pressure_window_seconds, + effective_policy.create_pressure_window_seconds, + ), + ) + lifecycle_events = metrics_store.load_events( + max_events=20_000, + kinds=("vm_submitted", "node_first_heartbeat", "sandbox_scheduled"), + since_seconds=effective_policy.provisioning_latency_lookback_seconds, + ) + return build_live_scale_signals( + sorted( + [*pressure_events, *lifecycle_events], + key=lambda event: event.timestamp, + ), + effective_policy, + ) + + +def _evaluate_with_counterfactual_drains( + *, + jobs: list[ProviderInstance], + nodes: list[SandboxNode], + sandbox_nodes: list[SandboxNode], + builder_nodes: list[SandboxNode], + sandbox_demand: SandboxDemand, + builder_pending: int, + builder_prepared: int, + effective_policy: ScalePolicy, + max_builder_nodes: int, + live_scale_signals: LiveScaleSignals | None, + drain_workflow_enabled: bool, + provider_state: AutoscalerStateStore | None, + operation_deployment_id: str, +) -> _ScaleEvaluation: + decision = evaluate_scale( + sandbox_nodes, + sandbox_demand, + effective_policy, + live_signals=live_scale_signals, + ) + builder_decision = evaluate_builder_scale( + builder_nodes, + pending_builds=builder_pending, + prepared_builders=builder_prepared, + policy=effective_policy, + max_builder_nodes=max_builder_nodes, + ) + pending_drain_intents: list[DrainIntent] = [] + irreversible_stop_job_ids: set[str] = set() + if not drain_workflow_enabled or provider_state is None: + return _ScaleEvaluation( + decision=decision, + builder_decision=builder_decision, + pending_drain_intents=pending_drain_intents, + irreversible_stop_job_ids=irreversible_stop_job_ids, + ) + + pending_drain_intents = provider_state.pending_drain_intents( + deployment_id=operation_deployment_id + ) + final_job_ids = {job.id for job in jobs if job.id and job.is_final} + for intent in pending_drain_intents: + if intent.job_id in final_job_ids: + provider_state.retire_drain_intent( + deployment_id=intent.deployment_id, job_id=intent.job_id + ) + pending_drain_intents = provider_state.pending_drain_intents( + deployment_id=operation_deployment_id + ) + for operation in provider_state.list_operations(kind="stop"): + provider_call_started = operation.state in {"uncertain", "accepted"} or ( + operation.state == "prepared" + and ( + operation.response.get("providerCallStarted") is True + or operation.updated_at > operation.created_at + or bool(operation.last_error) + ) + ) + if provider_call_started: + irreversible_stop_job_ids.update(operation.target_job_ids) + + nodes_by_job_id = {node.job_id: node for node in nodes} + reopen_job_ids = { + intent.job_id + for intent in pending_drain_intents + if intent.state == "active" + and intent.job_id not in irreversible_stop_job_ids + and (node := nodes_by_job_id.get(intent.job_id)) is not None + and node.heartbeat is not None + and node.heartbeat_fresh + } + if reopen_job_ids: + decision = evaluate_scale( + nodes_with_drain_admission_reopened(sandbox_nodes, reopen_job_ids), + sandbox_demand, + effective_policy, + live_signals=live_scale_signals, + ) + builder_decision = evaluate_builder_scale( + nodes_with_drain_admission_reopened(builder_nodes, reopen_job_ids), + pending_builds=builder_pending, + prepared_builders=builder_prepared, + policy=effective_policy, + max_builder_nodes=max_builder_nodes, + ) + return _ScaleEvaluation( + decision=decision, + builder_decision=builder_decision, + pending_drain_intents=pending_drain_intents, + irreversible_stop_job_ids=irreversible_stop_job_ids, + ) + + +def _partition_stop_targets( + *, + sandbox_nodes: list[SandboxNode], + builder_nodes: list[SandboxNode], + decision: ScaleDecision, + builder_decision: ScaleDecision, + route_reservations: dict[str, tuple[SandboxRoute, ...]], + deployment_id: str, + effective_policy: ScalePolicy, + observation: ProviderObservation, + drain_workflow_enabled: bool, + pending_drain_intents: list[DrainIntent], +) -> _StopPartitions: + requested_sandbox = decision.stops + requested_builder = builder_decision.stops + detachable, blocked_detach = partition_storage_native_detachable_stop_job_ids( + sandbox_nodes, requested_sandbox, route_reservations + ) + sandbox_stops, blocked_sandbox = partition_safe_stop_job_ids( + sandbox_nodes, + detachable, + deployment_id=deployment_id, + ownership_label=NODE_LABEL, + ) + builder_stops, blocked_builder = partition_safe_stop_job_ids( + builder_nodes, + requested_builder, + deployment_id=deployment_id, + ownership_label=BUILDER_LABEL, + ) + requested_stops = tuple(dict.fromkeys([*requested_sandbox, *requested_builder])) + stop_job_ids = tuple(dict.fromkeys([*sandbox_stops, *builder_stops])) + blocked_stops = tuple( + dict.fromkeys([*blocked_sandbox, *blocked_detach, *blocked_builder]) + ) + if drain_workflow_enabled: + canceling_job_ids = { + intent.job_id + for intent in pending_drain_intents + if intent.state == "canceling" + } + if canceling_job_ids: + blocked_canceling = tuple( + job_id for job_id in stop_job_ids if job_id in canceling_job_ids + ) + sandbox_stops = tuple( + job_id for job_id in sandbox_stops if job_id not in canceling_job_ids + ) + builder_stops = tuple( + job_id for job_id in builder_stops if job_id not in canceling_job_ids + ) + stop_job_ids = (*sandbox_stops, *builder_stops) + blocked_stops = (*blocked_stops, *blocked_canceling) + + stop_nodes_by_job_id = { + node.job_id: node for node in (*sandbox_nodes, *builder_nodes) + } + unreachable_stops = tuple( + job_id + for job_id in stop_job_ids + if (node := stop_nodes_by_job_id.get(job_id)) is not None + and unreachable_node_stop_ready(node, effective_policy) + and ( + node.heartbeat is None + or job_id in observation.unreachable_probe_failed_job_ids + ) + ) + return _StopPartitions( + requested_stop_job_ids=requested_stops, + sandbox_stop_job_ids=sandbox_stops, + builder_stop_job_ids=builder_stops, + stop_job_ids=stop_job_ids, + blocked_stop_job_ids=blocked_stops, + blocked_storage_native_detach_stop_job_ids=blocked_detach, + unreachable_stop_job_ids=unreachable_stops, + ) + + +def _run_maintenance_actions( + *, + config: DeploymentConfig, + sandbox_nodes: list[SandboxNode], + sandbox_routes: tuple[SandboxRoute, ...], + quarantined_job_ids: set[str], + provider_state: AutoscalerStateStore, + operation_deployment_id: str, + detach_gateway_url: str, + gateway_control_bearer_token: str, + node_control_bearer_token: str, + routing_store: RoutingStore | None, + assert_provider_fence: Callable[[], None], + ports: AutoscalerPorts, +) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + if ports.replay_pending_deletes is not None: + pending_delete_results = ports.replay_pending_deletes( + [route for route in sandbox_routes if route.delete_operation_id], + skip_job_ids=quarantined_job_ids, + provider_state=provider_state, + deployment_id=operation_deployment_id, + budget=config.autoscaler_max_pending_delete_retries_per_cycle, + gateway_url=detach_gateway_url, + bearer_token=gateway_control_bearer_token, + ) + else: + pending_delete_results = replay_pending_deletes( + [route for route in sandbox_routes if route.delete_operation_id], + skip_job_ids=quarantined_job_ids, + provider_state=provider_state, + deployment_id=operation_deployment_id, + budget=config.autoscaler_max_pending_delete_retries_per_cycle, + gateway_url=detach_gateway_url, + bearer_token=gateway_control_bearer_token, + delete_gateway_sandbox=ports.delete_gateway_sandbox, + timeout_seconds=ports.pending_delete_timeout_seconds, + ) + stuck_start_results: list[dict[str, Any]] = [] + stuck_budget = config.autoscaler_max_stuck_start_deletes_per_cycle + unrouted_budget = config.autoscaler_max_unrouted_sandbox_deletes_per_cycle + if (stuck_budget > 0 or unrouted_budget > 0) and routing_store is not None: + candidates = stuck_start_candidates( + [node for node in sandbox_nodes if node.job_id not in quarantined_job_ids], + sandbox_routes, + unrouted=unrouted_budget > 0, + ) + first_seen = provider_state.track_stuck_starts( + deployment_id=operation_deployment_id, + keys=[item.key for item in candidates], + ) + now = utc_now() + due = stuck_starts_due( + [item for item in candidates if item.state == "planned"], + first_seen, + now, + budget=stuck_budget, + ) + due += stuck_starts_due( + [item for item in candidates if item.state != "planned"], + first_seen, + now, + budget=unrouted_budget, + ) + due = [ + item + for item in due + if unowned( + item.state, + item.generation, + routing_store.get_sandbox_readonly(item.sandbox_id), + ) + ] + assert_provider_fence() + if ports.delete_stuck_starts is not None: + stuck_start_results = ports.delete_stuck_starts( + due, bearer_token=node_control_bearer_token + ) + else: + stuck_start_results = delete_stuck_starts( + due, + bearer_token=node_control_bearer_token, + delete_node_sandbox=ports.delete_node_sandbox, + timeout_seconds=ports.pending_delete_timeout_seconds, + ) + return pending_delete_results, stuck_start_results + + +def _plan_bootstrap_intents( + *, + config: DeploymentConfig, + args: argparse.Namespace, + provider: ComputeProvider, + sandbox_nodes: list[SandboxNode], + builder_nodes: list[SandboxNode], + control_state: ControlStateStore, + bootstrap_coordinator: Any, + execution_authorized: bool, + excluded_job_ids: set[str], + ports: AutoscalerPorts, +) -> tuple[dict[str, VmBootstrapRecord], list[dict[str, Any]], list[VmBootstrapIntent]]: + active_bootstrap_job_ids = { + node.job_id + for node in (*sandbox_nodes, *builder_nodes) + if not node.job.is_final + } + bootstrap_records = prune_bootstrap_records( + control_state.load_bootstrap_records(), active_bootstrap_job_ids + ) + completed_bootstrap_results: list[dict[str, Any]] = [] + if bootstrap_coordinator is not None and execution_authorized: + bootstrap_records, completed_bootstrap_results = ( + bootstrap_coordinator.collect_completed( + bootstrap_records, + control_state, + active_job_ids=active_bootstrap_job_ids, + ) + ) + + def refresh_access_for_instance( + instance: ProviderInstance, + ) -> InstanceBootstrapAccess: + try: + refreshed = provider.retrieve_instance(instance.id, include_updates=True) + except ProviderError as exc: + current = provider.bootstrap_access(instance) + return replace( + current, + runnable=False, + reason=f"Provider access refresh failed: {exc}", + ) + return provider.bootstrap_access(refreshed) + + bootstrap_nodes = [*sandbox_nodes, *builder_nodes] + max_bootstraps = config.autoscaler_max_init_per_cycle + if bootstrap_coordinator is not None: + in_flight_job_ids = bootstrap_coordinator.in_flight_job_ids + bootstrap_nodes = [ + node for node in bootstrap_nodes if node.job_id not in in_flight_job_ids + ] + max_bootstraps = min(max_bootstraps, bootstrap_coordinator.available_slots) + + bootstrap_intents = build_vm_bootstrap_intents( + bootstrap_nodes, + bootstrap_records, + retry_seconds=config.autoscaler_init_retry_seconds, + max_per_cycle=max_bootstraps, + options_for_node=lambda node, role: ports.vm_init_options_for_node( + node, role, args, config + ), + access_for_instance=provider.bootstrap_access, + refresh_access_for_instance=( + refresh_access_for_instance + if args.execute and not getattr(args, "jobs_file", None) + else None + ), + max_access_refreshes=max_bootstraps, + excluded_job_ids=excluded_job_ids, + ) + refreshed_access = False + for intent in bootstrap_intents: + if intent.access_refreshed_at is not None: + refreshed_access = True + bootstrap_records = mark_bootstrap_access_refresh(bootstrap_records, intent) + if refreshed_access: + control_state.save_bootstrap_records(bootstrap_records) + bootstrap_intents = [ + ports.apply_bootstrap_requirements(intent) for intent in bootstrap_intents + ] + return bootstrap_records, completed_bootstrap_results, bootstrap_intents + + +def _apply_planned_provider_operations( + *, + provider_state: AutoscalerStateStore, + provider: ComputeProvider, + execute: bool, + journaled_create_operations: list[ProviderOperation], + journaled_stop_operations: list[ProviderOperation], + provider_operation_results: list[ProviderOperationOutcome], + telemetry: Telemetry, +) -> list[str] | None: + has_prepared_stop = any( + operation.kind == "stop" + for operation in provider_state.list_operations(states={"prepared"}) + ) + if not ( + journaled_create_operations or journaled_stop_operations or has_prepared_stop + ): + return None + planned_allowed_kinds = {"create", "stop"} if execute else set() + planned_results = apply_prepared_provider_operations( + provider_state, + provider, + source="planned", + allowed_kinds=planned_allowed_kinds, + allowed_stop_operation_ids={ + operation.operation_id for operation in journaled_stop_operations + }, + telemetry=telemetry, + ) + provider_operation_results.extend(planned_results) + for operation in journaled_stop_operations: + current = provider_state.get_operation(operation.operation_id) + if ( + current is not None + and current.state == "accepted" + and not any( + item.operation_id == current.operation_id + for item in provider_operation_results + ) + ): + provider_operation_results.append( + ProviderOperationOutcome.from_operation(current, source="journal") + ) + return [ + job_id + for item in planned_results + if item.kind == "create" and item.state == "accepted" + for job_id in item.job_ids + ] + + +def run_reconcile_cycle( + config: DeploymentConfig, + args: argparse.Namespace, + *, + ports: AutoscalerPorts, + provider: ComputeProvider | None = None, + demand: SandboxDemand, + pending_image_builds: int | None = None, + prepared_builder_count: int | None = None, + metrics_store: MetricsStore | None = None, + provider_state: AutoscalerStateStore | None = None, + provider_mutations_allowed: bool = False, + route_reservations: dict[str, tuple[SandboxRoute, ...]] | None = None, + sandbox_routes: tuple[SandboxRoute, ...] = (), + program_requests: tuple[ProgramRequestState, ...] = (), + pending_wake_sandbox_ids: set[str] | None = None, + bootstrap_coordinator: Any = None, + provider_fence: Callable[[], None] | None = None, + telemetry: Telemetry | None = None, + routing_store: RoutingStore | None = None, +) -> dict[str, Any]: + execution_requested = bool(args.execute) + _validate_execution_preconditions( + execution_requested=execution_requested, + provider_mutations_allowed=provider_mutations_allowed, + provider_state=provider_state, + ) + execution_authorized = bool(provider_mutations_allowed) + routes_by_job = route_reservations or {} + + def assert_provider_fence() -> None: + if not provider_mutations_allowed: + raise AutoscalerStateError("autoscaler controller lock is not held") + if provider_fence is not None: + provider_fence() + + # 1. Observe provider inventory, heartbeats, continuity, and live pressure. + provider = provider or ports.compute_provider_from_args(args, config) + telemetry = telemetry or _DISABLED_AUTOSCALER_TELEMETRY + jobs = ports.load_instances(config, provider, args, telemetry=telemetry) + operation_deployment_id = config.deployment_id or provider.scope_id + ( + provider_operation_results, + create_visibility_guards, + blocked_create_roles, + ) = reconcile_provider_operation_inventory( + provider_state=provider_state, + provider=provider, + jobs=jobs, + execution_authorized=execution_authorized, + execute=execution_requested, + telemetry=telemetry, + ) + control_state_file = config.control_state_file() + control_state = ControlStateStore(control_state_file) + effective_policy = config.policy + node_control_bearer_token = ports.read_required_token_file( + config.node_control_token_file(), "node control bearer token" + ) + observation = observe_provider_nodes( + jobs=jobs, + provider=provider, + provider_state=provider_state, + control_state=control_state, + policy=effective_policy, + deployment_id=config.deployment_id, + route_reservations=routes_by_job, + execution_authorized=execution_authorized, + retrieve_history=not bool(getattr(args, "jobs_file", None)), + node_control_bearer_token=node_control_bearer_token, + routing_store=routing_store, + probe_nodes_fn=ports.probe_nodes, + quarantine_fn=ports.quarantine_unverified_guests, + ) + jobs = observation.jobs + nodes = observation.nodes + sandbox_nodes = observation.sandbox_nodes + builder_nodes = observation.builder_nodes + quarantined_job_ids = {node.job_id for node in nodes if node.job.is_unavailable} + + # 2. Forecast demand and run pure scale decisions (with counterfactual drains). + builder_pending = max( + 0, + int( + pending_image_builds + if pending_image_builds is not None + else getattr(args, "pending_image_builds", 0) or 0 + ), + ) + builder_prepared = max( + 0, int(prepared_builder_count if prepared_builder_count is not None else 0) + ) + active_image_builds = sum( + max(0, node.heartbeat.active_image_builds) + for node in builder_nodes + if node.heartbeat is not None and node.heartbeat_fresh + ) + build_warm_resources = build_activity_sandbox_warm_resources( + active_image_builds=active_image_builds, + pending_image_builds=builder_pending, + prepared_builder_count=builder_prepared, + policy=effective_policy, + ) + demand = demand_forecast_from_usage( + config, + demand, + [ + node.heartbeat + for node in sandbox_nodes + if node.heartbeat is not None and node.heartbeat_fresh + ], + routes_by_job, + ) + sandbox_demand = demand_with_build_warm_resources(demand, build_warm_resources) + live_scale_signals = _load_live_scale_signals(metrics_store, effective_policy) + drain_workflow_enabled = bool( + execution_requested and execution_authorized and provider_state is not None + ) + evaluation = _evaluate_with_counterfactual_drains( + jobs=jobs, + nodes=nodes, + sandbox_nodes=sandbox_nodes, + builder_nodes=builder_nodes, + sandbox_demand=sandbox_demand, + builder_pending=builder_pending, + builder_prepared=builder_prepared, + effective_policy=effective_policy, + max_builder_nodes=config.builder.max_nodes, + live_scale_signals=live_scale_signals, + drain_workflow_enabled=drain_workflow_enabled, + provider_state=provider_state, + operation_deployment_id=operation_deployment_id, + ) + decision = evaluation.decision + builder_decision = evaluation.builder_decision + + sandbox_create_intents = ( + [] + if "sandbox" in blocked_create_roles + else build_create_intents( + config, decision, role="sandbox", seed_prefix=args.seed_prefix + ) + ) + builder_create_intents = ( + [] + if "builder" in blocked_create_roles + else build_create_intents( + config, builder_decision, role="builder", seed_prefix=args.seed_prefix + ) + ) + create_intents = [*sandbox_create_intents, *builder_create_intents] + stops = _partition_stop_targets( + sandbox_nodes=sandbox_nodes, + builder_nodes=builder_nodes, + decision=decision, + builder_decision=builder_decision, + route_reservations=routes_by_job, + deployment_id=config.deployment_id, + effective_policy=effective_policy, + observation=observation, + drain_workflow_enabled=drain_workflow_enabled, + pending_drain_intents=evaluation.pending_drain_intents, + ) + + # 3. Execute maintenance (pending deletes, stuck starts, cold offload) and drains. + detach_gateway_url = f"http://127.0.0.1:{config.gateway_port}" + gateway_control_bearer_token = ports.read_required_token_file( + config.gateway_token_file(), "gateway control bearer token" + ) + pending_delete_results: list[dict[str, Any]] = [] + stuck_start_results: list[dict[str, Any]] = [] + if execution_requested and execution_authorized: + assert provider_state is not None + pending_delete_results, stuck_start_results = _run_maintenance_actions( + config=config, + sandbox_nodes=sandbox_nodes, + sandbox_routes=sandbox_routes, + quarantined_job_ids=quarantined_job_ids, + provider_state=provider_state, + operation_deployment_id=operation_deployment_id, + detach_gateway_url=detach_gateway_url, + gateway_control_bearer_token=gateway_control_bearer_token, + node_control_bearer_token=node_control_bearer_token, + routing_store=routing_store, + assert_provider_fence=assert_provider_fence, + ports=ports, + ) + + remaining_detach_budget = max( + 0, config.autoscaler_max_storage_native_detaches_per_cycle + ) + cold_offload_plan = plan_cold_offload( + sandbox_nodes, + sandbox_routes, + program_requests, + pending_wake_sandbox_ids=pending_wake_sandbox_ids or (), + excluded_job_ids=(*stops.stop_job_ids, *quarantined_job_ids), + limit=remaining_detach_budget, + pending_disk_mb=( + max((item.resources.disk_mb for item in demand.placement_requests), default=0) + or math.ceil(demand.pending_resources.disk_mb / max(1, demand.pending_count)) + ) + if demand.pending_count + else 0, + ) + storage_native_detach_results: list[dict[str, Any]] = [] + if execution_requested and execution_authorized: + storage_native_detach_results = execute_cold_offload( + cold_offload_plan, + gateway_url=detach_gateway_url, + bearer_token=gateway_control_bearer_token, + assert_provider_fence=assert_provider_fence, + post_gateway_detach=ports.post_gateway_detach, + ) + remaining_detach_budget -= len(storage_native_detach_results) + + drain_outcome = DrainReconcileOutcome( + pending_drain_intents=evaluation.pending_drain_intents, + active_drain_intents=[], + drain_results=[], + drain_ready_stop_job_ids=[], + canceled_drain_job_ids=[], + detach_results=[], + ) + if drain_workflow_enabled: + assert provider_state is not None + drain_outcome = reconcile_drain_intents( + provider_state=provider_state, + operation_deployment_id=operation_deployment_id, + nodes=nodes, + stop_job_ids=stops.stop_job_ids, + sandbox_stop_job_ids=stops.sandbox_stop_job_ids, + unreachable_stop_job_id_set=set(stops.unreachable_stop_job_ids), + irreversible_stop_job_ids=evaluation.irreversible_stop_job_ids, + quarantined_job_ids=quarantined_job_ids, + route_reservations=routes_by_job, + remaining_detach_budget=remaining_detach_budget, + detach_gateway_url=detach_gateway_url, + node_control_bearer_token=node_control_bearer_token, + gateway_control_bearer_token=gateway_control_bearer_token, + post_node_drain=ports.post_node_drain, + post_gateway_detach=ports.post_gateway_detach, + ) + storage_native_detach_results.extend(drain_outcome.detach_results) + + active_drain_job_ids = {intent.job_id for intent in drain_outcome.active_drain_intents} + canceling_drain_job_ids = { + intent.job_id + for intent in drain_outcome.pending_drain_intents + if intent.state == "canceling" + } + pending_drain_job_ids = active_drain_job_ids | canceling_drain_job_ids + soft_drain_fn = ports.apply_soft_drain + if soft_drain_fn is not None: + soft_drain_result, soft_drain_move_results = soft_drain_fn( + decision, + sandbox_nodes, + control_state=control_state, + policy=effective_policy, + route_reservations=routes_by_job, + blocked_job_ids=( + pending_drain_job_ids | set(stops.stop_job_ids) | quarantined_job_ids + ), + pending_wake_sandbox_ids=pending_wake_sandbox_ids or set(), + gateway_url=detach_gateway_url, + bearer_token=gateway_control_bearer_token, + execute=bool(execution_requested and execution_authorized), + assert_provider_fence=assert_provider_fence, + ) + else: + soft_drain_result, soft_drain_move_results = apply_soft_drain( + decision, + sandbox_nodes, + control_state=control_state, + policy=effective_policy, + route_reservations=routes_by_job, + blocked_job_ids=( + pending_drain_job_ids | set(stops.stop_job_ids) | quarantined_job_ids + ), + pending_wake_sandbox_ids=pending_wake_sandbox_ids or set(), + gateway_url=detach_gateway_url, + bearer_token=gateway_control_bearer_token, + execute=bool(execution_requested and execution_authorized), + assert_provider_fence=assert_provider_fence, + post_migration=ports.post_gateway_migration, + ) + + # 4. Plan bootstraps and journal + apply provider mutations. + bootstrap_records, completed_bootstrap_results, bootstrap_intents = ( + _plan_bootstrap_intents( + config=config, + args=args, + provider=provider, + sandbox_nodes=sandbox_nodes, + builder_nodes=builder_nodes, + control_state=control_state, + bootstrap_coordinator=bootstrap_coordinator, + execution_authorized=execution_authorized, + excluded_job_ids=set(stops.stop_job_ids) | pending_drain_job_ids, + ports=ports, + ) + ) + + journaled_create_operations: list[ProviderOperation] = [] + journaled_stop_operations: list[ProviderOperation] = [] + if execution_authorized and execution_requested and provider_state is not None: + ( + journaled_create_operations, + sandbox_create_intents, + builder_create_intents, + ) = journal_create_operations( + provider_state=provider_state, + provider=provider, + operation_deployment_id=operation_deployment_id, + sandbox_create_intents=sandbox_create_intents, + builder_create_intents=builder_create_intents, + ) + create_intents = [*sandbox_create_intents, *builder_create_intents] + journaled_stop_operations = journal_stop_operations( + provider_state=provider_state, + operation_deployment_id=operation_deployment_id, + drain_ready_stop_job_ids=drain_outcome.drain_ready_stop_job_ids, + unreachable_stop_job_ids=stops.unreachable_stop_job_ids, + sandbox_stop_job_ids=stops.sandbox_stop_job_ids, + active_drain_intents=drain_outcome.active_drain_intents, + stop_nodes_by_job_id={ + node.job_id: node for node in (*sandbox_nodes, *builder_nodes) + }, + route_reservations=routes_by_job, + ) + + result: dict[str, Any] = { + "provider": {"kind": provider.kind, "scopeId": provider.scope_id}, + "controlStateFile": str(control_state_file), + "nodes": [ports.node_to_dict(node) for node in nodes], + "decision": ports.scale_decision_to_dict(decision), + "effectivePolicy": ports.dashboard_scale_policy_to_dict(effective_policy), + "builderDecision": ports.scale_decision_to_dict(builder_decision), + "pendingImageBuilds": builder_pending, + "activeImageBuilds": active_image_builds, + "preparedBuilderCount": builder_prepared, + "unexpectedly_suspended_job_ids": sorted( + node.job_id for node in (*sandbox_nodes, *builder_nodes) if node.job.is_lost + ), + "quarantined_job_ids": sorted(quarantined_job_ids), + "unreachableNodeProbes": observation.unreachable_probe_results, + "buildWarmSandboxResources": build_warm_resources.to_dict(), + "createIntents": [intent.to_dict() for intent in create_intents], + "requestedStopJobIds": list(stops.requested_stop_job_ids), + "stopJobIds": list(stops.stop_job_ids), + "blockedStopJobIds": list(stops.blocked_stop_job_ids), + "blocked_storage_native_detach_stop_job_ids": list( + stops.blocked_storage_native_detach_stop_job_ids + ), + "drainingJobIds": sorted(active_drain_job_ids), + "cancelingDrainJobIds": sorted(canceling_drain_job_ids), + "canceledDrainJobIds": list(drain_outcome.canceled_drain_job_ids), + "drainReadyStopJobIds": list(drain_outcome.drain_ready_stop_job_ids), + "unreachableReadyStopJobIds": list(stops.unreachable_stop_job_ids), + "drainIntents": [ + drain_intent_to_dict(intent) + for intent in drain_outcome.pending_drain_intents + ], + "drainResults": drain_outcome.drain_results, + "pending_delete_results": pending_delete_results, + "stuck_start_results": stuck_start_results, + "storage_native_migration_results": [], + "storage_native_detach_results": storage_native_detach_results, + "softDrain": soft_drain_result, + "softDrainMoveResults": soft_drain_move_results, + "coldOffloadPlan": [candidate.to_dict() for candidate in cold_offload_plan], + "prunedFinalHeartbeats": list(observation.final_heartbeat_job_ids), + "prunedOrphanedStaleHeartbeats": list( + observation.orphaned_stale_heartbeat_job_ids + ), + "removedStoppedHeartbeats": [], + "bootstrapIntents": [ + ports.vm_bootstrap_intent_to_dict(intent) for intent in bootstrap_intents + ], + "bootstrapResults": list(completed_bootstrap_results), + "execute": bool(execution_requested and execution_authorized), + "controllerLockHeld": provider_mutations_allowed, + "blockedCreateRoles": sorted(blocked_create_roles), + "createVisibilityGuards": create_visibility_guards, + "providerOperationResults": [], + "sandboxCapacityOperationSucceeded": False, + "builderCapacityOperationSucceeded": False, + "definitelyTerminatedJobIds": [], + "rawNodes": nodes, + "rawRetiredRoutes": observation.retired_routes, + "rawSandboxNodes": sandbox_nodes, + "rawBuilderNodes": builder_nodes, + "rawDecision": decision, + "rawBuilderDecision": builder_decision, + "rawCreateIntents": create_intents, + "rawBootstrapIntents": bootstrap_intents, + } + + if execution_authorized and provider_state is not None: + created_job_ids = _apply_planned_provider_operations( + provider_state=provider_state, + provider=provider, + execute=execution_requested, + journaled_create_operations=journaled_create_operations, + journaled_stop_operations=journaled_stop_operations, + provider_operation_results=provider_operation_results, + telemetry=telemetry, + ) + if created_job_ids is not None: + result["createdJobIds"] = created_job_ids + + definitely_terminated = sorted( + { + job_id + for item in provider_operation_results + if item.kind == "stop" and item.state in {"accepted", "recovered"} + for job_id in item.job_ids + } + ) + result["definitelyTerminatedJobIds"] = definitely_terminated + if definitely_terminated: + result["removedStoppedHeartbeats"] = sorted( + control_state.remove_heartbeats(definitely_terminated) + ) + result["sandboxCapacityOperationSucceeded"] = sandbox_capacity_operation_succeeded( + provider_operation_results, + decision.resource_deficit, + effective_policy.default_node_resources, + ) + desired_builders = min( + requested_builder_nodes( + builder_nodes, + pending_builds=builder_pending, + prepared_builders=builder_prepared, + ), + config.builder.max_nodes, + ) + result["builderCapacityOperationSucceeded"] = builder_capacity_operation_succeeded( + provider_operation_results, + existing_builders=builder_decision.total_nodes, + desired_builders=desired_builders, + ) + + if execution_requested and execution_authorized: + bootstrap_records, result["bootstrapResults"] = ports.execute_bootstrap_phase( + coordinator=bootstrap_coordinator, + intents=bootstrap_intents, + records=bootstrap_records, + completed_results=completed_bootstrap_results, + config=config, + control_state=control_state, + assert_provider_fence=assert_provider_fence, + metrics_store=metrics_store, + telemetry=telemetry, + ) + if execution_authorized and provider_state is not None: + result["compactedProviderOperations"] = ( + provider_state.compact_terminal_history(keep=1000) + ) + result["providerOperationResults"] = [ + item.to_dict() for item in provider_operation_results + ] + return result diff --git a/sandboxes/builder_agent.py b/sandboxes/builder_agent.py new file mode 100644 index 00000000..4a121143 --- /dev/null +++ b/sandboxes/builder_agent.py @@ -0,0 +1,696 @@ +"""Builder-only HTTP node agent server (split out of sandboxes/node_agent.py). + +Builders run Docker/BuildKit image builds, build-context uploads, and +environment publishing. They do not run direct-runsc sandboxes or import any +sandbox-worker runtime modules (direct_service, direct_warden, hibernation, +etc.). +""" + +from __future__ import annotations + +import hmac +import shutil +import sys +import time +from dataclasses import replace +from http import HTTPStatus +from pathlib import Path +from typing import Any, Callable +from urllib.parse import unquote, urlparse +from uuid import UUID, uuid4 + +from .agent import build_heartbeat +from .build_admission import BUILD_ADMISSION_CAPACITY_LABEL +from .build_context_store import ( + BuildContextBlobStore, + BuildContextHttpHandler, + build_context_digest_from_path, +) +from .capabilities import REQUEST_BODY_KEEPALIVE_CAPABILITY +from .deployment import service_health +from .heartbeat_sender import HeartbeatSenderConfig, NodeHeartbeatSender +from .http_server import ( + DEFAULT_MAX_JSON_BODY_BYTES, + HighBacklogThreadingHTTPServer, + RequestBodyTooLargeError, + traced_http_request, +) +from .images import ( + DEFAULT_MAX_ACTIVE_IMAGE_BUILDS, + DockerImageRuntime, + ImageBuildCapacityError, + ImageBuildConflictError, + ImageBuildSpec, + ImageManager, + ImageStore, + materialize_uploaded_build_context, + uploaded_build_context_reference, +) +from .models import NodeHeartbeat, NodeRuntimeMetrics, ResourceQuantity, utc_now +from .node_runtime import BuilderNodeRuntime, NodeStateStore +from .registry import heartbeat_to_dict +from .runtime_metrics import ( + SingleFlightRuntimeMetricsSampler, + cpu_check_ms, + sample_node_runtime_metrics, +) +from .sandbox import ( + SandboxAdmissionClosedError, + SandboxConflictError, + SandboxFileTooLargeError, +) +from .telemetry import Telemetry + +DEFAULT_MAX_FILE_BODY_BYTES = 256 * 1024 * 1024 +DEFAULT_MAX_BUILD_CONTEXT_STORE_BYTES = 2 * 1024 * 1024 * 1024 +DEFAULT_MAX_BUILD_CONTEXT_ENTRIES = 8192 +DEFAULT_MAX_BUILD_CONTEXT_AGE_SECONDS = 24 * 60 * 60 + +_HOST_BOOT_ID_PATH = Path("/proc/sys/kernel/random/boot_id") +_PROCESS_NODE_EPOCH = uuid4().hex + + +def _host_runtime_metrics_sampler( + provider: Callable[[], NodeRuntimeMetrics | None] | None, +) -> SingleFlightRuntimeMetricsSampler: + if provider is None: + cpu_check_ms() + source = provider if provider is not None else sample_node_runtime_metrics + if isinstance(source, SingleFlightRuntimeMetricsSampler): + return source + return SingleFlightRuntimeMetricsSampler(source) + + +def _resolve_node_epoch(node_epoch: str | None) -> str: + if node_epoch is not None: + resolved = node_epoch.strip() + if not resolved: + raise ValueError("node_epoch cannot be empty") + return resolved + try: + raw = _HOST_BOOT_ID_PATH.read_text(encoding="utf-8").strip() + except OSError as exc: + if sys.platform.startswith("linux"): + raise RuntimeError("host boot identity is unavailable") from exc + return _PROCESS_NODE_EPOCH + try: + return UUID(raw).hex + except (AttributeError, ValueError) as exc: + raise RuntimeError("host boot identity is invalid") from exc + + +def _cached_image_refs(image_manager: ImageManager) -> tuple[str, ...]: + refs: list[str] = [] + for record in image_manager.list(): + refs.append(record.id) + if record.tag: + refs.append(record.tag) + if record.digest_ref: + refs.append(record.digest_ref) + return tuple(dict.fromkeys(refs)) + + +def _physical_disk_usage_mb(path: Path) -> tuple[int, int]: + candidate = path + while not candidate.exists() and candidate != candidate.parent: + candidate = candidate.parent + try: + usage = shutil.disk_usage(candidate) + except OSError: + return 0, 0 + divisor = 1024 * 1024 + return usage.total // divisor, usage.free // divisor + + +def _elapsed_ms(started: float) -> int: + return max(0, int((time.monotonic() - started) * 1000)) + + +def _image_build_key_from_path(path: str) -> str | None: + prefix = "/v1/images/builds/" + if not path.startswith(prefix): + return None + key = unquote(path[len(prefix) :]) + return key or None + + +def _image_build_cancel_id_from_path(path: str) -> str | None: + key = _image_build_key_from_path(path) + if key is None or not key.endswith(":cancel"): + return None + return key[: -len(":cancel")] or None + + +class BuilderAgentHandler(BuildContextHttpHandler): + manager: BuilderNodeRuntime + image_manager: ImageManager + build_context_store: BuildContextBlobStore + job_id: str + node_id: str + node_url: str | None + agent_version: str + deployment_id: str + init_version: str + total_resources: ResourceQuantity + capabilities: tuple[str, ...] + runtime_metrics_provider: Callable[[], NodeRuntimeMetrics | None] + node_epoch: str + physical_disk_path: Path + node_control_bearer_token: str + max_file_body_bytes = DEFAULT_MAX_FILE_BODY_BYTES + server_version = "ucloud-sandboxes-builder-agent/0.1" + + def node_heartbeat(self) -> NodeHeartbeat: + admission: dict[str, int] = {} + + def active_build_count() -> int: + admission.update(self.image_manager.build_admission_snapshot()) + return admission["active_builds"] + + node_snapshot = self.manager.heartbeat_snapshot(active_build_count=active_build_count) + activity = node_snapshot.activity + physical_disk_total_mb, physical_disk_free_mb = _physical_disk_usage_mb( + self.physical_disk_path + ) + drain = node_snapshot.drain + return build_heartbeat( + job_id=self.job_id, + node_id=self.node_id, + node_url=self.node_url, + agent_version=self.agent_version, + deployment_id=self.deployment_id, + init_version=self.init_version, + active_sandboxes=0, + active_image_builds=node_snapshot.active_image_builds, + labels={BUILD_ADMISSION_CAPACITY_LABEL: str(admission["admission_capacity"])}, + active_sandbox_creates=0, + capabilities=self.capabilities, + total_resources=self.total_resources, + used_resources=activity.used_resources, + reserved_resources=activity.reserved_resources, + cached_images=_cached_image_refs(self.image_manager), + runtime_metrics=self._runtime_metrics_snapshot(), + node_epoch=self.node_epoch, + activity_epoch=activity.activity_revision, + inventory=(), + inventory_complete=True, + physical_disk_total_mb=physical_disk_total_mb, + physical_disk_free_mb=physical_disk_free_mb, + draining=drain.draining, + drain_token=drain.token if drain.draining else "", + drain_activity_epoch=drain.drain_activity_epoch, + admission_open=drain.admission_open, + ) + + def _runtime_metrics_snapshot(self) -> NodeRuntimeMetrics: + metrics = self.runtime_metrics_provider() + if metrics is None: + metrics = NodeRuntimeMetrics(collected_at=utc_now()) + pull_snapshot = self.image_manager.pull_operation_snapshot() + return replace( + metrics, + image_pull_active_operations=max(0, int(pull_snapshot.get("active_operations") or 0)), + image_pull_waiting_operations=max(0, int(pull_snapshot.get("waiting_operations") or 0)), + image_pull_max_concurrent_operations=max( + 0, int(pull_snapshot.get("max_concurrent_operations") or 0) + ), + ) + + def _check_node_control_authorized(self) -> bool: + expected = self.node_control_bearer_token + authorization = self.headers.get("Authorization") or "" + supplied = authorization[7:] if authorization.startswith("Bearer ") else "" + if supplied and hmac.compare_digest(supplied, expected): + return True + self._write_json( + {"error": "unauthorized"}, + status=HTTPStatus.UNAUTHORIZED, + headers={"WWW-Authenticate": "Bearer"}, + ) + return False + + @traced_http_request + def do_HEAD(self) -> None: + if not self._check_node_control_authorized(): + return + parsed = urlparse(self.path) + digest = build_context_digest_from_path(parsed.path) + if digest is not None: + try: + size = self.build_context_store.size_and_touch(digest) + except (FileNotFoundError, ValueError): + self.send_response(HTTPStatus.NOT_FOUND) + self.send_header("Content-Length", "0") + self.end_headers() + return + self.send_response(HTTPStatus.OK) + self.send_header("Content-Length", "0") + self.send_header("X-UCloud-Context-Size", str(size)) + self.end_headers() + return + self.send_response(HTTPStatus.NOT_FOUND) + self.send_header("Content-Length", "0") + self.end_headers() + + @traced_http_request + def do_GET(self) -> None: + parsed = urlparse(self.path) + if parsed.path == "/healthz": + self._write_json(service_health("node-agent")) + return + if not self._check_node_control_authorized(): + return + if parsed.path == "/v1/heartbeat": + self._write_json({"heartbeat": heartbeat_to_dict(self.node_heartbeat())}) + return + if parsed.path == "/v1/images": + self._write_json( + { + "images": [ + record.to_dict() + for record in sorted(self.image_manager.list(), key=lambda item: item.id) + ] + } + ) + return + digest = build_context_digest_from_path(parsed.path) + if digest is not None: + try: + size = self.build_context_store.size_and_touch(digest) + except (FileNotFoundError, ValueError): + self._write_json({"error": "build context not found"}, status=HTTPStatus.NOT_FOUND) + return + self._write_json({"digest": digest, "size": size, "deduplicated": True}) + return + if parsed.path == "/v1/images/builds": + self._write_json( + { + "builds": [ + record.to_dict() + for record in sorted( + self.image_manager.list_builds(), + key=lambda item: (item.created_at, item.build_id), + ) + ] + } + ) + return + build_key = _image_build_key_from_path(parsed.path) + if build_key is not None: + record = self.image_manager.get_build(build_key) + if record is None: + self._write_json({"error": "image build not found"}, status=HTTPStatus.NOT_FOUND) + return + self._write_json({"build": record.to_dict()}) + return + self._write_json({"error": "not found"}, status=HTTPStatus.NOT_FOUND) + + @traced_http_request + def do_PUT(self) -> None: + if not self._check_node_control_authorized(): + return + parsed = urlparse(self.path) + digest = build_context_digest_from_path(parsed.path) + if digest is not None: + self._store_build_context(digest) + return + self._write_json({"error": "not found"}, status=HTTPStatus.NOT_FOUND) + + @traced_http_request + def do_POST(self) -> None: + if not self._check_node_control_authorized(): + return + parsed = urlparse(self.path) + if parsed.path == "/v1/drain": + self._configure_drain() + return + if parsed.path == "/v1/images/build": + self._build_image() + return + if parsed.path == "/v1/images/pull": + self._pull_image() + return + cancel_id = _image_build_cancel_id_from_path(parsed.path) + if cancel_id is not None: + self._cancel_image_build(cancel_id) + return + self._write_json({"error": "not found"}, status=HTTPStatus.NOT_FOUND) + + @traced_http_request + def do_DELETE(self) -> None: + if not self._check_node_control_authorized(): + return + self._write_json({"error": "not found"}, status=HTTPStatus.NOT_FOUND) + + def _configure_drain(self) -> None: + try: + raw = self._read_json_body() + if not isinstance(raw, dict): + raise ValueError("drain payload must be a JSON object") + if set(raw) != {"draining", "token"}: + raise ValueError("drain payload has an invalid schema") + token = raw.get("token") + if not isinstance(token, str): + raise ValueError("drain token must be a string") + token = token.strip() + draining = raw.get("draining") + if not isinstance(draining, bool): + raise ValueError("draining must be a boolean") + snapshot = self.manager.configure_drain( + token, + draining, + active_build_count=self.image_manager.active_build_count, + ) + except SandboxConflictError as exc: + self._write_json({"error": str(exc)}, status=HTTPStatus.CONFLICT) + return + except (RuntimeError, ValueError) as exc: + self._write_exception(exc) + return + self._write_json( + { + "drain": { + "token": snapshot.drain.token, + "draining": snapshot.drain.draining, + "admission_open": snapshot.drain.admission_open, + "drain_activity_epoch": snapshot.drain.drain_activity_epoch, + "activity_epoch": snapshot.activity.activity_revision, + "active_sandboxes": snapshot.activity.active_sandboxes, + "reserved_resources": snapshot.activity.reserved_resources.to_dict(), + "active_image_builds": snapshot.active_image_builds, + "ready": snapshot.ready, + } + } + ) + + def _build_image(self) -> None: + started = time.monotonic() + phases: dict[str, int] = {} + try: + phase = time.monotonic() + raw = self._read_json_body() + phases["read_request_ms"] = _elapsed_ms(phase) + if not isinstance(raw, dict): + raise ValueError("image build payload must be a JSON object") + push = bool(raw.get("push", False)) + wait = bool(raw.get("wait", True)) + logical_spec = ImageBuildSpec.from_dict(raw) + phase = time.monotonic() + digest, _stored_size = uploaded_build_context_reference(raw, self.build_context_store) + context_identity = f"archive:{digest}" + + def materialize_context(): + return materialize_uploaded_build_context(digest, self.build_context_store) + + phases["parse_spec_ms"] = _elapsed_ms(phase) + phase = time.monotonic() + with self.manager.image_operation(self.image_manager): + build, build_started = self.image_manager.start_build( + logical_spec, + push=push, + context_identity=context_identity, + materialize_context=materialize_context, + ) + phases["start_build_ms"] = _elapsed_ms(phase) + if wait: + phase = time.monotonic() + build = self.image_manager.wait_for_build(build.build_id) or build + phases["wait_for_build_ms"] = _elapsed_ms(phase) + except (RuntimeError, ValueError) as exc: + self._write_exception(exc) + return + timings = { + "total_ms": _elapsed_ms(started), + "phases": phases, + "build": build.timings, + } + self.telemetry.add_event("image.build.timings", timings) + self.telemetry.set_current_attributes( + { + "image.build.id": build.build_id, + "image.build.status": build.status, + "image.build.started": build_started, + } + ) + if not wait: + self._write_json( + {"build": build.to_dict(), "started": build_started, "timings": timings}, + status=HTTPStatus.ACCEPTED, + ) + return + if build.status != "succeeded": + self._write_json( + { + "error": build.error or f"image build {build.status}", + "build": build.to_dict(), + "timings": timings, + }, + status=HTTPStatus.BAD_REQUEST, + ) + return + image_record = self.image_manager.get_image(build.image_id) + payload: dict[str, Any] = { + "build": build.to_dict(), + "image": image_record.to_dict() if image_record is not None else build.image, + "command": list(build.command), + "exit_code": build.exit_code, + "timings": timings, + } + if build.push_command: + payload["push_command"] = list(build.push_command) + payload["push_exit_code"] = build.push_exit_code + self._write_json(payload, status=HTTPStatus.CREATED) + + def _cancel_image_build(self, build_id: str) -> None: + try: + outcome, record = self.image_manager.cancel_build(build_id) + except (RuntimeError, ValueError) as exc: + self._write_exception(exc) + return + if outcome == "not_found" or record is None: + self._write_json({"error": "image build not found"}, status=HTTPStatus.NOT_FOUND) + return + if outcome == "unowned": + self._write_json( + {"error": "image build is not owned by this node agent", "retryable": True}, + status=HTTPStatus.SERVICE_UNAVAILABLE, + ) + return + status = { + "cancelled": HTTPStatus.OK, + "stopping": HTTPStatus.ACCEPTED, + "finished": HTTPStatus.CONFLICT, + }[outcome] + payload: dict[str, Any] = {"build": record.to_dict()} + if outcome == "finished": + payload["error"] = "image build already finished" + self._write_json(payload, status=status) + + def _pull_image(self) -> None: + started = time.monotonic() + failed_phase = "read_request" + pull_queue_ms = 0 + try: + raw = self._read_json_body() + if not isinstance(raw, dict): + raise ValueError("image pull payload must be a JSON object") + image = str(raw.get("image") or "") + image_id = str(raw["id"]) if raw.get("id") else None + with self.manager.image_operation(self.image_manager): + failed_phase = getattr(self.image_manager.runtime, "pull_phase", "docker_pull") + with self.image_manager.pull_slot() as pull_admission: + pull_queue_ms = int(pull_admission["queue_wait_ms"]) + pull_started = time.monotonic() + record, result = self.image_manager.pull(image, image_id=image_id) + pull_finished = time.monotonic() + except SandboxAdmissionClosedError as exc: + self._write_exception(exc) + return + except RuntimeError as exc: + self._write_json( + { + "error": str(exc), + "error_code": "image_pull_failed", + "retryable": True, + "timings": { + "total_ms": _elapsed_ms(started), + "pull_queue_ms": pull_queue_ms, + "failed_phase": failed_phase, + }, + }, + status=HTTPStatus.SERVICE_UNAVAILABLE, + ) + return + except ValueError as exc: + self._write_json( + { + "error": str(exc), + "timings": { + "total_ms": _elapsed_ms(started), + "failed_phase": failed_phase, + }, + }, + status=HTTPStatus.BAD_REQUEST, + ) + return + self._write_json( + { + "image": record.to_dict(), + "command": list(result.argv), + "exit_code": result.exit_code, + "timings": { + "pull_queue_ms": pull_queue_ms, + "docker_pull_ms": int(max(0.0, pull_finished - pull_started) * 1000), + }, + }, + status=HTTPStatus.CREATED, + ) + + def _write_exception(self, exc: RuntimeError | ValueError) -> None: + if isinstance(exc, ImageBuildCapacityError): + self._write_json( + {"error": str(exc), "error_code": "builder_busy", "retryable": True}, + status=HTTPStatus.SERVICE_UNAVAILABLE, + headers={"Retry-After": "2", "X-UCloud-Sandbox-Retryable": "true"}, + ) + return + if isinstance(exc, SandboxAdmissionClosedError): + self._write_json( + {"error": str(exc), "error_code": "node_admission_closed", "retryable": True}, + status=HTTPStatus.SERVICE_UNAVAILABLE, + headers={"Retry-After": "1", "X-UCloud-Sandbox-Retryable": "true"}, + ) + return + if isinstance(exc, (RequestBodyTooLargeError, SandboxFileTooLargeError)): + status = HTTPStatus.REQUEST_ENTITY_TOO_LARGE + elif isinstance(exc, ImageBuildConflictError): + status = HTTPStatus.CONFLICT + elif isinstance(exc, RuntimeError): + status = HTTPStatus.SERVICE_UNAVAILABLE + else: + status = HTTPStatus.BAD_REQUEST + self._write_json({"error": str(exc)}, status=status) + + +class BuilderAgentHTTPServer(HighBacklogThreadingHTTPServer): + """Builder node API with optional background heartbeat sender.""" + + heartbeat_sender: NodeHeartbeatSender | None = None + + def attach_heartbeats(self, config: HeartbeatSenderConfig | None) -> None: + if config is not None: + sample = object.__new__(self.RequestHandlerClass).node_heartbeat + self.heartbeat_sender = NodeHeartbeatSender(sample, config) + + def serve_forever(self, poll_interval: float = 0.5) -> None: + if self.heartbeat_sender is not None: + self.heartbeat_sender.start() + try: + super().serve_forever(poll_interval) + finally: + self.stop_heartbeats() + + def stop_heartbeats(self) -> None: + if self.heartbeat_sender is not None: + self.heartbeat_sender.stop() + + def server_close(self) -> None: + self.stop_heartbeats() + super().server_close() + + +def build_builder_node_agent_server( + host: str, + port: int, + *, + state_file: Path, + image_file: Path, + job_id: str, + node_id: str, + node_url: str | None = None, + agent_version: str = "", + deployment_id: str, + init_version: str = "", + total_resources: ResourceQuantity | None = None, + image_runtime: DockerImageRuntime, + node_control_bearer_token: str, + runtime_metrics_provider: Callable[[], NodeRuntimeMetrics | None] | None = None, + max_json_body_bytes: int = DEFAULT_MAX_JSON_BODY_BYTES, + max_file_body_bytes: int = DEFAULT_MAX_FILE_BODY_BYTES, + max_active_image_builds: int = DEFAULT_MAX_ACTIVE_IMAGE_BUILDS, + max_finishing_image_builds: int = 0, + build_execution_timeout_seconds: float = 1800.0, + max_concurrent_image_pulls: int = 8, + physical_disk_path: Path | None = None, + build_context_store_dir: Path | None = None, + node_epoch: str | None = None, + telemetry: Telemetry | None = None, + environment_publisher: Callable[[Any], str] | None = None, + heartbeat: HeartbeatSenderConfig | None = None, +) -> BuilderAgentHTTPServer: + token = node_control_bearer_token.strip() + if not token: + raise ValueError("node control bearer token cannot be empty") + if not deployment_id.strip(): + raise ValueError("deployment_id cannot be empty") + if ( + max_json_body_bytes < 1 + or max_file_body_bytes < 1 + or max_active_image_builds < 1 + or max_concurrent_image_pulls < 1 + ): + raise ValueError("node-agent request and build limits must be positive") + if type(max_finishing_image_builds) is not int or not 0 <= max_finishing_image_builds <= 2: + raise ValueError("max finishing image builds must be between 0 and 2") + resources = total_resources or ResourceQuantity() + if not resources.is_valid: + raise ValueError("total_resources cannot contain negative or non-finite values") + + resolved_telemetry = telemetry or Telemetry.disabled("ucloud-sandbox-builder") + runtime = BuilderNodeRuntime(NodeStateStore(state_file)) + image_manager = ImageManager( + ImageStore(image_file), + image_runtime, + max_active_builds=max_active_image_builds, + max_finishing_builds=max_finishing_image_builds, + build_execution_timeout_seconds=build_execution_timeout_seconds, + queue_builds=True, + max_queued_builds=0, + max_concurrent_pulls=max_concurrent_image_pulls, + telemetry=resolved_telemetry, + environment_publisher=environment_publisher, + ) + context_store = BuildContextBlobStore( + build_context_store_dir or image_file.parent / f"{image_file.stem}-contexts", + max_blob_bytes=max_file_body_bytes, + max_total_bytes=DEFAULT_MAX_BUILD_CONTEXT_STORE_BYTES, + max_entries=DEFAULT_MAX_BUILD_CONTEXT_ENTRIES, + max_age_seconds=DEFAULT_MAX_BUILD_CONTEXT_AGE_SECONDS, + ) + + class BuilderHandler(BuilderAgentHandler): + pass + + BuilderHandler.manager = runtime + BuilderHandler.image_manager = image_manager + BuilderHandler.build_context_store = context_store + BuilderHandler.job_id = job_id + BuilderHandler.node_id = node_id + BuilderHandler.node_url = node_url + BuilderHandler.agent_version = agent_version + BuilderHandler.deployment_id = deployment_id + BuilderHandler.init_version = init_version + BuilderHandler.total_resources = resources + BuilderHandler.capabilities = ("image-cache", "image-build", REQUEST_BODY_KEEPALIVE_CAPABILITY) + BuilderHandler.node_epoch = _resolve_node_epoch(node_epoch) + BuilderHandler.physical_disk_path = physical_disk_path or image_file.parent + BuilderHandler.node_control_bearer_token = token + BuilderHandler.max_json_body_bytes = max_json_body_bytes + BuilderHandler.max_file_body_bytes = max_file_body_bytes + BuilderHandler.runtime_metrics_provider = staticmethod( + _host_runtime_metrics_sampler(runtime_metrics_provider) + ) + BuilderHandler.telemetry = resolved_telemetry + server = BuilderAgentHTTPServer((host, port), BuilderHandler) + server.attach_heartbeats(heartbeat) + return server diff --git a/sandboxes/capabilities.py b/sandboxes/capabilities.py index 12e5cefd..68c5a5ad 100644 --- a/sandboxes/capabilities.py +++ b/sandboxes/capabilities.py @@ -7,7 +7,6 @@ MANAGED_PRIMARY_CAPABILITY = "managed-primary-v1" STORAGE_NATIVE_CAPABILITY = "storage-native-v1" SPLIT_CHECKPOINT_CAPABILITY = "sandbox-checkpoint-v3" -REFLINK_MEMORY_RESTORE_CAPABILITY = "sandbox-memory-reflink-restore-v1" HOST_EROFS_CAPABILITY = "immutable-environment-host-erofs-v1" # Chunk store M2: honours SandboxSpec.environment_root; reads RAFS components # through a chunk index and store node. diff --git a/sandboxes/chunk_migrate.py b/sandboxes/chunk_migrate.py index 26110935..c74493d0 100644 --- a/sandboxes/chunk_migrate.py +++ b/sandboxes/chunk_migrate.py @@ -301,7 +301,7 @@ def switch_wave(roots, environments, usage, wave, *, registry_host, keys=None, w wave 1: a cold object waits on S3's tail, past the NBD timeout).""" from .environment_artifact import load_environment from .environment_dependencies import EnvironmentDependencyResolver - from .gateway.registry_refs import _persist_registry_image_protection + from .gateway.registry_refs import persist_registry_image_protection resolver = EnvironmentDependencyResolver(environments, image_roots=roots) owners, switched, repointed, cold = durable_owners(usage), 0, 0, {} pending = [(row["repository"], row["manifest_digest"], row["new_root"]) for row in roots.rows(wave=wave) @@ -329,7 +329,7 @@ def switch_wave(roots, environments, usage, wave, *, registry_host, keys=None, w roots.transition(*key, "switched", detail=json.dumps({"owners": [owner for owner, _ in held]})) for owner, tag in held: image = f"{registry_host}/{key[0]}:{tag}@{key[1]}" - if not _persist_registry_image_protection(usage, image, owner, touch=False, persistent=True, + if not persist_registry_image_protection(usage, image, owner, touch=False, persistent=True, dependency_resolver=resolver): raise RuntimeError(f"{image}: the new closure was not retained for {owner}") switched += 1 diff --git a/sandboxes/cli.py b/sandboxes/cli.py index 08efce57..1deecd21 100644 --- a/sandboxes/cli.py +++ b/sandboxes/cli.py @@ -5,9 +5,7 @@ from concurrent.futures import Future, ThreadPoolExecutor from dataclasses import asdict, dataclass, replace from datetime import datetime, timedelta -from http import HTTPStatus import json -import math import os from pathlib import Path, PurePosixPath import socket @@ -17,8 +15,8 @@ import threading from threading import Event, Lock, local import time -from typing import Any, Callable, Iterable -from urllib.error import HTTPError, URLError +from typing import Any, Callable +from urllib.error import HTTPError as HTTPError from urllib.parse import quote, urlparse from urllib.request import HTTPRedirectHandler, HTTPSHandler, Request, build_opener from uuid import uuid4 @@ -26,41 +24,50 @@ from opentelemetry.propagate import inject from .gvisor_distribution import distribution_files -from .disk_claims import IDLE_MEMORY_CLAIM_MB -from .usage_history import ( - UsageHistory, - demand_with_usage_forecast, - record_inventory_usage, -) from .agent import default_node_id, detect_job_id, fetch_node_agent_heartbeat +from .autoscaler import ( + AutoscalerPorts, + CREATE_QUOTA_BACKOFF as CREATE_QUOTA_BACKOFF, + ProviderObservation as _ProviderObservation, + apply_prepared_provider_operations as apply_prepared_provider_operations, + apply_route_reservations_to_heartbeats as apply_route_reservations_to_heartbeats, + apply_route_reservations_to_nodes as apply_route_reservations_to_nodes, + apply_soft_drain as _autoscaler_apply_soft_drain, + build_activity_sandbox_warm_resources as build_activity_sandbox_warm_resources, + builder_pool_nodes as builder_pool_nodes, + delete_stuck_starts as _autoscaler_delete_stuck_starts, + demand_with_build_warm_resources as demand_with_build_warm_resources, + is_managed_compute_instance as is_managed_compute_instance, + observe_provider_nodes as _autoscaler_observe_provider_nodes, + partition_storage_native_detachable_stop_job_ids as partition_storage_native_detachable_stop_job_ids, + probe_nodes as _autoscaler_probe_nodes, + probe_unreachable_node as _autoscaler_probe_unreachable_node, + quarantine_unverified_guests as _autoscaler_quarantine_unverified_guests, + quota_blocked_roles as quota_blocked_roles, + replay_pending_deletes as _autoscaler_replay_pending_deletes, + run_reconcile_cycle as _autoscaler_run_reconcile_cycle, + sandbox_pool_nodes as sandbox_pool_nodes, + sandbox_route_reservations as sandbox_route_reservations, + should_include_job as should_include_job, +) from .autoscaler_state import ( AutoscalerStateError, AutoscalerProcessLock, AutoscalerStateStore, - DrainIntent, - ProviderOperation, - ProviderOperationOutcome, - stable_provider_operation_id, ) -from .capabilities import STORAGE_NATIVE_CAPABILITY, STORAGE_NATIVE_DETACH_CAPABILITY from .bootstrap import ( VmBootstrapIntent, VmBootstrapRecord, - build_vm_bootstrap_intents, - mark_bootstrap_access_refresh, mark_bootstrap_attempt, mark_bootstrap_failure, mark_bootstrap_success, - prune_bootstrap_records, ) from .config import DeploymentConfig -from .cold_offload import plan_cold_offload from .control_state import ( - CONTINUITY_VERIFIED_THROUGH, QUARANTINE_EPOCH, QUARANTINE_REASON, ControlStateStore, - quarantined_labels, recovered_labels, + ControlStateStore, ) -from .control_plane import SANDBOX_GENERATION_HEADER, SANDBOX_OPERATION_ID_HEADER, build_server +from .control_plane import build_server from .heartbeat_sender import DEFAULT_HEARTBEAT_INTERVAL_SECONDS, HeartbeatSenderConfig from .deployment import ( AGENT_VERSION_LABEL, @@ -81,53 +88,21 @@ stage_file_over_ssh, ) from .gateway.registry_refs import release_registry_route_references -from .images import DEFAULT_MAX_ACTIVE_IMAGE_BUILDS, DockerImageRuntime, ImageRecord, ImageStore +from .images import DEFAULT_MAX_ACTIVE_IMAGE_BUILDS, DockerImageRuntime from .managed_registry import ( RegistryClient, - RegistryRequestError, - RegistryUsageGenerationChanged, RegistryUsageStore, - apply_registry_usage, - execute_registry_prune, - list_registry_tags, - registry_host_from_image_ref, registry_repository_tag_from_image_ref, - registry_prune_plan, - select_prune_candidates, - RegistryTag, +) +from .registry_prune import ( + run_registry_prune as _run_registry_prune, ) from .registry_disk import ( RegistryDiskMonitor, - RegistryDiskUsage, - record_image_evictions, - record_registry_prune, registry_disk_usage, ) -from .registry_retention import ( - ENVIRONMENT_REASON, - SNAPSHOT_REASON, - EnvironmentBlobIndex, - ImageEnvironmentIndex, - ManagedImage, - ReferenceRetentionDecision, - RegistryTagClock, - environment_live_identities, - hold_unrecorded_conversions, - execute_reference_prune, - image_is_referenced, - list_repository_tags, - managed_images, - manifest_blob_sizes, - manifest_layer_bytes, - routing_image_identities, - select_lru_evictions, - select_unreferenced, - snapshot_live_identities, - still_unreferenced_environment, -) from .metrics import ( MetricsStore, - build_live_scale_signals, record_autoscaler_cycle, record_vm_init_attempt, record_vm_observed, @@ -139,24 +114,18 @@ create_model_relay_app, ) from .models import ( - InstancePhase, NodeHeartbeat, ResourceQuantity, SandboxDemand, SandboxNode, - SandboxPlacementRequest, ScalePolicy, ProviderInstance, - is_soft_drained, - parse_iso_datetime, utc_now, ) from .providers.base import ( ComputeProvider, - InstanceBootstrapAccess, InstanceCreateIntent, ProviderError, - QUOTA_EXCEEDED, ) from .providers.loader import load_external_provider from .providers.ucloud import ( @@ -170,22 +139,8 @@ from .networking import ( stable_hostname, ) -from .policy import ( - evaluate_scale, - unreachable_node_reference, - unreachable_node_stop_ready, -) -from .reconcile import ( - build_create_intents, - evaluate_builder_scale, - requested_builder_nodes, - node_drain_ready, - partition_safe_stop_job_ids, - with_provider_operation_label, -) from .registry import ( heartbeat_to_dict, - merge_jobs_and_heartbeats, ) from .routing import ( open_routing_store, @@ -193,11 +148,9 @@ ProgramRequestState, RoutingStore, SandboxRoute, - is_portable_parked_route, - is_worker_detachable_parked_route, sandbox_demand_from_routing_state, ) -from .stuck_starts import StuckStart, stuck_start_candidates, stuck_starts_due, unowned +from .stuck_starts import StuckStart from .telemetry import Telemetry, TelemetrySettings from .providers.ucloud.api import ( SessionStore, @@ -415,10 +368,6 @@ def build_parser() -> argparse.ArgumentParser: help="The XFS project-quota memory backing's physical disk budget.") direct_node_agent.add_argument("--application-memory-root", type=Path, help="Qualified nodewide noswap tmpfs for active application memory.") - direct_node_agent.add_argument( - "--reflink-memory-restore", action="store_true", - help="Use the qualified file-backed reflink restore capability with split checkpoints.", - ) direct_node_agent.add_argument( "--workspace-initial-grant-mb", type=int, default=0, help="Format split workspaces at this size and grow them online toward disk_mb (0: full size).", @@ -1049,7 +998,7 @@ def cmd_toolkit_register(args: argparse.Namespace) -> int: from .environment_artifact import load_image_environment from .environment_config import environment_registry_from_deployment from .gateway.toolkits import ToolkitComposer, ToolkitStore, toolkits_path - from .managed_registry import manifest_digest_from_image_ref, registry_repository_tag_from_image_ref + from .managed_registry import manifest_digest_from_image_ref config = load_config(args) registry = environment_registry_from_deployment(config) coordinates = registry_repository_tag_from_image_ref(args.image_ref) @@ -1275,8 +1224,8 @@ def watch(): def cmd_serve_builder_agent(args: argparse.Namespace) -> int: + from .builder_agent import build_builder_node_agent_server from .environment_config import environment_publisher_from_args - from .node_agent import build_builder_node_agent_server job_id = args.job_id or detect_job_id() if not job_id: @@ -1395,7 +1344,6 @@ def cmd_serve_direct_node_agent(args: argparse.Namespace) -> int: max_concurrent_startups=args.max_concurrent_startups, idle_park_seconds=float(args.idle_park_seconds), storage_native_socket=args.storage_native_socket.absolute(), - reflink_memory_restore=args.reflink_memory_restore, workspace_initial_grant_mb=args.workspace_initial_grant_mb, application_memory_root=(args.application_memory_root.absolute() if args.application_memory_root is not None else None), @@ -1864,486 +1812,15 @@ def run_registry_prune( repository_prefix: str = "", evict_lru: bool = False, ) -> dict[str, Any]: - """Age retention for image repositories, reference retention for the rest. - - The snapshot and environment repositories are excluded from the age rules - and pruned by reference (docs/images.md). With ``evict_lru`` and - the registry volume above its cleanup threshold, least-recently-used - managed images are evicted down to the target first, so their - environments are pruned in the same run. Callers hold the registry - maintenance lock; this function never garbage collects. - """ - - client = RegistryClient(config.registry_url) - usage_store = RegistryUsageStore(config.registry_usage_file()) - usage_snapshot = usage_store.snapshot() - usage_records = usage_snapshot.records - reference_repositories = _reference_retained_repositories(config) - cache_policy = None - excluded_repositories = list(reference_repositories.values()) - if config.builder.buildx_cache_ref: - from .build_cache import RegistryBuildCache - cache_policy = RegistryBuildCache( - config.builder.buildx_cache_ref, registry_url=config.registry_url, - max_bytes=config.builder.buildx_cache_max_bytes, - max_entries=config.builder.buildx_cache_max_entries, - max_age_seconds=config.builder.buildx_cache_max_age_seconds, - ) - excluded_repositories.append(cache_policy.repository) - plan = registry_prune_plan( - client, - keep_per_repository=config.registry_keep_per_repository, - repository_prefix=repository_prefix, - max_age_days=config.registry_retention_days, - usage_records=usage_records, - active_leases=usage_snapshot.leases, - usage_generation=usage_snapshot.generation, - exclude_repositories=excluded_repositories, - ) - plan["execute"] = bool(execute) - plan["usage_file"] = str(config.registry_usage_file()) - plan["image_file"] = str(config.image_file()) - image_records = [RegistryTag(**item) for item in plan["tags"]] - removed_images = {(item["repository"], item["tag"]) for item in plan["delete"]} - deleted: list[RegistryTag] = [] - if execute: - for attempt in range(3): - usage_snapshot = usage_store.snapshot() - usage_records = usage_snapshot.records - records = list_registry_tags( - client, - repository_prefix=repository_prefix, - exclude_repositories=excluded_repositories, - ) - records = apply_registry_usage(records, usage_records) - candidates = select_prune_candidates( - records, - keep_per_repository=config.registry_keep_per_repository, - max_age_days=config.registry_retention_days, - use_last_used_at=True, - active_leases=usage_snapshot.leases, - ) - try: - deleted = execute_registry_prune( - client, - candidates, - usage_store=usage_store, - expected_usage_generation=usage_snapshot.generation, - all_records=records, - ) - break - except RegistryUsageGenerationChanged: - if attempt == 2: - raise - continue - image_records = records - removed_images = {(item.repository, item.tag) for item in deleted} - plan["deleted"] = [item.to_dict() for item in deleted] - plan["usage_generation"] = usage_snapshot.generation - plan["active_lease_count"] = len(usage_snapshot.leases) - removed = _remove_image_records_for_registry_tags( - config.image_file(), - {(record.repository, record.tag) for record in deleted}, - ) - removed.extend( - _remove_stale_private_build_image_records( - config.image_file(), - client, - ) - ) - plan["removed_image_records"] = [ - item.to_dict() for item in _dedupe_image_records(removed) - ] - evicted: list[RegistryTag] = [] - usage = registry_disk_usage(config) if evict_lru else None - if usage is not None and usage.cleanup_needed and not repository_prefix: - eviction, evicted, evicted_records = _run_lru_eviction( - config, - client, - usage_store, - images=[ - record - for record in image_records - if (record.repository, record.tag) not in removed_images - ], - usage=usage, - execute=execute, - ) - plan["lru_eviction"] = eviction - if execute: - removed_images |= {(item.repository, item.tag) for item in evicted} - plan.setdefault("removed_image_records", []).extend( - item.to_dict() for item in evicted_records - ) - else: - removed_images |= { - (item["repository"], tag) - for item in eviction["evict_sample_all"] - for tag in item["tags"] - } - eviction.pop("evict_sample_all", None) - reference = _run_reference_retention( + """Age retention for image repositories, reference retention for the rest.""" + return _run_registry_prune( config, - client, - usage_store, - repositories=reference_repositories, - # A dry run treats its planned deletions as already gone. - remaining_images=[ - record - for record in image_records - if (record.repository, record.tag) not in removed_images - ], - repository_prefix=repository_prefix, execute=execute, + repository_prefix=repository_prefix, + evict_lru=evict_lru, + client_factory=RegistryClient, + disk_usage_fn=registry_disk_usage, ) - plan["reference_retention"] = reference - cache_deleted = 0 - if cache_policy is not None and ( - not repository_prefix or cache_policy.repository.startswith(repository_prefix) - ): - try: - plan["build_cache"] = cache_policy.prune(execute=execute) - cache_deleted = plan["build_cache"].get("deleted_manifests", 0) - except (OSError, ValueError, RuntimeError) as exc: - # A disposable cache must not prevent image/reference maintenance. - plan["build_cache"] = {"error": type(exc).__name__, "deleted_manifests": 0} - if execute: - deleted_manifests = len( - {(item.repository, item.digest) for item in (*deleted, *evicted)} - ) - deleted_manifests += sum( - item["deleted_manifests"] for item in reference["decisions"] - ) - deleted_manifests += cache_deleted - plan["deleted_manifest_count"] = deleted_manifests - try: - state = record_registry_prune( - config.registry_maintenance_state_file(), deleted=deleted_manifests - ) - state.pop("evicted_images", None) - plan["maintenance_state"] = state - except OSError as exc: - plan["maintenance_state_error"] = str(exc) - usage = registry_disk_usage(config) - plan["registry_disk"] = usage.to_dict() if usage is not None else None - return plan - - -def _run_lru_eviction( - config: DeploymentConfig, - client: RegistryClient, - usage_store: RegistryUsageStore, - *, - images: list[RegistryTag], - usage: RegistryDiskUsage, - execute: bool, -) -> tuple[dict[str, Any], list[RegistryTag], list[ImageRecord]]: - """Evict managed images, oldest use first, down to the target usage.""" - - grace = config.registry_reference_grace_seconds - usage_snapshot = usage_store.snapshot() - data_dir = ( - config.registry_data_dir() - if config.registry_store.kind == "filesystem" - and config.registry_data_dir().is_dir() - else None - ) - routing_store = open_routing_store(config.routing_file()) - environments = ( - (ImageEnvironmentIndex(client), - EnvironmentBlobIndex(client, config.immutable_environments.repository)) - if config.immutable_environments is not None - else None - ) - - def blobs(repository: str, digest: str) -> dict[str, int]: - result = manifest_blob_sizes(client, repository, digest) - if environments is not None: - roots, environment_blobs = environments - try: - result.update(environment_blobs.blobs(roots.root(repository, digest))) - except (RegistryRequestError, ValueError): - # An unreadable environment only makes the projection - # undercount what evicting this image frees. - pass - return result - - # Chunk store M2: a dispatched image's bytes are in the chunk store; its - # OCI goes by OCI release, which remembers its tags (plan §3.3, §5.4). - from .gateway.image_roots import retention_view - _mapped_roots, dispatched = retention_view(config.image_file()) - now = utc_now() - plan = select_lru_evictions( - managed_images( - [record for record in images if (record.repository, record.digest) not in dispatched], - tag_time=RegistryTagClock(data_dir, usage_snapshot.records), - blobs=blobs, - ), - used_bytes=usage.used_bytes, - target_used_bytes=usage.target_used_bytes, - grace_seconds=grace, - live=routing_image_identities(routing_store), - leased_digests=usage_snapshot.active_lease_digests(), - now=now, - ) - summary = plan.to_dict() - summary["evict_sample_all"] = [ - {"repository": image.repository, "tags": [tag.tag for tag in image.tags]} - for image in plan.evict - ] - if not execute or not plan.evict: - return summary, [], [] - fresh = routing_image_identities(routing_store) - evicted = execute_reference_prune( - client, - plan.records, - usage_store=usage_store, - still_unreferenced=lambda record: not image_is_referenced( - ManagedImage(record.repository, record.digest, (record,), None), fresh, - ), - unused_since=now - timedelta(seconds=grace), - ) - # A later create must rebuild or re-import the image, never resolve a - # gateway record to the deleted manifest. - removed = _remove_image_records_for_registry_tags( - config.image_file(), - {(record.repository, record.tag) for record in evicted}, - ) - if evicted: - try: - record_image_evictions( - config.registry_maintenance_state_file(), - [{"image_id": item.id, "tag": item.tag} for item in removed], - ) - except OSError as exc: - summary["tombstone_error"] = str(exc) - summary["evicted_images"] = len({(item.repository, item.digest) for item in evicted}) - summary["evicted_tags"] = len(evicted) - print( - "registry disk pressure evicted " - f"{summary['evicted_images']} least-recently-used managed images", - file=sys.stderr, - ) - return summary, evicted, removed - - -def _reference_retained_repositories(config: DeploymentConfig) -> dict[str, str]: - repositories: dict[str, str] = {} - if config.snapshot_store.kind == "registry": - repositories[SNAPSHOT_REASON] = config.sandbox.storage_native_repository - if config.immutable_environments is not None: - repositories[ENVIRONMENT_REASON] = config.immutable_environments.repository - return repositories - - -def _run_reference_retention( - config: DeploymentConfig, - client: RegistryClient, - usage_store: RegistryUsageStore, - *, - repositories: dict[str, str], - remaining_images: list[RegistryTag], - repository_prefix: str, - execute: bool, -) -> dict[str, Any]: - grace = config.registry_reference_grace_seconds - result: dict[str, Any] = {"grace_seconds": grace, "decisions": []} - if not repositories: - return result - catalog = set(client.catalog()) - usage_snapshot = usage_store.snapshot() - leased = usage_snapshot.active_lease_digests() - data_dir = ( - config.registry_data_dir() - if config.registry_store.kind == "filesystem" - and config.registry_data_dir().is_dir() - else None - ) - tag_time = RegistryTagClock(data_dir, usage_snapshot.records) - now = utc_now() - - def present(reason: str) -> bool: - repository = repositories.get(reason, "") - return repository in catalog and repository.startswith(repository_prefix) - - def decide(reason: str, live: set[str]) -> ReferenceRetentionDecision: - return select_unreferenced( - list_repository_tags(client, repositories[reason]), - reason=reason, - repository=repositories[reason], - live=live, - grace_seconds=grace, - tag_time=tag_time, - leased_digests=leased, - now=now, - ) - - def skip(reason: str, message: str) -> ReferenceRetentionDecision: - return ReferenceRetentionDecision( - reason=reason, repository=repositories[reason], skipped=message, - ) - - outcomes: list[tuple[ReferenceRetentionDecision, list[RegistryTag]]] = [] - if present(SNAPSHOT_REASON): - routing_store = open_routing_store(config.routing_file()) - try: - decision = decide(SNAPSHOT_REASON, snapshot_live_identities(routing_store)) - except ValueError as exc: - decision = skip(SNAPSHOT_REASON, f"snapshot liveness unknown: {exc}") - deleted_snapshots: list[RegistryTag] = [] - if execute and decision.delete: - # Revalidate against references committed while the repository - # was listed; a route adopting an old snapshot also leases it. - fresh = snapshot_live_identities(routing_store) - deleted_snapshots = execute_reference_prune( - client, decision, usage_store=usage_store, - still_unreferenced=lambda record: ( - record.digest not in fresh and record.tag not in fresh - ), - ) - outcomes.append((decision, deleted_snapshots)) - if present(ENVIRONMENT_REASON): - environment_repository = repositories[ENVIRONMENT_REASON] - excluded = set(repositories.values()) - index = ImageEnvironmentIndex(client) - # Chunk store M2 (plan §3.3): converted and dispatched roots stay live on - # their image_roots rows; a dispatched image's annotation no longer counts. - from .gateway.image_roots import retention_view - mapped_roots, dispatched = retention_view(config.image_file()) - if repository_prefix: - decision = skip( - ENVIRONMENT_REASON, "a repository prefix limits the managed image scan", - ) - else: - try: - live = environment_live_identities( - client, - environment_repository, - index.roots( - record - for record in remaining_images - if record.repository not in excluded - and (record.repository, record.digest) not in dispatched - ) | mapped_roots, - ) - decision = hold_unrecorded_conversions(decide(ENVIRONMENT_REASON, live), tag_time, now) - if decision.delete: - decision = replace( - decision, - delete_layer_bytes=manifest_layer_bytes( - client, - environment_repository, - (record.digest for record in decision.delete), - ), - ) - except (RegistryRequestError, ValueError) as exc: - decision = skip( - ENVIRONMENT_REASON, f"environment liveness unknown: {exc}", - ) - deleted_environments: list[RegistryTag] = [] - if execute and decision.delete: - # An image pushed since the scan may annotate an old root, and a - # row may have been recorded or switched since. - mapped_roots, dispatched = retention_view(config.image_file()) - fresh = environment_live_identities( - client, - environment_repository, - index.roots( - record - for repository in client.catalog() - if repository not in excluded - for record in list_repository_tags(client, repository) - if (record.repository, record.digest) not in dispatched - ) | mapped_roots, - ) - deleted_environments = execute_reference_prune( - client, decision, usage_store=usage_store, - still_unreferenced=still_unreferenced_environment( - fresh, tag_time, now - timedelta(seconds=grace), - ), - ) - outcomes.append((decision, deleted_environments)) - for decision, deleted in outcomes: - item = decision.to_dict() - if execute: - item["deleted_manifests"] = len({record.digest for record in deleted}) - item["deleted_tags"] = len(deleted) - result["decisions"].append(item) - return result - - -def _remove_image_records_for_registry_tags( - image_file: Path, - registry_tags: set[tuple[str, str]], -) -> list[ImageRecord]: - if not registry_tags: - return [] - store = ImageStore(image_file) - records = store.load() - tags_to_remove = [ - record.tag - for record in records.values() - if registry_repository_tag_from_image_ref(record.tag) in registry_tags - ] - return store.delete_by_tags(tags_to_remove) - - -def _remove_stale_private_build_image_records( - image_file: Path, - client: RegistryClient, -) -> list[ImageRecord]: - from .gateway.image_roots import released_lookup - store = ImageStore(image_file) - records = store.load() - tags_to_remove: list[str] = [] - released = released_lookup(image_file) - for record in records.values(): - if not _image_record_is_pushed_private_build(record, client.base_url): - continue - parsed = registry_repository_tag_from_image_ref(record.tag) - if parsed is None: - continue - try: - exists = client.tag_exists(*parsed) - except (OSError, ValueError, RegistryRequestError): - continue - # Chunk store M2: OCI release deleted a released image's tags, not the image. - if not exists and not released(parsed[0], parsed[1], record.manifest_digest): - tags_to_remove.append(record.tag) - return store.delete_by_tags(tags_to_remove) - - -def _image_record_is_pushed_private_build( - record: ImageRecord, - registry_url: str, -) -> bool: - return bool( - record.pushed - and record.source.startswith("build:") - and _image_ref_uses_private_registry(record.tag, registry_url) - ) - - -def _image_ref_uses_private_registry(image_ref: str, registry_url: str) -> bool: - host = registry_host_from_image_ref(image_ref) - if not host: - return False - registry_host = urlparse(registry_url).netloc - allowed = { - "ucloud-sandbox-registry:5000", - "localhost:5000", - "127.0.0.1:5000", - } - if registry_host: - allowed.add(registry_host) - return host in allowed - - -def _dedupe_image_records(records: list[ImageRecord]) -> list[ImageRecord]: - deduped: dict[str, ImageRecord] = {} - for record in records: - deduped[record.id] = record - return [deduped[key] for key in sorted(deduped)] def cmd_submit_vm(args: argparse.Namespace) -> int: @@ -3101,76 +2578,6 @@ def _post_gateway_sandbox_migration( )[0] -# Measured moves take under a second; a slower one is retried by migration id. -_SOFT_DRAIN_MOVE_TIMEOUT_SECONDS = 60.0 - - -def _soft_drain_migration_id(route: SandboxRoute) -> str: - # Stable per parked incarnation, so an ambiguous retry resumes the same - # migration instead of starting a second one. - return f"drain-{route.job_id}-{route.sandbox_id}-{route.generation}" - - -def _soft_drain_movable_routes( - routes: Iterable[SandboxRoute], - *, - pending_wake_sandbox_ids: set[str], - limit: int, -) -> list[SandboxRoute]: - # Running, waking and creating sandboxes stay; they move after parking. - # A park the gateway has not yet seen published still qualifies: the move - # asks the owner to publish (or reuse) its snapshot first. - return [ - route - for route in routes - if route.worker_state == "attached" - and (route.state or "").lower() == "parked" - and not route.delete_operation_id - and route.sandbox_id not in pending_wake_sandbox_ids - ][: max(0, limit)] - - -def _move_soft_drained_sandbox( - route: SandboxRoute, - *, - gateway_url: str, - bearer_token: str | None, -) -> dict[str, Any]: - migration_id = _soft_drain_migration_id(route) - entry: dict[str, Any] = { - "jobId": route.job_id, - "sandboxId": route.sandbox_id, - "migrationId": migration_id, - "requestSucceeded": False, - "skipped": False, - "destinationJobId": "", - "error": "", - } - try: - payload = _post_gateway_sandbox_migration( - gateway_url, - route.sandbox_id, - bearer_token=bearer_token, - timeout_seconds=_SOFT_DRAIN_MOVE_TIMEOUT_SECONDS, - migration_id=migration_id, - soft_drain=True, - ) - except HTTPError as exc: - # 503: no destination fits now, or a retryable incomplete migration. - # Either way the next cycle retries; nothing is lost. - entry["skipped"] = exc.code == HTTPStatus.SERVICE_UNAVAILABLE - entry["error"] = f"HTTP {exc.code}: {exc.reason}" - return entry - except Exception as exc: - entry["error"] = str(exc) - return entry - migration = payload.get("migration") - migration = migration if isinstance(migration, dict) else {} - entry["requestSucceeded"] = migration.get("phase") == "complete" - entry["destinationJobId"] = str(migration.get("destination_job_id") or "") - return entry - - def _apply_soft_drain( decision: Any, nodes: list[SandboxNode], @@ -3185,47 +2592,20 @@ def _apply_soft_drain( execute: bool, assert_provider_fence: Callable[[], None], ) -> tuple[dict[str, Any], list[dict[str, Any]]]: - """Persist the soft-drain plan, then move the worker's published parks.""" - - job_id = decision.soft_drain_job_id - selected = bool(job_id and decision.soft_drain_selected) - if selected and job_id in blocked_job_ids: - # Stopping, lost or quarantined workers are never newly selected. - job_id, selected = "", False - result: dict[str, Any] = { - "jobId": job_id, - "selected": selected, - "clearedJobIds": list(decision.soft_drain_clear_job_ids), - "applied": False, - } - if not execute: - return result, [] - for cleared in decision.soft_drain_clear_job_ids: - control_state.clear_soft_drain(cleared) - heartbeats = {node.job_id: node.heartbeat for node in nodes} - if job_id and not is_soft_drained(heartbeats.get(job_id)): - control_state.set_soft_drain(job_id, utc_now().isoformat()) - result["applied"] = True - if not job_id or job_id in blocked_job_ids: - return result, [] - routes = _soft_drain_movable_routes( - route_reservations.get(job_id, ()), + return _autoscaler_apply_soft_drain( + decision, + nodes, + control_state=control_state, + policy=policy, + route_reservations=route_reservations, + blocked_job_ids=blocked_job_ids, pending_wake_sandbox_ids=pending_wake_sandbox_ids, - limit=policy.drain_on_park_moves_per_cycle, - ) - if not routes: - return result, [] - assert_provider_fence() - with ThreadPoolExecutor(max_workers=len(routes)) as pool: - moves = list( - pool.map( - lambda route: _move_soft_drained_sandbox( - route, gateway_url=gateway_url, bearer_token=bearer_token, - ), - routes, - ) - ) - return result, moves + gateway_url=gateway_url, + bearer_token=bearer_token, + execute=execute, + assert_provider_fence=assert_provider_fence, + post_migration=_post_gateway_sandbox_migration, + ) def _post_gateway_sandbox_detach( @@ -3269,730 +2649,146 @@ def _delete_gateway_sandbox( # A hung worker holds one bounded slot, never the cycle; the durable delete # operation id makes an abandoned attempt safe to repeat. _PENDING_DELETE_REPLAY_TIMEOUT_SECONDS = 30.0 -_PENDING_DELETE_REPLAY_CONCURRENCY = 8 def _delete_stuck_starts( items: list[StuckStart], *, bearer_token: str, ) -> list[dict[str, Any]]: - """Delete each stuck registration on its worker, fenced to its own incarnation.""" - - def delete(item: StuckStart) -> dict[str, Any]: - error = "" - try: - _delete_bounded_json( - item.node_url, f"/v1/sandboxes/{quote(item.sandbox_id, safe='')}", - bearer_token=bearer_token, - invalid_url_error="node heartbeat has an invalid node URL", - empty_token_error="node control bearer token cannot be empty", - timeout_seconds=_PENDING_DELETE_REPLAY_TIMEOUT_SECONDS, - response_name="node stuck start delete", - extra_headers={ - SANDBOX_GENERATION_HEADER: str(item.generation), - SANDBOX_OPERATION_ID_HEADER: item.operation_id, - }, - ) - except Exception as exc: - error = str(exc) - return { - "job_id": item.job_id, "sandbox_id": item.sandbox_id, "generation": item.generation, - "operation_id": item.operation_id, "deleted": not error, "error": error, - } - - if not items: - return [] - with ThreadPoolExecutor(min(_PENDING_DELETE_REPLAY_CONCURRENCY, len(items))) as pool: - return list(pool.map(delete, items)) + return _autoscaler_delete_stuck_starts( + items, + bearer_token=bearer_token, + delete_node_sandbox=_delete_bounded_json, + timeout_seconds=_PENDING_DELETE_REPLAY_TIMEOUT_SECONDS, + ) def _replay_pending_deletes( routes: list[SandboxRoute], *, skip_job_ids: set[str], provider_state: AutoscalerStateStore, deployment_id: str, budget: int, gateway_url: str, bearer_token: str | None, ) -> list[dict[str, Any]]: - """Deliver recorded client DELETE intents, least recently attempted first. - - Intent age alone would let a silent worker's oldest intents take the - whole budget every cycle and starve every younger one. A skipped job's - intents keep their attempt times, so they cannot jump the queue later. - """ - by_key = {(route.sandbox_id, route.delete_operation_id): route for route in sorted( - routes, key=lambda route: (route.updated_at, route.sandbox_id))} - eligible = [key for key, route in by_key.items() if route.job_id not in skip_job_ids] - - def replay(key: tuple[str, str]) -> dict[str, Any]: - route, error, payload = by_key[key], "", {} - try: - payload = _delete_gateway_sandbox( - gateway_url, route.sandbox_id, bearer_token=bearer_token, - timeout_seconds=_PENDING_DELETE_REPLAY_TIMEOUT_SECONDS, - ) - except Exception as exc: - error = str(exc) - return { - "job_id": route.job_id, "sandbox_id": route.sandbox_id, "gateway_url": gateway_url, - "delete_operation_id": route.delete_operation_id, "request_succeeded": not error, - "deleted": payload.get("deleted"), "error": error, - } - - selected = provider_state.rotate_pending_deletes( - deployment_id=deployment_id, pending=eligible, recorded=by_key, budget=budget, + return _autoscaler_replay_pending_deletes( + routes, + skip_job_ids=skip_job_ids, + provider_state=provider_state, + deployment_id=deployment_id, + budget=budget, + gateway_url=gateway_url, + bearer_token=bearer_token, + delete_gateway_sandbox=_delete_gateway_sandbox, + timeout_seconds=_PENDING_DELETE_REPLAY_TIMEOUT_SECONDS, ) - if not selected: - return [] - with ThreadPoolExecutor(min(_PENDING_DELETE_REPLAY_CONCURRENCY, len(selected))) as pool: - return list(pool.map(replay, selected)) -def _drain_response_acknowledges( - response: dict[str, Any], - *, - token: str, - draining: bool, -) -> bool: - drain = response.get("drain") - return bool( - isinstance(drain, dict) - and str(drain.get("token") or "").strip() == str(token).strip() - and drain.get("draining") is draining - and drain.get("admission_open") is (not draining) +def _probe_unreachable_node( + heartbeat: NodeHeartbeat, + bearer_token: str | None, + heartbeat_ttl_seconds: int = 60, +) -> tuple[NodeHeartbeat | None, bool]: + return _autoscaler_probe_unreachable_node( + heartbeat, + bearer_token, + heartbeat_ttl_seconds, + fetch_heartbeat=fetch_node_agent_heartbeat, ) -def _nodes_with_drain_admission_reopened( - nodes: list[SandboxNode], - job_ids: set[str], -) -> list[SandboxNode]: - """Return a planning-only view where selected drain intents are canceled.""" - - reopened: list[SandboxNode] = [] - for node in nodes: - heartbeat = node.heartbeat - if node.job_id not in job_ids or heartbeat is None: - reopened.append(node) - continue - reopened.append( - replace( - node, - heartbeat=replace( - heartbeat, - draining=False, - admission_open=True, - ), - ) - ) - return reopened - - -def _drain_intent_to_dict(intent: DrainIntent) -> dict[str, Any]: - return { - "deploymentId": intent.deployment_id, - "jobId": intent.job_id, - "role": intent.role, - "token": intent.token, - "state": intent.state, - "updatedAt": intent.updated_at.isoformat(), - } - - -def _stop_operation_has_safety_proof( - provider_state: AutoscalerStateStore, - provider: ComputeProvider, - operation: ProviderOperation, -) -> bool: - if operation.kind != "stop" or len(operation.target_job_ids) != 1: - return operation.kind != "stop" - if operation.request.get("unreachableStaleReady") is True: - route_count = operation.request.get("routeCount") - active_sandboxes = operation.request.get("lastKnownActiveSandboxes") - return bool( - str(operation.request.get("unreachableReference") or "").strip() - and type(route_count) is int - and route_count == 0 - and type(active_sandboxes) is int - and active_sandboxes == 0 - and operation.request.get("lastHeartbeatSafeToStop") is True - # A worker that heartbeated also failed this cycle's direct probe. - and ( - operation.request.get("lastHeartbeatPresent") is False - or operation.request.get("directProbeFailed") is True - ) - ) - token = str(operation.request.get("drainToken") or "").strip() - if not token or operation.request.get("drainReady") is not True: - return False - intent = provider_state.get_drain_intent( - operation.deployment_id, - operation.target_job_ids[0], - ) - return bool( - intent is not None - and intent.state == "active" - and intent.token == token - and intent.role == operation.role +def _probe_nodes( + heartbeats: dict[str, NodeHeartbeat], bearer_token: str | None, ttl_seconds: int, +) -> dict[str, tuple[NodeHeartbeat | None, bool]]: + return _autoscaler_probe_nodes( + heartbeats, + bearer_token, + ttl_seconds, + probe_one=_probe_unreachable_node, ) -def apply_prepared_provider_operations( - provider_state: AutoscalerStateStore, - provider: ComputeProvider, +def _quarantine_unverified_guests( + jobs: list[ProviderInstance], + heartbeats: dict[str, NodeHeartbeat], *, - source: str, - allowed_kinds: set[str], - allowed_stop_operation_ids: set[str] | None = None, - telemetry: Telemetry | None = None, -) -> list[ProviderOperationOutcome]: - telemetry = telemetry or _DISABLED_AUTOSCALER_TELEMETRY - results: list[ProviderOperationOutcome] = [] - prepared_operations = provider_state.list_operations(states={"prepared"}) - for prepared in prepared_operations: - if prepared.kind not in allowed_kinds: - continue - if prepared.kind == "stop" and prepared.operation_id not in ( - allowed_stop_operation_ids or set() - ): - continue - # Autoscaler stops require a fresh drain proof or a conservative - # unreachable-empty lease proof. - if prepared.kind == "stop" and not _stop_operation_has_safety_proof( - provider_state, - provider, - prepared, - ): - continue - submitting = provider_state.begin_provider_call(prepared.operation_id) - try: - with telemetry.span( - f"provider.{submitting.kind}", - attributes={ - "provider.operation.id": submitting.operation_id, - "provider.operation.kind": submitting.kind, - "provider.role": submitting.role, - "provider.target_count": len(submitting.target_job_ids), - }, - ) as provider_span: - if submitting.kind == "create": - outcome = provider.create(submitting.request) - else: - outcome = provider.terminate(submitting.target_job_ids) - provider_span.set_attribute("provider.outcome", outcome.status) - except Exception as exc: - # Unknown adapter failures cannot prove whether the provider applied - # the request. Adapters should normally return an uncertain result. - operation = provider_state.mark_operation_uncertain( - submitting.operation_id, - error=str(exc), - ) - else: - if outcome.status == "rejected": - operation = provider_state.mark_operation_failed( - submitting.operation_id, - error=outcome.error or "provider explicitly rejected the operation", - response=outcome.response, - ) - elif outcome.status == "accepted": - operation = provider_state.mark_operation_accepted( - submitting.operation_id, - response=outcome.response, - target_job_ids=outcome.instance_ids, - ) - else: - operation = provider_state.mark_operation_uncertain( - submitting.operation_id, - error=outcome.error - or "provider response did not prove whether the operation applied", - ) - results.append( - ProviderOperationOutcome.from_operation(operation, source=source) - ) - return results - - -def _successful_create_operation_count( - operation_results: list[ProviderOperationOutcome], - role: str, -) -> int: - relevant = [ - item - for item in operation_results - if item.kind == "create" and item.role == role - ] - job_ids = [job_id for item in relevant for job_id in item.job_ids] - if ( - not relevant - or not all(item.state in {"accepted", "recovered"} for item in relevant) - or len(job_ids) != len(relevant) - or len(set(job_ids)) != len(job_ids) - ): - return 0 - return len(job_ids) - - -def _sandbox_capacity_operation_succeeded( - operation_results: list[ProviderOperationOutcome], - resource_deficit: ResourceQuantity, - default_node_resources: ResourceQuantity, -) -> bool: - count = _successful_create_operation_count(operation_results, "sandbox") - if count <= 0: - return False - created = ResourceQuantity( - vcpu=default_node_resources.vcpu * count, - memory_mb=default_node_resources.memory_mb * count, - disk_mb=default_node_resources.disk_mb * count, + control_state: ControlStateStore, + policy: ScalePolicy, + deployment_id: str, + route_reservations: dict[str, tuple[SandboxRoute, ...]], + execution_authorized: bool, + bearer_token: str | None, + routing_store: RoutingStore | None = None, + retired_routes: list[SandboxRoute] | None = None, +) -> tuple[list[ProviderInstance], dict[str, NodeHeartbeat]]: + return _autoscaler_quarantine_unverified_guests( + jobs, + heartbeats, + control_state=control_state, + policy=policy, + deployment_id=deployment_id, + route_reservations=route_reservations, + execution_authorized=execution_authorized, + bearer_token=bearer_token, + routing_store=routing_store, + retired_routes=retired_routes, + probe_nodes_fn=_probe_nodes, ) - return resource_deficit.fits_within(created) - - -def _builder_capacity_operation_succeeded( - operation_results: list[ProviderOperationOutcome], - *, - existing_builders: int, - desired_builders: int, -) -> bool: - count = _successful_create_operation_count(operation_results, "builder") - return count > 0 and existing_builders + count >= desired_builders - -# An account limit does not lift within a cycle. Retrying it every cycle spends -# the provider's API rate limit, which inventory and stops share. -CREATE_QUOTA_BACKOFF = timedelta(minutes=5) - -def quota_blocked_roles( - failed_creates: Iterable[ProviderOperation], now: datetime, - backoff: timedelta = CREATE_QUOTA_BACKOFF, -) -> set[str]: - """Roles whose creates the provider refused for quota within ``backoff``.""" - - return { - operation.role for operation in failed_creates - if operation.response.get(QUOTA_EXCEEDED) and now - operation.updated_at < backoff - } - - -def _reconcile_provider_operation_inventory( +def _observe_provider_nodes( *, - provider_state: AutoscalerStateStore | None, - provider: ComputeProvider, jobs: list[ProviderInstance], - execution_authorized: bool, - execute: bool, - telemetry: Telemetry, -) -> tuple[list[ProviderOperationOutcome], list[dict[str, Any]], set[str]]: - """Replay safe creates and fence creates not yet visible in inventory.""" - - if not execution_authorized or provider_state is None: - return [], [], set() - results = list(provider_state.reconcile_provider_inventory(jobs)) - # Stops are replayed only after this cycle refreshes every active drain. - replay_results = apply_prepared_provider_operations( - provider_state, - provider, - source="prepared-replay", - allowed_kinds={"create"} if execute else set(), - allowed_stop_operation_ids=set(), - telemetry=telemetry, - ) - results.extend(replay_results) - blocked_roles = { - operation.role - for operation in provider_state.list_operations( - kind="create", - states={"uncertain", "accepted"}, - ) - } - blocked_roles.update( - item.role - for item in replay_results - if item.kind == "create" and item.state == "accepted" - ) - blocked_roles.update(quota_blocked_roles( - provider_state.list_operations(kind="create", states={"failed"}), utc_now(), - )) - observed_job_ids = {job.id for job in jobs if job.id} - guards: list[dict[str, Any]] = [] - for operation in provider_state.list_operations( - kind="create", - states={"accepted"}, - ): - missing_job_ids = sorted(set(operation.target_job_ids) - observed_job_ids) - if not missing_job_ids: - continue - blocked_roles.add(operation.role) - guards.append( - { - "operationId": operation.operation_id, - "role": operation.role, - "state": operation.state, - "missingJobIds": missing_job_ids, - } - ) - return results, guards, blocked_roles - - -@dataclass(frozen=True) -class _ProviderObservation: - jobs: list[ProviderInstance] - nodes: list[SandboxNode] - sandbox_nodes: list[SandboxNode] - builder_nodes: list[SandboxNode] - unreachable_probe_results: list[dict[str, Any]] - # Lease-expired empty workers whose direct probe failed in transport. - unreachable_probe_failed_job_ids: frozenset[str] - final_heartbeat_job_ids: tuple[str, ...] - orphaned_stale_heartbeat_job_ids: tuple[str, ...] - # Routes a verified same-boot quarantine probe proved absent. - retired_routes: tuple[SandboxRoute, ...] = () - - -def _probe_unreachable_node( - heartbeat: NodeHeartbeat, - bearer_token: str | None, - heartbeat_ttl_seconds: int = 60, -) -> tuple[NodeHeartbeat | None, bool]: - """Recover a lost push path; only transport failure supports retirement.""" - if not heartbeat.node_url: - return None, False - try: - fresh = fetch_node_agent_heartbeat( - heartbeat.node_url, - bearer_token=bearer_token, - timeout_seconds=3.0, - ) - except Exception as exc: - reason = exc.__cause__ or exc - # HTTP/auth/schema failures prove contact, not VM loss. Do not turn a - # token or protocol misconfiguration into destructive VM retirement. - return None, isinstance(reason, (URLError, OSError)) and not isinstance( - reason, HTTPError - ) - if (fresh.job_id, fresh.node_id, fresh.deployment_id) != ( - heartbeat.job_id, - heartbeat.node_id, - heartbeat.deployment_id, - ): - return None, False - if not fresh.is_fresh(utc_now(), heartbeat_ttl_seconds): - return None, False - # The probe reached this canonical endpoint; that is the proven node URL. - return replace(fresh, node_url=heartbeat.node_url, received_at=utc_now()), False - - -def _guest_continuity_matches( - previous: NodeHeartbeat, - fresh: NodeHeartbeat, - routes: tuple[SandboxRoute, ...], -) -> bool: - """A reachable endpoint alone cannot restore placement authority.""" - if ( - not fresh.node_epoch - or not fresh.inventory_complete - or fresh.active_sandbox_creates - or fresh.node_epoch in previous.retired_node_epochs - ): - return False - anchor = previous.labels.get(QUARANTINE_EPOCH, previous.node_epoch) - if anchor != fresh.node_epoch and ( - routes or fresh.inventory or fresh.active_workloads - ): - return False - inventory = {item.sandbox_id: item for item in fresh.inventory} - if len(inventory) != len(fresh.inventory): - return False - for route in routes: - item = inventory.get(route.sandbox_id) - if ( - item is None - or route.node_epoch != fresh.node_epoch - or route.node_id != fresh.node_id - or (route.generation, route.create_operation_id, route.spec_hash) - != (item.generation, item.operation_id, item.spec_hash) - ): - return False - return True - - -def _unverified_interruption(job: ProviderInstance, heartbeat: NodeHeartbeat) -> bool: - """A provider interruption newer than the last verified guest continuity.""" - verified = parse_iso_datetime(heartbeat.labels.get(CONTINUITY_VERIFIED_THROUGH)) - return job.interrupted_at is not None and (verified is None or job.interrupted_at > verified) - - -def _retire_absent_routes( - routing_store: RoutingStore, fresh: NodeHeartbeat, routes: tuple[SandboxRoute, ...], -) -> tuple[tuple[SandboxRoute, ...], list[SandboxRoute]]: - """Apply a verified same-boot inventory's absences by the ingest rules.""" - removed, _ = routing_store.reconcile_sandboxes_for_node( - fresh.node_url or "", (), node_id=fresh.node_id, job_id=fresh.job_id, - reported_sandbox_ids=[item.sandbox_id for item in fresh.inventory], - observed_at=fresh.freshness_at.isoformat(), node_epoch=fresh.node_epoch, - activity_epoch=fresh.activity_epoch, - ) - # A protected absence (in-flight state, newer activity) still blocks. - return tuple(route for route in routes if ( - (current := routing_store.get_sandbox_readonly(route.sandbox_id)) is not None - and current.job_id == route.job_id and current.worker_state != "detached" - )), removed - - -def _probe_nodes( - heartbeats: dict[str, NodeHeartbeat], bearer_token: str | None, ttl_seconds: int, -) -> dict[str, tuple[NodeHeartbeat | None, bool]]: - """Probe each worker directly, eight at a time; results in input order.""" - if not heartbeats: - return {} - with ThreadPoolExecutor(max_workers=min(8, len(heartbeats))) as pool: - futures = { - job_id: pool.submit(_probe_unreachable_node, heartbeat, bearer_token, ttl_seconds) - for job_id, heartbeat in heartbeats.items() - } - return {job_id: future.result() for job_id, future in futures.items()} - - -def _quarantine_unverified_guests( - jobs: list[ProviderInstance], - heartbeats: dict[str, NodeHeartbeat], - *, - control_state: ControlStateStore, - policy: ScalePolicy, - deployment_id: str, - route_reservations: dict[str, tuple[SandboxRoute, ...]], - execution_authorized: bool, - bearer_token: str | None, - routing_store: RoutingStore | None = None, - retired_routes: list[SandboxRoute] | None = None, -) -> tuple[list[ProviderInstance], dict[str, NodeHeartbeat]]: - """Fence unverified guests; ``retired_routes`` receives verified absences.""" - candidates = {} - jobs_by_id = {job.id: job for job in jobs} - for job in jobs: - previous = heartbeats.get(job.id) - if job.is_final or not is_managed_compute_instance(job, deployment_id): - continue - if previous is None: - continue - unready = job.is_unavailable or _unverified_interruption(job, previous) - if not ( - unready - or previous.labels.get(QUARANTINE_REASON) - or not previous.is_fresh(utc_now(), policy.heartbeat_ttl_seconds) - ): - continue - reason = ( - "provider_readiness_unverified" - if unready - else "heartbeat_continuity_unverified" - ) - if execution_authorized: - guarded = control_state.quarantine_node(job.id, reason) - if guarded is None: - continue - else: - guarded = replace( - previous, admission_open=False, labels=quarantined_labels(previous, reason), - ) - heartbeats[job.id] = guarded - # An authenticated guest may still serve existing work while UCloud - # readiness is false. Do not reopen placement until both agree. - if job.state == "RUNNING": - candidates[job.id] = guarded - recovered = set() - probes = _probe_nodes(candidates, bearer_token, policy.heartbeat_ttl_seconds) - for jid, (fresh, _transport_failed) in probes.items(): - previous, routes = candidates[jid], route_reservations.get(jid, ()) - if fresh is None: - continue - reported = {item.sandbox_id for item in fresh.inventory} - if ( - routing_store is not None - and fresh.node_epoch == previous.node_epoch == previous.labels.get(QUARANTINE_EPOCH) - and _guest_continuity_matches(previous, fresh, tuple( - route for route in routes if route.sandbox_id in reported - )) - ): - # Quarantined ingest retires nothing, yet continuity needs every - # route present: without this, one vanished sandbox pins - # quarantine. Never across an epoch. - routes, removed = _retire_absent_routes(routing_store, fresh, routes) - if retired_routes is not None: - retired_routes.extend(removed) - if not _guest_continuity_matches(previous, fresh, routes): - continue - verified_through = jobs_by_id[jid].interrupted_at - if not execution_authorized: - fresh = replace(fresh, labels=recovered_labels(fresh, previous, verified_through)) - elif (fresh := control_state.recover_quarantined_node( - fresh, verified_through=verified_through, - )) is None: - continue - heartbeats[jid] = fresh - recovered.add(jid) - jobs = [ - replace(job, phase=InstancePhase.RUNNING) - if job.id in recovered - else replace(job, phase=InstancePhase.UNAVAILABLE) - if job.id in heartbeats - and heartbeats[job.id].labels.get(QUARANTINE_REASON) - and not job.is_final - else job - for job in jobs - ] - return jobs, heartbeats - - -def _observe_provider_nodes( - *, - jobs: list[ProviderInstance], - provider: ComputeProvider, - provider_state: AutoscalerStateStore | None, - control_state: ControlStateStore, - policy: ScalePolicy, - deployment_id: str, - route_reservations: dict[str, tuple[SandboxRoute, ...]], + provider: ComputeProvider, + provider_state: AutoscalerStateStore | None, + control_state: ControlStateStore, + policy: ScalePolicy, + deployment_id: str, + route_reservations: dict[str, tuple[SandboxRoute, ...]], execution_authorized: bool, retrieve_history: bool, node_control_bearer_token: str | None = None, routing_store: RoutingStore | None = None, ) -> _ProviderObservation: - """Normalize provider continuity and heartbeat evidence into node state.""" - - heartbeats = control_state.load_heartbeats() - jobs_by_id = {job.id: job for job in jobs} - if retrieve_history: - for job in tuple(jobs): - heartbeat = heartbeats.get(job.id) - owned_routes = route_reservations.get(job.id, ()) - stale_heartbeat = bool( - heartbeat is not None - and not heartbeat.is_fresh(utc_now(), policy.heartbeat_ttl_seconds) - ) - route_epoch_mismatch = bool( - heartbeat is not None - and heartbeat.node_epoch - and any( - route.node_epoch and route.node_epoch != heartbeat.node_epoch - for route in owned_routes - ) - ) - continuity_history_required = bool( - provider.requires_continuity_history - and is_managed_compute_instance(job, deployment_id) - ) - should_retrieve_history = bool( - job.state == "RUNNING" - and not job.is_lost - and ( - continuity_history_required - or (owned_routes and (stale_heartbeat or route_epoch_mismatch)) - ) - ) - if not should_retrieve_history: - continue - try: - jobs_by_id[job.id] = provider.retrieve_instance( - job.id, - include_updates=True, - ) - except ProviderError: - continue - jobs = [jobs_by_id[job.id] for job in jobs] - - provider_job_ids = {job.id for job in jobs} - orphaned_stale_heartbeat_job_ids = tuple( - sorted( - job_id - for job_id, heartbeat in heartbeats.items() - if job_id not in provider_job_ids - and not route_reservations.get(job_id) - and not heartbeat.is_fresh(utc_now(), policy.heartbeat_ttl_seconds) - ) - ) - if orphaned_stale_heartbeat_job_ids and execution_authorized: - control_state.remove_heartbeats(orphaned_stale_heartbeat_job_ids) - heartbeats = { - job_id: heartbeat - for job_id, heartbeat in heartbeats.items() - if job_id not in orphaned_stale_heartbeat_job_ids - } - - retired_routes: list[SandboxRoute] = [] - if provider.requires_guest_continuity: - jobs, heartbeats = _quarantine_unverified_guests( - jobs, - heartbeats, - control_state=control_state, - policy=policy, - deployment_id=deployment_id, - route_reservations=route_reservations, - execution_authorized=execution_authorized, - bearer_token=node_control_bearer_token, - routing_store=routing_store if execution_authorized else None, - retired_routes=retired_routes, - ) - - observed_nodes = merge_jobs_and_heartbeats( - jobs, - apply_route_reservations_to_heartbeats(heartbeats, route_reservations), - policy, - ) - # Silence is never loss: an unreachable-empty stop of a worker that has - # heartbeated also needs this cycle's direct probe to fail in transport. - unreachable_probe_results: list[dict[str, Any]] = [] - probe_failed: set[str] = set() - expired = { - node.job_id: node.heartbeat - for node in observed_nodes - if is_managed_compute_instance(node.job, deployment_id) - and node.heartbeat is not None - and unreachable_node_stop_ready(node, policy) - } - probes = _probe_nodes(expired, node_control_bearer_token, policy.heartbeat_ttl_seconds) - for job_id, (fresh, transport_failed) in probes.items(): - unreachable_probe_results.append({"jobId": job_id, "status": ( - "healthy" if fresh else "unreachable" if transport_failed else "unverified" - )}) - stored = heartbeats[job_id] - if transport_failed: - probe_failed.add(job_id) - elif fresh is not None and fresh.node_epoch == stored.node_epoch: - # Only the same boot; a new one arrives through ingest. - heartbeats[job_id] = ( - control_state.receive_heartbeat(fresh).stored if execution_authorized else fresh - ) - else: - # Contact without a same-boot heartbeat proves no empty worker. - heartbeats[job_id] = replace(stored, inventory_complete=False) - - final_heartbeat_job_ids = tuple( - sorted(job.id for job in jobs if job.is_final and job.id in heartbeats) - ) - if final_heartbeat_job_ids and execution_authorized: - control_state.remove_heartbeats(final_heartbeat_job_ids) - heartbeats = { - job_id: heartbeat - for job_id, heartbeat in heartbeats.items() - if job_id not in final_heartbeat_job_ids - } - heartbeats = apply_route_reservations_to_heartbeats( - heartbeats, - route_reservations, - ) - nodes = merge_jobs_and_heartbeats(jobs, heartbeats, policy) - nodes = apply_route_reservations_to_nodes(nodes, route_reservations) - return _ProviderObservation( + return _autoscaler_observe_provider_nodes( jobs=jobs, - nodes=nodes, - sandbox_nodes=sandbox_pool_nodes(nodes), - builder_nodes=builder_pool_nodes(nodes), - unreachable_probe_results=unreachable_probe_results, - unreachable_probe_failed_job_ids=frozenset(probe_failed), - final_heartbeat_job_ids=final_heartbeat_job_ids, - orphaned_stale_heartbeat_job_ids=orphaned_stale_heartbeat_job_ids, - retired_routes=tuple(retired_routes), - ) - - -def run_reconcile_cycle( # noqa: C901 + provider=provider, + provider_state=provider_state, + control_state=control_state, + policy=policy, + deployment_id=deployment_id, + route_reservations=route_reservations, + execution_authorized=execution_authorized, + retrieve_history=retrieve_history, + node_control_bearer_token=node_control_bearer_token, + routing_store=routing_store, + probe_nodes_fn=_probe_nodes, + quarantine_fn=_quarantine_unverified_guests, + ) + + +def _autoscaler_ports() -> AutoscalerPorts: + return AutoscalerPorts( + load_instances=load_instances_for_plan, + read_required_token_file=read_required_token_file, + post_node_drain=_post_node_drain, + post_gateway_migration=_post_gateway_sandbox_migration, + post_gateway_detach=_post_gateway_sandbox_detach, + delete_gateway_sandbox=_delete_gateway_sandbox, + delete_node_sandbox=_delete_bounded_json, + probe_nodes=_probe_nodes, + vm_init_options_for_node=vm_init_options_for_autoscaled_node, + apply_bootstrap_requirements=apply_bootstrap_requirements, + execute_bootstrap_phase=_execute_bootstrap_phase, + compute_provider_from_args=compute_provider_from_args, + node_to_dict=node_to_dict, + scale_decision_to_dict=scale_decision_to_dict, + dashboard_scale_policy_to_dict=dashboard_scale_policy_to_dict, + vm_bootstrap_intent_to_dict=vm_bootstrap_intent_to_dict, + apply_soft_drain=_apply_soft_drain, + replay_pending_deletes=_replay_pending_deletes, + delete_stuck_starts=_delete_stuck_starts, + quarantine_unverified_guests=_quarantine_unverified_guests, + pending_delete_timeout_seconds=_PENDING_DELETE_REPLAY_TIMEOUT_SECONDS, + ) + + +def run_reconcile_cycle( config: DeploymentConfig, args: argparse.Namespace, *, @@ -4012,940 +2808,26 @@ def run_reconcile_cycle( # noqa: C901 telemetry: Telemetry | None = None, routing_store: RoutingStore | None = None, ) -> dict[str, Any]: - execution_requested = bool(args.execute) - if ( - execution_requested - and not provider_mutations_allowed - and provider_state is None - ): - raise AutoscalerStateError( - "provider mutations require the local autoscaler controller lock" - ) - if execution_requested and provider_mutations_allowed and provider_state is None: - raise AutoscalerStateError( - "provider mutations require the autoscaler operation journal" - ) - execution_authorized = bool(provider_mutations_allowed) - - def assert_provider_fence() -> None: - if not provider_mutations_allowed: - raise AutoscalerStateError("autoscaler controller lock is not held") - if provider_fence is not None: - provider_fence() - - provider = provider or compute_provider_from_args(args, config) - telemetry = telemetry or _DISABLED_AUTOSCALER_TELEMETRY - jobs = load_instances_for_plan(config, provider, args, telemetry=telemetry) - operation_deployment_id = config.deployment_id or provider.scope_id - ( - provider_operation_results, - create_visibility_guards, - blocked_create_roles, - ) = _reconcile_provider_operation_inventory( - provider_state=provider_state, - provider=provider, - jobs=jobs, - execution_authorized=execution_authorized, - execute=bool(args.execute), - telemetry=telemetry, - ) - - control_state_file = config.control_state_file() - control_state = ControlStateStore(control_state_file) - effective_policy = config.policy - observation = _observe_provider_nodes( - jobs=jobs, + return _autoscaler_run_reconcile_cycle( + config, + args, + ports=_autoscaler_ports(), provider=provider, + demand=demand, + pending_image_builds=pending_image_builds, + prepared_builder_count=prepared_builder_count, + metrics_store=metrics_store, provider_state=provider_state, - control_state=control_state, - policy=effective_policy, - deployment_id=config.deployment_id, - route_reservations=route_reservations or {}, - execution_authorized=execution_authorized, - retrieve_history=not bool(getattr(args, "jobs_file", None)), - node_control_bearer_token=read_required_token_file( - config.node_control_token_file(), - "node control bearer token", - ), + provider_mutations_allowed=provider_mutations_allowed, + route_reservations=route_reservations, + sandbox_routes=sandbox_routes, + program_requests=program_requests, + pending_wake_sandbox_ids=pending_wake_sandbox_ids, + bootstrap_coordinator=bootstrap_coordinator, + provider_fence=provider_fence, + telemetry=telemetry, routing_store=routing_store, ) - jobs = observation.jobs - nodes = observation.nodes - sandbox_nodes = observation.sandbox_nodes - builder_nodes = observation.builder_nodes - final_heartbeat_job_ids = observation.final_heartbeat_job_ids - orphaned_stale_heartbeat_job_ids = observation.orphaned_stale_heartbeat_job_ids - quarantined_job_ids = {node.job_id for node in nodes if node.job.is_unavailable} - builder_pending = max( - 0, - int( - pending_image_builds - if pending_image_builds is not None - else getattr(args, "pending_image_builds", 0) or 0 - ), - ) - builder_prepared = max( - 0, - int(prepared_builder_count if prepared_builder_count is not None else 0), - ) - active_image_builds = sum( - max(0, node.heartbeat.active_image_builds) - for node in builder_nodes - if node.heartbeat is not None and node.heartbeat_fresh - ) - build_warm_resources = build_activity_sandbox_warm_resources( - active_image_builds=active_image_builds, - pending_image_builds=builder_pending, - prepared_builder_count=builder_prepared, - policy=effective_policy, - ) - demand = _demand_forecast_from_usage( - config, - demand, - [ - node.heartbeat for node in sandbox_nodes - if node.heartbeat is not None and node.heartbeat_fresh - ], - route_reservations or {}, - ) - sandbox_demand = demand_with_build_warm_resources( - demand, - build_warm_resources, - ) - live_scale_signals = None - if metrics_store is not None: - pressure_events = metrics_store.load_events( - max_events=10_000, - kinds=("node_heartbeat", "sandbox_create_busy"), - since_seconds=max( - effective_policy.live_pressure_window_seconds, - effective_policy.create_pressure_window_seconds, - ), - ) - lifecycle_events = metrics_store.load_events( - max_events=20_000, - kinds=( - "vm_submitted", - "node_first_heartbeat", - "sandbox_scheduled", - ), - since_seconds=effective_policy.provisioning_latency_lookback_seconds, - ) - live_scale_signals = build_live_scale_signals( - sorted( - [*pressure_events, *lifecycle_events], - key=lambda event: event.timestamp, - ), - effective_policy, - ) - decision = evaluate_scale( - sandbox_nodes, - sandbox_demand, - effective_policy, - live_signals=live_scale_signals, - ) - builder_decision = evaluate_builder_scale( - builder_nodes, - pending_builds=builder_pending, - prepared_builders=builder_prepared, - policy=effective_policy, - max_builder_nodes=config.builder.max_nodes, - ) - drain_workflow_enabled = bool( - args.execute and execution_authorized and provider_state is not None - ) - pending_drain_intents: list[DrainIntent] = [] - irreversible_stop_job_ids: set[str] = set() - if drain_workflow_enabled: - # Adopt both directions of the durable handshake before planning. An - # active drain is evaluated counterfactually as admission-open so a - # demand increase can cancel it, while an already-started provider - # termination is irreversible and must never reopen the node. - pending_drain_intents = provider_state.pending_drain_intents( - deployment_id=operation_deployment_id, - ) - final_job_ids = {job.id for job in jobs if job.id and job.is_final} - for intent in pending_drain_intents: - if intent.job_id in final_job_ids: - provider_state.retire_drain_intent( - deployment_id=intent.deployment_id, - job_id=intent.job_id, - ) - pending_drain_intents = provider_state.pending_drain_intents( - deployment_id=operation_deployment_id, - ) - for operation in provider_state.list_operations( - kind="stop", - ): - provider_call_started = operation.state in { - "uncertain", - "accepted", - } or ( - operation.state == "prepared" - and ( - operation.response.get("providerCallStarted") is True - or operation.updated_at > operation.created_at - or bool(operation.last_error) - ) - ) - if provider_call_started: - irreversible_stop_job_ids.update(operation.target_job_ids) - - nodes_by_job_id = {node.job_id: node for node in nodes} - reopen_job_ids = { - intent.job_id - for intent in pending_drain_intents - if intent.state == "active" - and intent.job_id not in irreversible_stop_job_ids - and (node := nodes_by_job_id.get(intent.job_id)) is not None - and node.heartbeat is not None - and node.heartbeat_fresh - } - if reopen_job_ids: - counterfactual_sandbox_nodes = _nodes_with_drain_admission_reopened( - sandbox_nodes, - reopen_job_ids, - ) - counterfactual_builder_nodes = _nodes_with_drain_admission_reopened( - builder_nodes, - reopen_job_ids, - ) - decision = evaluate_scale( - counterfactual_sandbox_nodes, - sandbox_demand, - effective_policy, - live_signals=live_scale_signals, - ) - builder_decision = evaluate_builder_scale( - counterfactual_builder_nodes, - pending_builds=builder_pending, - prepared_builders=builder_prepared, - policy=effective_policy, - max_builder_nodes=config.builder.max_nodes, - ) - sandbox_create_intents = build_create_intents( - config, - decision, - role="sandbox", - seed_prefix=args.seed_prefix, - ) - builder_create_intents = build_create_intents( - config, - builder_decision, - role="builder", - seed_prefix=args.seed_prefix, - ) - if "sandbox" in blocked_create_roles: - sandbox_create_intents = [] - if "builder" in blocked_create_roles: - builder_create_intents = [] - create_intents = [*sandbox_create_intents, *builder_create_intents] - requested_sandbox_stop_job_ids = decision.stops - requested_builder_stop_job_ids = builder_decision.stops - ( - sandbox_stop_job_ids_with_detachable_storage, - blocked_storage_native_detach_stop_job_ids, - ) = partition_storage_native_detachable_stop_job_ids( - sandbox_nodes, - requested_sandbox_stop_job_ids, - route_reservations or {}, - ) - sandbox_stop_job_ids, blocked_sandbox_stop_job_ids = partition_safe_stop_job_ids( - sandbox_nodes, - sandbox_stop_job_ids_with_detachable_storage, - deployment_id=config.deployment_id, - ownership_label=NODE_LABEL, - ) - builder_stop_job_ids, blocked_builder_stop_job_ids = partition_safe_stop_job_ids( - builder_nodes, - requested_builder_stop_job_ids, - deployment_id=config.deployment_id, - ownership_label=BUILDER_LABEL, - ) - requested_stop_job_ids = tuple( - dict.fromkeys( - [ - *requested_sandbox_stop_job_ids, - *requested_builder_stop_job_ids, - ] - ) - ) - stop_job_ids = tuple(dict.fromkeys([*sandbox_stop_job_ids, *builder_stop_job_ids])) - blocked_stop_job_ids = tuple( - dict.fromkeys( - [ - *blocked_sandbox_stop_job_ids, - *blocked_storage_native_detach_stop_job_ids, - *blocked_builder_stop_job_ids, - ] - ) - ) - if drain_workflow_enabled: - canceling_job_ids = { - intent.job_id - for intent in pending_drain_intents - if intent.state == "canceling" - } - if canceling_job_ids: - blocked_canceling = tuple( - job_id - for job_id in stop_job_ids - if job_id in canceling_job_ids - ) - sandbox_stop_job_ids = tuple( - job_id - for job_id in sandbox_stop_job_ids - if job_id not in canceling_job_ids - ) - builder_stop_job_ids = tuple( - job_id - for job_id in builder_stop_job_ids - if job_id not in canceling_job_ids - ) - stop_job_ids = (*sandbox_stop_job_ids, *builder_stop_job_ids) - blocked_stop_job_ids = (*blocked_stop_job_ids, *blocked_canceling) - stop_nodes_by_job_id = { - node.job_id: node for node in (*sandbox_nodes, *builder_nodes) - } - unreachable_stop_job_ids = tuple( - job_id - for job_id in stop_job_ids - if (node := stop_nodes_by_job_id.get(job_id)) is not None - and unreachable_node_stop_ready(node, effective_policy) - and ( - node.heartbeat is None - or job_id in observation.unreachable_probe_failed_job_ids - ) - ) - unreachable_stop_job_id_set = set(unreachable_stop_job_ids) - active_drain_intents: list[DrainIntent] = [] - drain_results: list[dict[str, Any]] = [] - storage_native_migration_results: list[dict[str, Any]] = [] - storage_native_detach_results: list[dict[str, Any]] = [] - pending_delete_results: list[dict[str, Any]] = [] - stuck_start_results: list[dict[str, Any]] = [] - drain_ready_stop_job_ids: list[str] = [] - canceled_drain_job_ids: list[str] = [] - detach_gateway_url = f"http://127.0.0.1:{config.gateway_port}" - detach_gateway_error = "" - node_control_bearer_token = read_required_token_file( - config.node_control_token_file(), - "node control bearer token", - ) - gateway_control_bearer_token = read_required_token_file( - config.gateway_token_file(), - "gateway control bearer token", - ) - if execution_requested and execution_authorized: - assert provider_state is not None - pending_delete_results = _replay_pending_deletes( - [route for route in sandbox_routes if route.delete_operation_id], - skip_job_ids=quarantined_job_ids, - provider_state=provider_state, - deployment_id=operation_deployment_id, - budget=config.autoscaler_max_pending_delete_retries_per_cycle, - gateway_url=detach_gateway_url, - bearer_token=gateway_control_bearer_token, - ) - stuck_budget = config.autoscaler_max_stuck_start_deletes_per_cycle - unrouted_budget = config.autoscaler_max_unrouted_sandbox_deletes_per_cycle - if (stuck_budget > 0 or unrouted_budget > 0) and routing_store is not None: - candidates = stuck_start_candidates( - [node for node in sandbox_nodes if node.job_id not in quarantined_job_ids], - sandbox_routes, unrouted=unrouted_budget > 0, - ) - first_seen = provider_state.track_stuck_starts( - deployment_id=operation_deployment_id, keys=[item.key for item in candidates], - ) - now = utc_now() - due = stuck_starts_due([item for item in candidates if item.state == "planned"], - first_seen, now, budget=stuck_budget) - due += stuck_starts_due([item for item in candidates if item.state != "planned"], - first_seen, now, budget=unrouted_budget) - # The cycle's route snapshot may predate a new create: re-read each. - due = [item for item in due if unowned( - item.state, item.generation, routing_store.get_sandbox_readonly(item.sandbox_id))] - assert_provider_fence() - stuck_start_results = _delete_stuck_starts(due, bearer_token=node_control_bearer_token) - remaining_detach_budget = max( - 0, - config.autoscaler_max_storage_native_detaches_per_cycle, - ) - cold_offload_plan = plan_cold_offload( - sandbox_nodes, sandbox_routes, program_requests, - pending_wake_sandbox_ids=pending_wake_sandbox_ids or (), - excluded_job_ids=(*stop_job_ids, *quarantined_job_ids), - limit=remaining_detach_budget, - pending_disk_mb=( - max((item.resources.disk_mb for item in demand.placement_requests), default=0) - or math.ceil(demand.pending_resources.disk_mb / max(1, demand.pending_count)) - ) if demand.pending_count else 0, - ) - if execution_requested and execution_authorized: - for candidate in cold_offload_plan: - assert_provider_fence() - detach_payload, detach_error = {}, "" - try: - detach_payload = _post_gateway_sandbox_detach( - detach_gateway_url, candidate.route.sandbox_id, - bearer_token=gateway_control_bearer_token, if_cold=candidate.route, - ) - except Exception as exc: - # An ambiguous eviction retains the canonical detaching route; - # retry the same gateway protocol next cycle or during wake. - detach_error = str(exc) - storage_native_detach_results.append({ - **candidate.to_dict(), "gateway_url": detach_gateway_url, - "request_succeeded": not detach_error, - "sandbox": detach_payload.get("sandbox", {}), "error": detach_error, - }) - remaining_detach_budget -= 1 - # No speculative capacity credit: routing/worker journal commit and - # the next heartbeat must expose the released hard reservation. - if drain_workflow_enabled: - nodes_by_job_id = {node.job_id: node for node in nodes} - pending_drain_intents = provider_state.pending_drain_intents( - deployment_id=operation_deployment_id, - ) - desired_stop_job_ids = set(stop_job_ids) - for intent in pending_drain_intents: - node = nodes_by_job_id.get(intent.job_id) - if ( - intent.state == "active" - and intent.job_id not in desired_stop_job_ids - and intent.job_id not in irreversible_stop_job_ids - and node is not None - and node.heartbeat is not None - and node.heartbeat_fresh - ): - provider_state.begin_drain_cancellation( - deployment_id=intent.deployment_id, - job_id=intent.job_id, - ) - - sandbox_stop_set = set(sandbox_stop_job_ids) - for job_id in stop_job_ids: - if job_id in unreachable_stop_job_id_set: - continue - provider_state.prepare_drain_intent( - deployment_id=operation_deployment_id, - job_id=job_id, - role="sandbox" if job_id in sandbox_stop_set else "builder", - ) - - pending_drain_intents = provider_state.pending_drain_intents( - deployment_id=operation_deployment_id, - ) - for intent in pending_drain_intents: - node = nodes_by_job_id.get(intent.job_id) - heartbeat = node.heartbeat if node is not None else None - node_url = str(heartbeat.node_url or "").strip() if heartbeat else "" - response: dict[str, Any] = {} - error = "" - if ( - intent.state == "active" - and intent.job_id in unreachable_stop_job_id_set - ): - error = "unreachable stale-node stop proof selected" - elif intent.state == "active" and intent.job_id in quarantined_job_ids: - error = ( - "guest continuity is unverified; drain cannot authorize termination" - ) - elif not node_url: - error = "fresh node heartbeat has no node URL" - else: - try: - if intent.state == "canceling": - response = _post_node_drain( - node_url, - intent.token, - draining=False, - bearer_token=node_control_bearer_token, - ) - elif node_control_bearer_token is None: - response = _post_node_drain(node_url, intent.token) - else: - response = _post_node_drain( - node_url, - intent.token, - bearer_token=node_control_bearer_token, - ) - except Exception as exc: - # A timeout or malformed response is ambiguous. The stable - # intent remains in its current direction and a canceling - # intent can never authorize a provider stop. - error = str(exc) - drain_acknowledged = bool( - intent.state == "active" - and not error - and _drain_response_acknowledges( - response, - token=intent.token, - draining=True, - ) - ) - if ( - drain_acknowledged - and intent.role == "sandbox" - and heartbeat is not None - and STORAGE_NATIVE_CAPABILITY in heartbeat.capabilities - and STORAGE_NATIVE_DETACH_CAPABILITY in heartbeat.capabilities - and remaining_detach_budget > 0 - ): - parked_routes = [ - route - for route in (route_reservations or {}).get(intent.job_id, ()) - if is_worker_detachable_parked_route(route) - ] - for route in parked_routes[:remaining_detach_budget]: - detach_error = detach_gateway_error - detach_payload: dict[str, Any] = {} - if not detach_error and not detach_gateway_url: - detach_error = ( - "gateway control URL is required for storage-native " - "worker detach" - ) - if not detach_error: - try: - detach_payload = _post_gateway_sandbox_detach( - detach_gateway_url, - route.sandbox_id, - bearer_token=gateway_control_bearer_token, - ) - except Exception as exc: - # The route and node deletion journals make an ambiguous - # request safe to retry in a later autoscaler cycle. - detach_error = str(exc) - storage_native_detach_results.append( - { - "job_id": intent.job_id, - "sandbox_id": route.sandbox_id, - "gateway_url": detach_gateway_url, - "request_succeeded": not detach_error, - "sandbox": detach_payload.get("sandbox", {}), - "error": detach_error, - } - ) - remaining_detach_budget -= 1 - if remaining_detach_budget <= 0: - break - cancellation_acknowledged = False - ready = False - if intent.state == "canceling": - cancellation_acknowledged = bool( - not error - and _drain_response_acknowledges( - response, - token=intent.token, - draining=False, - ) - ) - if cancellation_acknowledged: - provider_state.retire_drain_intent( - deployment_id=intent.deployment_id, - job_id=intent.job_id, - ) - canceled_drain_job_ids.append(intent.job_id) - else: - ready = ( - not error - and node is not None - and node_drain_ready(node, intent.token) - ) - if ready: - drain_ready_stop_job_ids.append(intent.job_id) - drain_results.append( - { - "jobId": intent.job_id, - "role": intent.role, - "action": ("undrain" if intent.state == "canceling" else "drain"), - "nodeUrl": node_url, - "requestSucceeded": not error, - "heartbeatReady": ready, - "cancellationAcknowledged": cancellation_acknowledged, - "error": error, - } - ) - pending_drain_intents = provider_state.pending_drain_intents( - deployment_id=operation_deployment_id, - ) - active_drain_intents = [ - intent for intent in pending_drain_intents if intent.state == "active" - ] - active_drain_job_ids = {intent.job_id for intent in active_drain_intents} - canceling_drain_job_ids = { - intent.job_id for intent in pending_drain_intents if intent.state == "canceling" - } - pending_drain_job_ids = active_drain_job_ids | canceling_drain_job_ids - soft_drain_result, soft_drain_move_results = _apply_soft_drain( - decision, - sandbox_nodes, - control_state=control_state, - policy=effective_policy, - route_reservations=route_reservations or {}, - blocked_job_ids=( - pending_drain_job_ids - | set(stop_job_ids) - | quarantined_job_ids - ), - pending_wake_sandbox_ids=pending_wake_sandbox_ids or set(), - gateway_url=detach_gateway_url, - bearer_token=gateway_control_bearer_token, - execute=bool(execution_requested and execution_authorized), - assert_provider_fence=assert_provider_fence, - ) - active_bootstrap_job_ids = { - node.job_id - for node in (*sandbox_nodes, *builder_nodes) - if not node.job.is_final - } - bootstrap_records = prune_bootstrap_records( - control_state.load_bootstrap_records(), - active_bootstrap_job_ids, - ) - completed_bootstrap_results: list[dict[str, Any]] = [] - if bootstrap_coordinator is not None and execution_authorized: - bootstrap_records, completed_bootstrap_results = ( - bootstrap_coordinator.collect_completed( - bootstrap_records, - control_state, - active_job_ids=active_bootstrap_job_ids, - ) - ) - - def refresh_access_for_instance( - instance: ProviderInstance, - ) -> InstanceBootstrapAccess: - try: - refreshed = provider.retrieve_instance(instance.id, include_updates=True) - except ProviderError as exc: - current = provider.bootstrap_access(instance) - return replace( - current, - runnable=False, - reason=f"Provider access refresh failed: {exc}", - ) - return provider.bootstrap_access(refreshed) - - bootstrap_nodes = [*sandbox_nodes, *builder_nodes] - max_bootstraps = config.autoscaler_max_init_per_cycle - if bootstrap_coordinator is not None: - in_flight_job_ids = bootstrap_coordinator.in_flight_job_ids - bootstrap_nodes = [ - node for node in bootstrap_nodes if node.job_id not in in_flight_job_ids - ] - max_bootstraps = min( - max_bootstraps, - bootstrap_coordinator.available_slots, - ) - bootstrap_intents = build_vm_bootstrap_intents( - bootstrap_nodes, - bootstrap_records, - retry_seconds=config.autoscaler_init_retry_seconds, - max_per_cycle=max_bootstraps, - options_for_node=lambda node, role: vm_init_options_for_autoscaled_node( - node, - role, - args, - config, - ), - access_for_instance=provider.bootstrap_access, - refresh_access_for_instance=( - refresh_access_for_instance - if args.execute and not getattr(args, "jobs_file", None) - else None - ), - max_access_refreshes=max_bootstraps, - excluded_job_ids=set(stop_job_ids) | pending_drain_job_ids, - ) - refreshed_access = False - for intent in bootstrap_intents: - if intent.access_refreshed_at is not None: - refreshed_access = True - bootstrap_records = mark_bootstrap_access_refresh( - bootstrap_records, - intent, - ) - if refreshed_access: - control_state.save_bootstrap_records(bootstrap_records) - bootstrap_intents = [ - apply_bootstrap_requirements(intent) for intent in bootstrap_intents - ] - journaled_create_operations: list[ProviderOperation] = [] - journaled_stop_operations: list[ProviderOperation] = [] - if execution_authorized and provider_state is not None: - if args.execute: - labeled_sandbox_intents: list[InstanceCreateIntent] = [] - labeled_builder_intents: list[InstanceCreateIntent] = [] - for role, intents, destination in ( - ("sandbox", sandbox_create_intents, labeled_sandbox_intents), - ("builder", builder_create_intents, labeled_builder_intents), - ): - for intent in intents: - intent_key = provider_state.allocate_operation_intent_key( - deployment_id=operation_deployment_id, - kind="create", - base_key=f"{role}:{intent.seed}", - ) - operation_id = stable_provider_operation_id( - operation_deployment_id, - "create", - intent_key, - ) - labeled = with_provider_operation_label( - intent, - operation_id, - deployment_id=operation_deployment_id, - ) - operation = provider_state.prepare_operation( - intent_key=intent_key, - kind="create", - deployment_id=operation_deployment_id, - role=role, - request=provider.render_create_request([labeled]), - ) - journaled_create_operations.append(operation) - destination.append(labeled) - sandbox_create_intents = labeled_sandbox_intents - builder_create_intents = labeled_builder_intents - create_intents = [*sandbox_create_intents, *builder_create_intents] - if args.execute: - stop_ids_to_journal = tuple( - dict.fromkeys( - [ - *drain_ready_stop_job_ids, - *unreachable_stop_job_ids, - ] - ) - ) - sandbox_stop_set = set(sandbox_stop_job_ids) - drain_intents_by_job = { - intent.job_id: intent for intent in active_drain_intents - } - for job_id in stop_ids_to_journal: - unreachable_ready = job_id in unreachable_stop_job_id_set - drain_intent = drain_intents_by_job.get(job_id) - role = ( - drain_intent.role - if drain_intent is not None - and not unreachable_ready - else ("sandbox" if job_id in sandbox_stop_set else "builder") - ) - request: dict[str, Any] = { - "type": "bulk", - "items": [{"id": job_id}], - } - if unreachable_ready: - node = stop_nodes_by_job_id[job_id] - reference = unreachable_node_reference(node) - request.update( - { - "unreachableStaleReady": True, - "unreachableReference": ( - reference.isoformat() if reference is not None else "" - ), - "routeCount": len( - (route_reservations or {}).get(job_id, ()) - ), - "lastKnownActiveSandboxes": node.active_sandboxes, - "lastHeartbeatSafeToStop": True, - "lastHeartbeatPresent": node.heartbeat is not None, - "directProbeFailed": node.heartbeat is not None, - } - ) - elif drain_intent is None: - raise AutoscalerStateError( - f"drain-ready job has no durable intent: {job_id}" - ) - else: - request.update( - { - "drainToken": drain_intent.token, - "drainReady": True, - } - ) - intent_key = ( - f"{role}:{job_id}:unreachable-empty:{request['unreachableReference']}" - if unreachable_ready - else f"{role}:{job_id}:{drain_intent.token}" - ) - journaled_stop_operations.append( - provider_state.prepare_operation( - intent_key=intent_key, - kind="stop", - deployment_id=operation_deployment_id, - role=role, - request=request, - target_job_ids=(job_id,), - ) - ) - result: dict[str, Any] = { - "provider": { - "kind": provider.kind, - "scopeId": provider.scope_id, - }, - "controlStateFile": str(control_state_file), - "nodes": [node_to_dict(node) for node in nodes], - "decision": scale_decision_to_dict(decision), - "effectivePolicy": dashboard_scale_policy_to_dict(effective_policy), - "builderDecision": scale_decision_to_dict(builder_decision), - "pendingImageBuilds": builder_pending, - "activeImageBuilds": active_image_builds, - "preparedBuilderCount": builder_prepared, - "unexpectedly_suspended_job_ids": sorted( - node.job_id for node in (*sandbox_nodes, *builder_nodes) if node.job.is_lost - ), - "quarantined_job_ids": sorted(quarantined_job_ids), - "unreachableNodeProbes": observation.unreachable_probe_results, - "buildWarmSandboxResources": build_warm_resources.to_dict(), - "createIntents": [intent.to_dict() for intent in create_intents], - "requestedStopJobIds": list(requested_stop_job_ids), - "stopJobIds": list(stop_job_ids), - "blockedStopJobIds": list(blocked_stop_job_ids), - "blocked_storage_native_detach_stop_job_ids": list( - blocked_storage_native_detach_stop_job_ids - ), - "drainingJobIds": sorted(active_drain_job_ids), - "cancelingDrainJobIds": sorted(canceling_drain_job_ids), - "canceledDrainJobIds": sorted(canceled_drain_job_ids), - "drainReadyStopJobIds": list(drain_ready_stop_job_ids), - "unreachableReadyStopJobIds": list(unreachable_stop_job_ids), - "drainIntents": [ - _drain_intent_to_dict(intent) for intent in pending_drain_intents - ], - "drainResults": drain_results, - "pending_delete_results": pending_delete_results, - "stuck_start_results": stuck_start_results, - "storage_native_migration_results": storage_native_migration_results, - "storage_native_detach_results": storage_native_detach_results, - "softDrain": soft_drain_result, - "softDrainMoveResults": soft_drain_move_results, - "coldOffloadPlan": [candidate.to_dict() for candidate in cold_offload_plan], - "prunedFinalHeartbeats": list(final_heartbeat_job_ids), - "prunedOrphanedStaleHeartbeats": list(orphaned_stale_heartbeat_job_ids), - "removedStoppedHeartbeats": [], - "bootstrapIntents": [ - vm_bootstrap_intent_to_dict(intent) for intent in bootstrap_intents - ], - "bootstrapResults": list(completed_bootstrap_results), - "execute": bool(args.execute and execution_authorized), - "controllerLockHeld": provider_mutations_allowed, - "blockedCreateRoles": sorted(blocked_create_roles), - "createVisibilityGuards": create_visibility_guards, - "providerOperationResults": [], - "sandboxCapacityOperationSucceeded": False, - "builderCapacityOperationSucceeded": False, - "definitelyTerminatedJobIds": [], - "rawNodes": nodes, - "rawRetiredRoutes": observation.retired_routes, - "rawSandboxNodes": sandbox_nodes, - "rawBuilderNodes": builder_nodes, - "rawDecision": decision, - "rawBuilderDecision": builder_decision, - "rawCreateIntents": create_intents, - "rawBootstrapIntents": bootstrap_intents, - } - - if ( - execution_authorized - and provider_state is not None - and ( - journaled_create_operations - or journaled_stop_operations - or any( - operation.kind == "stop" - for operation in provider_state.list_operations(states={"prepared"}) - ) - ) - ): - planned_allowed_kinds: set[str] = set() - if args.execute: - planned_allowed_kinds.update(("create", "stop")) - planned_results = apply_prepared_provider_operations( - provider_state, - provider, - source="planned", - allowed_kinds=planned_allowed_kinds, - allowed_stop_operation_ids={ - operation.operation_id for operation in journaled_stop_operations - }, - telemetry=telemetry, - ) - provider_operation_results.extend(planned_results) - # An already-applied stop can be encountered again before the next job - # inventory observes it final; it remains definite and is never replayed. - for operation in journaled_stop_operations: - current = provider_state.get_operation(operation.operation_id) - if ( - current is not None - and current.state == "accepted" - and not any( - item.operation_id == current.operation_id - for item in provider_operation_results - ) - ): - provider_operation_results.append( - ProviderOperationOutcome.from_operation( - current, - source="journal", - ) - ) - result["createdJobIds"] = [ - job_id - for item in planned_results - if item.kind == "create" and item.state == "accepted" - for job_id in item.job_ids - ] - definitely_terminated = sorted( - { - job_id - for item in provider_operation_results - if item.kind == "stop" and item.state in {"accepted", "recovered"} - for job_id in item.job_ids - } - ) - result["definitelyTerminatedJobIds"] = definitely_terminated - if definitely_terminated: - result["removedStoppedHeartbeats"] = sorted( - control_state.remove_heartbeats(definitely_terminated) - ) - result["sandboxCapacityOperationSucceeded"] = _sandbox_capacity_operation_succeeded( - provider_operation_results, - decision.resource_deficit, - effective_policy.default_node_resources, - ) - desired_builders = min( - requested_builder_nodes( - builder_nodes, pending_builds=builder_pending, prepared_builders=builder_prepared, - ), - config.builder.max_nodes, - ) - result["builderCapacityOperationSucceeded"] = _builder_capacity_operation_succeeded( - provider_operation_results, - existing_builders=builder_decision.total_nodes, - desired_builders=desired_builders, - ) - - if args.execute and execution_authorized: - bootstrap_records, result["bootstrapResults"] = _execute_bootstrap_phase( - coordinator=bootstrap_coordinator, - intents=bootstrap_intents, - records=bootstrap_records, - completed_results=completed_bootstrap_results, - config=config, - control_state=control_state, - assert_provider_fence=assert_provider_fence, - metrics_store=metrics_store, - telemetry=telemetry, - ) - if execution_authorized and provider_state is not None: - result["compactedProviderOperations"] = provider_state.compact_terminal_history( - keep=1000 - ) - result["providerOperationResults"] = [ - item.to_dict() for item in provider_operation_results - ] - return result def _execute_bootstrap_phase( @@ -5593,323 +3475,6 @@ def load_instances_for_plan( return jobs -def sandbox_route_reservations( - routes: Iterable[SandboxRoute], -) -> dict[str, tuple[SandboxRoute, ...]]: - routes_by_job: dict[str, list[SandboxRoute]] = {} - for route in routes: - if route.worker_state == "detached" and is_portable_parked_route(route): - continue - job_id = route.job_id.strip() - if not job_id: - continue - routes_by_job.setdefault(job_id, []).append(route) - return { - job_id: tuple(sorted(items, key=lambda route: route.sandbox_id)) - for job_id, items in routes_by_job.items() - } - - -def partition_storage_native_detachable_stop_job_ids( - nodes: list[SandboxNode], - requested_job_ids: tuple[str, ...], - routes_by_job: dict[str, tuple[SandboxRoute, ...]], -) -> tuple[tuple[str, ...], tuple[str, ...]]: - """Allow stops whose remaining routes can release worker-local storage.""" - if not requested_job_ids: - return (), () - nodes_by_job_id = {node.job_id: node for node in nodes} - allowed: list[str] = [] - blocked: list[str] = [] - for job_id in dict.fromkeys(requested_job_ids): - if _storage_native_stop_set_has_detachable_storage( - nodes, - nodes_by_job_id, - (job_id,), - routes_by_job, - ): - allowed.append(job_id) - else: - blocked.append(job_id) - return tuple(allowed), tuple(blocked) - - -def _storage_native_stop_set_has_detachable_storage( - nodes: list[SandboxNode], - nodes_by_job_id: dict[str, SandboxNode], - stop_job_ids: tuple[str, ...], - routes_by_job: dict[str, tuple[SandboxRoute, ...]], -) -> bool: - del nodes - for job_id in stop_job_ids: - routes = tuple( - route - for route in routes_by_job.get(job_id, ()) - if route.worker_state != "detached" - ) - if not routes: - continue - node = nodes_by_job_id.get(job_id) - heartbeat = node.heartbeat if node is not None else None - if not ( - node is not None - and node.heartbeat_fresh - and heartbeat is not None - and heartbeat.inventory_complete - and STORAGE_NATIVE_CAPABILITY in heartbeat.capabilities - and STORAGE_NATIVE_DETACH_CAPABILITY in heartbeat.capabilities - and all(is_worker_detachable_parked_route(route) for route in routes) - ): - return False - for route in routes: - inventory = {item.sandbox_id: item for item in heartbeat.inventory} - if ( - route.worker_state == "attached" - and not _heartbeat_inventory_contains_route( - inventory, - route, - ) - ): - return False - return True - - -def apply_route_reservations_to_heartbeats( - heartbeats: dict[str, NodeHeartbeat], - routes_by_job: dict[str, tuple[SandboxRoute, ...]], -) -> dict[str, NodeHeartbeat]: - """Conservatively merge newer route reservations into stale heartbeats.""" - - reconciled: dict[str, NodeHeartbeat] = {} - for job_id, heartbeat in heartbeats.items(): - inventory = {item.sandbox_id: item for item in heartbeat.inventory} - missing_routes = [ - route - for route in routes_by_job.get(job_id, ()) - if route.worker_state != "detached" - if not _heartbeat_inventory_contains_route(inventory, route) - ] - missing_resources = ResourceQuantity() - for route in missing_routes: - missing_resources = missing_resources + ResourceQuantity( - disk_mb=route.resources.disk_mb - ) - used = heartbeat.used_resources + missing_resources - # A newly assigned create/wake may precede its worker reservation. - # Forecast that near-term RAM demand, but do not reserve every parked - # owner's limit. The worker and route views describe overlapping work; - # taking their maximum avoids charging the same transition twice. - transitioning = { - (item.sandbox_id, item.generation, item.spec_hash, item.operation_id): - item.resources.memory_mb - for item in heartbeat.inventory - if item.state in {"creating", "waking"} - } - for route in routes_by_job.get(job_id, ()): - if route.worker_state == "attached" and route.state in {"creating", "waking"}: - identity = (route.sandbox_id, route.generation, route.spec_hash, - route.create_operation_id) - transitioning[identity] = max( - transitioning.get(identity, 0), route.resources.memory_mb, - ) - reserved = replace(heartbeat.reserved_resources, memory_mb=max( - heartbeat.reserved_resources.memory_mb, sum(transitioning.values()), - )) - active_sandboxes = heartbeat.active_sandboxes + len(missing_routes) - reconciled[job_id] = replace( - heartbeat, - used_resources=used, - reserved_resources=reserved, - active_sandboxes=active_sandboxes, - ) - return reconciled - - -def apply_route_reservations_to_nodes( - nodes: list[SandboxNode], - routes_by_job: dict[str, tuple[SandboxRoute, ...]], -) -> list[SandboxNode]: - """Keep route ownership visible even when a job has no heartbeat record.""" - - reconciled: list[SandboxNode] = [] - for node in nodes: - heartbeat = node.heartbeat - owns_releasable_inventory = bool( - node.heartbeat_fresh - and heartbeat is not None - and heartbeat.inventory_complete - and STORAGE_NATIVE_CAPABILITY in heartbeat.capabilities - and STORAGE_NATIVE_DETACH_CAPABILITY in heartbeat.capabilities - and all( - is_worker_detachable_parked_route(route) - for route in routes_by_job.get(node.job_id, ()) - if route.worker_state != "detached" - ) - ) - reconciled.append( - replace( - node, - # Parked ownership is disk inventory, not active - # compute. A fresh complete inventory can therefore enter the - # storage-native detach workflow. Missing or stale observations - # retain the conservative route-count fence. - active_sandboxes=( - node.active_sandboxes - if owns_releasable_inventory - else max( - node.active_sandboxes, - len(routes_by_job.get(node.job_id, ())), - ) - ), - ) - ) - return reconciled - - -def _heartbeat_inventory_contains_route( - inventory: dict[str, Any], - route: SandboxRoute, -) -> bool: - item = inventory.get(route.sandbox_id) - if item is None: - return False - if route.generation <= 0 and item.generation <= 0: - return True - return bool( - route.generation == item.generation - and route.create_operation_id == item.operation_id - and route.spec_hash == item.spec_hash - ) - - -def build_activity_sandbox_warm_resources( - *, - active_image_builds: int, - pending_image_builds: int, - prepared_builder_count: int, - policy: ScalePolicy, -) -> ResourceQuantity: - del prepared_builder_count - if max(0, active_image_builds) <= 0 and max(0, pending_image_builds) <= 0: - return ResourceQuantity() - # A build proves that a sandbox node will probably be needed soon, but it - # says nothing about the eventual sandbox shape. Reserve a small runnable - # probe to keep one node warm. Reserving the entire schedulable node shape - # (especially all hard disk) demanded a pristine empty node and created a - # second VM as soon as the first node stored even one image or sandbox. - capacity = policy.default_node_resources - return ResourceQuantity( - vcpu=min(1.0, capacity.vcpu), - memory_mb=min(512, capacity.memory_mb), - disk_mb=min(1024, capacity.disk_mb), - ) - - -_USAGE_HISTORIES: dict[Path, UsageHistory] = {} - - -def _initial_disk_claim_mb(config: DeploymentConfig, heartbeats) -> int: - """What a worker charges a new sandbox's disk at create; 0 if not dynamic.""" - - for heartbeat in heartbeats: - metrics = heartbeat.runtime_metrics - if metrics is not None and metrics.storage_workspace_grant_mb > 0: - return metrics.storage_workspace_grant_mb + metrics.storage_memory_idle_claim_mb - # No worker yet (a cold start): the deployment says what they will charge. - sandbox = config.sandbox - if sandbox.direct_workspace_initial_grant_mb > 0: - return sandbox.direct_workspace_initial_grant_mb + IDLE_MEMORY_CLAIM_MB - return 0 - - -def _demand_forecast_from_usage( - config: DeploymentConfig, - demand: SandboxDemand, - heartbeats: list[NodeHeartbeat], - route_reservations: dict[str, tuple[SandboxRoute, ...]], -) -> SandboxDemand: - """Record running sandboxes' usage, then size cold demand from that history.""" - - path = config.usage_history_file() - history = _USAGE_HISTORIES.get(path) - if history is None: - history = _USAGE_HISTORIES[path] = UsageHistory.load(path) - now = time.time() - images = { - (route.sandbox_id, route.generation): str(route.spec.get("image") or "") - for routes in route_reservations.values() - for route in routes - } - record_inventory_usage(history, heartbeats, images, now) - history.prune(now) - forecast = demand_with_usage_forecast( - demand, - history, - initial_disk_claim_mb=_initial_disk_claim_mb(config, heartbeats), - now=now, - ) - try: - history.save_if_due(now) - except OSError as exc: - print(f"warning: could not save sandbox usage history: {exc}", file=sys.stderr) - return forecast - - -def demand_with_build_warm_resources( - demand: SandboxDemand, - build_warm_resources: ResourceQuantity, -) -> SandboxDemand: - desired = demand.desired_resources - supplement = ResourceQuantity( - vcpu=max(0.0, build_warm_resources.vcpu - desired.vcpu), - memory_mb=max(0, build_warm_resources.memory_mb - desired.memory_mb), - disk_mb=max(0, build_warm_resources.disk_mb - desired.disk_mb), - ) - if supplement == ResourceQuantity(): - return demand - return replace( - demand, - prepared_placement_requests=( - *demand.prepared_placement_requests, - SandboxPlacementRequest(resources=supplement), - ), - ) - - -def should_include_job( - job: ProviderInstance, - config: DeploymentConfig, - provider: ComputeProvider, - include_ids: set[str], -) -> bool: - if job.id in include_ids: - return True - if not is_managed_compute_instance(job, config.deployment_id): - return False - return provider.instance_is_eligible(job) - - -def is_managed_compute_instance(job: ProviderInstance, deployment_id: str) -> bool: - """Return whether a provider instance belongs to this managed deployment.""" - - return bool( - deployment_id - and job.labels.get(DEPLOYMENT_LABEL) == deployment_id - and ( - job.labels.get(NODE_LABEL) == "true" - or job.labels.get(BUILDER_LABEL) == "true" - ) - ) - - -def sandbox_pool_nodes(nodes: list[Any]) -> list[Any]: - return [node for node in nodes if node.job.labels.get(NODE_LABEL) == "true"] - - -def builder_pool_nodes(nodes: list[Any]) -> list[Any]: - return [node for node in nodes if node.job.labels.get(BUILDER_LABEL) == "true"] - - def vm_init_options_for_autoscaled_node( node: SandboxNode, role: str, @@ -6767,11 +4332,9 @@ def vm_init_options_for_job( direct_ram_memory_backing=( role == "sandbox" and config.sandbox.direct_ram_memory_backing ), - direct_reflink_memory_restore=( - role == "sandbox" and config.sandbox.direct_reflink_memory_restore - ), direct_pause_tier_zswap=role == "sandbox" and config.sandbox.direct_pause_tier_zswap, direct_node_rust_admission=role == "sandbox" and config.sandbox.direct_node_rust_admission, + direct_node_standalone_rust=role == "sandbox" and config.sandbox.direct_node_standalone_rust, direct_workspace_initial_grant_mb=( config.sandbox.direct_workspace_initial_grant_mb if role == "sandbox" else 0 ), @@ -6824,9 +4387,9 @@ def vm_init_options_to_dict(options: VmInitOptions) -> dict[str, Any]: "directNetworkAllowTcp": list(options.direct_network_allow_tcp), "networkRelays": dict(options.network_relays or {}), "directRamMemoryBacking": options.direct_ram_memory_backing, - "directReflinkMemoryRestore": options.direct_reflink_memory_restore, "directPauseTierZswap": options.direct_pause_tier_zswap, "directNodeRustAdmission": options.direct_node_rust_admission, + "directNodeStandaloneRust": options.direct_node_standalone_rust, "directWorkspaceInitialGrantMb": options.direct_workspace_initial_grant_mb, "storageNativeRegistryUrl": options.storage_native_registry_url, "storageNativeRepository": options.storage_native_repository, diff --git a/sandboxes/config.py b/sandboxes/config.py index 9c9b9748..c8fab650 100644 --- a/sandboxes/config.py +++ b/sandboxes/config.py @@ -26,6 +26,7 @@ DEFAULT_INSTALL_ROOT = "/work/ucloud-sandboxes" DEFAULT_DIRECT_RUNSC_COMMIT = "0" * 40 _REGISTRY_GUARD_DEFAULTS = { + "registry_disk_guard_enabled": True, "registry_disk_cleanup_percent": 70.0, "registry_disk_target_percent": 60.0, "registry_disk_refuse_percent": 90.0, @@ -267,6 +268,7 @@ def normalize_s3_endpoint( "direct_node_rust_pause", "direct_pause_tier", "direct_local_model_waits", "direct_split_memory_backing", ) +RETIRED_FALSE_FLAGS = ("direct_reflink_memory_restore",) @dataclass(frozen=True) @@ -300,14 +302,15 @@ class SandboxPoolConfig: direct_disk_headroom_mb: int = 16 * 1024 direct_max_concurrent_restores: int = 8 direct_idle_park_seconds: float = 0.0 - direct_ram_memory_backing: bool = False - direct_reflink_memory_restore: bool = False + direct_ram_memory_backing: bool = True # zswap ahead of the pause tier's swap: only for measured compressible heaps. direct_pause_tier_zswap: bool = False # Node admission moves to noded (docs/architecture.md); step 3c.0 # adds noded's internal socket and the agent's hello on it, and noded's # resident sampling of managed sandboxes for the agent (3b). direct_node_rust_admission: bool = False + # Standalone Rust ucloud-noded worker without Python ucloud-sandbox-node.service. + direct_node_standalone_rust: bool = False # Split workspaces start with an XFS filesystem this large and grow online # toward disk_mb (docs/architecture.md). 0 formats full-size workspaces. direct_workspace_initial_grant_mb: int = 512 @@ -331,9 +334,10 @@ def resources(self) -> ResourceQuantity: def from_dict(cls, raw: object) -> "SandboxPoolConfig": # Optional extension of schema 5; existing deployment files remain valid. if isinstance(raw, dict): - raw = {"network_relays": {}, "direct_ram_memory_backing": False, - "direct_reflink_memory_restore": False, "direct_pause_tier_zswap": False, + raw = {"network_relays": {}, "direct_ram_memory_backing": True, + "direct_pause_tier_zswap": False, "direct_node_rust_admission": False, + "direct_node_standalone_rust": False, "direct_workspace_initial_grant_mb": cls.direct_workspace_initial_grant_mb, "storage_native_max_concurrent_prepares": 0, **raw} @@ -341,6 +345,9 @@ def from_dict(cls, raw: object) -> "SandboxPoolConfig": if raw.pop(name, True) is not True: raise ValueError(f"sandbox.{name} is retired and must be true or absent: " "the agent and noded always run it") + for name in RETIRED_FALSE_FLAGS: + if raw.pop(name, False) is not False: + raise ValueError(f"sandbox.{name} is retired and must be false or absent") values = _exact_dataclass_values("sandbox", raw, cls()) values["direct_network_allow_tcp"] = _string_tuple( "sandbox.direct_network_allow_tcp", @@ -397,8 +404,9 @@ def from_dict(cls, raw: object) -> "SandboxPoolConfig": ) if result.swap_gb < 1: raise ValueError("the pause tier requires sandbox.swap_gb") - for name in ("direct_ram_memory_backing", "direct_reflink_memory_restore", - "direct_pause_tier_zswap", "direct_node_rust_admission"): + for name in ("direct_ram_memory_backing", + "direct_pause_tier_zswap", "direct_node_rust_admission", + "direct_node_standalone_rust"): if not isinstance(getattr(result, name), bool): raise ValueError(f"sandbox.{name} must be a boolean") grant = result.direct_workspace_initial_grant_mb @@ -616,6 +624,9 @@ class DeploymentConfig: # threshold the registry-pressure unit prunes, evicts least-recently-used # managed images down to the target, and garbage collects; at the refuse # threshold the gateway stops accepting image builds and imports. + # Set false on shared filesystems where whole-volume statvfs percentages do + # not reflect registry usage. + registry_disk_guard_enabled: bool = True registry_disk_cleanup_percent: float = 70.0 registry_disk_target_percent: float = 60.0 registry_disk_refuse_percent: float = 90.0 @@ -836,6 +847,10 @@ def from_dict(cls, raw: object) -> "DeploymentConfig": policy=policy, sandbox=sandbox, builder=builder, + registry_disk_guard_enabled=_require_bool( + "registry_disk_guard_enabled", + raw["registry_disk_guard_enabled"], + ), registry_disk_cleanup_percent=_require_float( "registry_disk_cleanup_percent", raw["registry_disk_cleanup_percent"], @@ -1060,6 +1075,7 @@ def to_dict(self) -> dict[str, Any]: "registry_port": self.registry_port, "registry_retention_days": self.registry_retention_days, "registry_keep_per_repository": self.registry_keep_per_repository, + **({"registry_disk_guard_enabled": False} if not self.registry_disk_guard_enabled else {}), "registry_disk_cleanup_percent": self.registry_disk_cleanup_percent, "registry_disk_target_percent": self.registry_disk_target_percent, "registry_disk_refuse_percent": self.registry_disk_refuse_percent, @@ -1229,6 +1245,12 @@ def _require_absolute_path(label: str, value: object) -> str: return path +def _require_bool(label: str, value: object) -> bool: + if not isinstance(value, bool): + raise ValueError(f"{label} must be a boolean") + return value + + def _require_int( label: str, value: object, diff --git a/sandboxes/control_plane.py b/sandboxes/control_plane.py index cc518a80..5bdc6050 100644 --- a/sandboxes/control_plane.py +++ b/sandboxes/control_plane.py @@ -1,20 +1,15 @@ from __future__ import annotations import asyncio -from collections import OrderedDict from concurrent.futures import Future, TimeoutError as FutureTimeoutError -from contextlib import contextmanager, nullcontext -from dataclasses import dataclass, replace -from datetime import datetime, timezone +from contextlib import contextmanager +from dataclasses import replace from http import HTTPStatus import hashlib import json -import math from pathlib import Path -import re import sqlite3 from threading import RLock, Thread -import time from typing import Any, Callable from urllib import error, request from urllib.parse import parse_qs, quote, urlparse @@ -33,107 +28,73 @@ import_image_id, ) from .placement_accounting import ( - _node_available_resources, - _node_has_storage_device_capacity, - _placement_route_index, - _route_targets_node, + route_targets_node, ) from .worker_receipts import ( - _record_generation, create_incarnation_unowned, - _route_with_sandbox_record, - _sandbox_create_request_body, - _sandbox_inventory_from_record, - _sandbox_record_matches_route, + route_with_sandbox_record, + sandbox_create_request_body, + sandbox_inventory_from_record, + sandbox_record_matches_route, ) from .admission import FairCapacity -from .capabilities import ( - STORAGE_NATIVE_CAPABILITY, - STORAGE_NATIVE_MIGRATION_CAPABILITY, - SPLIT_CHECKPOINT_CAPABILITY, - HOST_EROFS_CAPABILITY, - RUNTIME_COMPATIBILITY_CAPABILITY_PREFIX, - RUNTIME_CPU_CAPABILITY_PREFIX, -) -from .build_admission import BUILD_ADMISSION_CAPACITY_LABEL, build_admission_capacity from .build_context_store import ( BuildContextBlobStore, BuildContextHttpHandler, build_context_digest_from_path, ) from .deployment import service_health -from .storage_native_migration import ( - STORAGE_NATIVE_MIGRATION_SCHEMA, - SUPPORTED_STORAGE_NATIVE_MIGRATION_SCHEMAS, - SPLIT_MIGRATION_SCHEMA, - StorageNativeMigration, -) # Patch node transport via node_rpc; its pools, limits and opener are not imported here. from .gateway import node_rpc -from .gateway.auth import _is_sdk_api_request, _token_matches +from .gateway.auth import is_sdk_api_request, token_matches +from .gateway.build_service import BuildDispatch from .gateway.create import ( - SANDBOX_CREATE_PROXY_TIMEOUT_SECONDS, _is_duplicate_sandbox_response, _node_create_rejection_reason, + SANDBOX_CREATE_PROXY_TIMEOUT_SECONDS, is_duplicate_sandbox_response, node_create_rejection_reason, ) -from .gateway.fleet import _heartbeat_has_image, _node_metadata, _requested_image_cache_keys +from .gateway.fleet import heartbeat_has_image, node_metadata from .gateway.groups import GROUP_PATH, group_id_from_path, parse_group_request -from .gateway.heartbeats import PULL_TIMEOUT_SECONDS from .gateway.operator import CREATES_CANCEL_PATH, CREATES_PATH, drain_job_id_from_path -from .gateway.job_reads import ( - cache_parked_job, cached_job_logs_response, cached_job_status_response, - job_read_timeout_seconds, job_read_wait_ms, project_job_response, record_job_response, -) from .gateway.image_resolution import ( - TRANSIENT_IMAGE_RESOLUTION_ERROR_CODES, _image_record_available_to_sandboxes, - _image_reference_kind_from_headers, + TRANSIENT_IMAGE_RESOLUTION_ERROR_CODES, image_record_available_to_sandboxes, + image_reference_kind_from_headers, ) from .gateway.node_rpc import ( DEFAULT_MAX_PROXY_ERROR_BYTES, DEFAULT_PROXY_TIMEOUT_SECONDS, NODE_CONNECT_TIMEOUT_SECONDS, - PROXY_STREAM_CHUNK_BYTES, ProxiedResponse, ProxyResponseTooLargeError, _async_proxy_response, - _node_request_headers, _node_transport_error_response, _proxy_content_length, - _proxy_response_too_large, _read_bounded_proxy_body, _structured_proxy_error, -) -from .gateway.placement import ( - _has_resource_values, _node_can_fit, _node_can_fit_available, _sandbox_required_capabilities, + PROXY_STREAM_CHUNK_BYTES, ProxiedResponse, ProxyResponseTooLargeError, async_proxy_response, + node_request_headers, node_transport_error_response, proxy_content_length, + proxy_response_too_large, read_bounded_proxy_body, structured_proxy_error, ) from .gateway.registry_refs import ( - RegistryImageReferenceUnavailable, _managed_registry_build_tag, _managed_registry_worker_reference, - _portable_snapshot_for_route, _registry_operation_lease_owner, + RegistryImageReferenceUnavailable, managed_registry_build_tag, registry_operation_lease_owner, ) from .gateway.request_parsing import ( - _builder_prepare_id_from_path, _exec_session_id_from_path, _image_build_key_from_path, - _image_build_cancel_key_from_path, - _prepare_id_from_path, _prepared_resources_from_payload, _sandbox_detach_id_from_path, - _sandbox_id_from_path, _sandbox_migration_id_from_path, _strict_positive_integer, - _truthy_query_param, _validate_prepared_resources, + builder_prepare_id_from_path, exec_session_id_from_path, image_build_key_from_path, + image_build_cancel_key_from_path, + prepare_id_from_path, prepared_resources_from_payload, sandbox_detach_id_from_path, + sandbox_id_from_path, sandbox_migration_id_from_path, strict_positive_integer, + truthy_query_param, validate_prepared_resources, ) from .gateway.heartbeats import REBOOT_REAP_TIMEOUT_SECONDS from .gateway.services import GatewayServices, build_services -from .host_locks import HOST_LOCKS +from .gateway.state import GatewayRuntimeState from .http_server import ( DEFAULT_MAX_JSON_BODY_BYTES, HighBacklogThreadingHTTPServer, - RequestBodyStream, - TRANSFER_CHUNK_BYTES, traced_http_request, ) -from .http_contract import UPLOAD_ACTIONS, SandboxHttpRoute, match_sandbox_http_route -from .gateway.base_regeneration import BaseRegenerating, BaseReleased +from .http_contract import SandboxHttpRoute, match_sandbox_http_route from .images import ( DockerImageRuntime, - ImageBuildSpec, ImageManager, ImageRecord, ImageStore, - image_id_from_tag, uploaded_build_context_reference, ) from .managed_registry import ( RegistryUsageStore, - canonical_image_digest_ref, manifest_digest_from_image_ref, - normalize_manifest_digest, registry_repository_tag_from_image_ref, ) from .metrics import ( @@ -141,7 +102,6 @@ GatewayBusySampler, MetricsStore, build_metrics_snapshot, - record_sandbox_pending_deleted, record_sandbox_scheduled, ) from .metrics_prometheus import CONTENT_TYPE as PROMETHEUS_CONTENT_TYPE, render_snapshot @@ -151,29 +111,22 @@ ResourceQuantity, SandboxInventoryEntry, ScalePolicy, - is_soft_drained, sandbox_route_state_from_observation, utc_now, ) from .control_state import ControlStateStore from .wake_admission import WakeAdmission from .wake_placement import ( - WakePlaced, WakePlacement, WakePlacementPorts, WakePlacementStopped, WakeUnavailable, -) -from .lifecycle_commit import ( - InvalidLifecycleReceipt, LifecycleCommitter, LifecycleRouteChanged, - SnapshotReferences, route_with_snapshot_payload as _route_with_snapshot_payload, + WakePlacement, WakeUnavailable, ) from .exec_routing import (ExecRoutingService, ExecRouteUnavailable, heartbeat_proves_route_absent as _heartbeat_proves_route_absent) -from .exec_session_routes import EXEC_SESSION_PREFIX_HEADER, ExecSessionRoutes +from .exec_session_routes import ExecSessionRoutes from .registry import ( - heartbeat_from_dict, heartbeat_to_dict, ) from .routing import ( open_routing_store, - cold_offload_fence, ExecRoute, MAX_PREPARED_CAPACITY_COUNT, PendingSandboxDemand, @@ -181,19 +134,11 @@ RoutingStore, SandboxGroup, SandboxRoute, - SandboxRouteConflictError, is_portable_parked_route, - is_worker_detachable_parked_route, ) -from .consolidation import consolidation_rank from .sandbox import SandboxSpec, sandbox_spec_fingerprint, sandbox_specs_match -_BUILDER_DISPATCH_GUARD = RLock() -_BUILDER_DISPATCH_COUNTS: dict[str, int] = {} -_BUILDER_DISPATCH_INFLIGHT: dict[str, int] = {} -_IMAGE_PULL_LOCKS_GUARD = RLock() -_IMAGE_PULL_LOCKS: dict[tuple[str, str], RLock] = {} DEFAULT_MAX_CONCURRENT_SANDBOX_CREATES = 0 DEFAULT_MAX_GATEWAY_HTTP_REQUEST_THREADS = 2048 SANDBOX_CREATE_BUSY_RETRY_AFTER_SECONDS = 2 @@ -230,57 +175,6 @@ METRICS_RESPONSE_CACHE_TTL_SECONDS = 1.0 -def _migration_pending_demand_id(sandbox_id: str) -> str: - return f"__migration__:{sandbox_id}" - - -def _is_warm_wake_route(route: SandboxRoute | None, generation: int | None = None) -> bool: - """A resident owner needs no placement; its worker fences the wake itself.""" - return bool( - route is not None - and not route.delete_operation_id - and route.worker_state == "attached" - and (route.state or "").lower() in {"running", "waking"} - and (generation is None or route.generation == generation) - ) - - -def _sandbox_supports_managed_lifecycle(spec: dict[str, Any]) -> bool: - """Return whether request-bound relay park/wake is valid for this spec.""" - - try: - parsed = SandboxSpec.from_dict(spec) - except (TypeError, ValueError): - return False - return parsed.parkable and parsed.managed_process - - -def _sandbox_transport_epoch( - route: SandboxRoute, - migrations: list[Any], -) -> str: - """Hash every committed route handoff for this sandbox incarnation.""" - - committed = sorted( - migration.migration_id - for migration in migrations - if migration.sandbox_id == route.sandbox_id - and migration.generation == route.generation - and migration.create_operation_id == route.create_operation_id - and migration.phase in {"routed", "activated", "complete"} - ) - return hashlib.sha256( - "\0".join( - ( - route.sandbox_id, - str(route.generation), - route.create_operation_id, - *committed, - ) - ).encode("utf-8") - ).hexdigest() - - class SandboxShapeUnschedulableError(ValueError): def __init__( self, @@ -292,18 +186,6 @@ def __init__( self.maximum = maximum -class ImageBuildLookupUnavailableError(RuntimeError): - """A failed status observation cannot establish that a build is absent.""" - - def __init__(self, upstream_status: int = HTTPStatus.SERVICE_UNAVAILABLE) -> None: - super().__init__("image build status is temporarily unavailable") - self.status = ( - upstream_status - if upstream_status in {408, 429, 500, 502, 503, 504} - else HTTPStatus.BAD_GATEWAY - ) - - class CreateImagePullTasks: """Share cold pulls without retaining HTTP admission slots indefinitely. @@ -351,59 +233,6 @@ def work() -> None: del self.tasks[key] -class _LocalWakeBatcher: - """Coalesce waiting local admissions without a timer or a concurrency cap.""" - - def __init__(self): - self.lock = RLock() - self.pending = [] - self.running = False - - def reserve(self, handler, route): - future = Future() - with self.lock: - self.pending.append((handler, route, future)) - if not self.running: - self.running = True - Thread(target=self._drain, name="local-wake-admission", daemon=True).start() - observation = (handler.telemetry.span("gateway.wake.await_admission") - if handler.telemetry is not None else nullcontext()) - with observation: - return future.result() - - def _drain(self): - while True: - with self.lock: - if not self.pending: - self.running = False - return - leader = self.pending[0][0] - batch = [] - try: - # Callers that arrived while the previous batch's placement - # transaction ran share this inventory read and durable commit. - with self.lock: - batch, self.pending = self.pending, [] - results = leader.services.placement.atomic(lambda: leader._reserve_local_wake_batch(batch),worker_id=batch[0][1].job_id) - for (_, _, future), result in zip(batch, results, strict=True): - future.set_result(result) - except BaseException as exc: - if not batch: - with self.lock: - batch, self.pending = self.pending, [] - for _, _, future in batch: - future.set_exception(exc) - - -_LOCAL_WAKE_BATCHERS_LOCK = RLock() -_LOCAL_WAKE_BATCHERS: dict[tuple[Path,str], _LocalWakeBatcher] = {} - - -def _local_wake_batcher(path: Path, *, owner: str = '') -> _LocalWakeBatcher: - with _LOCAL_WAKE_BATCHERS_LOCK: - return _LOCAL_WAKE_BATCHERS.setdefault((path.resolve(),owner), _LocalWakeBatcher()) - - def _create_image_pull_pending_response() -> ProxiedResponse: return ProxiedResponse( HTTPStatus.SERVICE_UNAVAILABLE, @@ -433,15 +262,7 @@ class ControlPlaneHandler(BuildContextHttpHandler): image_manager: ImageManager build_context_store: BuildContextBlobStore metrics_store: MetricsStore - image_build_owners: OrderedDict[str, tuple[str, str, str]] = OrderedDict() - image_build_owners_lock = RLock() - image_build_metrics_seen: OrderedDict[tuple[str, str], None] = OrderedDict() - metrics_response_cache: bytes | None - metrics_response_cache_at: float - metrics_response_lock: RLock - fleet_response_lock: RLock - fleet_response_future: Future | None - fleet_status_futures: dict[tuple[str, ...], Future] + runtime_state: GatewayRuntimeState sandbox_create_limiter: FairCapacity | None upload_memory_limiter: FairCapacity admission_wait_seconds = 30.0 @@ -521,8 +342,8 @@ def do_GET(self) -> None: if parsed.path == "/v1/metrics": try: body = self._metrics_response_bytes( - full=_truthy_query_param(parsed, "full"), - refresh_registry=_truthy_query_param(parsed, "refresh_registry"), + full=truthy_query_param(parsed, "full"), + refresh_registry=truthy_query_param(parsed, "refresh_registry"), ) except sqlite3.DatabaseError as exc: self._write_routing_store_unavailable(exc) @@ -624,7 +445,7 @@ def _route_to_nodes(self, path: str) -> bool: self._write_registry_lease_unavailable(exc) return True - def _route_to_nodes_unchecked(self, path: str) -> bool: + def _route_sandbox_collection_request(self, path: str) -> bool: if path == "/v1/sandboxes" and self.command == "GET": parsed = urlparse(self.path) query = parse_qs(parsed.query, keep_blank_values=True) @@ -633,17 +454,20 @@ def _route_to_nodes_unchecked(self, path: str) -> bool: self._write_json({"error": "view must be full or status"}, status=400) elif view[0] == "status": from .fleet_reader import status_ids + try: ids = status_ids(query.get("id", [])) - if _truthy_query_param(parsed, "refresh"): + if truthy_query_param(parsed, "refresh"): raise ValueError("status view does not support refresh") except ValueError as exc: self._write_json({"error": str(exc)}, status=400) else: self._list_sandbox_statuses(ids) elif "id" in query: - self._write_json({"error": "id filters require view=status"}, status=400) - elif _truthy_query_param(parsed, "refresh"): + self._write_json( + {"error": "id filters require view=status"}, status=400 + ) + elif truthy_query_param(parsed, "refresh"): self._list_sandboxes_across_nodes() else: self._list_sandboxes_from_cache() @@ -662,6 +486,9 @@ def _route_to_nodes_unchecked(self, path: str) -> bool: status, payload, headers = self.services.groups.delete(self, group_id) self._write_json(payload, status=status, headers=headers) return True + return False + + def _route_operator_and_capacity_request(self, path: str) -> bool: if path == CREATES_PATH and self.command == "GET": self._write_json(self.services.queued_creates.list()) return True @@ -677,19 +504,26 @@ def _route_to_nodes_unchecked(self, path: str) -> bool: drain_job_id = drain_job_id_from_path(path) if drain_job_id is not None and self.command in {"POST", "DELETE"}: if self.command == "DELETE": - status, payload, headers = (*self.services.drains.undrain(drain_job_id), {}) + status, payload, headers = ( + *self.services.drains.undrain(drain_job_id), + {}, + ) else: try: raw = self._read_raw_body(max_bytes=DEFAULT_MAX_JSON_BODY_BYTES) options = json.loads(raw) if raw.strip() else {} - if not isinstance(options, dict) or set(options) - {"evict"} \ - or not isinstance(options.get("evict", False), bool): + if ( + not isinstance(options, dict) + or set(options) - {"evict"} + or not isinstance(options.get("evict", False), bool) + ): raise ValueError('the body is {"evict": } or empty') except ValueError as exc: self._write_json({"error": str(exc)}, status=HTTPStatus.BAD_REQUEST) return True status, payload, headers = self.services.drains.drain( - self, drain_job_id, evict=options.get("evict", False)) + self, drain_job_id, evict=options.get("evict", False) + ) self._write_json(payload, status=status, headers=headers) return True if path == "/v1/capacity/prepare" and self.command == "GET": @@ -698,7 +532,7 @@ def _route_to_nodes_unchecked(self, path: str) -> bool: if path == "/v1/capacity/prepare" and self.command == "POST": self._prepare_capacity() return True - prepare_id = _prepare_id_from_path(path) + prepare_id = prepare_id_from_path(path) if prepare_id is not None and self.command == "DELETE": self._delete_prepared_capacity(prepare_id) return True @@ -708,10 +542,13 @@ def _route_to_nodes_unchecked(self, path: str) -> bool: if path == "/v1/builders/prepare" and self.command == "POST": self._prepare_builder() return True - builder_prepare_id = _builder_prepare_id_from_path(path) + builder_prepare_id = builder_prepare_id_from_path(path) if builder_prepare_id is not None and self.command == "DELETE": self._delete_prepared_builder(builder_prepare_id) return True + return False + + def _route_image_request(self, path: str) -> bool: if path == "/v1/images" and self.command == "GET": self._write_json(self.services.images.inventory(self)) return True @@ -727,11 +564,11 @@ def _route_to_nodes_unchecked(self, path: str) -> bool: if path.startswith("/v1/image-index") and self.command == "GET": self._read_image_index(path) return True - cancel_build_key = _image_build_cancel_key_from_path(path) + cancel_build_key = image_build_cancel_key_from_path(path) if cancel_build_key is not None and self.command == "POST": self._cancel_image_build(cancel_build_key) return True - build_key = _image_build_key_from_path(path) + build_key = image_build_key_from_path(path) if build_key is not None and self.command == "GET": self._get_image_build(build_key) return True @@ -741,336 +578,66 @@ def _route_to_nodes_unchecked(self, path: str) -> bool: if path == "/v1/images/pull" and self.command == "POST": self._route_image_pull() return True - migration_sandbox_id = _sandbox_migration_id_from_path(path) + return False + + def _route_sandbox_resource_request(self, path: str) -> bool: + migration_sandbox_id = sandbox_migration_id_from_path(path) if migration_sandbox_id is not None and self.command == "POST": self._migrate_sandbox_on_node(migration_sandbox_id) return True if migration_sandbox_id is not None and self.command == "DELETE": self._cancel_sandbox_migration(migration_sandbox_id) return True - detach_sandbox_id = _sandbox_detach_id_from_path(path) + detach_sandbox_id = sandbox_detach_id_from_path(path) if detach_sandbox_id is not None and self.command == "POST": self._detach_sandbox_from_worker(detach_sandbox_id) return True - sandbox_id = _sandbox_id_from_path(path) + sandbox_id = sandbox_id_from_path(path) if sandbox_id is not None: self._route_sandbox_request(sandbox_id, path) return True - session_id = _exec_session_id_from_path(path) + session_id = exec_session_id_from_path(path) if session_id is not None: self._route_exec_request(session_id) return True return False + def _route_to_nodes_unchecked(self, path: str) -> bool: + return ( + self._route_sandbox_collection_request(path) + or self._route_operator_and_capacity_request(path) + or self._route_image_request(path) + or self._route_sandbox_resource_request(path) + ) + def _detach_sandbox_from_worker(self, sandbox_id: str) -> None: - try: - raw = self._read_json_body() - if not isinstance(raw, dict) or (raw and set(raw) != {"if_cold"}): - raise ValueError("sandbox detach payload must be empty or contain if_cold") - require_cold = bool(raw) - if require_cold and not isinstance(raw["if_cold"], dict): - raise ValueError("conditional detach requires an owner observation") - route = self.routing_store.get_sandbox_readonly(sandbox_id) - if route is None: - self._write_missing_sandbox_route(sandbox_id) - return - if require_cold: - expected = cold_offload_fence(route) - if raw["if_cold"] != expected or any( - type(raw["if_cold"][key]) is not type(value) for key, value in expected.items() - ): - raise SandboxRouteConflictError("cold offload observation no longer owns the snapshot") - if route.worker_state == "detached": - self._write_json({"ok": True, "sandbox": route.to_dict()}) - return - if route.worker_state == "attached" and not is_portable_parked_route(route): - if not is_worker_detachable_parked_route(route): - raise SandboxRouteConflictError( - "only a parked sandbox can detach from a worker" - ) - route, publication_error = self._publish_route_for_detach(route) - if route is None: - self._write_json( - { - "error": publication_error - or "parked snapshot publication is incomplete", - "retryable": True, - }, - status=HTTPStatus.SERVICE_UNAVAILABLE, - headers={ - "Retry-After": str( - SANDBOX_CREATE_IN_PROGRESS_RETRY_AFTER_SECONDS - ), - "X-UCloud-Sandbox-Retryable": "true", - }, - ) - return - if not is_portable_parked_route(route): - raise SandboxRouteConflictError( - "only a fully published parked sandbox can detach from a worker" - ) - _portable_snapshot_for_route(route) - self.services.registry_refs.ensure_route_reference(route, touch=True) - fenced = self.routing_store.begin_sandbox_detach(route, require_cold=require_cold) - if fenced is None: - raise SandboxRouteConflictError( - "sandbox route changed before worker detach began" - ) - detached, error_message = self._finish_sandbox_detach(fenced) - if detached is None: - self._write_json( - { - "error": error_message or "worker detach is incomplete", - "retryable": True, - }, - status=HTTPStatus.SERVICE_UNAVAILABLE, - headers={ - "Retry-After": str( - SANDBOX_CREATE_IN_PROGRESS_RETRY_AFTER_SECONDS - ), - "X-UCloud-Sandbox-Retryable": "true", - }, - ) - return - self._write_json({"ok": True, "sandbox": detached.to_dict()}) - except RegistryImageReferenceUnavailable as exc: - self._write_registry_lease_unavailable(exc) - except (SandboxRouteConflictError, ValueError) as exc: - self._write_json({"error": str(exc)}, status=HTTPStatus.CONFLICT) + self.services.migrations.detach_sandbox( + self, + sandbox_id, + publish_for_detach=self._publish_route_for_detach, + finish_detach=self._finish_sandbox_detach, + ) def _publish_route_for_detach( self, route: SandboxRoute, ) -> tuple[SandboxRoute | None, str]: - response = self._proxy_request( - route.node_url, - (f"/v1/sandboxes/{quote(route.sandbox_id, safe='')}/publish-parked"), - method="POST", - body=json.dumps( - { - "generation": route.generation, - "create_operation_id": route.create_operation_id, - "spec_hash": route.spec_hash, - }, - separators=(",", ":"), - ).encode("utf-8"), - extra_headers={"Content-Type": "application/json"}, - timeout_seconds=3600, - ) - if response.status >= 400: - error_message = str(response.json().get("error") or "").strip() - return ( - None, - error_message - or f"worker parked publication returned HTTP {response.status}", - ) - try: - payload = response.json() - candidate = _route_with_snapshot_payload(route, payload) - except (TypeError, ValueError, json.JSONDecodeError) as exc: - return None, f"worker returned invalid parked publication: {exc}" - self.services.registry_refs.ensure_snapshot_reference( - candidate, - repository=candidate.snapshot_repository, - tag=candidate.snapshot_tag, - digest=candidate.snapshot_manifest_digest, - ) - try: - stored = self.routing_store.set_sandbox_state_if_current( - route, - expected_states={"parked"}, - state="parked", - storage_schema=candidate.storage_schema, - snapshot_manifest_digest=candidate.snapshot_manifest_digest, - snapshot_repository=candidate.snapshot_repository, - snapshot_tag=candidate.snapshot_tag, - storage_snapshot=candidate.storage_snapshot, - ) - except BaseException: - # Commit acknowledgement can fail after the candidate became - # durable. Reconcile against a successful read-back and otherwise - # retain the candidate reference conservatively. - try: - current = self.routing_store.get_sandbox_readonly(route.sandbox_id) - except BaseException: - raise - self.services.registry_refs.release_snapshot_reference( - candidate, - keep_route=current, - ) - raise - if stored is None: - self.services.registry_refs.release_snapshot_reference( - candidate, - keep_route=self.routing_store.get_sandbox_readonly(route.sandbox_id), - ) - return None, "sandbox route changed while its parked snapshot published" - self.services.registry_refs.release_snapshot_reference(route, keep_route=stored) - return stored, "" + return self.services.migrations.publish_route_for_detach(self, route) def _finish_sandbox_detach( self, route: SandboxRoute, ) -> tuple[SandboxRoute | None, str]: - current = self.routing_store.get_sandbox_readonly(route.sandbox_id) - if current is None: - return None, "sandbox route disappeared during worker detach" - if not WakeAdmission.same_incarnation(current, route) or current.delete_operation_id: - return None, "sandbox route changed during worker detach" - if current.worker_state == "detached": - return current, "" - if current.worker_state != "detaching" or not is_portable_parked_route(current): - return None, "sandbox route changed during worker detach" - heartbeat = self._heartbeat_for_route( - job_id=current.job_id, - ) - if _heartbeat_proves_route_absent( - heartbeat, - sandbox_id=current.sandbox_id, - route_created_at=current.created_at, - route_updated_at=current.updated_at, - heartbeat_ttl_seconds=self.services.fleet.heartbeat_ttl_seconds, - ): - completed = self.routing_store.complete_sandbox_detach(current) - return completed, "" if completed is not None else "detach fence changed" - response = self._proxy_request( - current.node_url, - (f"/v1/sandboxes/{quote(current.sandbox_id, safe='')}/evict-published"), - method="POST", - body=json.dumps( - { - "generation": current.generation, - "snapshot_manifest_digest": current.snapshot_manifest_digest, - }, - separators=(",", ":"), - ).encode("utf-8"), - extra_headers={"Content-Type": "application/json"}, - ) - if response.status >= 400: - error_message = str(response.json().get("error") or "").strip() - return ( - None, - error_message - or f"worker published eviction returned HTTP {response.status}", - ) - completed = self.routing_store.complete_sandbox_detach(current) - if completed is None: - return None, "sandbox route changed before worker detach committed" - return completed, "" + return self.services.migrations.finish_sandbox_detach(self, route) def _migrate_sandbox_on_node(self, sandbox_id: str) -> None: - try: - raw = self._read_json_body() - if not isinstance(raw, dict): - raise ValueError("migration payload must be a JSON object") - migration_id = str( - raw.get("migration_id") or f"migration-{uuid4().hex}" - ).strip() - requested_destination = str(raw.get("destination_node_id") or "").strip() - # An autoscaler drain move is optional work: it never buys capacity. - soft_drain = raw.get("soft_drain") is True - migration = self.routing_store.get_sandbox_migration(migration_id) - if migration is not None and migration.sandbox_id != sandbox_id: - raise SandboxRouteConflictError( - "migration id belongs to another sandbox" - ) - if migration is None and soft_drain: - # The gateway learns a worker's publication from its next - # heartbeat; agents that wake every few seconds are rarely seen - # as published parks. Ask the owner now, outside the placement - # lock (the worker reuses an existing publication). - source = self.routing_store.get_sandbox_readonly(sandbox_id) - if ( - source is not None - and source.state.lower() == "parked" - and source.worker_state == "attached" - and not source.delete_operation_id - and not is_portable_parked_route(source) - ): - published, error = self._publish_route_for_detach(source) - if published is None: - self._write_wake_unavailable(WakeUnavailable( - error or "sandbox is no longer a parked sandbox", - error_code="migration_source_not_parked", retry_after=1, - )) - return - if migration is None: - def reserve_migration(): - existing = self.routing_store.get_sandbox_migration(migration_id) - if existing is not None: - if existing.sandbox_id != sandbox_id: - raise SandboxRouteConflictError('migration id belongs to another sandbox') - return existing - source = self.routing_store.get_sandbox_readonly(sandbox_id) - if source is None: - return WakeUnavailable('sandbox route not found',missing_sandbox_id=sandbox_id) - if soft_drain and not is_portable_parked_route(source): - return WakeUnavailable('sandbox is no longer a published park', - error_code='migration_source_not_parked',retry_after=1) - destination = self._select_migration_destination( - source,requested_node_id=requested_destination) - if destination is None and soft_drain: - return WakeUnavailable('no ready destination for soft-drain move', - error_code='migration_destination_unavailable',retry_after=1) - if destination is None: - _,demand = self.routing_store.upsert_pending_with_demand( - _migration_pending_demand_id(sandbox_id), - ResourceQuantity(disk_mb=source.resources.disk_mb), - failure_reason='migration_destination_unavailable') - return WakeUnavailable('no ready destination has disk capacity for parked sandbox migration', - error_code='migration_destination_unavailable',retry_after=1, - pending_resources=demand.pending_resources) - return self.routing_store.begin_sandbox_migration(source,migration_id=migration_id, - destination_node_id=destination.node_id,destination_job_id=destination.job_id, - destination_node_url=destination.node_url or '') - reserved = self.services.placement.atomic(reserve_migration) - if isinstance(reserved,WakeUnavailable): - self._write_wake_unavailable(reserved) - return - migration = reserved - assert migration is not None - self.routing_store.clear_pending(_migration_pending_demand_id(sandbox_id)) - migration_timings_ms: dict[str, float] = {} - migration = self._prepare_and_advance_sandbox_migration( - migration, - timings_ms=migration_timings_ms, - ) - if migration is None: - return - except WakePlacementStopped as stopped: - self._write_wake_unavailable(stopped.outcome) - return - except (SandboxRouteConflictError, ValueError) as exc: - self._write_json({"error": str(exc)}, status=HTTPStatus.CONFLICT) - return - except sqlite3.DatabaseError as exc: - self._write_routing_store_unavailable(exc) - return - if migration.phase != "complete": - aborted = False - if soft_drain and migration.phase in {"planned", "prepared", "staged"}: - # A drain move is optional: roll it back at once so the source - # is never left fenced (unable to wake) by a failed import. - migration, abort_error = self._abort_sandbox_migration(migration) - aborted = not abort_error - self._write_json( - { - "error": migration.error or "sandbox migration is incomplete", - "migration": migration.to_dict(), - "retryable": True, - "aborted": aborted, - "timings_ms": migration_timings_ms, - }, - status=HTTPStatus.SERVICE_UNAVAILABLE, - ) - return - route = self.routing_store.get_sandbox_readonly(sandbox_id) - self._write_json( - { - "migration": migration.to_dict(), - "sandbox": route.to_dict() if route is not None else None, - "timings_ms": migration_timings_ms, - } + self.services.migrations.migrate_sandbox( + self, + sandbox_id, + publish_for_detach=self._publish_route_for_detach, + select_destination=self._select_migration_destination, + prepare_and_advance=self._prepare_and_advance_sandbox_migration, + abort_migration=self._abort_sandbox_migration, ) def _select_migration_destination( @@ -1080,600 +647,65 @@ def _select_migration_destination( requested_node_id: str, require_active_resources: bool = False, ) -> NodeHeartbeat | None: - routes = self.services.placement.routes() - active_migrations = self.routing_store.sandbox_migrations(active_only=True) - ready_heartbeats = self.services.fleet.ready_sandbox_heartbeats() - source_heartbeat = next( - ( - heartbeat - for heartbeat in ready_heartbeats - if heartbeat.node_id == source.node_id - or ( - source.node_url - and heartbeat.node_url - and heartbeat.node_url.rstrip("/") == source.node_url.rstrip("/") - ) - ), - None, - ) - if source_heartbeat is None and source.worker_state == "attached": - # Closed admission/draining excludes a destination, not a source. - # Busy workers must still be able to export their parked state. - owner = self._heartbeat_for_route(job_id=source.job_id) - if ( - owner is not None and owner.node_id == source.node_id - and owner.is_fresh(utc_now(), self.services.fleet.heartbeat_ttl_seconds) - ): - source_heartbeat = owner - source_storage_native = bool( - source_heartbeat is not None - and STORAGE_NATIVE_CAPABILITY in source_heartbeat.capabilities - and STORAGE_NATIVE_MIGRATION_CAPABILITY in source_heartbeat.capabilities - ) - source_is_attached = source.worker_state == "attached" - if source_is_attached: - if not source_storage_native: - return None - elif source.worker_state != "detached" or not is_portable_parked_route(source): - return None - try: - runtime_capability = _migration_runtime_capability(source, source_heartbeat) - except ValueError: - return None - source_cpu = _migration_cpu_capability(source, source_heartbeat) - required_destination_capabilities = _sandbox_required_capabilities(source.spec) - if runtime_capability is not None: - required_destination_capabilities = (*required_destination_capabilities, runtime_capability) - if (source.storage_schema == SPLIT_MIGRATION_SCHEMA or (source_is_attached - and source_heartbeat is not None - and SPLIT_CHECKPOINT_CAPABILITY in source_heartbeat.capabilities)): - required_destination_capabilities = (*required_destination_capabilities, SPLIT_CHECKPOINT_CAPABILITY) - reservations: dict[str, int] = {} - routes_by_id = { - route.sandbox_id: route for route in routes if isinstance(route, SandboxRoute) - } - for migration in active_migrations: - if migration.phase in {"routed", "activated"}: - continue - route = routes_by_id.get(migration.sandbox_id) - if route is None: - continue - reservations[migration.destination_node_id] = ( - reservations.get(migration.destination_node_id, 0) - + route.resources.disk_mb - ) - route_index = _placement_route_index(routes) - available_by_node: dict[str, ResourceQuantity] = {} - candidates: list[NodeHeartbeat] = [] - for heartbeat in ready_heartbeats: - if ( - # A former owner, or any worker still registering this id, - # would refuse the import as a registration conflict. - heartbeat.node_id == source.node_id - or any(item.sandbox_id == source.sandbox_id for item in heartbeat.inventory) - or STORAGE_NATIVE_CAPABILITY not in heartbeat.capabilities - or STORAGE_NATIVE_MIGRATION_CAPABILITY not in heartbeat.capabilities - # A legacy attached source cannot prove compatibility with - # the new EROFS adapter. Published parks instead carry the - # exact import fingerprint, including their rootfs ABI. - or (runtime_capability is None and HOST_EROFS_CAPABILITY in heartbeat.capabilities) - or any( - capability not in heartbeat.capabilities - for capability in required_destination_capabilities - ) - or (requested_node_id and heartbeat.node_id != requested_node_id) - or not _cpu_compatible(heartbeat, source_cpu) - ): - continue - node_routes = route_index.routes_for(heartbeat) - available = _node_available_resources(heartbeat, node_routes) - requested = ( - source.resources - if require_active_resources - else ResourceQuantity(disk_mb=source.resources.disk_mb) - ) - if requested.disk_mb <= 0 or not _node_can_fit_available( - heartbeat, - requested, - available, - ): - continue - available_by_node[heartbeat.node_id] = available - candidates.append(heartbeat) - undrained = [item for item in candidates if not is_soft_drained(item)] - # Moves (plain migrations) never target a soft-drained worker. A wake - # falls back to it rather than failing. - if undrained or not require_active_resources: - candidates = undrained - if not candidates: - return None - image = str(source.spec.get("image") or "") - return min( - candidates, - key=lambda heartbeat: ( - 0 if _heartbeat_has_image(heartbeat, image) else 1, - reservations.get(heartbeat.node_id, 0), - -available_by_node[heartbeat.node_id].disk_mb, - heartbeat.node_id, - ), + return self.services.migrations.select_destination( + self, + source, + requested_node_id=requested_node_id, + require_active_resources=require_active_resources, ) - def _prepare_migration_destination_image(self, source: SandboxRoute, destination: NodeHeartbeat) -> None: - image = str(source.spec.get("image") or "").strip() - response = self._ensure_image_on_node(destination, image, source.spec.get("environment_root")) - if response is not None and response.status >= 400: - error = response.json() - raise WakePlacementStopped(WakeUnavailable( - "migration destination could not prepare the sandbox image", - details={"image": image, "node_id": destination.node_id, - "node_error": error.get("error") or error})) + def _prepare_migration_destination_image( + self, source: SandboxRoute, destination: NodeHeartbeat + ) -> None: + self.services.migrations.prepare_destination_image(self, source, destination) def _prepare_and_advance_sandbox_migration( - self, migration, *, timings_ms: dict[str, float] | None = None, - wake_on_complete: bool = False, - ): - """Existing migration authority, with domain failures rather than HTTP writes.""" - with _migration_operation_lock(migration.migration_id): - current = self.routing_store.get_sandbox_migration(migration.migration_id) - if current is None: - raise WakePlacementStopped(WakeUnavailable("sandbox migration disappeared")) - if current.phase == "complete": - return self.routing_store.complete_sandbox_migration( - current.migration_id, wake_destination=wake_on_complete) or current - if current.phase == "planned": - source = self.routing_store.get_sandbox_readonly(current.sandbox_id) - destination = next((heartbeat for heartbeat in self.services.fleet.ready_sandbox_heartbeats() - if heartbeat.node_id == current.destination_node_id - and heartbeat.job_id == current.destination_job_id - and (heartbeat.node_url or "").rstrip("/") == current.destination_node_url.rstrip("/")), None) - if source is None or destination is None: - raise WakePlacementStopped(WakeUnavailable( - "migration source or destination is unavailable", migration=current)) - self._prepare_migration_destination_image(source, destination) - return self._advance_sandbox_migration( - current, timings_ms=timings_ms, wake_on_complete=wake_on_complete) - - def _advance_sandbox_migration( self, migration, *, timings_ms: dict[str, float] | None = None, wake_on_complete: bool = False, ): - advance_started = time.monotonic() - measured = timings_ms if timings_ms is not None else {} - if migration.phase == "planned": - source_route = self.routing_store.get_sandbox_readonly(migration.sandbox_id) - route_snapshot: StorageNativeMigration | None = None - if source_route is not None and is_portable_parked_route(source_route): - try: - route_snapshot = _portable_snapshot_for_route(source_route) - except ValueError: - route_snapshot = None - phase_started = time.monotonic() - if source_route is None: - return self._record_migration_error( - migration, - error_message="migration source route disappeared", - ) - if source_route.worker_state == "detached": - if route_snapshot is None: - return self._record_migration_error( - migration, - error_message="detached route has no valid published snapshot", - ) - migration = ( - self.routing_store.advance_sandbox_migration( - migration.migration_id, - expected_phases={"planned"}, - phase="prepared", - storage_schema=route_snapshot.schema, - snapshot_sha256=route_snapshot.sha256, - storage_snapshot=route_snapshot.to_dict(), - source_fenced=False, - error="", - ) - or migration - ) - elif source_route.worker_state == "attached": - response = self._proxy_request( - migration.source_node_url, - ( - f"/v1/sandboxes/{quote(migration.sandbox_id, safe='')}" - "/migration/prepare" - ), - method="POST", - body=json.dumps( - { - "migration_id": migration.migration_id, - "format": STORAGE_NATIVE_MIGRATION_SCHEMA, - } - ).encode("utf-8"), - extra_headers={"Content-Type": "application/json"}, - timeout_seconds=3600, - ) - if response.status >= 400: - return self._record_migration_error(migration, response) - prepared = response.json().get("migration") - if not isinstance(prepared, dict): - return self._record_migration_error( - migration, - error_message="source returned invalid migration metadata", - ) - storage_schema = str(prepared.get("storage_schema") or "") - try: - if storage_schema not in SUPPORTED_STORAGE_NATIVE_MIGRATION_SCHEMAS: - raise ValueError("unsupported migration storage schema") - storage_snapshot = StorageNativeMigration.from_dict( - prepared.get("storage_snapshot") - ) - snapshot_sha256 = str(prepared.get("snapshot_sha256") or "") - if storage_snapshot.schema != storage_schema: - raise ValueError("source schema does not match snapshot descriptor") - if storage_snapshot.sha256 != snapshot_sha256: - raise ValueError( - "source snapshot digest does not match metadata" - ) - except ValueError as exc: - return self._record_migration_error( - migration, - error_message=f"source returned invalid snapshot: {exc}", - ) - migration = ( - self.routing_store.advance_sandbox_migration( - migration.migration_id, - expected_phases={"planned"}, - phase="prepared", - storage_schema=storage_schema, - snapshot_sha256=snapshot_sha256, - storage_snapshot=storage_snapshot.to_dict(), - source_fenced=True, - error="", - ) - or migration - ) - else: - return self._record_migration_error( - migration, - error_message="migration source is still detaching", - ) - measured["prepare_export"] = _precise_elapsed_ms(phase_started) - if migration.phase == "prepared": - phase_started = time.monotonic() - if migration.storage_schema not in SUPPORTED_STORAGE_NATIVE_MIGRATION_SCHEMAS: - return self._record_migration_error( - migration, - error_message="migration is missing storage-native metadata", - ) - import_payload = { - "migration_id": migration.migration_id, - "sandbox_id": migration.sandbox_id, - "snapshot_sha256": migration.snapshot_sha256, - "storage_schema": migration.storage_schema, - "storage_snapshot": migration.storage_snapshot, - } - response = self._proxy_request( - migration.destination_node_url, - "/v1/migrations/import", - method="POST", - body=json.dumps(import_payload).encode("utf-8"), - extra_headers={"Content-Type": "application/json"}, - timeout_seconds=3600, - ) - measured["transfer_and_stage"] = _precise_elapsed_ms(phase_started) - if response.status >= 400: - return self._record_migration_error(migration, response) - destination_snapshot: dict[str, Any] | None = None - try: - response_body = response.json() - if ( - str(response_body.get("storage_schema") or "") - != migration.storage_schema - ): - raise ValueError("destination changed the storage schema") - parsed_destination = StorageNativeMigration.from_dict( - response_body.get("storage_snapshot") - ) - if ( - parsed_destination.manifest - != StorageNativeMigration.from_dict( - migration.storage_snapshot - ).manifest - ): - raise ValueError("destination changed portable migration metadata") - destination_snapshot = parsed_destination.to_dict() - except ValueError as exc: - return self._record_migration_error( - migration, - error_message=f"destination returned invalid snapshot: {exc}", - ) - migration = ( - self.routing_store.advance_sandbox_migration( - migration.migration_id, - expected_phases={"prepared"}, - phase="staged", - storage_snapshot=destination_snapshot, - error="", - ) - or migration - ) - if migration.phase == "staged": - phase_started = time.monotonic() - source_route = self.routing_store.get_sandbox_readonly(migration.sandbox_id) - destination_route: SandboxRoute | None = None - try: - destination_snapshot = StorageNativeMigration.from_dict( - migration.storage_snapshot - ) - destination_publication = destination_snapshot.reference - if source_route is None: - raise ValueError("source route disappeared") - destination_route = replace( - source_route, - node_id=migration.destination_node_id, - job_id=migration.destination_job_id, - node_url=migration.destination_node_url, - storage_schema=migration.storage_schema, - snapshot_manifest_digest=(destination_publication.manifest_digest), - snapshot_repository=destination_publication.repository, - snapshot_tag=destination_publication.tag, - storage_snapshot=destination_snapshot.to_dict(), - ) - # Both the image and portable snapshot must be protected under - # the destination owner before routing can point at it. - self.services.registry_refs.ensure_route_reference( - destination_route, - touch=True, - ) - except ( - RegistryImageReferenceUnavailable, - ValueError, - ) as exc: - if destination_route is not None and source_route is not None: - self.services.registry_refs.release_route_reference( - destination_route, - keep_route=source_route, - ) - return self._record_migration_error( - migration, - error_message=( - f"destination registry references could not be persisted: {exc}" - ), - ) - try: - routed = self.routing_store.route_sandbox_migration( - migration.migration_id - ) - except BaseException: - # A SQLite commit error is ambiguous: the destination route - # may already be durable. Release only after a read-back proves - # which owner still needs protection; a failed read leaks - # conservatively instead of risking live image/snapshot data. - try: - current_route = self.routing_store.get_sandbox_readonly( - migration.sandbox_id - ) - except BaseException: - raise - self.services.registry_refs.release_route_reference( - destination_route, - keep_route=current_route, - ) - raise - measured["route_commit"] = _precise_elapsed_ms(phase_started) - if routed is None: - self.services.registry_refs.release_route_reference( - destination_route, - keep_route=source_route, - ) - return self._record_migration_error( - migration, - error_message="sandbox route changed before migration commit", - ) - migration, destination_route = routed - self.services.registry_refs.release_route_reference( - source_route, - keep_route=destination_route, - ) - if migration.phase == "routed": - phase_started = time.monotonic() - response = self._proxy_request( - migration.destination_node_url, - ( - f"/v1/sandboxes/{quote(migration.sandbox_id, safe='')}" - "/migration/activate" - ), - method="POST", - body=json.dumps( - { - "snapshot_sha256": migration.snapshot_sha256, - "migration_id": migration.migration_id, - } - ).encode("utf-8"), - extra_headers={"Content-Type": "application/json"}, - timeout_seconds=3600, - ) - measured["activate_destination"] = _precise_elapsed_ms(phase_started) - if response.status >= 400: - return self._record_migration_error(migration, response) - migration = ( - self.routing_store.advance_sandbox_migration( - migration.migration_id, - expected_phases={"routed"}, - phase="activated", - error="", - ) - or migration - ) - if migration.phase == "activated": - phase_started = time.monotonic() - if not migration.source_fenced: - measured["finalize_source"] = 0.0 - migration = ( - self.routing_store.complete_sandbox_migration( - migration.migration_id, - wake_destination=wake_on_complete, - ) - or migration - ) - measured["protocol_total"] = _precise_elapsed_ms(advance_started) - return migration - response = self._proxy_request( - migration.source_node_url, - ( - f"/v1/sandboxes/{quote(migration.sandbox_id, safe='')}" - "/migration/finalize" - ), - method="POST", - body=json.dumps( - { - "snapshot_sha256": migration.snapshot_sha256, - "migration_id": migration.migration_id, - } - ).encode("utf-8"), - extra_headers={"Content-Type": "application/json"}, - timeout_seconds=3600, - ) - measured["finalize_source"] = _precise_elapsed_ms(phase_started) - if response.status >= 400: - return self._record_migration_error(migration, response) - migration = ( - self.routing_store.complete_sandbox_migration( - migration.migration_id, - wake_destination=wake_on_complete, - ) - or migration - ) - measured["protocol_total"] = _precise_elapsed_ms(advance_started) - return migration + return self.services.migrations.prepare_and_advance( + self, + migration, + timings_ms=timings_ms, + wake_on_complete=wake_on_complete, + prepare_destination_image=self._prepare_migration_destination_image, + advance=self._advance_sandbox_migration, + ) - def _record_migration_error( + def _advance_sandbox_migration( self, migration, - response: ProxiedResponse | None = None, *, - error_message: str = "", + timings_ms: dict[str, float] | None = None, + wake_on_complete: bool = False, ): - detail = error_message - if response is not None: - payload = response.json() - detail = str(payload.get("error") or "").strip() - if not detail: - detail = f"node migration request returned HTTP {response.status}" - return ( - self.routing_store.advance_sandbox_migration( - migration.migration_id, - expected_phases={migration.phase}, - phase=migration.phase, - error=detail, - ) - or migration + return self.services.migrations.advance( + self, + migration, + timings_ms=timings_ms, + wake_on_complete=wake_on_complete, ) def _cancel_sandbox_migration(self, sandbox_id: str) -> None: - query = parse_qs(urlparse(self.path).query, keep_blank_values=True) - migration_id = (query.get("migration_id") or [""])[0].strip() - migration = self.routing_store.get_sandbox_migration(migration_id) - if migration is None or migration.sandbox_id != sandbox_id: - self._write_json( - {"error": "sandbox migration not found"}, - status=HTTPStatus.NOT_FOUND, - ) - return - if migration.phase in {"routed", "activated"}: - self._write_json( - { - "error": ( - "migration routing is already committed; retry the " - "migration to finish it" - ) - }, - status=HTTPStatus.CONFLICT, - ) - return - if migration.phase == "complete": - self._write_json({"migration": migration.to_dict()}) - return - migration, error_message = self._abort_sandbox_migration(migration) - if error_message: - self._write_json( - { - "error": error_message, - "migration": migration.to_dict(), - "retryable": True, - }, - status=HTTPStatus.SERVICE_UNAVAILABLE, - ) - return - self._write_json({"migration": migration.to_dict()}) + self.services.migrations.cancel_migration( + self, + sandbox_id, + abort_migration=self._abort_sandbox_migration, + ) def _abort_sandbox_migration(self, migration): - """Roll back an uncommitted migration using its durable journal.""" + return self.services.migrations.abort_migration(self, migration) - payload = json.dumps( - { - "snapshot_sha256": migration.snapshot_sha256, - "migration_id": migration.migration_id, - } - ).encode("utf-8") - headers = {"Content-Type": "application/json"} - if migration.phase in {"prepared", "staged"}: - destination = self._proxy_request( - migration.destination_node_url, - ( - f"/v1/sandboxes/{quote(migration.sandbox_id, safe='')}" - "/migration/abort-import" - ), - method="POST", - body=payload, - extra_headers=headers, - timeout_seconds=3600, - ) - if destination.status >= 400: - migration = self._record_migration_error(migration, destination) - return migration, migration.error - source = self._proxy_request( - migration.source_node_url, - (f"/v1/sandboxes/{quote(migration.sandbox_id, safe='')}/migration/abort"), - method="POST", - body=payload, - extra_headers=headers, - timeout_seconds=3600, - ) - if source.status >= 400: - migration = self._record_migration_error(migration, source) - return migration, migration.error - migration = ( - self.routing_store.advance_sandbox_migration( - migration.migration_id, - expected_phases={migration.phase}, - phase="complete", - error="cancelled before route commit", - ) - or migration + def _resolve_sandbox_migrations_for_delete(self, sandbox_id: str) -> str: + return self.services.migrations.resolve_for_delete( + self, + sandbox_id, + advance=self._advance_sandbox_migration, + abort_migration=self._abort_sandbox_migration, ) - return migration, "" - - def _resolve_sandbox_migrations_for_delete(self, sandbox_id: str) -> str: - """Finish or roll back migration journals before replaying deletion.""" - - active = [ - migration - for migration in self.routing_store.sandbox_migrations(active_only=True) - if migration.sandbox_id == sandbox_id - ] - for migration in active: - if migration.phase in {"routed", "activated"}: - migration = self._advance_sandbox_migration(migration) - if migration.phase != "complete": - return ( - migration.error or "committed sandbox migration is incomplete" - ) - continue - migration, error_message = self._abort_sandbox_migration(migration) - if error_message: - return error_message - return "" def _write_routing_store_unavailable(self, _exc: sqlite3.DatabaseError) -> None: self._write_json( @@ -1721,17 +753,8 @@ def _metrics_response_bytes( refresh_registry: bool, ) -> bytes: cacheable = not full and not refresh_registry - handler_cls = type(self) - with handler_cls.metrics_response_lock: - now = time.monotonic() - if ( - cacheable - and handler_cls.metrics_response_cache is not None - and now - handler_cls.metrics_response_cache_at - <= METRICS_RESPONSE_CACHE_TTL_SECONDS - ): - return handler_cls.metrics_response_cache + def compute() -> tuple[bytes, bytes]: load_metrics = getattr(self.routing_store, "load_metrics", None) routing_state = ( self.routing_store.load() if load_metrics is None else load_metrics() @@ -1789,17 +812,23 @@ def _metrics_response_bytes( separators=(",", ":"), sort_keys=True, ).encode("utf-8") - if cacheable: - cached_registry = dict(snapshot.get("registry") or {}) - cached_registry["cached"] = True - snapshot["registry"] = cached_registry - handler_cls.metrics_response_cache = json.dumps( - snapshot, - separators=(",", ":"), - sort_keys=True, - ).encode("utf-8") - handler_cls.metrics_response_cache_at = time.monotonic() - return body + if not cacheable: + return body, body + cached_registry = dict(snapshot.get("registry") or {}) + cached_registry["cached"] = True + snapshot["registry"] = cached_registry + cached_body = json.dumps( + snapshot, + separators=(",", ":"), + sort_keys=True, + ).encode("utf-8") + return body, cached_body + + return self.runtime_state.metrics_cache.get_or_compute( + ttl_seconds=METRICS_RESPONSE_CACHE_TTL_SECONDS, + cacheable=cacheable, + compute=compute, + ) def _list_prepared_capacity(self) -> None: self._write_json( @@ -1836,20 +865,20 @@ def _prepare_capacity(self) -> None: prepare_id = str(raw.get("id") or f"prep-{uuid4().hex[:16]}").strip() if not prepare_id or "/" in prepare_id: raise ValueError("prepare id must be non-empty and cannot contain '/'.") - count = _strict_positive_integer(raw.get("count", 1), "count") + count = strict_positive_integer(raw.get("count", 1), "count") if count > MAX_PREPARED_CAPACITY_COUNT: raise ValueError(f"count cannot exceed {MAX_PREPARED_CAPACITY_COUNT}.") - ttl_seconds = _strict_positive_integer( + ttl_seconds = strict_positive_integer( raw.get("ttl_seconds", 900), "ttl_seconds", ) - resources = _prepared_resources_from_payload(raw) + resources = prepared_resources_from_payload(raw) image = str(raw.get("image") or "").strip() if count <= 0: raise ValueError("count must be positive.") if ttl_seconds <= 0: raise ValueError("ttl_seconds must be positive.") - _validate_prepared_resources(resources) + validate_prepared_resources(resources) except (TypeError, ValueError) as exc: self._write_json({"error": str(exc)}, status=HTTPStatus.BAD_REQUEST) return @@ -1912,8 +941,8 @@ def _prepare_builder(self) -> None: ).strip() if not prepare_id or "/" in prepare_id: raise ValueError("prepare id must be non-empty and cannot contain '/'.") - count = _strict_positive_integer(raw.get("count", 1), "count") - ttl_seconds = _strict_positive_integer( + count = strict_positive_integer(raw.get("count", 1), "count") + ttl_seconds = strict_positive_integer( raw.get("ttl_seconds", 900), "ttl_seconds", ) @@ -1952,23 +981,8 @@ def _list_sandboxes_from_cache(self) -> None: # Concurrent public polls need the same observation. Share the scan # and JSON encoding, not merely a lock that makes every waiter rescan. # There is no TTL: a request after completion takes a new snapshot. - handler_cls = type(self) - with handler_cls.fleet_response_lock: - future = handler_cls.fleet_response_future - owner = future is None - if owner: - future = Future() - handler_cls.fleet_response_future = future - if owner: - try: - future.set_result(self._sandbox_list_response()) - except BaseException as exc: - future.set_exception(exc) - raise - finally: - with handler_cls.fleet_response_lock: - handler_cls.fleet_response_future = None - self._write_bytes(future.result(), "application/json") + payload = self.runtime_state.fleet_list.run(None, self._sandbox_list_response) + self._write_bytes(payload, "application/json") def _sandbox_list_response(self) -> bytes: reader = getattr(type(self), "fleet_snapshot_reader", None) @@ -1981,27 +995,21 @@ def _list_sandbox_statuses(self, sandbox_ids: tuple[str, ...]) -> None: # Coalesce identical in-flight projections only; full reads and other # filters must never receive this response. Completion retains no TTL. handler_cls = type(self) - with handler_cls.fleet_response_lock: - future = handler_cls.fleet_status_futures.get(sandbox_ids) - owner = future is None - if owner: - future = Future() - handler_cls.fleet_status_futures[sandbox_ids] = future - if owner: - try: - reader = getattr(handler_cls, "fleet_snapshot_reader", None) - payload = (reader.read_status(sandbox_ids) if reader is not None else - _sandbox_list_bytes(self.services.fleet.store, self.routing_store, - self.services.fleet.heartbeat_ttl_seconds, status_only=True, - sandbox_ids=sandbox_ids)) - future.set_result(payload) - except BaseException as exc: - future.set_exception(exc) - raise - finally: - with handler_cls.fleet_response_lock: - del handler_cls.fleet_status_futures[sandbox_ids] - self._write_bytes(future.result(), "application/json") + + def compute() -> bytes: + reader = getattr(handler_cls, "fleet_snapshot_reader", None) + if reader is not None: + return reader.read_status(sandbox_ids) + return _sandbox_list_bytes( + self.services.fleet.store, + self.routing_store, + self.services.fleet.heartbeat_ttl_seconds, + status_only=True, + sandbox_ids=sandbox_ids, + ) + + payload = self.runtime_state.fleet_status.run(sandbox_ids, compute) + self._write_bytes(payload, "application/json") def _list_sandboxes_across_nodes(self) -> None: sandboxes: list[dict[str, Any]] = [] @@ -2037,7 +1045,7 @@ def _list_sandboxes_across_nodes(self) -> None: if isinstance(sandbox_id, str) and sandbox_id: reported_ids.add(sandbox_id) try: - observation = _sandbox_inventory_from_record(record) + observation = sandbox_inventory_from_record(record) except (TypeError, ValueError): # Protect a known route from absence reconciliation, but do # not publish malformed node state as a gateway record. @@ -2066,7 +1074,7 @@ def _list_sandboxes_across_nodes(self) -> None: record = records_by_id.get(sandbox_id) if stored_route is None or record is None: continue - if _route_targets_node(stored_route, heartbeat): + if route_targets_node(stored_route, heartbeat): try: # The record was sampled after this heartbeat revision, # not after whichever route happens to be current when @@ -2078,7 +1086,7 @@ def _list_sandboxes_across_nodes(self) -> None: node_epoch=heartbeat.node_epoch, activity_epoch=heartbeat.activity_epoch, ) - confirmed = _route_with_sandbox_record( + confirmed = route_with_sandbox_record( observed_route, record, ) @@ -2129,7 +1137,9 @@ def _list_sandboxes_across_nodes(self) -> None: keep_route=stored_route, ) if stored_route is not None: - self._cache_parked_job(stored_route, record) + self.services.sandbox_proxy.cache_parked_job( + self, stored_route, record + ) if stored_route is None: continue sandboxes.append(_enrich_sandbox_record(record, heartbeat)) @@ -2152,275 +1162,39 @@ def _list_image_builds_across_nodes(self) -> None: self._write_json({"builds": self._image_build_records_across_nodes()}) def _get_image_build(self, build_key: str) -> None: - if self.sandbox_builds is not None and build_key.startswith("sandbox:"): - build = self.sandbox_builds.record(build_key) - if build is None: - self._write_json({"error": "image build not found"}, status=HTTPStatus.NOT_FOUND) - else: - self._write_json({"build": build}) - return - try: - builds = self._image_build_records_for_key(build_key) - except ImageBuildLookupUnavailableError as exc: - self._write_json( - {"error": str(exc), "error_code": "image_build_status_unavailable", - "retryable": True}, - status=exc.status, - headers={"Retry-After": "2", "X-UCloud-Sandbox-Retryable": "true"}, - ) - return - matches = [ - build - for build in builds - if build.get("build_id") == build_key or build.get("image_id") == build_key - ] - if not matches: - self._write_json( - {"error": "image build not found"}, - status=HTTPStatus.NOT_FOUND, - ) - return - selected = sorted( - matches, - key=lambda item: ( - str(item.get("created_at") or ""), - str(item.get("build_id") or ""), - ), - )[-1] - selected_image_id = str(selected.get("image_id") or "") - if selected_image_id and _image_build_response_terminal({"build": selected}): - self.routing_store.clear_pending_image_build(selected_image_id) - self._record_successful_build_image(selected) - self._write_json({"build": selected}) + self.services.builds.get_build( + self, + build_key, + records_for_key=self._image_build_records_for_key, + record_successful_image=self._record_successful_build_image, + ) def _cancel_image_build(self, build_key: str) -> None: - """POST /v1/images/builds/:cancel (docs/api.md): a spool build - through the spool, a builder's build on the builder that owns it.""" - def unavailable(error: str) -> None: - self._write_json( - {"error": error, "error_code": "image_build_cancel_unavailable", "retryable": True}, - status=HTTPStatus.SERVICE_UNAVAILABLE, - headers={"Retry-After": "2", "X-UCloud-Sandbox-Retryable": "true"}, - ) - - statuses = {"cancelled": HTTPStatus.OK, "stopping": HTTPStatus.ACCEPTED, - "finished": HTTPStatus.CONFLICT} - if build_key.startswith("sandbox:"): - outcome, build = (self.sandbox_builds.cancel(build_key) if self.sandbox_builds is not None - else (None, None)) - if outcome is None: - self._write_json({"error": "image build not found"}, status=HTTPStatus.NOT_FOUND) - return - payload = {"build": build} - if outcome == "finished": - payload["error"] = "image build already finished" - self._write_json(payload, status=statuses[outcome]) - return - try: - builds = self._image_build_records_for_key(build_key) - except ImageBuildLookupUnavailableError as exc: - unavailable(str(exc)) - return - build = next((item for item in builds if item.get("build_id") == build_key), None) - if build is None: - self._write_json({"error": "image build not found"}, status=HTTPStatus.NOT_FOUND) - return - owner = next((heartbeat for heartbeat in self.services.fleet.ready_heartbeats() - if "image-build" in heartbeat.capabilities - and heartbeat.node_id == build.get("location")), None) - if owner is None: - unavailable("the builder that owns this build is not ready") - return - try: - response = self._proxy_request( - owner.node_url or "", - "/v1/images/builds/" + quote(build_key, safe="") + ":cancel", - method="POST", - timeout_seconds=IMAGE_BUILD_CANCEL_PROXY_TIMEOUT_SECONDS, - ) - payload = response.json() - except (OSError, ValueError) as exc: - unavailable(f"the builder did not answer the cancellation: {exc}") - return - record = payload.get("build") if isinstance(payload, dict) else None - if response.status == HTTPStatus.NOT_FOUND: - self._write_json({"error": "image build not found"}, status=HTTPStatus.NOT_FOUND) - return - if response.status not in statuses.values() or not isinstance(record, dict): - unavailable(str((payload or {}).get("error") or f"the builder answered {response.status}")) - return - record = {**record, "location": owner.node_id, "node": _node_metadata(owner)} - if _image_build_response_terminal({"build": record}): - self.routing_store.clear_pending_image_build(str(record.get("image_id") or "")) - self._record_successful_build_image(record) - answer: dict[str, Any] = {"build": record} - if response.status == HTTPStatus.CONFLICT: - answer["error"] = "image build already finished" - self._write_json(answer, status=response.status) + self.services.builds.cancel_build( + self, + build_key, + records_for_key=self._image_build_records_for_key, + record_successful_image=self._record_successful_build_image, + ) def _image_build_records_for_key(self, build_key: str) -> list[dict[str, Any]]: - """Read one build, using an incarnation-checked owner hint for exact IDs. - - Image names deliberately search all builders: a later build can own the - same name elsewhere. Hints are disposable and never cache build state. - Only explicit 404 responses establish absence. A failed known-owner - probe is retried without fanning out to unrelated overloaded builders. - """ - builders = [ - h for h in self.services.fleet.ready_heartbeats() if "image-build" in h.capabilities - ] - with self.image_build_owners_lock: - owner = self.image_build_owners.get(build_key) - - def identity(heartbeat: NodeHeartbeat) -> tuple[str, str, str]: - return (heartbeat.job_id, heartbeat.node_id, heartbeat.node_epoch) - - def fetch(heartbeat: NodeHeartbeat) -> dict[str, Any] | None: - response = self._proxy_request( - heartbeat.node_url or "", - "/v1/images/builds/" + quote(build_key, safe=""), - method="GET", - timeout_seconds=NODE_RECONCILE_PROXY_TIMEOUT_SECONDS, - ) - if response.status == HTTPStatus.NOT_FOUND: - return None - if not 200 <= response.status < 300: - raise ImageBuildLookupUnavailableError(response.status) - raw = response.json().get("build") - if not isinstance(raw, dict) or build_key not in ( - raw.get("build_id"), raw.get("image_id") - ): - raise ImageBuildLookupUnavailableError(HTTPStatus.BAD_GATEWAY) - build = dict(raw) - build.update(location=heartbeat.node_id, node=_node_metadata(heartbeat)) - if raw.get("build_id") == build_key: - with self.image_build_owners_lock: - self.image_build_owners[build_key] = identity(heartbeat) - self.image_build_owners.move_to_end(build_key) - while len(self.image_build_owners) > 4096: - self.image_build_owners.popitem(last=False) - return build - - if owner is not None and not any( - identity(heartbeat)[:2] == owner[:2] for heartbeat in builders - ): - # A missing/stale heartbeat does not prove the owner's build gone. - # A new incarnation of the same node may still recover its record. - raise ImageBuildLookupUnavailableError() - - tried = None - for heartbeat in builders: - if identity(heartbeat) == owner: - tried = identity(heartbeat) - build = fetch(heartbeat) - if build is not None and build.get("build_id") == build_key: - return [build] - break - builds: list[dict[str, Any]] = [] - failure = None - for heartbeat in builders: - if identity(heartbeat) == tried: - continue - try: - build = fetch(heartbeat) - except ImageBuildLookupUnavailableError as exc: - failure = failure or exc - continue - if build is not None: - builds.append(build) - if build.get("build_id") == build_key: - return [build] - if failure is not None: - # Partial image-name results cannot identify the latest build; - # partial exact-ID discovery cannot establish a negative result. - raise failure - return builds + return self.services.builds.records_for_key(self, build_key) def _image_build_records_across_nodes(self) -> list[dict[str, Any]]: - builds: list[dict[str, Any]] = [] - for heartbeat in self.services.fleet.ready_heartbeats(): - if "image-build" not in heartbeat.capabilities: - continue - response = self._proxy_request( - heartbeat.node_url or "", - "/v1/images/builds", - method="GET", - timeout_seconds=NODE_RECONCILE_PROXY_TIMEOUT_SECONDS, - ) - if response.status >= 400: - continue - raw_builds = response.json().get("builds") - if not isinstance(raw_builds, list): - continue - for record in raw_builds: - if isinstance(record, dict): - enriched = dict(record) - enriched["location"] = heartbeat.node_id - enriched["node"] = _node_metadata(heartbeat) - self._record_successful_build_image(enriched) - builds.append(enriched) - return builds + return self.services.builds.records_across_nodes( + self, + record_successful_image=self._record_successful_build_image, + ) def _record_terminal_build_metrics(self, build: dict[str, Any]) -> None: - """Retain observed terminal timings after an ephemeral builder exits.""" - if build.get("status") not in {"succeeded", "failed"} or not build.get("build_id"): - return - history = getattr(self, "build_history", None) - if history is not None: - try: - history.record(build) - except (OSError, sqlite3.Error, ValueError): - # Retry on a subsequent observation even if metrics already - # accepted this result. Never fail a successful client poll. - pass - store = getattr(self, "metrics_store", None) - if store is None: - return - key = (str(build["build_id"]), str(build.get("updated_at", ""))) - with self.image_build_owners_lock: - if key in self.image_build_metrics_seen: - return - timings = build.get("timings") or {} - if not isinstance(timings, dict): - return - summary = {name: build.get(name, "") for name in ( - "build_id", "image_id", "status", "created_at", "started_at", "finished_at", "location")} - summary["timings"] = { - "total_ms": timings.get("total_ms"), - **{name: timings[name] for name in ("preparation_ms", "queue_wait_ms", "end_to_end_ms") - if type(timings.get(name)) in {int, float}}, - **{name: {k: v for k, v in (timings.get(name) or {}).items() - if type(v) in {int, float}} - for name in ("phases", "environment") if isinstance(timings.get(name), dict)}, - } - try: - store.append("image_build_completed", summary) - except (OSError, sqlite3.Error, ValueError): - # Observability must not turn a successful build into a retry. - return - self.image_build_metrics_seen[key] = None - while len(self.image_build_metrics_seen) > 4096: - self.image_build_metrics_seen.popitem(last=False) + self.services.builds.record_terminal_metrics(self, build) def _record_successful_build_image(self, build: dict[str, Any]) -> None: - self._record_terminal_build_metrics(build) - if build.get("status") != "succeeded": - return - raw_image = build.get("image") - if not isinstance(raw_image, dict) or not _image_record_available_to_sandboxes( - raw_image - ): - return - raw_image = self.services.images.record_with_digest(raw_image) - build["image"] = raw_image - try: - changed = self.image_manager.store.upsert_if_changed( - ImageRecord.from_dict(raw_image) - ) - except ValueError: - return - if changed: - self.services.images.invalidate_inventory() + self.services.builds.record_successful_image( + self, + build, + record_terminal_metrics=self._record_terminal_build_metrics, + ) @contextmanager def _startup_request_admission(self, *, creating: bool = False, weight: int = 1): @@ -2845,11 +1619,11 @@ def _send_existing_sandbox_response( record = self._sandbox_record_on_node(route.node_url, spec.id) if ( record is None - or not _sandbox_record_matches_route(record, route, spec) + or not sandbox_record_matches_route(record, route, spec) or not _sandbox_record_is_ready(record) ): return False - route = _route_with_sandbox_record(route, record) + route = route_with_sandbox_record(route, record) route=self._confirm_sandbox_observation(route) if route is None: return True @@ -2895,18 +1669,18 @@ def _retry_sandbox_create_on_assigned_node( route.node_url, "/v1/sandboxes", method="POST", - body=_sandbox_create_request_body(spec, route), + body=sandbox_create_request_body(spec, route), timeout_seconds=SANDBOX_CREATE_PROXY_TIMEOUT_SECONDS, ) payload = response.json() record = payload.get("sandbox") if 200 <= response.status < 300: - if not isinstance(record, dict) or not _sandbox_record_matches_route( + if not isinstance(record, dict) or not sandbox_record_matches_route( record, route, spec ): self._write_invalid_create_confirmation() return - stored = self._confirm_sandbox_observation(_route_with_sandbox_record(route, record)) + stored = self._confirm_sandbox_observation(route_with_sandbox_record(route, record)) if stored is None: return self.services.registry_refs.ensure_route_reference(stored, touch=True) @@ -2916,7 +1690,7 @@ def _retry_sandbox_create_on_assigned_node( status=HTTPStatus.OK, ) return - if _is_duplicate_sandbox_response(response, spec.id) and ( + if is_duplicate_sandbox_response(response, spec.id) and ( self._send_existing_sandbox_response( route, spec, @@ -2924,7 +1698,7 @@ def _retry_sandbox_create_on_assigned_node( ) ): return - rejection_reason = _node_create_rejection_reason(response) + rejection_reason = node_create_rejection_reason(response) if rejection_reason is not None: removed = self.routing_store.delete_sandbox_if_current( spec.id, @@ -3201,7 +1975,7 @@ def adopt(build: dict[str, Any]) -> None: image = build.get("image") if build.get("sandbox_build") and self.sandbox_builds is not None: image = self.sandbox_builds.adopt(build) - if isinstance(image, dict) and _image_record_available_to_sandboxes(image): + if isinstance(image, dict) and image_record_available_to_sandboxes(image): image = self.services.images.record_with_digest(image) try: self.image_manager.store.upsert(ImageRecord.from_dict(image)) @@ -3298,1263 +2072,214 @@ def _route_image_build(self) -> None: return self._write_build_dispatch(self._dispatch_image_build(raw)) - def _write_build_dispatch(self, result: "_BuildDispatch") -> None: + def _write_build_dispatch(self, result: BuildDispatch) -> None: if result.response is not None: self._send_proxied_response(result.response) else: self._write_json(result.payload, status=result.status, headers=result.headers) - def _dispatch_image_build(self, raw: dict[str, Any]) -> "_BuildDispatch": - """Submit one build through the gateway's path (prepared foundations, - regenerated bases, builder selection): /v1/images/build and image recipes.""" - reserved_job_id = "" - try: - pressure = self.services.images.disk_refusal() - if pressure is not None: - return _BuildDispatch( - HTTPStatus.SERVICE_UNAVAILABLE, - registry_disk_pressure_payload(pressure, action="image builds"), - {"Retry-After": str(REGISTRY_DISK_RETRY_AFTER_SECONDS), "X-UCloud-Sandbox-Retryable": "true"}, - ) - raw = dict(raw) - raw.pop("base_contexts", None) # Only the gateway names regenerated bases. - context_reference = uploaded_build_context_reference( - raw, self.build_context_store - ) - if context_reference is not None: - # Keep it recent while this build is copied to a builder. - self.build_context_store.touch(context_reference[0]) - spec = ImageBuildSpec.from_dict(raw) - push = bool(raw.get("push", False)) - refs = self.services.registry_refs - if not spec.tag.strip(): - if not str(raw.get("id") or "").strip(): - raise ValueError("gateway-managed image builds require an image id") - spec = replace( - spec, - tag=_managed_registry_build_tag(spec.id, refs.registry_worker_url or ""), - ) - push = True - elif refs.registry_url and refs.registry_worker_url: - spec = replace( - spec, - tag=_managed_registry_worker_reference( - spec.tag, - refs.registry_url, - refs.registry_worker_url, - ), - ) - spec.validate() - raw = dict(raw) - raw["tag"] = spec.tag - raw["push"] = push - prepared_resolution = None - prepared_catalog = getattr(self, "prepared_image_catalog", None) - if prepared_catalog is not None: - from .prepared_images import resolve_build - raw, prepared_resolution = resolve_build( - prepared_catalog, self.build_context_store, raw, spec, - protect=lambda reference: self.services.registry_refs.ensure_image_lease( - reference, _registry_operation_lease_owner("prepared-build", { - "id": spec.id, "context": raw["context_archive_digest"], - }), touch=True, - ), - ) - context_reference = uploaded_build_context_reference(raw, self.build_context_store) - regeneration = getattr(self, "base_regeneration", None) - if regeneration is not None and raw.get("context_archive_digest"): - from .gateway.base_regeneration import context_dockerfile - - def texts(): # Lazy: no context is read until an image has a receipt. - yield context_dockerfile(self.build_context_store, raw["context_archive_digest"], spec.dockerfile) - yield from spec.build_args.values() - contexts, copies = regeneration.contexts(texts()) - for copy in copies: # Kept, and touched for the age rule, while the build runs. - self.services.registry_refs.ensure_image_lease(copy, _registry_operation_lease_owner( - "regenerated-base", {"id": spec.id, "context": raw["context_archive_digest"]}), touch=True) - if contexts: - raw["base_contexts"] = contexts - body = json.dumps(raw, separators=(",", ":")).encode("utf-8") - with _builder_image_dispatch_lock(spec.id): - with self.telemetry.span( - "gateway.image_build", - attributes={ - "image.id": spec.id, - "container.image.name": spec.tag, - "image.push": push, - }, - ) as root: - with self.telemetry.span( - "gateway.image_build_select_builder", - ) as span: - heartbeat = self._select_builder_node(image_id=spec.id, reserve=True) - reserved_job_id = heartbeat.job_id if heartbeat else "" - span.set_attribute( - "selected_node_id", heartbeat.node_id if heartbeat else "" - ) - span.set_attribute( - "selected_job_id", heartbeat.job_id if heartbeat else "" - ) - if heartbeat is None: - self.routing_store.upsert_pending_image_build(spec.id, spec.tag) - pending_builds = self.routing_store.pending_image_build_count() - root.status = "error" - root.set_attribute("outcome", "queued_no_builder") - root.set_attribute("pending_image_builds", pending_builds) - return _BuildDispatch( - HTTPStatus.SERVICE_UNAVAILABLE, - { - "error": "no ready builder execution slot is available", - "error_code": "builder_not_ready", - "retryable": True, - "pending_image_builds": pending_builds, - }, - {"Retry-After": "2", "X-UCloud-Sandbox-Retryable": "true"}, - ) - with self.telemetry.span( - "gateway.image_build_enqueue", - attributes={"node.id": heartbeat.node_id}, - ): - self.routing_store.upsert_pending_image_build(spec.id, spec.tag) - with self.telemetry.span( - "gateway.image_build_context_sync", - attributes={"node.id": heartbeat.node_id}, - ) as span: - context_response = self._ensure_node_build_context( - heartbeat.node_url or "", context_reference - ) - span.set_attribute("status_code", int(context_response.status)) - context_payload = context_response.json() - if "deduplicated" in context_payload: - span.set_attribute( - "deduplicated", - bool(context_payload["deduplicated"]), - ) - if not 200 <= context_response.status < 300: - root.status = "error" - root.set_attribute("outcome", "context_proxy_failed") - root.set_attribute("status_code", int(context_response.status)) - return _BuildDispatch(context_response.status, response=context_response) - self.services.registry_refs.protect_build_target( - spec, - push=push, - ) - with self.telemetry.span( - "gateway.image_build_proxy_builder", - attributes={"node.id": heartbeat.node_id}, - ) as span: - response = self._proxy_request( - heartbeat.node_url or "", - "/v1/images/build", - method="POST", - body=body, - timeout_seconds=IMAGE_BUILD_PROXY_TIMEOUT_SECONDS, - ) - span.set_attribute("status_code", int(response.status)) - response_payload = response.json() - if prepared_resolution and 200 <= response.status < 300: - response_payload["prepared"] = prepared_resolution - response.body = json.dumps(response_payload).encode("utf-8") - raw_image = response_payload.get("image") - if isinstance( - raw_image, dict - ) and _image_record_available_to_sandboxes(raw_image): - raw_image = self.services.images.record_with_digest(raw_image) - response_payload["image"] = raw_image - raw_build = response_payload.get("build") - if isinstance(raw_build, dict): - raw_build["image"] = raw_image - response.body = json.dumps(response_payload).encode("utf-8") - node_timings = response_payload.get("timings") - if isinstance(node_timings, dict): - span.add_event("node.timings", node_timings) - if isinstance(response_payload.get("build"), dict): - self._record_terminal_build_metrics(response_payload["build"]) - accepted_build_response = 200 <= response.status < 300 - terminal_build_response = _image_build_response_terminal( - response_payload - ) or ( - not 200 <= response.status < 300 - and response.status < 500 - and response.status not in {408, 425, 429} - ) - if accepted_build_response or terminal_build_response: - self.routing_store.clear_pending_image_build(spec.id) - if 200 <= response.status < 300: - raw_image = response_payload.get("image") - if isinstance( - raw_image, dict - ) and _image_record_available_to_sandboxes(raw_image): - try: - self.image_manager.store.upsert( - ImageRecord.from_dict(raw_image) - ) - except ValueError: - pass - self.services.images.invalidate_inventory() - if 200 <= response.status < 300: - root.set_attribute("outcome", "builder_completed") - root.set_attribute("node_id", heartbeat.node_id) - else: - root.status = "error" - root.set_attribute("outcome", "builder_failed") - root.set_attribute("status_code", int(response.status)) - return _BuildDispatch(response.status, response=response) - except BaseReleased as exc: - return _BuildDispatch(HTTPStatus.CONFLICT, {"error": str(exc), "error_code": "base_released"}) - except (json.JSONDecodeError, ValueError) as exc: - return _BuildDispatch(HTTPStatus.BAD_REQUEST, {"error": str(exc)}) - except RegistryImageReferenceUnavailable: - return _BuildDispatch(HTTPStatus.SERVICE_UNAVAILABLE, - {"error": "registry image-use state is unavailable", "retryable": True}, - {"Retry-After": "2"}) - except BaseRegenerating as exc: - return _BuildDispatch(HTTPStatus.SERVICE_UNAVAILABLE, - {"error": str(exc), "error_code": "base_regenerating", "retryable": True}, - {"Retry-After": "30", "X-UCloud-Sandbox-Retryable": "true"}) - except RuntimeError as exc: - return _BuildDispatch(HTTPStatus.BAD_REQUEST, {"error": str(exc)}) - - finally: - if reserved_job_id: - with _BUILDER_DISPATCH_GUARD: - _BUILDER_DISPATCH_INFLIGHT[reserved_job_id] -= 1 + def _dispatch_image_build(self, raw: dict[str, Any]) -> BuildDispatch: + return self.services.builds.dispatch_build( + self, + raw, + select_builder=self._select_builder_node, + ensure_context=self._ensure_node_build_context, + record_terminal_metrics=self._record_terminal_build_metrics, + ) def _ensure_node_build_context( self, node_url: str, reference: tuple[str, int], ) -> ProxiedResponse: - digest, size = reference - path = f"/v1/image-contexts/{quote(digest, safe=':')}" - # A small context is re-sent rather than probed: the builder's - # least-recently-used store could evict a probed context before the - # build starts (older builders do not refresh it on probe), while an - # identical upload only refreshes it. - if size > _BUILD_CONTEXT_PROBE_MIN_BYTES: - probe = self._proxy_request(node_url, path, method="GET") - if 200 <= probe.status < 300: - payload = probe.json() - if payload.get("digest") == digest and payload.get("size") == size: - return probe - elif probe.status != HTTPStatus.NOT_FOUND: - return probe - - try: - with self.build_context_store.open(digest) as archive: - return self._proxy_request( - node_url, - path, - method="PUT", - body=archive, - extra_headers={ - "Content-Type": "application/gzip", - "Content-Length": str(size), - }, - timeout_seconds=IMAGE_BUILD_PROXY_TIMEOUT_SECONDS, - ) - except FileNotFoundError: - return ProxiedResponse( - HTTPStatus.BAD_REQUEST, - {"Content-Type": "application/json"}, - json.dumps( - {"error": f"build context {digest!r} has not been uploaded"} - ).encode("utf-8"), - ) + return self.services.builds.ensure_node_build_context(self, node_url, reference) def _route_image_pull(self) -> None: - try: - body = self._read_raw_body(max_bytes=self.max_json_body_bytes) - raw = json.loads(body.decode("utf-8")) if body else None - if not isinstance(raw, dict): - raise ValueError("image pull payload must be a JSON object") - unsupported = sorted( - set(raw) - - { - "count", - "cpus", - "disk_mb", - "id", - "image", - "memory_mb", - "sandbox_nodes_only", - } - ) - if unsupported: - raise ValueError( - "unsupported image pull fields: " + ", ".join(unsupported) - ) - image = str(raw.get("image") or "") - if not image.strip(): - raise ValueError("image is required.") - count = _strict_positive_integer(raw.get("count", 1), "count") - resources = _prepared_resources_from_payload(raw) - sandbox_nodes_only = raw.get("sandbox_nodes_only", True) - if not isinstance(sandbox_nodes_only, bool): - raise ValueError("sandbox_nodes_only must be a boolean.") - if count <= 0: - raise ValueError("count must be positive.") - except (json.JSONDecodeError, ValueError) as exc: - self._write_json({"error": str(exc)}, status=HTTPStatus.BAD_REQUEST) - return - - image, image_error = self._resolve_request_image_reference(image) - if image_error is not None: - self._write_image_resolution_error(image_error) - return - - self.services.registry_refs.ensure_image_lease( - image, - _registry_operation_lease_owner( - "image-pull", - { - "image": image, - "image_id": str(raw.get("id") or "").strip(), - "count": count, - "resources": resources.to_dict(), - "sandbox_nodes_only": sandbox_nodes_only, - }, - ), - touch=True, - ) - result = self._warm_image_on_ready_nodes( - image, - count=count, - resources=resources, - sandbox_nodes_only=sandbox_nodes_only, - image_id=str(raw.get("id") or "").strip(), + self.services.builds.route_image_pull( + self, + warm_image=self._warm_image_on_ready_nodes, ) - if result["ready"] <= 0: - error_message = ( - "image pull failed on ready image-cache nodes" - if result["failed"] - else "no ready image-cache node is available" - ) - self._write_json( - { - "error": error_message, - "image": image, - "result": result, - }, - status=HTTPStatus.SERVICE_UNAVAILABLE, - ) - return - self._write_json(result, status=HTTPStatus.OK) def _route_sandbox_request(self, sandbox_id: str, path: str) -> None: - action = match_sandbox_http_route(self.command, path) - if action and action.action=='delete': - self.routing_store.cancel_create_commands(sandbox_id) - if action and action.action=='wake' and getattr(self,'placement_queue',None) is not None: - try: - body=self._read_raw_body(max_bytes=DEFAULT_MAX_JSON_BODY_BYTES) - raw=json.loads(body) - if not isinstance(raw,dict) or not raw.get('operation_id') or int(raw.get('generation',0))<1: - raise ValueError('wake requires operation_id and generation') - except (ValueError,TypeError) as exc: - self._write_json({'error':str(exc)},status=400) - return - if not self._warm_wake_route(sandbox_id,int(raw['generation'])): - self._prefetched_route = None - self._defer_placement('wake',sandbox_id,path,body) - return - # A running owner already holds its capacity: there is no placement - # to serialize. Forward the worker-fenced wake directly instead of - # paying the durable queue round trip. Admission re-reads the route - # and returns to the queue if it parked in between. - self._placement_request_body=body - self._warm_wake_fallback=(path,body) - try: - weight = max(1, int(self.headers.get("Content-Length", "0"))) - if weight > DEFAULT_MAX_PROXY_BODY_BYTES: - raise ValueError("request exceeds gateway body limit") - except ValueError as exc: - self.close_connection = True - self._write_json({"error": str(exc)}, status=HTTPStatus.BAD_REQUEST) - return - buffered_bulk = self.command in {"POST", "PUT", "PATCH"} and ( - weight > 64 * 1024 - or (action is not None and action.action == "files") - ) and not (self.command == "PUT" and action is not None and action.action in UPLOAD_ACTIONS) - if buffered_bulk: - with self._startup_request_admission(weight=weight) as admitted: - if admitted: - self._route_sandbox_request_admitted(sandbox_id, path) - else: - self._route_sandbox_request_admitted(sandbox_id, path) + self.services.sandbox_proxy.route_sandbox_request( + self, + sandbox_id, + path, + warm_wake_route=self._warm_wake_route, + route_admitted=self._route_sandbox_request_admitted, + ) def _warm_wake_route(self, sandbox_id: str, generation: int) -> bool: - try: - route = self.routing_store.get_sandbox_readonly(sandbox_id) - except sqlite3.DatabaseError: - return False # The durable queue owns availability errors. - # The admitted path runs immediately (a wake body is never buffered - # behind admission), so it reuses this read instead of repeating it. - self._prefetched_route = (sandbox_id, route) - return _is_warm_wake_route(route, generation) + return self.services.sandbox_proxy.warm_wake_route(self, sandbox_id, generation) def _write_missing_sandbox_route(self, sandbox_id: str) -> None: - loss = self.routing_store.get_sandbox_loss(sandbox_id) - if loss is not None: - self._write_json( - { - "error": "sandbox worker was lost; this sandbox incarnation cannot resume", - "error_code": "node_lost", - "reason": loss["reason"], - "retryable": False, - "sandbox_id": sandbox_id, - "sandbox_generation": loss["generation"], - "lost_at": loss["lost_at"], - }, - status=HTTPStatus.GONE, - ) - return - self._write_json( - {"error": "sandbox route not found"}, status=HTTPStatus.NOT_FOUND - ) + self.services.sandbox_proxy.write_missing_sandbox_route(self, sandbox_id) def _write_absent_route(self, sandbox_id: str) -> None: - if self.command == "DELETE": - pending_before = self.routing_store.get_pending(sandbox_id) - self.routing_store.delete_sandbox(sandbox_id) - record_sandbox_pending_deleted( - self.metrics_store, - sandbox_id=sandbox_id, - pending=pending_before, - ) - self._write_json({"ok": True, "deleted": False}) - return - self._write_missing_sandbox_route(sandbox_id) - - def _route_sandbox_request_admitted(self, sandbox_id: str, path: str) -> None: # noqa: C901 - prefetched, self._prefetched_route = getattr(self, "_prefetched_route", None), None - if prefetched is not None and prefetched[0] == sandbox_id: - route = prefetched[1] - else: - route = self.routing_store.get_sandbox(sandbox_id) - fallback, self._warm_wake_fallback = getattr(self, "_warm_wake_fallback", None), None - if fallback is not None and not _is_warm_wake_route(route): - # Placement belongs to the durable queue; never reserve it here. - self._placement_request_body = None - self._defer_placement("wake", sandbox_id, *fallback) - return - if route is None: - self._write_absent_route(sandbox_id) - return - - if self.command != "DELETE" and route.delete_operation_id: - self._write_json( - { - "error": "sandbox deletion is in progress", - "error_code": "sandbox_delete_pending", - "retryable": False, - }, - status=HTTPStatus.CONFLICT, - ) - return + self.services.sandbox_proxy.write_absent_route(self, sandbox_id) - sandbox_http_route = match_sandbox_http_route(self.command, path) - request_wakes = bool( - sandbox_http_route is not None and sandbox_http_route.wakes - ) - - # Placement is durable before provisioning begins. Do not forward - # tool traffic into a registration that is still planned, quota-ready, - # or preparing its rootfs. Reconcile a completed node record first; - # otherwise keep the caller on the retryable create boundary. - if self.command != "DELETE": - route = self._reconcile_routable_sandbox(route) - if route is None: - return - - try: - if self.command == "PUT" and sandbox_http_route is not None and sandbox_http_route.action in UPLOAD_ACTIONS: - length = self._request_content_length(max_bytes=DEFAULT_MAX_PROXY_BODY_BYTES) - # One transfer chunk is already the streaming adapter's memory - # bound. Buffer small tools/signals within that same bound so - # they use the canonical pooled RPC transport; larger uploads - # still reach the worker before the entire body arrives. - body = ( - self._read_raw_body(max_bytes=TRANSFER_CHUNK_BYTES) - if length <= TRANSFER_CHUNK_BYTES - else RequestBodyStream(self.rfile, length) - ) - else: - body = ( - self._read_raw_body(max_bytes=DEFAULT_MAX_PROXY_BODY_BYTES) - if self.command in {"POST", "PUT", "PATCH"} - else None - ) - except ValueError as exc: - self._write_json({"error": str(exc)}, status=HTTPStatus.BAD_REQUEST) - return - - transport_reset = False - lifecycle_payload: dict[str, Any] = {} - lifecycle_action = ( - sandbox_http_route.action - if sandbox_http_route is not None - and sandbox_http_route.action in {"park", "wake"} - else "" - ) - if lifecycle_action: - parsed_lifecycle = self._parse_lifecycle_request( - route, - lifecycle_action, - body, - ) - if parsed_lifecycle is None: - return - lifecycle_payload = parsed_lifecycle - - job_read_wait = job_read_wait_ms(sandbox_http_route, self.path) - if ( - sandbox_http_route is not None - and sandbox_http_route.action == "job_status" - and (route.state or "unknown").lower() - in {"parking", "parked", "moving", "restoring", "waking"} - ): - self._serve_cached_job_status( - route, - sandbox_http_route, - missing_status=HTTPStatus.NOT_FOUND, - ) - return - if ( - (route.state or "unknown").lower() - in {"parking", "parked", "moving", "restoring", "waking"} - and self._serve_cached_job_logs(route, sandbox_http_route) - ): - # A waiting read at or past the cached bytes needs nothing from - # the parked image, so it does not wake the sandbox. - return - - self._prepare_program_lifecycle(route, lifecycle_action, lifecycle_payload) - - implicit_wake = bool( - not lifecycle_action - and request_wakes - and (route.state or "unknown").lower() in {"parked", "waking"} - ) - if (route.state or "unknown").lower() == "parked" and request_wakes: - placement = self._prepare_wake_placement(route) - if placement is None: - return - route, transport_reset = placement - - if (lifecycle_action == "wake" and lifecycle_payload.get("request_id") - and not self._program_wake_started): - self._record_program_request_transition( - route, - lifecycle_payload, - state="waking", - ) - - if self.command == "DELETE": - prepared_delete = self._prepare_delete_route(route) - if prepared_delete is None: - return - route = prepared_delete - - if not self._route_worker_is_fresh(route, pull=True): - if self.routing_store.get_sandbox_readonly(sandbox_id) is None: - # The pull proved a new boot, whose ingest retired this route. - self._write_absent_route(sandbox_id) - return - if self._serve_cached_job_status(route, sandbox_http_route): - return - self._write_route_worker_unreachable(route) - return - if implicit_wake: - completed_wake = self._perform_implicit_wake(route) - if completed_wake is None: - return - route = completed_wake - - extra_headers = ( - { - SANDBOX_GENERATION_HEADER: str(route.generation), - SANDBOX_OPERATION_ID_HEADER: route.delete_operation_id, - } - if self.command == "DELETE" - else None - ) - if self.command == "PUT" and sandbox_http_route is not None and sandbox_http_route.action in UPLOAD_ACTIONS: - extra_headers = { - "Content-Length": str(body.length if isinstance(body, RequestBodyStream) else len(body)), - SANDBOX_GENERATION_HEADER: str(route.generation), - } - if sandbox_http_route is not None and sandbox_http_route.action == "exec": - # The worker names the session under this signed route, so later - # requests for it route without any stored state. - try: - extra_headers = {EXEC_SESSION_PREFIX_HEADER: self.exec_routing.signed_prefix(route)} - except ExecRouteUnavailable as exc: - self._write_json(exc.payload, status=exc.status, headers=exc.headers) - return - # Downloads stream their response; uploads stream the request body and - # receive a small JSON acknowledgement after the worker commits it. - if ( - sandbox_http_route is not None - and sandbox_http_route.action == "files" - and self.command == "GET" - ): - self._stream_proxy_request( - route.node_url, - self.path, - method=self.command, - extra_headers=extra_headers, - ) - return - proxy_body = body - if lifecycle_action: - proxy_body = self._lifecycle_proxy_body( - route, - lifecycle_action, - lifecycle_payload, - ) - if proxy_body is None: - return - if (self.command == "PUT" and sandbox_http_route is not None - and sandbox_http_route.action in UPLOAD_ACTIONS and isinstance(proxy_body, bytes) - and len(proxy_body) <= TRANSFER_CHUNK_BYTES - and self._defer_node_response(route.node_url, self.path, method="PUT", - body=proxy_body, extra_headers=extra_headers)): - return - if job_read_wait is not None and self._defer_job_read( - route, sandbox_http_route, job_read_wait, - ): - return - response = self._proxy_request( - route.node_url, - self.path, - method=self.command, - body=proxy_body, - extra_headers=extra_headers, - timeout_seconds=job_read_timeout_seconds(job_read_wait), - ) - if self._serve_cached_transition_job_read( - route, - sandbox_http_route, - response, - ): - return - if not self._record_successful_sandbox_proxy_state( - route, - sandbox_http_route, - response, - ): - return - if lifecycle_action == "park" and response.status == HTTPStatus.ACCEPTED: - # Publication is pending; the route commits from inventory later. - self._cache_parked_job(route, response.json().get("sandbox")) - self._send_proxied_response(response) - return - if lifecycle_action: - lifecycle_route = self._handle_lifecycle_proxy_response( - route, - lifecycle_action, - lifecycle_payload, - response, - ) - if lifecycle_route is None: - return - route = lifecycle_route - if self.command == "DELETE" and 200 <= response.status < 300: - if not self._commit_successful_worker_delete(route, response): - return - response_headers: dict[str, str] | None = None - if lifecycle_action: - response_headers = { - SANDBOX_TRANSPORT_EPOCH_HEADER: _sandbox_transport_epoch( - route, - self.routing_store.sandbox_migrations( - active_only=False, sandbox_id=route.sandbox_id, - ), - ) - } - if transport_reset: - response_headers[SANDBOX_TRANSPORT_RESET_HEADER] = "true" - self._send_proxied_response(response, extra_headers=response_headers) - - def _reconcile_routable_sandbox( - self, - route: SandboxRoute, - ) -> SandboxRoute | None: - """Promote a completed create before forwarding sandbox traffic.""" - - if route.state.lower() not in { - "creating", - "unknown", - "planned", - "quota_ready", - "rootfs_ready", - }: - return route - try: - routed_spec = SandboxSpec.from_dict(route.spec) - except (TypeError, ValueError): - routed_spec = None - if not self._route_worker_is_fresh(route): - self._write_create_in_progress_response(route.sandbox_id) - return None - record = self._sandbox_record_on_node(route.node_url, route.sandbox_id) - if ( - routed_spec is None - or record is None - or not _sandbox_record_matches_route(record, route, routed_spec) - or not _sandbox_record_is_ready(record) - ): - self._write_create_in_progress_response(route.sandbox_id) - return None - return self._confirm_sandbox_observation(_route_with_sandbox_record(route, record)) - - def _prepare_program_lifecycle( - self, - route: SandboxRoute, - action: str, - payload: dict[str, Any], - ) -> None: - self._program_wake_started = False - self._warm_program_wake_observation = None - request_id = str(payload.get("request_id") or "").strip() - if not action or not request_id: - return - if action == "wake" and route.state.lower() == "running" and payload.get("durable_lifecycle"): - # PostgreSQL has already committed this response and wake intent. - # A running owner needs no placement demand. Persist the local - # observational timestamps with the outcome, rather than make a - # warm wake wait for an extra SQLite commit before contacting it. - self._warm_program_wake_observation = ( - request_id, route.sandbox_id, route.generation, utc_now().isoformat(), - ) - self._program_wake_started = True - return - warm_wake = action == "wake" and route.state.lower() in {"running", "waking"} - # Warm work has no placement wait between response-ready and dispatch. - # Persist both timestamps in one transition instead of queueing twice. - transition = {"response_ready": True} if warm_wake else {} - program, _changed = self._record_program_request_transition( - route, - payload, - state=("waking" if warm_wake else "model_wait" if action == "park" else "ready_to_wake"), - **transition, - ) - self._program_wake_started = warm_wake and program is not None - - def _prepare_wake_placement(self, route: SandboxRoute) -> tuple[SandboxRoute, bool] | None: - outcome = self._wake_placement().place(route) - if isinstance(outcome, WakePlaced): - return outcome.route, outcome.owner_changed - self._write_wake_unavailable(outcome) - return None - - def _lifecycle_proxy_body( - self, - route: SandboxRoute, - action: str, - payload: dict[str, Any], - ) -> bytes | None: - try: - node_payload = lifecycle_node_payload(route.generation, action, payload) - except ValueError as exc: - self._write_json({"error": str(exc)}, status=HTTPStatus.BAD_REQUEST) - return None - return json.dumps(node_payload, separators=(",", ":")).encode("utf-8") - - def _parse_lifecycle_request( - self, - route: SandboxRoute, - action: str, - body: bytes | None, - ) -> dict[str, Any] | None: - """Parse and authorize one explicit lifecycle request.""" - - try: - payload = json.loads((body or b"{}").decode("utf-8")) - if not isinstance(payload, dict): - raise ValueError("sandbox lifecycle payload must be an object") - request_id = str(payload.get("request_id") or "").strip() - rollout_id = str(payload.get("rollout_id") or "").strip() - if "durable_lifecycle" in payload and (payload["durable_lifecycle"] is not True or not request_id): - raise ValueError("durable lifecycle requires a request binding") - if bool(request_id) != bool(rollout_id): - raise ValueError( - "program lifecycle requires both request_id and rollout_id" - ) - generation = payload.get("generation") - operation_id = str(payload.get("operation_id") or "").strip() - if not operation_id: - raise ValueError("sandbox lifecycle operation_id is required") - if action == "wake" and generation is None: - raise ValueError("wake generation is required") - if generation is not None and int(generation) != route.generation: - self._write_json( - { - "error": ( - f"{action} generation does not own the current " - "sandbox route" - ), - "retryable": False, - }, - status=HTTPStatus.CONFLICT, - ) - return None - except (TypeError, UnicodeDecodeError, json.JSONDecodeError, ValueError) as exc: - self._write_json({"error": str(exc)}, status=HTTPStatus.BAD_REQUEST) - return None - if request_id and not _sandbox_supports_managed_lifecycle(route.spec): - self._write_json( - { - "error": ( - f"request-bound {action} requires a parkable " - "managed_process sandbox" - ), - "retryable": False, - }, - status=HTTPStatus.CONFLICT, - ) - return None - if action == "park" and payload.get("durable_lifecycle"): - program = self.routing_store.program_request_readonly(request_id) - if (program is not None and program.sandbox_id == route.sandbox_id - and program.sandbox_generation == route.generation - and program.rollout_id == rollout_id and program.state != "model_wait"): - self._write_json({"skipped": True, "reason": "model_result_ready"}) - return None - return payload - - def _prepare_delete_route(self, route: SandboxRoute) -> SandboxRoute | None: - """Resolve detach/migration state before proxying a durable delete.""" - - sandbox_id = route.sandbox_id - route = self.routing_store.prepare_sandbox_delete(sandbox_id) or route - if route.worker_state != "detached": - migration_error = self._resolve_sandbox_migrations_for_delete(sandbox_id) - if migration_error: - self._write_json( - {"error": migration_error, "retryable": True}, - status=HTTPStatus.SERVICE_UNAVAILABLE, - headers={"X-UCloud-Sandbox-Retryable": "true"}, - ) - return None - current = self.routing_store.get_sandbox_readonly(sandbox_id) - if current is None: - self._write_json({"deleted": None}) - return None - route = current - if route.worker_state == "detaching": - detached, error_message = self._finish_sandbox_detach(route) - if detached is None: - self._write_json( - { - "error": error_message or "worker detach is incomplete", - "retryable": True, - }, - status=HTTPStatus.SERVICE_UNAVAILABLE, - headers={"X-UCloud-Sandbox-Retryable": "true"}, - ) - return None - route = detached - if route.worker_state != "detached": - return route - route = self.routing_store.prepare_sandbox_delete(sandbox_id) or route - removed = self.routing_store.delete_sandbox_if_current( + def _route_sandbox_request_admitted(self, sandbox_id: str, path: str) -> None: + self.services.sandbox_proxy.route_sandbox_request_admitted( + self, sandbox_id, - generation=route.generation, - delete_operation_id=route.delete_operation_id, - ) - if removed is not None: - self.services.registry_refs.release_route_reference(removed) - self._write_json( - {"deleted": removed.to_dict() if removed is not None else None} - ) - return None - - def _serve_cached_job_status( - self, - route: SandboxRoute, - http_route: SandboxHttpRoute | None, - *, - missing_status: HTTPStatus | None = None, - ) -> bool: - cached = cached_job_status_response( - self.routing_store, - route, - http_route, - wait_ms=job_read_wait_ms(http_route, self.path), - missing_status=missing_status, - ) - if cached is None: - return False - self._send_proxied_response(cached) - return True - - def _serve_cached_job_logs( - self, - route: SandboxRoute, - http_route: SandboxHttpRoute | None, - ) -> bool: - cached = cached_job_logs_response( - self.routing_store, - route, - http_route, - self.path, - wait_ms=job_read_wait_ms(http_route, self.path), + path, + parse_lifecycle=self._parse_lifecycle_request, + prepare_program=self._prepare_program_lifecycle, + prepare_forwarding=self._prepare_route_for_forwarding, + lifecycle_body=self._lifecycle_proxy_body, + finalize_response=self._finalize_sandbox_proxy_response, ) - if cached is None: - return False - self._send_proxied_response(cached) - return True - def _defer_job_read( + def _prepare_route_for_forwarding( self, + sandbox_id: str, route: SandboxRoute, - http_route: SandboxHttpRoute, - wait_ms: int, - ) -> bool: - """Hand a waiting job read to the asynchronous response owner. - - The worker may hold it for up to wait_ms, so it must not hold a handler - thread (docs/architecture.md). Its record is cached off the - I/O loop before the reply, as the synchronous path does. - """ - if self.async_responses is None or ( - self.headers.get("Transfer-Encoding") - or self.headers.get("Content-Length", "0") != "0" - ): - # Unread body bytes would remain on the transferred socket. - return False - routing_store, path = self.routing_store, self.path - - def project(status, headers, body): - response = ProxiedResponse(status, headers, body) - try: - projected = project_job_response( - routing_store, route, http_route, path, response, wait_ms=wait_ms, - ) - except sqlite3.DatabaseError: - return ( - HTTPStatus.SERVICE_UNAVAILABLE, - {"Content-Type": "application/json"}, - b'{"error":"routing state unavailable","retryable":true}', - ) - if projected is None: - return status, headers, body - return projected.status, projected.headers, projected.body - - try: - proxied = self._build_proxy_request(route.node_url, path, method="GET") - self.server.defer_proxy_response( - self.request, url=proxied.full_url, headers=_node_request_headers(proxied), - trace_headers=self.telemetry.current_trace_headers(), telemetry=self.telemetry, - method="GET", event_poll=False, timeout=job_read_timeout_seconds(wait_ms), - held_read=True, project=project, - ) - except (OSError, error.URLError, RuntimeError) as exc: - self._send_proxied_response(_node_transport_error_response(exc)) - return True - self.close_connection = True - return True - - def _perform_implicit_wake(self, route: SandboxRoute) -> SandboxRoute | None: - response = self._proxy_request( - route.node_url, - f"/v1/sandboxes/{quote(route.sandbox_id, safe='')}/wake", - method="POST", - body=json.dumps( - { - "generation": route.generation, - "operation_id": f"activity-wake:{uuid4().hex}", - }, - separators=(",", ":"), - ).encode("utf-8"), - extra_headers={"Content-Type": "application/json"}, - ) - if response.status < 300: - return self._commit_lifecycle_response(route, "wake", response) - if str(response.json().get("lifecycle_state") or "").lower() == "parked": - rolled_back = self.routing_store.set_sandbox_state_if_current( - route, - expected_states={"waking"}, - state="parked", - ) - if rolled_back is not None: - self._cache_parked_job(rolled_back, response.json().get("sandbox")) - if response.transport_error_kind: - # Only the internal wake was attempted. The caller's exec, upload - # or job mutation has not been dispatched, even if the wake reply - # timed out after resume began. Certify that boundary for existing - # SDKs without claiming the sandbox is still parked. - self._write_json( - { - "error": "sandbox wake is unavailable; requested operation has not started", - "error_code": "node_restore_busy", - "cause_code": response.json().get("code", "node_transport_error"), - "retryable": True, - }, - status=HTTPStatus.SERVICE_UNAVAILABLE, - headers={"Retry-After": "1", "X-UCloud-Sandbox-Retryable": "true"}, - ) - return None - self._send_proxied_response(response) - return None + sandbox_http_route: SandboxHttpRoute | None, + lifecycle_action: str, + lifecycle_payload: dict[str, Any], + ) -> tuple[SandboxRoute, bool] | None: + return self.services.sandbox_proxy.prepare_route_for_forwarding( + self, + sandbox_id, + route, + sandbox_http_route, + lifecycle_action, + lifecycle_payload, + prepare_wake_placement=self._prepare_wake_placement, + record_program_transition=self._record_program_request_transition, + prepare_delete=self._prepare_delete_route, + perform_implicit_wake=self._perform_implicit_wake, + ) - def _serve_cached_transition_job_read( + def _finalize_sandbox_proxy_response( self, route: SandboxRoute, - http_route: SandboxHttpRoute | None, + sandbox_http_route: SandboxHttpRoute | None, + lifecycle_action: str, + lifecycle_payload: dict[str, Any], + transport_reset: bool, response: ProxiedResponse, - ) -> bool: - if not 400 <= response.status < 500: - return False - cached = project_job_response( - self.routing_store, + ) -> None: + self.services.sandbox_proxy.finalize_sandbox_proxy_response( + self, route, - http_route, - self.path, + sandbox_http_route, + lifecycle_action, + lifecycle_payload, + transport_reset, response, - wait_ms=job_read_wait_ms(http_route, self.path), + handle_lifecycle_response=self._handle_lifecycle_proxy_response, ) - if cached is None: - return False - self._send_proxied_response(cached) - return True - def _record_successful_sandbox_proxy_state( + def _prepare_program_lifecycle( self, route: SandboxRoute, - http_route: SandboxHttpRoute | None, - response: ProxiedResponse, - ) -> bool: - """Project successful node responses into the gateway-owned ledgers.""" + action: str, + payload: dict[str, Any], + ) -> None: + self.services.sandbox_proxy.prepare_program_lifecycle( + self, + route, + action, + payload, + record_program_transition=self._record_program_request_transition, + ) - if http_route is None or not 200 <= response.status < 300: - return True - if http_route.action in {"job_create", "job_status", "job_signal", "job_logs"}: - invalid = record_job_response(self.routing_store, route, http_route, response) - if invalid is not None: - self._send_proxied_response(invalid) - return False - return True + def _prepare_wake_placement( + self, route: SandboxRoute + ) -> tuple[SandboxRoute, bool] | None: + return self.services.sandbox_proxy.prepare_wake_placement( + self, + route, + wake_placement=self._wake_placement, + write_wake_unavailable=self._write_wake_unavailable, + ) - def _handle_lifecycle_proxy_response( + def _lifecycle_proxy_body( self, route: SandboxRoute, action: str, payload: dict[str, Any], - response: ProxiedResponse, - ) -> SandboxRoute | None: - if response.status >= 300: - if action == "park" and response.status == HTTPStatus.CONFLICT: - try: - deferred = response.json() - except (TypeError, ValueError): - deferred = {} - if ( - isinstance(deferred, dict) - and deferred.get("error_code") == "park_deferred" - and deferred.get("retryable") is True - ): - # Retention is expected scheduling, not a failed park. - # Keep model_wait without another durable error write. - return route - if action == "wake": - try: - failed_state = str( - response.json().get("lifecycle_state") or "" - ).lower() - except (TypeError, ValueError, json.JSONDecodeError): - failed_state = "" - if failed_state == "parked": - rolled_back = self.routing_store.set_sandbox_state_if_current( - route, - expected_states={"waking"}, - state="parked", - ) - if rolled_back is not None: - route = rolled_back - self._cache_parked_job(route, response.json().get("sandbox")) - self._record_program_request_transition( - route, - payload, - state=("waking" if action == "wake" else "model_wait"), - last_error=_lifecycle_proxy_error(response), - ) - return route - if not 200 <= response.status < 300: - return route - updated = self._commit_lifecycle_response( - route, action, response, lifecycle_payload=payload if action == "wake" else None, + ) -> bytes | None: + return self.services.sandbox_proxy.lifecycle_proxy_body( + self, route, action, payload ) - if updated is None: - return None - if action != "wake": - self._record_completed_program_lifecycle(updated, action, payload) - return updated - def _commit_lifecycle_response( + def _parse_lifecycle_request( self, route: SandboxRoute, action: str, - response: ProxiedResponse, - *, lifecycle_payload: dict[str, Any] | None = None, - ) -> SandboxRoute | None: - """Decode worker HTTP evidence and translate domain commit outcomes.""" - commit = LifecycleCommitter( - self.routing_store, - heartbeat=lambda job_id: self._heartbeat_for_route( - job_id=job_id, include_inventory=False), - snapshots=SnapshotReferences( - protect=lambda candidate: self.services.registry_refs.ensure_snapshot_reference( - candidate, repository=candidate.snapshot_repository, - tag=candidate.snapshot_tag, digest=candidate.snapshot_manifest_digest), - release=self.services.registry_refs.release_snapshot_reference, - ), + body: bytes | None, + ) -> dict[str, Any] | None: + return self.services.sandbox_proxy.parse_lifecycle_request( + self, route, action, body ) - try: - try: - receipt = response.json() - except (ValueError, TypeError) as exc: - raise InvalidLifecycleReceipt("invalid node lifecycle response: expected JSON object") from exc - if not isinstance(receipt, dict): - raise InvalidLifecycleReceipt("invalid node lifecycle response: expected JSON object") - if action == "wake": - outcome = commit.wake(route, receipt, program_transition=( - self._program_request_transition_args( - route, lifecycle_payload, state="acting", clear_error=True, - ) if lifecycle_payload is not None else None)) - else: - outcome = commit.park(route, receipt) - except InvalidLifecycleReceipt as exc: - self._write_json({"error": str(exc)}, status=HTTPStatus.BAD_GATEWAY) - return None - except LifecycleRouteChanged as exc: - self._write_json({"error": str(exc), "retryable": True}, - status=HTTPStatus.SERVICE_UNAVAILABLE, - headers={"X-UCloud-Sandbox-Retryable": "true"}) - return None - except RegistryImageReferenceUnavailable as exc: - self._write_registry_lease_unavailable(exc) - return None - if action != "wake": - self._cache_parked_job(outcome.route, receipt.get("sandbox")) - if action == "wake" and lifecycle_payload is not None: - self._record_completed_program_lifecycle( - outcome.route, action, lifecycle_payload, - committed=outcome.program_transition) - return outcome.route - - def _cache_parked_job(self, route: SandboxRoute, sandbox_record: object) -> None: - """Cache the exact job record a parked worker sandbox record carries.""" - cache_parked_job(self.routing_store, route, sandbox_record) - def _record_completed_program_lifecycle( + def _prepare_delete_route(self, route: SandboxRoute) -> SandboxRoute | None: + return self.services.sandbox_proxy.prepare_delete_route( + self, + route, + resolve_migrations=self._resolve_sandbox_migrations_for_delete, + finish_detach=self._finish_sandbox_detach, + ) + + def _perform_implicit_wake(self, route: SandboxRoute) -> SandboxRoute | None: + return self.services.sandbox_proxy.perform_implicit_wake( + self, + route, + commit_lifecycle=self._commit_lifecycle_response, + ) + + def _handle_lifecycle_proxy_response( self, route: SandboxRoute, action: str, payload: dict[str, Any], - *, committed=None, - ) -> None: - if not payload.get("request_id"): - return - if action == "park": - self._record_program_request_transition( - route, - payload, - state="model_wait", - parked_at=utc_now().isoformat(), - clear_error=True, - ) - return - if committed is None: - _program, changed = self._record_program_request_transition( - route, payload, state="acting", clear_error=True, - ) - else: - _program, changed = committed - if changed: - self.metrics_store.append("program_state_transition", _program.to_dict()) - if not changed: - return - self.metrics_store.append( - "program_wake_actual", - { - "request_id": str(payload.get("request_id") or "").strip(), - "rollout_id": str(payload.get("rollout_id") or "").strip(), - "sandbox_id": route.sandbox_id, - "sandbox_generation": route.generation, - "node_id": route.node_id, - "job_id": route.job_id, - }, + response: ProxiedResponse, + ) -> SandboxRoute | None: + return self.services.sandbox_proxy.handle_lifecycle_proxy_response( + self, + route, + action, + payload, + response, + record_program_transition=self._record_program_request_transition, + commit_lifecycle=self._commit_lifecycle_response, + record_completed=self._record_completed_program_lifecycle, ) - def _commit_successful_worker_delete( + def _commit_lifecycle_response( self, route: SandboxRoute, + action: str, response: ProxiedResponse, - ) -> bool: - deleted = response.json().get("deleted") - response_generation = _record_generation(deleted) - if ( - isinstance(deleted, dict) - and response_generation is not None - and response_generation != route.generation - ): - self._write_json( - { - "error": "node delete response confirmed a different generation", - "retryable": True, - }, - status=HTTPStatus.BAD_GATEWAY, - ) - return False - removed = self.routing_store.delete_sandbox_if_current( - route.sandbox_id, - generation=route.generation, - delete_operation_id=route.delete_operation_id, + *, + lifecycle_payload: dict[str, Any] | None = None, + ) -> SandboxRoute | None: + return self.services.sandbox_proxy.commit_lifecycle_response( + self, + route, + action, + response, + lifecycle_payload=lifecycle_payload, + record_completed=self._record_completed_program_lifecycle, ) - if removed is not None: - self.services.registry_refs.release_route_reference(removed) - return True - def _program_request_transition_args( + def _record_completed_program_lifecycle( self, route: SandboxRoute, - lifecycle_payload: dict[str, Any], + action: str, + payload: dict[str, Any], *, - state: str, - parked_at: str | None = None, - response_ready: bool = False, - last_error: str = "", - clear_error: bool = False, - ) -> dict[str, Any] | None: - request_id = str(lifecycle_payload.get("request_id") or "").strip() - rollout_id = str(lifecycle_payload.get("rollout_id") or "").strip() - if not request_id or not rollout_id: - return None - observed = getattr(self, "_warm_program_wake_observation", None) - warm_started_at = ( - observed[3] if observed is not None - and observed[:3] == (request_id, route.sandbox_id, route.generation) - and state in {"waking", "acting"} else None - ) - accepted_at = "" - try: - raw_created_at = float(lifecycle_payload.get("request_created_at")) - if math.isfinite(raw_created_at) and raw_created_at >= 0: - accepted_at = datetime.fromtimestamp( - raw_created_at, - tz=timezone.utc, - ).isoformat() - except (TypeError, ValueError, OverflowError, OSError): - pass - return dict( - request_id=request_id, rollout_id=rollout_id, state=state, - accepted_at=accepted_at or None, parked_at=parked_at, - response_ready_at=warm_started_at or (utc_now().isoformat() if response_ready else None), - **({"wake_started_at": warm_started_at} if warm_started_at else {}), - last_error=last_error, clear_error=clear_error, + committed=None, + ) -> None: + self.services.sandbox_proxy.record_completed_program_lifecycle( + self, + route, + action, + payload, + committed=committed, + record_program_transition=self._record_program_request_transition, ) def _record_program_request_transition( @@ -4568,115 +2293,49 @@ def _record_program_request_transition( last_error: str = "", clear_error: bool = False, ) -> tuple[ProgramRequestState | None, bool]: - args = self._program_request_transition_args( - route, lifecycle_payload, state=state, parked_at=parked_at, - response_ready=response_ready, last_error=last_error, clear_error=clear_error, + return self.services.sandbox_proxy.record_program_request_transition( + self, + route, + lifecycle_payload, + state=state, + parked_at=parked_at, + response_ready=response_ready, + last_error=last_error, + clear_error=clear_error, ) - if args is None: - return None, False - try: - program, changed = self.routing_store.upsert_program_request_transition_with_change(route, **args) - except (OSError, sqlite3.Error, ValueError, SandboxRouteConflictError) as exc: - self.metrics_store.append( - "program_state_projection_error", - { - "request_id": args["request_id"], - "rollout_id": args["rollout_id"], - "sandbox_id": route.sandbox_id, - "sandbox_generation": route.generation, - "state": state, - "error": str(exc), - }, - ) - return None, False - if changed: - self.metrics_store.append( - "program_state_transition", - program.to_dict(), - ) - return program, changed def _read_worker_heartbeat(self, node_url: str) -> Any: - response = self._proxy_request( - node_url, "/v1/heartbeat", method="GET", timeout_seconds=PULL_TIMEOUT_SECONDS) - return response.json().get("heartbeat") if response.status == HTTPStatus.OK else None + return self.services.sandbox_proxy.read_worker_heartbeat(self, node_url) def _refresh_worker(self, heartbeat: NodeHeartbeat) -> NodeHeartbeat | None: - return self.services.heartbeats.refresh(heartbeat, self._read_worker_heartbeat) + return self.services.sandbox_proxy.refresh_worker(self, heartbeat) def _refresh_wake_capacity(self, route: SandboxRoute) -> None: - # A blocked owner may be stale, or fresh but full: only a live sample - # can admit locally. The pull is shared with every other caller. - owner = self.services.fleet.store.get_heartbeat(route.job_id, include_inventory=False) - if owner is not None: - self._refresh_worker(owner) - - def _request_wake_publication(self, route: SandboxRoute) -> dict[str, Any] | None: - response = self._proxy_request( - route.node_url, f"/v1/sandboxes/{quote(route.sandbox_id, safe='')}/snapshot/publish", - method="POST", body=json.dumps({"generation": route.generation}).encode(), - timeout_seconds=2.0) - return response.json() if response.status < 400 else None - - def _decode_wake_publication(self, route: SandboxRoute, payload: dict[str, Any]) -> SandboxRoute | None: - record = payload.get("sandbox") - if not isinstance(record, dict) or record.get("state") != "parked": - return None - if not _sandbox_record_matches_route(record, route, SandboxSpec.from_dict(route.spec)): - return None - self._cache_parked_job(route, record) - return _route_with_sandbox_record(route, record) + self.services.sandbox_proxy.refresh_wake_capacity(self, route) def _wake_placement(self) -> WakePlacement: - placement = self.services.placement - return WakePlacement(self.routing_store, self._wake_admission(), WakePlacementPorts( - owner=lambda job_id: self._heartbeat_for_route(job_id=job_id), - occupants=placement.routes_for_node, - destination=lambda route: self._select_migration_destination( - route, requested_node_id="", require_active_resources=True), - reserve_local=self._reserve_local_wake, + return self.services.sandbox_proxy.wake_placement( + self, + select_destination=lambda route: self._select_migration_destination( + route, requested_node_id="", require_active_resources=True + ), finish_detach=self._finish_sandbox_detach, advance_migration=self._prepare_and_advance_sandbox_migration, refresh_capacity=self._refresh_wake_capacity, - publish=self._request_wake_publication, - decode_publication=self._decode_wake_publication, - atomic=placement.atomic, - )) + reserve_local=self._reserve_local_wake, + ) def _reserve_local_wake(self, route): - return _local_wake_batcher(self.routing_store.path,owner=route.job_id).reserve(self,route) + return self.services.sandbox_proxy.reserve_local_wake(self, route) def _write_wake_unavailable(self, outcome: WakeUnavailable) -> None: - if outcome.missing_sandbox_id: - self._write_missing_sandbox_route(outcome.missing_sandbox_id) - return - payload = {"error": outcome.message, "retryable": True, **outcome.details} - if outcome.error_code: - payload["error_code"] = outcome.error_code - if outcome.pending_resources is not None: - payload["pending_resources"] = outcome.pending_resources.to_dict() - if outcome.migration is not None: - payload["migration"] = outcome.migration.to_dict() - self._write_json(payload, status=HTTPStatus.SERVICE_UNAVAILABLE, headers={ - "Retry-After": str(outcome.retry_after), "X-UCloud-Sandbox-Retryable": "true"}) + self.services.sandbox_proxy.write_wake_unavailable(self, outcome) def _wake_admission(self) -> WakeAdmission: - return WakeAdmission( - self.routing_store, - read_owner=self.services.fleet.store.get_heartbeat, - read_placement=self.services.placement.routes_for_node, - can_admit=lambda owner, routes, requested: ( - _node_has_storage_device_capacity(owner, routes) - and _node_can_fit_available( - owner, requested, _node_available_resources(owner, routes), - ) - ), - heartbeat_ttl_seconds=self.services.fleet.heartbeat_ttl_seconds, - ) + return self.services.sandbox_proxy.wake_admission(self) def _reserve_local_wake_batch(self, batch): - decisions = self._wake_admission().reserve_batch([route for _, route, _ in batch]) - return [decision.route for decision in decisions] + return self.services.sandbox_proxy.reserve_local_wake_batch(self, batch) def _route_exec_request(self, session_id: str) -> None: try: @@ -4731,7 +2390,7 @@ def _defer_node_response(self, node_url, path, *, method, body=None, proxied = self._build_proxy_request( node_url, path, method=method, body=body, extra_headers=extra_headers, ) - headers = _node_request_headers(proxied, allow_body_keep_alive=( + headers = node_request_headers(proxied, allow_body_keep_alive=( getattr(self, "_pooled_node_body_origin", None) == node_url.rstrip("/") )) self.server.defer_proxy_response( @@ -4746,7 +2405,7 @@ def _defer_node_response(self, node_url, path, *, method, body=None, release() if not isinstance(exc, (OSError, error.URLError, RuntimeError)): raise - self._send_proxied_response(_node_transport_error_response(exc)) + self._send_proxied_response(node_transport_error_response(exc)) return True def _heartbeat_for_route(self, *, job_id: str, include_inventory: bool = True) -> NodeHeartbeat | None: @@ -4889,7 +2548,7 @@ def _write_image_resolution_error(self, payload: dict[str, Any]) -> None: def _resolve_request_image_reference(self, image: str) -> tuple[str, dict[str, Any] | None]: """Resolve with the reference kind this request's header selects.""" try: - reference_kind = _image_reference_kind_from_headers(self.headers) + reference_kind = image_reference_kind_from_headers(self.headers) except ValueError as exc: return image, { "error": str(exc), @@ -4904,126 +2563,18 @@ def _image_cache_candidates( resources: ResourceQuantity, sandbox_nodes_only: bool, ) -> list[NodeHeartbeat]: - routes = list(self.routing_store.sandbox_routes_readonly()) - candidates = [] - for heartbeat in self.services.fleet.ready_heartbeats(): - if "image-cache" not in heartbeat.capabilities: - continue - if sandbox_nodes_only and "sandbox" not in heartbeat.capabilities: - continue - if _has_resource_values(resources) and "sandbox" in heartbeat.capabilities: - if not _node_can_fit(heartbeat, resources, routes): - continue - candidates.append(heartbeat) - return sorted( - candidates, - key=lambda heartbeat: ( - 0 if "sandbox" in heartbeat.capabilities else 1, - -heartbeat.free_resources.disk_mb, - -heartbeat.free_resources.memory_mb, - -heartbeat.free_resources.vcpu, - heartbeat.node_id, - ), + return self.services.builds.image_cache_candidates( + self, + resources=resources, + sandbox_nodes_only=sandbox_nodes_only, ) def _select_builder_node( self, *, image_id: str = "", reserve: bool = False, ) -> NodeHeartbeat | None: - candidates = [ - heartbeat - for heartbeat in self.services.fleet.ready_heartbeats() - if "image-build" in heartbeat.capabilities - and "sandbox" not in heartbeat.capabilities - ] - if not candidates: - return None - with _BUILDER_DISPATCH_GUARD: - live_ids = {h.job_id for h in candidates} - for job_id in list(_BUILDER_DISPATCH_COUNTS): - if job_id not in live_ids and not _BUILDER_DISPATCH_INFLIGHT.get(job_id): - _BUILDER_DISPATCH_COUNTS.pop(job_id, None) - _BUILDER_DISPATCH_INFLIGHT.pop(job_id, None) - baseline = { - h.job_id: _BUILDER_DISPATCH_COUNTS.get(h.job_id, 0) - - _BUILDER_DISPATCH_INFLIGHT.get(h.job_id, 0) - for h in candidates - } - # A retry must reach the active build's owner even when that node is - # busier than its peers. Probe before balancing new work so node-local - # build deduplication and conflicting-spec checks still apply. - if image_id: - for heartbeat in candidates: - response = self._proxy_request( - heartbeat.node_url or "", - f"/v1/images/builds/{quote(image_id, safe='')}", - method="GET", - timeout_seconds=NODE_RECONCILE_PROXY_TIMEOUT_SECONDS, - ) - if response.status == HTTPStatus.NOT_FOUND: - continue - if response.status != HTTPStatus.OK: - return None - build = response.json().get("build") - if not isinstance(build, dict) or build.get("status") not in { - "running", - "succeeded", - "failed", - }: - return None - if (build["status"] == "running" - or build.get("admission_phase") in {"preparing_solving", "finishing"}): - # Joining/conflicting with an existing build is allowed - # even at capacity, including terminal cleanup ownership; - # only new work needs another slot. - return _reserve_builder_candidate( - [heartbeat], baseline, reserve=reserve, allow_full=True, - ) - # Periodic heartbeats can lag an entire burst, including on a one-node - # pool. Keep new work pending at the gateway until a live slot exists; - # accepted local queues otherwise strand work when peers become free. - refreshed = [] - for heartbeat in candidates: - response = self._proxy_request( - heartbeat.node_url or "", - "/v1/heartbeat", - method="GET", - timeout_seconds=NODE_RECONCILE_PROXY_TIMEOUT_SECONDS, - ) - raw = response.json().get("heartbeat") - if response.status != HTTPStatus.OK or not isinstance(raw, dict): - continue - try: - current = heartbeat_from_dict(raw) - except (ValueError, TypeError): - continue - if ( - current is None - or current.job_id != heartbeat.job_id - or current.node_id != heartbeat.node_id - or current.deployment_id != heartbeat.deployment_id - or current.node_epoch != heartbeat.node_epoch - or current.draining - or not current.admission_open - ): - continue - # Keep gateway-owned metadata (for example quarantine labels), - # but take this scheduling hint from the same live sample as the - # admitted count. A response without it closes admission. - labels = dict(heartbeat.labels) - labels.pop(BUILD_ADMISSION_CAPACITY_LABEL, None) - if BUILD_ADMISSION_CAPACITY_LABEL in current.labels: - labels[BUILD_ADMISSION_CAPACITY_LABEL] = current.labels[ - BUILD_ADMISSION_CAPACITY_LABEL - ] - refreshed.append( - replace( - heartbeat, - active_image_builds=current.active_image_builds, - physical_disk_free_mb=current.physical_disk_free_mb, - labels=labels, - ) - ) - return _reserve_builder_candidate(refreshed, baseline, reserve=reserve) + return self.services.builds.select_builder_node( + self, image_id=image_id, reserve=reserve + ) def _nodes_with_image( self, @@ -5034,40 +2585,14 @@ def _nodes_with_image( use_heartbeat_cache: bool = True, probe_uncached: bool = True, ) -> set[str]: - if not image.strip() and not image_id.strip(): - return set() - node_ids = ( - self.services.fleet.nodes_with_cached_image(image, heartbeats, image_id=image_id) - if use_heartbeat_cache else set() - ) - uncached = [ - heartbeat for heartbeat in heartbeats - if not (use_heartbeat_cache and heartbeat.cached_images_known) - ] - if not probe_uncached or not uncached: - return node_ids - # Only workers whose heartbeat cache is unknown cost a node RPC. - image_keys = _requested_image_cache_keys( - image, image_id, require_digest=self.services.registry_refs.requires_digest_identity(image), + return self.services.builds.nodes_with_image( + self, + image, + heartbeats, + image_id=image_id, + use_heartbeat_cache=use_heartbeat_cache, + probe_uncached=probe_uncached, ) - for heartbeat in uncached: - response = self._proxy_request( - heartbeat.node_url or "", - "/v1/images", - method="GET", - ) - if response.status >= 400: - continue - raw_images = response.json().get("images") - if not isinstance(raw_images, list): - continue - for record in raw_images: - if not isinstance(record, dict): - continue - if image_keys.intersection(_image_record_cache_keys(record)): - node_ids.add(heartbeat.node_id) - break - return node_ids def _node_has_image( self, @@ -5077,20 +2602,13 @@ def _node_has_image( image_id: str = "", use_heartbeat_cache: bool = True, ) -> bool: - if not image.strip() and not image_id.strip(): - return False - image_keys = _requested_image_cache_keys( - image, - image_id, - require_digest=self.services.registry_refs.requires_digest_identity(image), - ) - if use_heartbeat_cache and heartbeat.cached_images_known: - return bool(image_keys.intersection(heartbeat.cached_images)) - return heartbeat.node_id in self._nodes_with_image( + return self.services.builds.node_has_image( + self, + heartbeat, image, - [heartbeat], image_id=image_id, use_heartbeat_cache=use_heartbeat_cache, + nodes_with_image=self._nodes_with_image, ) def _ensure_image_for_create( @@ -5100,7 +2618,7 @@ def _ensure_image_for_create( # The create attaches its pinned chunk-store root itself. The node's # pull would resolve the annotation, the released old root (M2 §3.3). return None - if not image.strip() or _heartbeat_has_image( + if not image.strip() or heartbeat_has_image( heartbeat, image, require_digest=self.services.registry_refs.requires_digest_identity(image), @@ -5112,7 +2630,7 @@ def pull() -> ProxiedResponse | None: # registry image independently of that route's lifetime. self.services.registry_refs.ensure_image_lease( image, - _registry_operation_lease_owner("create-image-pull", key), + registry_operation_lease_owner("create-image-pull", key), touch=True, ) return self._ensure_image_on_node(heartbeat, image, environment_root) @@ -5132,13 +2650,14 @@ def _ensure_image_on_node( image: str, environment_root: str | None = None, ) -> ProxiedResponse | None: - node_url = heartbeat.node_url or "" - if not image.strip() or self._node_has_image(heartbeat, image): - return None - with _image_pull_lock(node_url, image): - if self._node_has_image(heartbeat, image, use_heartbeat_cache=False): - return None - return self._pull_image_on_node(heartbeat, image, environment_root=environment_root) + return self.services.builds.ensure_image_on_node( + self, + heartbeat, + image, + environment_root, + node_has_image=self._node_has_image, + pull_image=self._pull_image_on_node, + ) def _warm_image_on_ready_nodes( self, @@ -5149,61 +2668,16 @@ def _warm_image_on_ready_nodes( sandbox_nodes_only: bool, image_id: str = "", ) -> dict[str, Any]: - image = image.strip() - image_id = image_id.strip() - requested = max(1, count) - candidates = self._image_cache_candidates( + return self.services.builds.warm_image_on_ready_nodes( + self, + image, + count=count, resources=resources, sandbox_nodes_only=sandbox_nodes_only, + image_id=image_id, + node_has_image=self._node_has_image, + pull_image=self._pull_image_on_node, ) - cache_hits: list[dict[str, Any]] = [] - pulled: list[dict[str, Any]] = [] - failed: list[dict[str, Any]] = [] - selected_image: dict[str, Any] | None = None - for heartbeat in candidates: - if len(cache_hits) + len(pulled) >= requested: - break - if self._node_has_image(heartbeat, image, image_id=image_id): - hit = { - "node": _node_metadata(heartbeat), - "image": { - "id": image_id or image_id_from_tag(image), - "tag": image, - }, - } - cache_hits.append(hit) - selected_image = selected_image or hit["image"] - continue - response = self._pull_image_on_node(heartbeat, image, image_id=image_id) - payload = response.json() - raw_image = payload.get("image") - image_record = ( - dict(raw_image) - if isinstance(raw_image, dict) - else {"id": image_id or image_id_from_tag(image), "tag": image} - ) - item = { - "node": _node_metadata(heartbeat), - "status": int(response.status), - "image": image_record, - } - if 200 <= response.status < 300: - pulled.append(item) - selected_image = selected_image or image_record - else: - item["error"] = payload.get("error") or payload - failed.append(item) - ready = len(cache_hits) + len(pulled) - return { - "image": selected_image - or {"id": image_id or image_id_from_tag(image), "tag": image}, - "image_ref": image, - "requested": requested, - "ready": ready, - "cache_hits": cache_hits, - "pulled": pulled, - "failed": failed, - } def _pull_image_on_node( self, @@ -5213,34 +2687,14 @@ def _pull_image_on_node( image_id: str = "", environment_root: str | None = None, ) -> ProxiedResponse: - payload: dict[str, Any] = {"image": image} - if image_id: - payload["id"] = image_id - # Chunk store M2: the worker attaches the root a create pins, else a - # mapped image's dispatched one; a released image may have no manifest - # (plan §5.4). Older workers ignore the field. - environment_root = environment_root or self._dispatched_root(image) - if environment_root: - payload["environment_root"] = environment_root - response: ProxiedResponse | None = None - for attempt in range(IMAGE_PULL_RETRY_ATTEMPTS): - response = self._proxy_request( - heartbeat.node_url or "", - "/v1/images/pull", - method="POST", - body=json.dumps(payload).encode("utf-8"), - timeout_seconds=IMAGE_PULL_PROXY_TIMEOUT_SECONDS, - ) - if not _retryable_image_pull_response(response): - if 200 <= response.status < 300: - self.services.images.invalidate_inventory() - return response - if attempt + 1 < IMAGE_PULL_RETRY_ATTEMPTS: - time.sleep(IMAGE_PULL_RETRY_BASE_DELAY_SECONDS * (2**attempt)) - assert response is not None - if 200 <= response.status < 300: - self.services.images.invalidate_inventory() - return response + return self.services.builds.pull_image_on_node( + self, + heartbeat, + image, + image_id=image_id, + environment_root=environment_root, + dispatched_root=self._dispatched_root, + ) def _dispatched_root(self, image: str) -> str | None: if not self.dispatch_environment_roots: @@ -5307,32 +2761,32 @@ def _stream_proxy_request( ) except error.HTTPError as exc: try: - response_body = _read_bounded_proxy_body( + response_body = read_bounded_proxy_body( exc, max_bytes=DEFAULT_MAX_PROXY_ERROR_BYTES, ) except ProxyResponseTooLargeError: - proxied_error = _proxy_response_too_large(DEFAULT_MAX_PROXY_ERROR_BYTES) + proxied_error = proxy_response_too_large(DEFAULT_MAX_PROXY_ERROR_BYTES) else: proxied_error = ProxiedResponse(exc.code, exc.headers, response_body) self._send_proxied_response(proxied_error) return except error.URLError as exc: - self._send_proxied_response(_node_transport_error_response(exc.reason)) + self._send_proxied_response(node_transport_error_response(exc.reason)) return except OSError as exc: - self._send_proxied_response(_node_transport_error_response(exc)) + self._send_proxied_response(node_transport_error_response(exc)) return with response: if response.status >= 400: try: - response_body = _read_bounded_proxy_body( + response_body = read_bounded_proxy_body( response, max_bytes=DEFAULT_MAX_PROXY_ERROR_BYTES, ) except ProxyResponseTooLargeError: - proxied_error = _proxy_response_too_large( + proxied_error = proxy_response_too_large( DEFAULT_MAX_PROXY_ERROR_BYTES ) else: @@ -5344,7 +2798,7 @@ def _stream_proxy_request( self._send_proxied_response(proxied_error) return try: - content_length = _proxy_content_length(response.headers) + content_length = proxy_content_length(response.headers) except ValueError as exc: self._write_json( {"error": f"invalid upstream node response: {exc}"}, @@ -5368,7 +2822,7 @@ def _send_proxied_response( *, extra_headers: dict[str, str] | None = None, ) -> None: - structured_error = _structured_proxy_error(response) + structured_error = structured_proxy_error(response) if structured_error is not None: self._write_json(structured_error, status=response.status) return @@ -5418,10 +2872,10 @@ def _copy_streaming_response_headers( self.send_header("Content-Length", str(content_length)) def _check_authorized(self) -> bool: - if _token_matches(self.headers, self.gateway_bearer_token, allow_ucloud_sandbox_header=True): + if token_matches(self.headers, self.gateway_bearer_token, allow_ucloud_sandbox_header=True): return True - if _token_matches(self.headers, self.sandbox_api_token, allow_ucloud_sandbox_header=True): - if _is_sdk_api_request(self.command, urlparse(self.path).path): + if token_matches(self.headers, self.sandbox_api_token, allow_ucloud_sandbox_header=True): + if is_sdk_api_request(self.command, urlparse(self.path).path): return True self._write_json( {"error": "sandbox API key is not authorized for this endpoint"}, @@ -5431,7 +2885,7 @@ def _check_authorized(self) -> bool: return self._write_unauthorized() def _check_heartbeat_authorized(self) -> bool: - if _token_matches(self.headers, self.heartbeat_bearer_token, allow_ucloud_sandbox_header=False): + if token_matches(self.headers, self.heartbeat_bearer_token, allow_ucloud_sandbox_header=False): return True return self._write_unauthorized() @@ -5578,21 +3032,13 @@ class BoundHandler(ControlPlaneHandler): BoundHandler.heartbeat_bearer_token = heartbeat_bearer_token BoundHandler.node_control_bearer_token = node_control_bearer_token BoundHandler.image_manager = image_manager - BoundHandler.image_build_owners = OrderedDict() - BoundHandler.image_build_metrics_seen = OrderedDict() - BoundHandler.image_build_owners_lock = RLock() + BoundHandler.runtime_state = GatewayRuntimeState() BoundHandler.build_context_store = build_context_store from .prepared_images import PreparedImageCatalog, catalog_path BoundHandler.prepared_image_catalog = PreparedImageCatalog(catalog_path(image_file)) BoundHandler.base_regeneration = base_regeneration BoundHandler.metrics_store = metrics_store BoundHandler.build_history = build_history - BoundHandler.metrics_response_cache = None - BoundHandler.metrics_response_cache_at = 0.0 - BoundHandler.metrics_response_lock = RLock() - BoundHandler.fleet_response_lock = RLock() - BoundHandler.fleet_response_future = None - BoundHandler.fleet_status_futures = {} from .fleet_reader import FleetSnapshotReader fleet_reader = (FleetSnapshotReader(control_state_file, routing_file, heartbeat_ttl_seconds) if isolate_fleet_reads else None) @@ -5622,7 +3068,7 @@ class BoundHandler(ControlPlaneHandler): BoundHandler.sandbox_builds = SandboxBuilds( Spool(sandbox_builds["spool"]), catalog=BoundHandler.prepared_image_catalog, contexts=build_context_store, roots=dependency_resolver.image_roots, environments=environment_registry, - tag_for=lambda image_id: _managed_registry_build_tag(image_id, registry_worker_url or ""), + tag_for=lambda image_id: managed_registry_build_tag(image_id, registry_worker_url or ""), apt_proxy=sandbox_builds.get("apt_proxy")) from .gateway.image_recipes import ImageRecipeStore, recipes_path BoundHandler.image_recipes = ImageRecipeStore(recipes_path(image_file)) @@ -5672,7 +3118,7 @@ class BoundHandler(ControlPlaneHandler): BoundHandler.telemetry = resolved_telemetry from .gateway_response_proxy import AsyncGatewayResponses async_responses = (AsyncGatewayResponses( - response_policy=_async_proxy_response, + response_policy=async_proxy_response, response_limit=node_rpc.DEFAULT_MAX_PROXY_RESPONSE_BYTES, timeout=DEFAULT_PROXY_TIMEOUT_SECONDS, connect_timeout=NODE_CONNECT_TIMEOUT_SECONDS, @@ -5852,63 +3298,6 @@ def _sandbox_list_bytes(store, routing_store, heartbeat_ttl_seconds, *, renderer ) -def _migration_runtime_capability( - route: SandboxRoute, owner: NodeHeartbeat | None, -) -> str | None: - """Use the same immutable runtime identity that import already validates. - - A detached checkpoint retains this identity without its former worker. - Only an attached, pre-capability Docker source keeps legacy eligibility. - Runtime fingerprints deliberately exclude node-local paths and addresses. - """ - if route.storage_snapshot: - snapshot = _portable_snapshot_for_route(route) - return RUNTIME_COMPATIBILITY_CAPABILITY_PREFIX + snapshot.manifest.runtime.node_compatibility_sha256 - if route.worker_state != "attached" or owner is None: - raise ValueError("migration source runtime is unavailable") - advertised = [value for value in owner.capabilities - if value.startswith(RUNTIME_COMPATIBILITY_CAPABILITY_PREFIX)] - if advertised: - if len(advertised) != 1 or not re.fullmatch( - r"[0-9a-f]{64}", advertised[0][len(RUNTIME_COMPATIBILITY_CAPABILITY_PREFIX):], - ): - raise ValueError("migration source advertises an invalid runtime") - return advertised[0] - if HOST_EROFS_CAPABILITY in owner.capabilities: - raise ValueError("immutable environment source lacks its runtime identity") - return None - - -def _migration_cpu_capability( - route: SandboxRoute, owner: NodeHeartbeat | None, -) -> str | None: - """The CPU feature identity a destination's import will require, if known.""" - - if route.storage_snapshot: - try: - snapshot = _portable_snapshot_for_route(route) - except ValueError: - return None - return RUNTIME_CPU_CAPABILITY_PREFIX + snapshot.manifest.runtime.cpu_features_sha256 - if owner is None: - return None - advertised = [value for value in owner.capabilities - if value.startswith(RUNTIME_CPU_CAPABILITY_PREFIX)] - return advertised[0] if len(advertised) == 1 else None - - -def _cpu_compatible(destination: NodeHeartbeat, required: str | None) -> bool: - # Workers that predate the CPU capability stay eligible; their import - # still validates the full fingerprint. - if required is None: - return True - advertised = [value for value in destination.capabilities - if value.startswith(RUNTIME_CPU_CAPABILITY_PREFIX)] - return not advertised or required in advertised - - - - def _sandbox_record_is_ready( record: dict[str, Any], ) -> bool: @@ -5930,7 +3319,7 @@ def _enrich_sandbox_record( heartbeat: NodeHeartbeat, ) -> dict[str, Any]: enriched = dict(record) - enriched["node"] = _node_metadata(heartbeat) + enriched["node"] = node_metadata(heartbeat) return enriched @@ -5986,7 +3375,7 @@ def _route_only_sandbox_record( if image: record["image"] = image if heartbeat is not None: - node = _node_metadata(heartbeat) + node = node_metadata(heartbeat) node["fresh"] = node_fresh node["attached"] = route.worker_state == "attached" record["node"] = node @@ -5994,80 +3383,6 @@ def _route_only_sandbox_record( -def _reserve_builder_candidate( - candidates: list[NodeHeartbeat], baseline: dict[str, int], *, reserve: bool, - allow_full: bool = False, -) -> NodeHeartbeat | None: - # Account for dispatches committed since the live-load sample began, even - # if their HTTP response already returned. A stale simultaneous sample - # must not make every request choose the same previously idle builder. - with _BUILDER_DISPATCH_GUARD: - def load(heartbeat: NodeHeartbeat): - additions = ( - _BUILDER_DISPATCH_COUNTS.get(heartbeat.job_id, 0) - - baseline.get(heartbeat.job_id, 0) - if reserve else 0 - ) - return heartbeat.active_image_builds + max(0, additions) - - eligible = [heartbeat for heartbeat in candidates - if allow_full or load(heartbeat) < build_admission_capacity(heartbeat.labels)] - if not eligible: - return None - - def rank(heartbeat: NodeHeartbeat): - # Pipeline admission includes solves waiting for publication; it - # is a hard safety ceiling, not a throughput target. Consolidate - # a trickle up to two builds, then use idle peers before queuing - # more output behind the two publication workers. Once every - # peer has work, prefer the least loaded. Dispatch reservations - # count here as well, so a simultaneous burst cannot defeat spreading. - active = load(heartbeat) - saturated = active >= 2 - return ( - int(saturated), - active if saturated else -active, - consolidation_rank(heartbeat), - -heartbeat.physical_disk_free_mb, - heartbeat.node_id, - ) - selected = min(eligible, key=rank) - if reserve: - job_id = selected.job_id - _BUILDER_DISPATCH_COUNTS[job_id] = _BUILDER_DISPATCH_COUNTS.get(job_id, 0) + 1 - _BUILDER_DISPATCH_INFLIGHT[job_id] = _BUILDER_DISPATCH_INFLIGHT.get(job_id, 0) + 1 - return selected - - -def _builder_image_dispatch_lock(image_id: str): - """Serialize one image submission across every gateway process on the host. - - The running-build probe, builder choice and dispatch must be one step, or - two processes both see "not running" and push the same managed tag. - """ - return HOST_LOCKS.hold("image-dispatch", image_id.strip()) - - -def _image_pull_lock(node_url: str, image: str) -> RLock: - key = (node_url.rstrip("/"), image) - with _IMAGE_PULL_LOCKS_GUARD: - lock = _IMAGE_PULL_LOCKS.get(key) - if lock is None: - lock = RLock() - _IMAGE_PULL_LOCKS[key] = lock - return lock - - -def _migration_operation_lock(migration_id: str): - """Serialize one migration's worker export and stage calls across processes. - - Phase commits are compare-and-set in PostgreSQL, but the worker calls between - them are not; the public gateways and the placement worker all advance - migrations. - """ - return HOST_LOCKS.hold("migration", migration_id.strip()) - - def _worker_delete(node_token: str, telemetry: Telemetry): """The fenced worker DELETE a gateway issues on its own, outside a request.""" @@ -6089,70 +3404,4 @@ def delete(node_url: str, sandbox_id: str, generation: int, operation_id: str): return delete -def _image_record_cache_keys(record: dict[str, Any]) -> set[str]: - tag = str(record.get("tag") or "") - image_id = str(record.get("id") or "") - digest = normalize_manifest_digest(str(record.get("manifest_digest") or "")) - digest_ref = canonical_image_digest_ref(tag, digest) - keys = {item for item in (tag, image_id, digest_ref) if item} - return keys - - -def _retryable_image_pull_response(response: ProxiedResponse) -> bool: - if response.status != HTTPStatus.SERVICE_UNAVAILABLE: - return False - payload = response.json() - return bool( - payload.get("retryable") is True - and payload.get("error_code") == "image_pull_failed" - ) - - -def _precise_elapsed_ms(started: float) -> float: - return round(max(0.0, (time.monotonic() - started) * 1000), 3) - - -@dataclass(frozen=True) -class _BuildDispatch: - """One build dispatch's answer: a proxied builder response, or a JSON one.""" - status: int - payload: dict[str, Any] | None = None - headers: dict[str, str] | None = None - response: ProxiedResponse | None = None - - -def _image_build_response_terminal(payload: dict[str, Any]) -> bool: - build = payload.get("build") - if not isinstance(build, dict): - return "image" in payload - return str(build.get("status") or "").lower() in {"succeeded", "failed"} - - -def lifecycle_node_payload(generation: int, action: str, payload: dict[str, Any]) -> dict[str, Any]: - """The worker's body for a parsed park or wake request on this route generation.""" - node_payload: dict[str, Any] = {"operation_id": str(payload["operation_id"]).strip()} - if payload.get("durable_lifecycle"): - node_payload["relay_request_id"] = payload["request_id"] - node_payload["generation"] = generation - if action == "wake": - node_payload["generation"] = generation - elif "background" in payload: - if not isinstance(payload["background"], bool): - raise ValueError("park background must be a boolean") - node_payload["background"] = payload["background"] - return node_payload - - -def _lifecycle_proxy_error(response: ProxiedResponse) -> str: - detail = "" - try: - payload = response.json() - if isinstance(payload, dict): - detail = str(payload.get("error") or "").strip() - except (TypeError, ValueError, json.JSONDecodeError): - pass - if not detail: - detail = response.body[:500].decode("utf-8", errors="replace").strip() - prefix = f"HTTP {int(response.status)}" - return f"{prefix}: {detail}" if detail else prefix diff --git a/sandboxes/create_handoff.py b/sandboxes/create_handoff.py index 18bd253c..9bb6c838 100644 --- a/sandboxes/create_handoff.py +++ b/sandboxes/create_handoff.py @@ -253,7 +253,8 @@ def admission_config(service: Any, *, rust_admission_enabled: bool) -> dict[str, def create_config(service: Any, *, node_epoch: str, exec_sessions: Any = None, - rust_admission_enabled: bool = False) -> dict[str, Any]: + rust_admission_enabled: bool = False, + max_file_body_bytes: int | None = None) -> dict[str, Any]: """The agent's effective create configuration, read from the assembled node. Python stays the single source of truth for flags and assembly checks; @@ -310,7 +311,6 @@ def path(value): "split_memory_backing": backing is not None, "memory_backing_hard_capacity_bytes": backing.hard_capacity_bytes if backing is not None else 0, "application_memory_root": path(getattr(config, "application_memory_root", None)), - "reflink_memory_restore": bool(getattr(config, "reflink_memory_restore", False)), "workspace_initial_grant_mb": policy.workspace_grant_mb, "demonstrated_memory": policy.demonstrated_memory, "init_binary": path(provisioner.oci.init_binary), @@ -338,4 +338,5 @@ def path(value): }, "pause": pause_config(service), "admission": admission_config(service, rust_admission_enabled=rust_admission_enabled), + "max_file_body_bytes": (256 * 1024 * 1024 if max_file_body_bytes is None else int(max_file_body_bytes)), } diff --git a/sandboxes/direct_provisioner.py b/sandboxes/direct_provisioner.py index 26c324c0..ea2bdb5b 100644 --- a/sandboxes/direct_provisioner.py +++ b/sandboxes/direct_provisioner.py @@ -930,8 +930,6 @@ def _drop_memory_backing(self, registration: DirectSandboxRegistration) -> None: self.warden.memory_backing.delete(registration.memory_reference, sandbox_id=registration.sandbox_id, sandbox_generation=registration.sandbox_generation) - if registration.has_direct_sandbox and getattr(self.warden, "memory_capacity", None) is not None: - self.warden.release_deleted_memory_capacity(registration.to_direct_sandbox()) def _require_storage_record( self, diff --git a/sandboxes/direct_runtime.py b/sandboxes/direct_runtime.py index 8c3feb40..e6128f50 100644 --- a/sandboxes/direct_runtime.py +++ b/sandboxes/direct_runtime.py @@ -22,7 +22,6 @@ installed_sidecar_fingerprints, require_capture_barrier_runtime, require_ram_backing_runtime, - require_reflink_restore_runtime, ) from .environment_backend import EnvironmentBackendClient from .environment_rootfs import EnvironmentRootfsStore @@ -48,7 +47,6 @@ def build_direct_runtime_service( idle_park_seconds: float = 0.0, storage_native_socket: Path, memory_backing_hard_capacity_bytes: int, - reflink_memory_restore: bool = False, workspace_initial_grant_mb: int = 0, application_memory_root: Path | None = None, checkpoint_registry_url: str = "", @@ -96,15 +94,11 @@ def build_direct_runtime_service( resolved_image_cache_root = image_cache_root or state_root / "image-cache" resolved_image_cache_root.mkdir(mode=0o700, parents=True, exist_ok=True) volume_mount_root.mkdir(mode=0o700, parents=True, exist_ok=True) - if not isinstance(reflink_memory_restore, bool): - raise ValueError("reflink_memory_restore must be a boolean") if memory_backing_hard_capacity_bytes <= 0: raise ValueError( "split memory backing requires the shared physical disk budget" ) - if reflink_memory_restore: - require_reflink_restore_runtime(runsc, runsc_commit) - elif application_memory_root is None: + if application_memory_root is None: require_capture_barrier_runtime(runsc, runsc_commit) else: require_ram_backing_runtime(runsc, runsc_commit) @@ -115,7 +109,7 @@ def build_direct_runtime_service( runsc_digest = _sha256_file(runsc) boot_digest = boot_config_sha256( runsc, runsc_commit, network=network, - reflink_memory_restore=reflink_memory_restore, ram_backing=application_memory_root is not None, + ram_backing=application_memory_root is not None, ) fingerprint = HibernationRuntimeFingerprint( runsc_sha256=runsc_digest, @@ -157,10 +151,6 @@ def build_direct_runtime_service( hard_disk_capacity_mb=memory_backing_hard_capacity_bytes // (1024 * 1024), cached_reads=True, ) - if not reflink_memory_restore and registry.reflink_overlap_bytes(): - # A crash may leave a global reservation before the allocator writes - # its retention row. Keep the cleanup-capable reader until it drains. - raise ValueError("reflink restore reader is required until overlap capacity drains") storage_client = StorageNativeNodeClient( storage_native_socket, telemetry=telemetry, @@ -199,7 +189,6 @@ def build_direct_runtime_service( runtime_root=state_root / "runsc", memory_root=volume_mount_root, application_memory_root=application_memory_root, - reflink_memory_restore=reflink_memory_restore, bundle_root=state_root / "bundles", journal_root=state_root / "journals", runtime_fingerprint=fingerprint, @@ -207,7 +196,6 @@ def build_direct_runtime_service( ), storage=storage_client, memory_backing=memory_backing, - memory_capacity=registry if reflink_memory_restore else None, disk_capacity=registry, rootfs_lifecycle=overlays, telemetry=telemetry, @@ -223,12 +211,9 @@ def build_direct_runtime_service( warden=warden, network_manager=network_manager, checkpoint_store=checkpoint_store, - # docs/architecture.md: claims follow demonstrated usage. Reflink - # restore turns owners file-backed at their first park, so their - # memory keeps the formula claim. disk_claim_policy=DiskClaimPolicy( workspace_grant_mb=workspace_initial_grant_mb, - demonstrated_memory=application_memory_root is not None and not reflink_memory_restore, + demonstrated_memory=application_memory_root is not None, ), ) return DirectSandboxService( @@ -241,7 +226,7 @@ def build_direct_runtime_service( def boot_config_sha256(runsc: Path, runsc_commit: str, *, network: str, - reflink_memory_restore: bool, ram_backing: bool) -> str: + ram_backing: bool) -> str: """The boot configuration a node's checkpoints bind (runtime fingerprint).""" boot_settings: dict[str, object] = { "network": network, @@ -249,11 +234,7 @@ def boot_config_sha256(runsc: Path, runsc_commit: str, *, network: str, "rootfs_format": "ucloud-host-erofs-environment-v1", "quota_layout": "split-memory-v3", } - if reflink_memory_restore: - # This is the portable reader capability. Fresh RAM/file placement and - # a particular owner's later restore mode never change checkpoint ABI. - boot_settings["application_memory_backend"] = "reflink-restore-v1" - elif ram_backing: + if ram_backing: boot_settings["application_memory_backend"] = "ram-sparse-capture-v1" # Bind checkpoints to every executable that can implement their kernel # and restore operations. diff --git a/sandboxes/direct_service.py b/sandboxes/direct_service.py index fd688f61..05471ef9 100644 --- a/sandboxes/direct_service.py +++ b/sandboxes/direct_service.py @@ -672,12 +672,6 @@ def _deletion_reconciliation_loop(self) -> None: exc, ) continue - try: - # Existing overlap claims are the durable worklist. Physical - # trim stays off foreground wake and holds no lifecycle lock. - self.warden.reconcile_retired_memory_capacity() - except Exception as exc: - _LOG.warning("could not retire restored memory capacity: %s", exc) try: self.warden.settle_idle_memory_claims() except Exception as exc: @@ -1951,10 +1945,6 @@ def admit_managed_continuation(self, sandbox_id, generation, request_id): current = self._require_registration(sandbox_id) if current.sandbox_generation != generation: raise SandboxConflictError("managed continuation lost incarnation") - sandbox = current.to_direct_sandbox() - lifecycle = self.warden.inspect(sandbox) - if lifecycle is not None and lifecycle.state == HibernationState.PARKED: - self.warden.prepare_restore_memory(sandbox) # A capacity refusal is a SandboxStartupBusyError: nothing has been # acknowledged or restored yet. self.admission.continuation(registration, request_id) @@ -2627,7 +2617,6 @@ def _restore_admission(self, sandbox_id: str, generation: int, requested: Resour registration = self._require_registration(sandbox_id) if registration.sandbox_generation != generation: raise DirectWardenError("queued restore generation lost incarnation ownership") - self.warden.prepare_restore_memory(registration.to_direct_sandbox()) cost = self._restore_cost(sandbox_id, generation, requested) initial = self.warden.inspect(self._require_registration(sandbox_id).to_direct_sandbox()) deadline = time.monotonic() + self.admission_wait_seconds diff --git a/sandboxes/direct_warden.py b/sandboxes/direct_warden.py index ff1bd28b..1a2be1fc 100644 --- a/sandboxes/direct_warden.py +++ b/sandboxes/direct_warden.py @@ -1,7 +1,7 @@ from __future__ import annotations from .checkpoint_components import MemoryBackingRef, WorkspaceCaptureRef -from .memory_backing import MemoryBackingStore, RetainedCheckpointRef +from .memory_backing import MemoryBackingStore from contextlib import contextmanager from dataclasses import dataclass, replace @@ -319,7 +319,6 @@ class DirectRunscWardenConfig: journal_root: Path runtime_fingerprint: HibernationRuntimeFingerprint application_memory_root: Path | None = None - reflink_memory_restore: bool = False proc_root: Path = Path("/proc") network: str = "none" command_timeout_seconds: float = 60.0 @@ -448,10 +447,6 @@ def __init__( self.storage = storage self.memory_backing = memory_backing self.memory_capacity = memory_capacity - if config.reflink_memory_restore and (memory_backing is None or memory_capacity is None): - raise ValueError("reflink memory restore requires quota-owned split backing and capacity ledger") - if memory_backing is not None: - memory_backing.configure_reflink_restore(config.reflink_memory_restore) self.rootfs_lifecycle = rootfs_lifecycle self.telemetry = telemetry or Telemetry.disabled("direct-runsc-warden") self.journals = HibernationJournalStore(config.journal_root) @@ -790,7 +785,6 @@ def adopt_parked( self._best_effort_delete(sandbox) parked = journal.initialize_parked(published) self._persist_parked_manifest(sandbox, published) - self._prepare_restore_memory(sandbox) return parked def park( @@ -904,7 +898,6 @@ def park( operation_id=operation_id, expected_revision=pending.revision, ) - self._prepare_restore_memory(sandbox) self._settle_capture_space(sandbox, reserved) return parked except Exception: @@ -917,28 +910,6 @@ def park( finally: handle.close() - def prepare_restore_memory(self, sandbox: DirectSandbox) -> None: - """Select parked placement before service admission quotes its cost. - - This does not launch a candidate or grant execution authority. Repeating - it after import/recovery is safe; a live owner can never change roots. - """ - if not self.config.reflink_memory_restore: - return - with self._locked(sandbox): - self._require_state(sandbox, HibernationState.PARKED) - self._prepare_restore_memory(sandbox) - - def _prepare_restore_memory(self, sandbox: DirectSandbox) -> None: - if not self.config.reflink_memory_restore: - return - if sandbox.memory is None or self.memory_backing is None: - raise DirectWardenError("reflink restore requires an owned memory allocation") - self.memory_backing.prepare_file_restore( - sandbox.memory, sandbox_id=sandbox.sandbox_id, - sandbox_generation=sandbox.sandbox_generation, - ) - def resume( self, sandbox: DirectSandbox, @@ -988,12 +959,6 @@ def resume( if before_restore is not None: before_restore() timings["join_network_prepare"] = (time.monotonic() - preparation_phase) * 1000 - preparation_phase = time.monotonic() - self._prepare_restore_memory(sandbox) - timings["prepare_memory"] = (time.monotonic() - preparation_phase) * 1000 - preparation_phase = time.monotonic() - self._retain_restore_source(sandbox, manifest) - timings["retain_source"] = (time.monotonic() - preparation_phase) * 1000 except Exception: self._rollback_parked_storage_mount( sandbox, @@ -1186,7 +1151,6 @@ def reconcile(self, sandbox: DirectSandbox) -> HibernationRecord: sandbox, operation_seed=f"reconcile:{parked.revision}", ) - self._prepare_restore_memory(sandbox) return parked if result.action == HibernationRecoveryAction.RESUME_OR_RETRY_HIBERNATE: @@ -1235,7 +1199,6 @@ def reconcile(self, sandbox: DirectSandbox) -> HibernationRecord: sandbox, operation_seed=f"reconcile:{record.revision}", ) - self._prepare_restore_memory(sandbox) return record def _quarantine_storage_error( @@ -1557,7 +1520,6 @@ def _rollback_restore( expected_revision=current.revision, candidate_reaped=True, ) - self._prepare_restore_memory(sandbox) return parked finally: if opened_candidate and candidate is not None: @@ -1593,164 +1555,19 @@ def _finalize_restore_artifacts( sandbox: DirectSandbox, manifest: HibernationManifest, ) -> None: - if self.config.reflink_memory_restore: - # RUNNING is durable. The overlap claim retains both immutable - # files and physical capacity until existing maintenance finishes. - # Even unlink/fsync can take seconds under storage pressure. - return with self.telemetry.span("sandbox.restore.artifact_unlink"): self.artifacts.delete_published( manifest, allow_consumed_main_memory=True, ) - if not self.config.reflink_memory_restore: - self._release_retired_memory_capacity(sandbox) self._queue_idle_memory(sandbox) - def _retain_restore_source( - self, sandbox: DirectSandbox, manifest: HibernationManifest, - ) -> None: - if not self.config.reflink_memory_restore: - return - if self.memory_capacity is None or self.memory_backing is None or sandbox.memory is None: - raise DirectWardenError("reflink restore capacity ownership is unavailable") - source = self.artifacts.generation_path( - sandbox_id=sandbox.sandbox_id, - sandbox_generation=sandbox.sandbox_generation, - hibernation_generation=manifest.hibernation_generation, - ) / _APPLICATION_MEMORY - info = source.lstat() - if not stat.S_ISREG(info.st_mode) or info.st_uid != os.geteuid(): - raise DirectWardenError("restore source is not an owned regular file") - # XFS enforces project quotas in filesystem blocks. Charge that exact - # rounded allocation, never the sparse logical heap length. - allocated = max(4096, ((info.st_blocks * 512 + 4095) // 4096) * 4096) - self.memory_capacity.reserve_reflink_overlap( - sandbox.sandbox_id, sandbox.sandbox_generation, - manifest.hibernation_generation, allocated, - manifest_sha256=manifest.metadata_sha256, - ) - self.memory_backing.retain_checkpoint( - sandbox.memory, sandbox_id=sandbox.sandbox_id, - sandbox_generation=sandbox.sandbox_generation, - hibernation_generation=manifest.hibernation_generation, - manifest_sha256=manifest.metadata_sha256, allocated_bytes=allocated, - ) - - def _release_retired_memory_capacity(self, sandbox: DirectSandbox) -> None: - if self.memory_capacity is None or sandbox.memory is None: - return - if self.memory_backing is None: - raise DirectWardenError("split memory allocator is unavailable") - for claim in self.memory_capacity.list_reflink_overlaps( - sandbox.sandbox_id, sandbox.sandbox_generation, - ): - if self.memory_backing.release_retained_checkpoint( - sandbox.memory, - hibernation_generation=claim.hibernation_generation, - manifest_sha256=claim.manifest_sha256, - ): - self.memory_capacity.release_reflink_overlap( - sandbox.sandbox_id, sandbox.sandbox_generation, - claim.hibernation_generation, - manifest_sha256=claim.manifest_sha256, - ) - - def release_deleted_memory_capacity(self, sandbox: DirectSandbox) -> None: - """Finish capacity cleanup after the allocator's successful deletion.""" - with self._locked(sandbox): - if self._journal(sandbox).load() is not None: - raise DirectWardenError("memory deletion still has lifecycle authority") - if sandbox.memory is not None and self.memory_backing is not None: - if os.path.lexists(self.memory_backing.root / sandbox.memory.allocation_id): - raise DirectWardenError("memory allocation still exists") - self._release_retired_memory_capacity(sandbox) - - def reconcile_retired_memory_capacity(self) -> int: - """Use durable overlap claims as the existing maintenance worklist.""" - if not self.config.reflink_memory_restore: - return 0 - if self.memory_capacity is None or self.memory_backing is None: - raise DirectWardenError("reflink restore capacity ownership is unavailable") - claims = self.memory_capacity.list_reflink_overlaps() - checkpoints = {} - registrations = {} - for claim in claims: - owner = (claim.sandbox_id, claim.sandbox_generation) - if owner not in registrations: - registrations[owner] = self.memory_capacity.get(claim.sandbox_id) - registration = registrations[owner] - if (registration is None or registration.sandbox_generation != claim.sandbox_generation - or registration.memory_reference is None): - raise DirectWardenError("retained checkpoint has no matching registry owner") - self._retire_restored_generation(registration, claim) - checkpoint = RetainedCheckpointRef(registration.memory_reference, - claim.hibernation_generation, claim.manifest_sha256) - checkpoints[checkpoint] = claim - - def release_claim(checkpoint): - claim = checkpoints[checkpoint] - self.memory_capacity.release_reflink_overlap( - claim.sandbox_id, claim.sandbox_generation, claim.hibernation_generation, - manifest_sha256=claim.manifest_sha256, - ) - - if not checkpoints: - return 0 - with self.telemetry.span("sandbox.memory.retire_physical", - attributes={"memory.retirement.candidates": len(checkpoints)}) as span: - released = self.memory_backing.release_retained_checkpoints( - checkpoints, release_claim=release_claim) - span.set_attribute("memory.retirement.released", released) - return released - - def _retire_restored_generation(self, registration, claim) -> None: - """Pin one allocation, prove its cutoff, then unlink outside lifecycle.""" - if registration.phase != "owned": - return # The ordinary deletion owner removes its entire allocation. - sandbox = registration.to_direct_sandbox() - with self.memory_backing.read_lease( - registration.memory_reference, sandbox_id=claim.sandbox_id, - sandbox_generation=claim.sandbox_generation, - ): - with self._locked(sandbox): - # The allocation lease prevents deletion/reimport while this - # exact immutable generation is touched. It does not block a - # later capture or retain the Warden lock during disk I/O. - current = self.memory_capacity.get(claim.sandbox_id) - if current != registration: - return - record = self._journal(sandbox).load() - if record is None or not ( - record.hibernation_generation > claim.hibernation_generation - or (record.hibernation_generation == claim.hibernation_generation - and record.state == HibernationState.RUNNING - and record.authority == HibernationAuthority.LIVE) - ): - return # Current PARKED/RESTORING source remains authoritative. - with self.telemetry.span("sandbox.restore.artifact_unlink", attributes={ - "sandbox.id": claim.sandbox_id, - "sandbox.generation": claim.sandbox_generation, - "hibernation.generation": claim.hibernation_generation, - "memory.retirement.background": True, - }): - self.artifacts.delete_retired_generation( - sandbox_id=claim.sandbox_id, - sandbox_generation=claim.sandbox_generation, - hibernation_generation=claim.hibernation_generation, - manifest_sha256=claim.manifest_sha256, - ) - def _cleanup_running_restore_artifacts( self, sandbox: DirectSandbox, record: HibernationRecord, ) -> None: """Finish ancillary cleanup after a crash past RUNNING commit.""" - if self.config.reflink_memory_restore: - # Claims survive restart and are the same maintenance worklist. - # Inspect/exec/reconcile must never join background artifact I/O. - return for item in self.artifacts.inventory_incarnation( sandbox_id=sandbox.sandbox_id, sandbox_generation=sandbox.sandbox_generation, @@ -1780,10 +1597,6 @@ def _cleanup_running_restore_artifacts( manifest, allow_consumed_main_memory=True, ) - # Artifact removal may have committed before a process crash, leaving - # only the capacity/project journals to finish. Inventory alone misses it. - if not self.config.reflink_memory_restore: - self._release_retired_memory_capacity(sandbox) def _manifest( self, @@ -2135,8 +1948,6 @@ def _common(self, sandbox: DirectSandbox) -> tuple[str, ...]: if ram else () ), - *(("--application-memory-reflink-restore=true",) - if self.config.reflink_memory_restore and not ram else ()), "--allow-connected-on-save=true", ) @@ -2728,7 +2539,6 @@ def _require_private_directory(path: Path, label: str) -> None: def _demonstrated_memory(self, sandbox: DirectSandbox) -> bool: return bool( self.config.application_memory_root is not None - and not self.config.reflink_memory_restore and sandbox.memory is not None and self.memory_backing is not None and self.disk_capacity is not None diff --git a/sandboxes/gateway/auth.py b/sandboxes/gateway/auth.py index 83d09cdb..43d78751 100644 --- a/sandboxes/gateway/auth.py +++ b/sandboxes/gateway/auth.py @@ -9,7 +9,7 @@ from ..http_contract import match_sandbox_http_route -def _token_matches(headers: Any, expected: str, *, allow_ucloud_sandbox_header: bool) -> bool: +def token_matches(headers: Any, expected: str, *, allow_ucloud_sandbox_header: bool) -> bool: authorization = headers.get("Authorization") or "" prefix = "Bearer " bearer = authorization[len(prefix) :] if authorization.startswith(prefix) else "" @@ -22,7 +22,7 @@ def _token_matches(headers: Any, expected: str, *, allow_ucloud_sandbox_header: return False -def _is_sdk_api_request(method: str, path: str) -> bool: +def is_sdk_api_request(method: str, path: str) -> bool: """Return whether the least-privileged public SDK key may use a route.""" method = method.upper() diff --git a/sandboxes/gateway/build_service.py b/sandboxes/gateway/build_service.py new file mode 100644 index 00000000..0a817aa2 --- /dev/null +++ b/sandboxes/gateway/build_service.py @@ -0,0 +1,1177 @@ +"""Gateway imperative shell for image builds, builder selection, and cache warming.""" + +from __future__ import annotations + +from dataclasses import dataclass +from http import HTTPStatus +import json +import sqlite3 +from threading import RLock +import time +from typing import Any, Callable, Protocol +from urllib.parse import quote + +from ..host_locks import HOST_LOCKS +from ..images import ImageManager, ImageRecord, image_id_from_tag, uploaded_build_context_reference +from ..metrics import MetricsStore +from ..models import NodeHeartbeat, ResourceQuantity +from ..registry import heartbeat_from_dict +from ..registry_disk import REGISTRY_DISK_RETRY_AFTER_SECONDS, registry_disk_pressure_payload +from ..routing import RoutingStore +from ..telemetry import Telemetry +from .base_regeneration import BaseRegenerating, BaseReleased +from .builds import ( + build_terminal_metrics_summary, + builder_owns_active_build, + image_build_payload_is_terminal, + image_build_response_is_terminal, + image_record_cache_keys, + is_builder_heartbeat, + merge_refreshed_builder_heartbeat, + normalize_build_spec, + parse_image_pull_request, + rank_image_cache_candidates, + retryable_image_pull_payload, + select_builder_candidate, + select_latest_build_record, +) +from .fleet import FleetView, node_metadata, requested_image_cache_keys +from .image_resolution import ImageResolution, image_record_available_to_sandboxes +from .node_rpc import ProxiedResponse +from .registry_refs import ( + RegistryImageReferenceUnavailable, + RegistryReferences, + registry_operation_lease_owner, +) + + +IMAGE_BUILD_PROXY_TIMEOUT_SECONDS = 30 * 60 +IMAGE_PULL_PROXY_TIMEOUT_SECONDS = 30 * 60 +IMAGE_PULL_RETRY_ATTEMPTS = 3 +IMAGE_PULL_RETRY_BASE_DELAY_SECONDS = 0.25 +BUILD_CONTEXT_PROBE_MIN_BYTES = 1024 * 1024 +NODE_RECONCILE_PROXY_TIMEOUT_SECONDS = 5 +IMAGE_BUILD_CANCEL_PROXY_TIMEOUT_SECONDS = 15 + + +class ImageBuildLookupUnavailableError(RuntimeError): + """A failed status observation cannot establish that a build is absent.""" + + def __init__(self, upstream_status: int = HTTPStatus.SERVICE_UNAVAILABLE) -> None: + super().__init__("image build status is temporarily unavailable") + self.status = ( + upstream_status + if upstream_status in {408, 429, 500, 502, 503, 504} + else HTTPStatus.BAD_GATEWAY + ) + + +@dataclass(frozen=True) +class BuildDispatch: + """One build dispatch's answer: a proxied builder response, or a JSON one.""" + + status: int + payload: dict[str, Any] | None = None + headers: dict[str, str] | None = None + response: ProxiedResponse | None = None + + +class BuilderDispatchTracker: + """Per-process reservation counters preventing simultaneous bursts from piling on one builder.""" + + def __init__(self) -> None: + self._guard = RLock() + self._counts: dict[str, int] = {} + self._inflight: dict[str, int] = {} + + def snapshot_baseline(self, candidates: list[NodeHeartbeat]) -> dict[str, int]: + with self._guard: + live_ids = {h.job_id for h in candidates} + for job_id in list(self._counts): + if job_id not in live_ids and not self._inflight.get(job_id): + self._counts.pop(job_id, None) + self._inflight.pop(job_id, None) + return { + h.job_id: self._counts.get(h.job_id, 0) - self._inflight.get(h.job_id, 0) + for h in candidates + } + + def select_and_reserve( + self, + candidates: list[NodeHeartbeat], + baseline: dict[str, int], + *, + reserve: bool, + allow_full: bool = False, + ) -> NodeHeartbeat | None: + with self._guard: + def effective_load(heartbeat: NodeHeartbeat) -> int: + additions = ( + self._counts.get(heartbeat.job_id, 0) - baseline.get(heartbeat.job_id, 0) + if reserve + else 0 + ) + return heartbeat.active_image_builds + max(0, additions) + + selected = select_builder_candidate( + candidates, + effective_load=effective_load, + allow_full=allow_full, + ) + if selected is not None and reserve: + job_id = selected.job_id + self._counts[job_id] = self._counts.get(job_id, 0) + 1 + self._inflight[job_id] = self._inflight.get(job_id, 0) + 1 + return selected + + def release(self, job_id: str) -> None: + if not job_id: + return + with self._guard: + self._inflight[job_id] = self._inflight.get(job_id, 0) - 1 + + +class ImagePullLocks: + """Serialize concurrent cold pulls of the same image onto the same node.""" + + def __init__(self) -> None: + self._guard = RLock() + self._locks: dict[tuple[str, str], RLock] = {} + + def for_node_image(self, node_url: str, image: str) -> RLock: + key = (node_url.rstrip("/"), image) + with self._guard: + lock = self._locks.get(key) + if lock is None: + lock = RLock() + self._locks[key] = lock + return lock + + +def builder_image_dispatch_lock(image_id: str): + """Serialize one image submission across every gateway process on the host.""" + return HOST_LOCKS.hold("image-dispatch", image_id.strip()) + + +class BuildExchange(Protocol): + """Request-scoped I/O and handler attachments required by ImageBuilds.""" + + max_json_body_bytes: int + build_context_store: Any + runtime_state: Any + sandbox_builds: Any + + def _read_raw_body(self, *, max_bytes: int) -> bytes: ... + def _write_json( + self, + payload: dict[str, Any], + *, + status: int = ..., + headers: dict[str, str] | None = None, + ) -> None: ... + def _proxy_request( + self, + node_url: str, + path: str, + *, + method: str, + body: Any = None, + timeout_seconds: float = ..., + extra_headers: dict[str, str] | None = None, + ) -> ProxiedResponse: ... + def _resolve_request_image_reference( + self, image: str + ) -> tuple[str, dict[str, Any] | None]: ... + def _write_image_resolution_error(self, payload: dict[str, Any]) -> None: ... + def _dispatched_root(self, image: str) -> str | None: ... + + +class ImageBuilds: + """Imperative orchestration for image builds, builder selection, and image cache warming.""" + + def __init__( + self, + *, + routing_store: RoutingStore | None, + fleet: FleetView, + registry_refs: RegistryReferences, + images: ImageResolution, + image_manager: ImageManager | None, + metrics_store: MetricsStore | None, + telemetry: Telemetry, + dispatch_tracker: BuilderDispatchTracker | None = None, + pull_locks: ImagePullLocks | None = None, + dispatch_lock: Callable[[str], Any] = builder_image_dispatch_lock, + ) -> None: + self.routing_store = routing_store + self.fleet = fleet + self.registry_refs = registry_refs + self.images = images + self.image_manager = image_manager + self.metrics_store = metrics_store + self.telemetry = telemetry + self.dispatch_tracker = dispatch_tracker or BuilderDispatchTracker() + self.pull_locks = pull_locks or ImagePullLocks() + self.dispatch_lock = dispatch_lock + + def _routing(self, ex: Any) -> RoutingStore: + return self.routing_store if self.routing_store is not None else ex.routing_store + + def _image_manager(self, ex: Any) -> ImageManager: + return self.image_manager if self.image_manager is not None else ex.image_manager + + def _metrics_store(self, ex: Any) -> MetricsStore | None: + return self.metrics_store if self.metrics_store is not None else getattr(ex, "metrics_store", None) + + def _telemetry(self, ex: Any) -> Telemetry: + return getattr(ex, "telemetry", None) or self.telemetry + + def get_build( + self, + ex: BuildExchange, + build_key: str, + *, + records_for_key: Callable[[str], list[dict[str, Any]]] | None = None, + record_successful_image: Callable[[dict[str, Any]], None] | None = None, + ) -> None: + sandbox_builds = getattr(ex, "sandbox_builds", None) + if sandbox_builds is not None and build_key.startswith("sandbox:"): + build = sandbox_builds.record(build_key) + if build is None: + ex._write_json({"error": "image build not found"}, status=HTTPStatus.NOT_FOUND) + else: + ex._write_json({"build": build}) + return + lookup = records_for_key or (lambda key: self.records_for_key(ex, key)) + record_success = record_successful_image or ( + lambda build: self.record_successful_image(ex, build) + ) + try: + builds = lookup(build_key) + except ImageBuildLookupUnavailableError as exc: + ex._write_json( + { + "error": str(exc), + "error_code": "image_build_status_unavailable", + "retryable": True, + }, + status=exc.status, + headers={"Retry-After": "2", "X-UCloud-Sandbox-Retryable": "true"}, + ) + return + selected = select_latest_build_record(builds, build_key) + if selected is None: + ex._write_json({"error": "image build not found"}, status=HTTPStatus.NOT_FOUND) + return + selected_image_id = str(selected.get("image_id") or "") + if selected_image_id and image_build_payload_is_terminal({"build": selected}): + self._routing(ex).clear_pending_image_build(selected_image_id) + record_success(selected) + ex._write_json({"build": selected}) + + def cancel_build( + self, + ex: BuildExchange, + build_key: str, + *, + records_for_key: Callable[[str], list[dict[str, Any]]] | None = None, + record_successful_image: Callable[[dict[str, Any]], None] | None = None, + ) -> None: + """POST /v1/images/builds/:cancel.""" + def unavailable(error: str) -> None: + ex._write_json( + { + "error": error, + "error_code": "image_build_cancel_unavailable", + "retryable": True, + }, + status=HTTPStatus.SERVICE_UNAVAILABLE, + headers={"Retry-After": "2", "X-UCloud-Sandbox-Retryable": "true"}, + ) + + statuses = { + "cancelled": HTTPStatus.OK, + "stopping": HTTPStatus.ACCEPTED, + "finished": HTTPStatus.CONFLICT, + } + sandbox_builds = getattr(ex, "sandbox_builds", None) + if build_key.startswith("sandbox:"): + outcome, build = ( + sandbox_builds.cancel(build_key) if sandbox_builds is not None else (None, None) + ) + if outcome is None: + ex._write_json({"error": "image build not found"}, status=HTTPStatus.NOT_FOUND) + return + payload: dict[str, Any] = {"build": build} + if outcome == "finished": + payload["error"] = "image build already finished" + ex._write_json(payload, status=statuses[outcome]) + return + lookup = records_for_key or (lambda key: self.records_for_key(ex, key)) + record_success = record_successful_image or ( + lambda build: self.record_successful_image(ex, build) + ) + try: + builds = lookup(build_key) + except ImageBuildLookupUnavailableError as exc: + unavailable(str(exc)) + return + build = next((item for item in builds if item.get("build_id") == build_key), None) + if build is None: + ex._write_json({"error": "image build not found"}, status=HTTPStatus.NOT_FOUND) + return + owner = next( + ( + heartbeat + for heartbeat in self.fleet.ready_heartbeats() + if "image-build" in heartbeat.capabilities + and heartbeat.node_id == build.get("location") + ), + None, + ) + if owner is None: + unavailable("the builder that owns this build is not ready") + return + try: + response = ex._proxy_request( + owner.node_url or "", + "/v1/images/builds/" + quote(build_key, safe="") + ":cancel", + method="POST", + timeout_seconds=IMAGE_BUILD_CANCEL_PROXY_TIMEOUT_SECONDS, + ) + payload = response.json() + except (OSError, ValueError) as exc: + unavailable(f"the builder did not answer the cancellation: {exc}") + return + record = payload.get("build") if isinstance(payload, dict) else None + if response.status == HTTPStatus.NOT_FOUND: + ex._write_json({"error": "image build not found"}, status=HTTPStatus.NOT_FOUND) + return + if response.status not in statuses.values() or not isinstance(record, dict): + unavailable(str((payload or {}).get("error") or f"the builder answered {response.status}")) + return + record = {**record, "location": owner.node_id, "node": node_metadata(owner)} + if image_build_payload_is_terminal({"build": record}): + self._routing(ex).clear_pending_image_build(str(record.get("image_id") or "")) + record_success(record) + answer: dict[str, Any] = {"build": record} + if response.status == HTTPStatus.CONFLICT: + answer["error"] = "image build already finished" + ex._write_json(answer, status=response.status) + + def records_for_key(self, ex: BuildExchange, build_key: str) -> list[dict[str, Any]]: + """Read one build, using an incarnation-checked owner hint for exact IDs.""" + builders = [ + h for h in self.fleet.ready_heartbeats() if "image-build" in h.capabilities + ] + owner = ex.runtime_state.builds.get_owner(build_key) + + def identity(heartbeat: NodeHeartbeat) -> tuple[str, str, str]: + return (heartbeat.job_id, heartbeat.node_id, heartbeat.node_epoch) + + def fetch(heartbeat: NodeHeartbeat) -> dict[str, Any] | None: + response = ex._proxy_request( + heartbeat.node_url or "", + "/v1/images/builds/" + quote(build_key, safe=""), + method="GET", + timeout_seconds=NODE_RECONCILE_PROXY_TIMEOUT_SECONDS, + ) + if response.status == HTTPStatus.NOT_FOUND: + return None + if not 200 <= response.status < 300: + raise ImageBuildLookupUnavailableError(response.status) + raw = response.json().get("build") + if not isinstance(raw, dict) or build_key not in ( + raw.get("build_id"), + raw.get("image_id"), + ): + raise ImageBuildLookupUnavailableError(HTTPStatus.BAD_GATEWAY) + build = dict(raw) + build.update(location=heartbeat.node_id, node=node_metadata(heartbeat)) + if raw.get("build_id") == build_key: + ex.runtime_state.builds.record_owner(build_key, identity(heartbeat)) + return build + + if owner is not None and not any( + identity(heartbeat)[:2] == owner[:2] for heartbeat in builders + ): + raise ImageBuildLookupUnavailableError() + + tried = None + for heartbeat in builders: + if identity(heartbeat) == owner: + tried = identity(heartbeat) + build = fetch(heartbeat) + if build is not None and build.get("build_id") == build_key: + return [build] + break + builds: list[dict[str, Any]] = [] + failure = None + for heartbeat in builders: + if identity(heartbeat) == tried: + continue + try: + build = fetch(heartbeat) + except ImageBuildLookupUnavailableError as exc: + failure = failure or exc + continue + if build is not None: + builds.append(build) + if build.get("build_id") == build_key: + return [build] + if failure is not None: + raise failure + return builds + + def records_across_nodes( + self, + ex: BuildExchange, + *, + record_successful_image: Callable[[dict[str, Any]], None] | None = None, + ) -> list[dict[str, Any]]: + record_success = record_successful_image or ( + lambda build: self.record_successful_image(ex, build) + ) + builds: list[dict[str, Any]] = [] + for heartbeat in self.fleet.ready_heartbeats(): + if "image-build" not in heartbeat.capabilities: + continue + response = ex._proxy_request( + heartbeat.node_url or "", + "/v1/images/builds", + method="GET", + timeout_seconds=NODE_RECONCILE_PROXY_TIMEOUT_SECONDS, + ) + if response.status >= 400: + continue + raw_builds = response.json().get("builds") + if not isinstance(raw_builds, list): + continue + for record in raw_builds: + if isinstance(record, dict): + enriched = dict(record) + enriched["location"] = heartbeat.node_id + enriched["node"] = node_metadata(heartbeat) + record_success(enriched) + builds.append(enriched) + return builds + + def record_terminal_metrics(self, ex: BuildExchange, build: dict[str, Any]) -> None: + """Retain observed terminal timings after an ephemeral builder exits.""" + if build.get("status") not in {"succeeded", "failed"} or not build.get("build_id"): + return + history = getattr(ex, "build_history", None) + if history is not None: + try: + history.record(build) + except (OSError, sqlite3.Error, ValueError): + pass + store = self._metrics_store(ex) + if store is None: + return + parsed = build_terminal_metrics_summary(build) + if parsed is None: + return + key, summary = parsed + try: + ex.runtime_state.builds.record_metric_once( + key, lambda: store.append("image_build_completed", summary) + ) + except (OSError, sqlite3.Error, ValueError): + return + + def record_successful_image( + self, + ex: BuildExchange, + build: dict[str, Any], + *, + record_terminal_metrics: Callable[[dict[str, Any]], None] | None = None, + ) -> None: + record_metrics = record_terminal_metrics or ( + lambda item: self.record_terminal_metrics(ex, item) + ) + record_metrics(build) + if build.get("status") != "succeeded": + return + raw_image = build.get("image") + if not isinstance(raw_image, dict) or not image_record_available_to_sandboxes(raw_image): + return + raw_image = self.images.record_with_digest(raw_image) + build["image"] = raw_image + try: + changed = self._image_manager(ex).store.upsert_if_changed( + ImageRecord.from_dict(raw_image) + ) + except ValueError: + return + if changed: + self.images.invalidate_inventory() + + def _prepare_build_payload( + self, + ex: BuildExchange, + raw: dict[str, Any], + ) -> tuple[bytes, Any, bool, tuple[str, int] | None, Any]: + context_reference = uploaded_build_context_reference(raw, ex.build_context_store) + if context_reference is not None: + ex.build_context_store.touch(context_reference[0]) + raw, spec, push = normalize_build_spec( + raw, + registry_url=self.registry_refs.registry_url, + registry_worker_url=self.registry_refs.registry_worker_url, + ) + prepared_resolution = None + prepared_catalog = getattr(ex, "prepared_image_catalog", None) + if prepared_catalog is not None: + from ..prepared_images import resolve_build + + raw, prepared_resolution = resolve_build( + prepared_catalog, + ex.build_context_store, + raw, + spec, + protect=lambda reference: self.registry_refs.ensure_image_lease( + reference, + registry_operation_lease_owner( + "prepared-build", + {"id": spec.id, "context": raw["context_archive_digest"]}, + ), + touch=True, + ), + ) + context_reference = uploaded_build_context_reference(raw, ex.build_context_store) + regeneration = getattr(ex, "base_regeneration", None) + if regeneration is not None and raw.get("context_archive_digest"): + from .base_regeneration import context_dockerfile + + def texts(): + yield context_dockerfile( + ex.build_context_store, raw["context_archive_digest"], spec.dockerfile + ) + yield from spec.build_args.values() + + contexts, copies = regeneration.contexts(texts()) + for copy in copies: + self.registry_refs.ensure_image_lease( + copy, + registry_operation_lease_owner( + "regenerated-base", + {"id": spec.id, "context": raw["context_archive_digest"]}, + ), + touch=True, + ) + if contexts: + raw["base_contexts"] = contexts + body = json.dumps(raw, separators=(",", ":")).encode("utf-8") + return body, spec, push, context_reference, prepared_resolution + + def _finalize_build_response( + self, + ex: BuildExchange, + response: ProxiedResponse, + *, + spec: Any, + prepared_resolution: Any, + record_terminal_metrics: Callable[[dict[str, Any]], None], + ) -> dict[str, Any]: + response_payload = response.json() + if prepared_resolution and 200 <= response.status < 300: + response_payload["prepared"] = prepared_resolution + response.body = json.dumps(response_payload).encode("utf-8") + raw_image = response_payload.get("image") + if isinstance(raw_image, dict) and image_record_available_to_sandboxes(raw_image): + raw_image = self.images.record_with_digest(raw_image) + response_payload["image"] = raw_image + raw_build = response_payload.get("build") + if isinstance(raw_build, dict): + raw_build["image"] = raw_image + response.body = json.dumps(response_payload).encode("utf-8") + if isinstance(response_payload.get("build"), dict): + record_terminal_metrics(response_payload["build"]) + if image_build_response_is_terminal(response.status, response_payload): + self._routing(ex).clear_pending_image_build(spec.id) + if 200 <= response.status < 300: + raw_image = response_payload.get("image") + if isinstance(raw_image, dict) and image_record_available_to_sandboxes(raw_image): + try: + self._image_manager(ex).store.upsert(ImageRecord.from_dict(raw_image)) + except ValueError: + pass + self.images.invalidate_inventory() + return response_payload + + def _dispatch_to_builder( + self, + ex: BuildExchange, + *, + body: bytes, + spec: Any, + push: bool, + context_reference: tuple[str, int] | None, + prepared_resolution: Any, + select_builder: Callable[..., NodeHeartbeat | None], + ensure_context: Callable[[str, tuple[str, int]], ProxiedResponse], + record_terminal_metrics: Callable[[dict[str, Any]], None], + ) -> tuple[BuildDispatch, str]: + telemetry = self._telemetry(ex) + routing = self._routing(ex) + reserved_job_id = "" + with self.dispatch_lock(spec.id): + with telemetry.span( + "gateway.image_build", + attributes={ + "image.id": spec.id, + "container.image.name": spec.tag, + "image.push": push, + }, + ) as root: + with telemetry.span("gateway.image_build_select_builder") as span: + heartbeat = select_builder(image_id=spec.id, reserve=True) + reserved_job_id = heartbeat.job_id if heartbeat else "" + span.set_attribute("selected_node_id", heartbeat.node_id if heartbeat else "") + span.set_attribute("selected_job_id", heartbeat.job_id if heartbeat else "") + if heartbeat is None: + routing.upsert_pending_image_build(spec.id, spec.tag) + pending_builds = routing.pending_image_build_count() + root.status = "error" + root.set_attribute("outcome", "queued_no_builder") + root.set_attribute("pending_image_builds", pending_builds) + return ( + BuildDispatch( + HTTPStatus.SERVICE_UNAVAILABLE, + { + "error": "no ready builder execution slot is available", + "error_code": "builder_not_ready", + "retryable": True, + "pending_image_builds": pending_builds, + }, + {"Retry-After": "2", "X-UCloud-Sandbox-Retryable": "true"}, + ), + reserved_job_id, + ) + with telemetry.span( + "gateway.image_build_enqueue", + attributes={"node.id": heartbeat.node_id}, + ): + routing.upsert_pending_image_build(spec.id, spec.tag) + with telemetry.span( + "gateway.image_build_context_sync", + attributes={"node.id": heartbeat.node_id}, + ) as span: + assert context_reference is not None + context_response = ensure_context(heartbeat.node_url or "", context_reference) + span.set_attribute("status_code", int(context_response.status)) + context_payload = context_response.json() + if "deduplicated" in context_payload: + span.set_attribute("deduplicated", bool(context_payload["deduplicated"])) + if not 200 <= context_response.status < 300: + root.status = "error" + root.set_attribute("outcome", "context_proxy_failed") + root.set_attribute("status_code", int(context_response.status)) + return BuildDispatch(context_response.status, response=context_response), reserved_job_id + self.registry_refs.protect_build_target(spec, push=push) + with telemetry.span( + "gateway.image_build_proxy_builder", + attributes={"node.id": heartbeat.node_id}, + ) as span: + response = ex._proxy_request( + heartbeat.node_url or "", + "/v1/images/build", + method="POST", + body=body, + timeout_seconds=IMAGE_BUILD_PROXY_TIMEOUT_SECONDS, + ) + span.set_attribute("status_code", int(response.status)) + response_payload = self._finalize_build_response( + ex, + response, + spec=spec, + prepared_resolution=prepared_resolution, + record_terminal_metrics=record_terminal_metrics, + ) + node_timings = response_payload.get("timings") + if isinstance(node_timings, dict): + span.add_event("node.timings", node_timings) + if 200 <= response.status < 300: + root.set_attribute("outcome", "builder_completed") + root.set_attribute("node_id", heartbeat.node_id) + else: + root.status = "error" + root.set_attribute("outcome", "builder_failed") + root.set_attribute("status_code", int(response.status)) + return BuildDispatch(response.status, response=response), reserved_job_id + + def dispatch_build( + self, + ex: BuildExchange, + raw: dict[str, Any], + *, + select_builder: Callable[..., NodeHeartbeat | None] | None = None, + ensure_context: Callable[[str, tuple[str, int]], ProxiedResponse] | None = None, + record_terminal_metrics: Callable[[dict[str, Any]], None] | None = None, + ) -> BuildDispatch: + """Submit one build through the gateway's path (prepared foundations, + regenerated bases, builder selection): /v1/images/build and image recipes.""" + reserved_job_id = "" + choose_builder = select_builder or ( + lambda *, image_id="", reserve=False: self.select_builder_node( + ex, image_id=image_id, reserve=reserve + ) + ) + sync_context = ensure_context or ( + lambda node_url, reference: self.ensure_node_build_context(ex, node_url, reference) + ) + record_metrics = record_terminal_metrics or ( + lambda item: self.record_terminal_metrics(ex, item) + ) + try: + pressure = self.images.disk_refusal() + if pressure is not None: + return BuildDispatch( + HTTPStatus.SERVICE_UNAVAILABLE, + registry_disk_pressure_payload(pressure, action="image builds"), + { + "Retry-After": str(REGISTRY_DISK_RETRY_AFTER_SECONDS), + "X-UCloud-Sandbox-Retryable": "true", + }, + ) + body, spec, push, context_reference, prepared_resolution = ( + self._prepare_build_payload(ex, raw) + ) + result, reserved_job_id = self._dispatch_to_builder( + ex, + body=body, + spec=spec, + push=push, + context_reference=context_reference, + prepared_resolution=prepared_resolution, + select_builder=choose_builder, + ensure_context=sync_context, + record_terminal_metrics=record_metrics, + ) + return result + except BaseReleased as exc: + return BuildDispatch( + HTTPStatus.CONFLICT, + {"error": str(exc), "error_code": "base_released"}, + ) + except (json.JSONDecodeError, ValueError) as exc: + return BuildDispatch(HTTPStatus.BAD_REQUEST, {"error": str(exc)}) + except RegistryImageReferenceUnavailable: + return BuildDispatch( + HTTPStatus.SERVICE_UNAVAILABLE, + {"error": "registry image-use state is unavailable", "retryable": True}, + {"Retry-After": "2"}, + ) + except BaseRegenerating as exc: + return BuildDispatch( + HTTPStatus.SERVICE_UNAVAILABLE, + {"error": str(exc), "error_code": "base_regenerating", "retryable": True}, + {"Retry-After": "30", "X-UCloud-Sandbox-Retryable": "true"}, + ) + except RuntimeError as exc: + return BuildDispatch(HTTPStatus.BAD_REQUEST, {"error": str(exc)}) + finally: + self.dispatch_tracker.release(reserved_job_id) + + def ensure_node_build_context( + self, + ex: BuildExchange, + node_url: str, + reference: tuple[str, int], + ) -> ProxiedResponse: + digest, size = reference + path = f"/v1/image-contexts/{quote(digest, safe=':')}" + if size > BUILD_CONTEXT_PROBE_MIN_BYTES: + probe = ex._proxy_request(node_url, path, method="GET") + if 200 <= probe.status < 300: + payload = probe.json() + if payload.get("digest") == digest and payload.get("size") == size: + return probe + elif probe.status != HTTPStatus.NOT_FOUND: + return probe + + try: + with ex.build_context_store.open(digest) as archive: + return ex._proxy_request( + node_url, + path, + method="PUT", + body=archive, + extra_headers={ + "Content-Type": "application/gzip", + "Content-Length": str(size), + }, + timeout_seconds=IMAGE_BUILD_PROXY_TIMEOUT_SECONDS, + ) + except FileNotFoundError: + return ProxiedResponse( + HTTPStatus.BAD_REQUEST, + {"Content-Type": "application/json"}, + json.dumps( + {"error": f"build context {digest!r} has not been uploaded"} + ).encode("utf-8"), + ) + + def route_image_pull( + self, + ex: BuildExchange, + *, + warm_image: Callable[..., dict[str, Any]] | None = None, + ) -> None: + try: + body = ex._read_raw_body(max_bytes=ex.max_json_body_bytes) + raw = json.loads(body.decode("utf-8")) if body else None + image, count, resources, sandbox_nodes_only, image_id = parse_image_pull_request(raw) + except (json.JSONDecodeError, ValueError) as exc: + ex._write_json({"error": str(exc)}, status=HTTPStatus.BAD_REQUEST) + return + + image, image_error = ex._resolve_request_image_reference(image) + if image_error is not None: + ex._write_image_resolution_error(image_error) + return + + self.registry_refs.ensure_image_lease( + image, + registry_operation_lease_owner( + "image-pull", + { + "image": image, + "image_id": image_id, + "count": count, + "resources": resources.to_dict(), + "sandbox_nodes_only": sandbox_nodes_only, + }, + ), + touch=True, + ) + warm = warm_image or ( + lambda img, *, count, resources, sandbox_nodes_only, image_id="": ( + self.warm_image_on_ready_nodes( + ex, + img, + count=count, + resources=resources, + sandbox_nodes_only=sandbox_nodes_only, + image_id=image_id, + ) + ) + ) + result = warm( + image, + count=count, + resources=resources, + sandbox_nodes_only=sandbox_nodes_only, + image_id=image_id, + ) + if result["ready"] <= 0: + error_message = ( + "image pull failed on ready image-cache nodes" + if result["failed"] + else "no ready image-cache node is available" + ) + ex._write_json( + { + "error": error_message, + "image": image, + "result": result, + }, + status=HTTPStatus.SERVICE_UNAVAILABLE, + ) + return + ex._write_json(result, status=HTTPStatus.OK) + + def select_builder_node( + self, + ex: BuildExchange, + *, + image_id: str = "", + reserve: bool = False, + ) -> NodeHeartbeat | None: + candidates = [ + heartbeat + for heartbeat in self.fleet.ready_heartbeats() + if is_builder_heartbeat(heartbeat) + ] + if not candidates: + return None + baseline = self.dispatch_tracker.snapshot_baseline(candidates) + if image_id: + for heartbeat in candidates: + response = ex._proxy_request( + heartbeat.node_url or "", + f"/v1/images/builds/{quote(image_id, safe='')}", + method="GET", + timeout_seconds=NODE_RECONCILE_PROXY_TIMEOUT_SECONDS, + ) + if response.status == HTTPStatus.NOT_FOUND: + continue + if response.status != HTTPStatus.OK: + return None + build = response.json().get("build") + if not isinstance(build, dict) or build.get("status") not in { + "running", + "succeeded", + "failed", + }: + return None + if builder_owns_active_build(build): + return self.dispatch_tracker.select_and_reserve( + [heartbeat], baseline, reserve=reserve, allow_full=True + ) + refreshed = [] + for heartbeat in candidates: + response = ex._proxy_request( + heartbeat.node_url or "", + "/v1/heartbeat", + method="GET", + timeout_seconds=NODE_RECONCILE_PROXY_TIMEOUT_SECONDS, + ) + raw = response.json().get("heartbeat") + if response.status != HTTPStatus.OK or not isinstance(raw, dict): + continue + try: + current = heartbeat_from_dict(raw) + except (ValueError, TypeError): + continue + merged = merge_refreshed_builder_heartbeat(heartbeat, current) + if merged is not None: + refreshed.append(merged) + return self.dispatch_tracker.select_and_reserve( + refreshed, baseline, reserve=reserve + ) + + def image_cache_candidates( + self, + ex: BuildExchange, + *, + resources: ResourceQuantity, + sandbox_nodes_only: bool, + ) -> list[NodeHeartbeat]: + routes = list(self._routing(ex).sandbox_routes_readonly()) + return rank_image_cache_candidates( + self.fleet.ready_heartbeats(), + routes, + resources=resources, + sandbox_nodes_only=sandbox_nodes_only, + ) + + def nodes_with_image( + self, + ex: BuildExchange, + image: str, + heartbeats: list[NodeHeartbeat], + *, + image_id: str = "", + use_heartbeat_cache: bool = True, + probe_uncached: bool = True, + ) -> set[str]: + if not image.strip() and not image_id.strip(): + return set() + node_ids = ( + self.fleet.nodes_with_cached_image(image, heartbeats, image_id=image_id) + if use_heartbeat_cache + else set() + ) + uncached = [ + heartbeat + for heartbeat in heartbeats + if not (use_heartbeat_cache and heartbeat.cached_images_known) + ] + if not probe_uncached or not uncached: + return node_ids + image_keys = requested_image_cache_keys( + image, + image_id, + require_digest=self.registry_refs.requires_digest_identity(image), + ) + for heartbeat in uncached: + response = ex._proxy_request( + heartbeat.node_url or "", + "/v1/images", + method="GET", + ) + if response.status >= 400: + continue + raw_images = response.json().get("images") + if not isinstance(raw_images, list): + continue + for record in raw_images: + if not isinstance(record, dict): + continue + if image_keys.intersection(image_record_cache_keys(record)): + node_ids.add(heartbeat.node_id) + break + return node_ids + + def node_has_image( + self, + ex: BuildExchange, + heartbeat: NodeHeartbeat, + image: str, + *, + image_id: str = "", + use_heartbeat_cache: bool = True, + nodes_with_image: Callable[..., set[str]] | None = None, + ) -> bool: + if not image.strip() and not image_id.strip(): + return False + image_keys = requested_image_cache_keys( + image, + image_id, + require_digest=self.registry_refs.requires_digest_identity(image), + ) + if use_heartbeat_cache and heartbeat.cached_images_known: + return bool(image_keys.intersection(heartbeat.cached_images)) + lookup_nodes = nodes_with_image or ( + lambda img, hbs, *, image_id="", use_heartbeat_cache=True: self.nodes_with_image( + ex, img, hbs, image_id=image_id, use_heartbeat_cache=use_heartbeat_cache + ) + ) + return heartbeat.node_id in lookup_nodes( + image, + [heartbeat], + image_id=image_id, + use_heartbeat_cache=use_heartbeat_cache, + ) + + def ensure_image_on_node( + self, + ex: BuildExchange, + heartbeat: NodeHeartbeat, + image: str, + environment_root: str | None = None, + *, + node_has_image: Callable[..., bool] | None = None, + pull_image: Callable[..., ProxiedResponse] | None = None, + ) -> ProxiedResponse | None: + node_url = heartbeat.node_url or "" + has_image = node_has_image or ( + lambda hb, img, *, use_heartbeat_cache=True: self.node_has_image( + ex, hb, img, use_heartbeat_cache=use_heartbeat_cache + ) + ) + pull = pull_image or ( + lambda hb, img, *, environment_root=None: self.pull_image_on_node( + ex, hb, img, environment_root=environment_root + ) + ) + if not image.strip() or has_image(heartbeat, image): + return None + with self.pull_locks.for_node_image(node_url, image): + if has_image(heartbeat, image, use_heartbeat_cache=False): + return None + return pull(heartbeat, image, environment_root=environment_root) + + def warm_image_on_ready_nodes( + self, + ex: BuildExchange, + image: str, + *, + count: int, + resources: ResourceQuantity, + sandbox_nodes_only: bool, + image_id: str = "", + node_has_image: Callable[..., bool] | None = None, + pull_image: Callable[..., ProxiedResponse] | None = None, + ) -> dict[str, Any]: + image = image.strip() + image_id = image_id.strip() + requested = max(1, count) + candidates = self.image_cache_candidates( + ex, + resources=resources, + sandbox_nodes_only=sandbox_nodes_only, + ) + has_image = node_has_image or ( + lambda hb, img, *, image_id="": self.node_has_image(ex, hb, img, image_id=image_id) + ) + pull = pull_image or ( + lambda hb, img, *, image_id="": self.pull_image_on_node(ex, hb, img, image_id=image_id) + ) + cache_hits: list[dict[str, Any]] = [] + pulled: list[dict[str, Any]] = [] + failed: list[dict[str, Any]] = [] + selected_image: dict[str, Any] | None = None + for heartbeat in candidates: + if len(cache_hits) + len(pulled) >= requested: + break + if has_image(heartbeat, image, image_id=image_id): + hit = { + "node": node_metadata(heartbeat), + "image": { + "id": image_id or image_id_from_tag(image), + "tag": image, + }, + } + cache_hits.append(hit) + selected_image = selected_image or hit["image"] + continue + response = pull(heartbeat, image, image_id=image_id) + payload = response.json() + raw_image = payload.get("image") + image_record = ( + dict(raw_image) + if isinstance(raw_image, dict) + else {"id": image_id or image_id_from_tag(image), "tag": image} + ) + item = { + "node": node_metadata(heartbeat), + "status": int(response.status), + "image": image_record, + } + if 200 <= response.status < 300: + pulled.append(item) + selected_image = selected_image or image_record + else: + item["error"] = payload.get("error") or payload + failed.append(item) + ready = len(cache_hits) + len(pulled) + return { + "image": selected_image + or {"id": image_id or image_id_from_tag(image), "tag": image}, + "image_ref": image, + "requested": requested, + "ready": ready, + "cache_hits": cache_hits, + "pulled": pulled, + "failed": failed, + } + + def pull_image_on_node( + self, + ex: BuildExchange, + heartbeat: NodeHeartbeat, + image: str, + *, + image_id: str = "", + environment_root: str | None = None, + dispatched_root: Callable[[str], str | None] | None = None, + ) -> ProxiedResponse: + payload: dict[str, Any] = {"image": image} + if image_id: + payload["id"] = image_id + resolve_root = dispatched_root or ex._dispatched_root + environment_root = environment_root or resolve_root(image) + if environment_root: + payload["environment_root"] = environment_root + response: ProxiedResponse | None = None + for attempt in range(IMAGE_PULL_RETRY_ATTEMPTS): + response = ex._proxy_request( + heartbeat.node_url or "", + "/v1/images/pull", + method="POST", + body=json.dumps(payload).encode("utf-8"), + timeout_seconds=IMAGE_PULL_PROXY_TIMEOUT_SECONDS, + ) + if not retryable_image_pull_payload(response.status, response.json()): + if 200 <= response.status < 300: + self.images.invalidate_inventory() + return response + if attempt + 1 < IMAGE_PULL_RETRY_ATTEMPTS: + time.sleep(IMAGE_PULL_RETRY_BASE_DELAY_SECONDS * (2**attempt)) + assert response is not None + if 200 <= response.status < 300: + self.images.invalidate_inventory() + return response diff --git a/sandboxes/gateway/builds.py b/sandboxes/gateway/builds.py new file mode 100644 index 00000000..4feb76b6 --- /dev/null +++ b/sandboxes/gateway/builds.py @@ -0,0 +1,306 @@ +"""Pure gateway image-build normalization, builder refresh merging, and candidate ranking.""" + +from __future__ import annotations + +from dataclasses import replace +from http import HTTPStatus +from typing import Any, Callable, Iterable + +from ..build_admission import BUILD_ADMISSION_CAPACITY_LABEL, build_admission_capacity +from ..consolidation import consolidation_rank +from ..images import ImageBuildSpec +from ..managed_registry import canonical_image_digest_ref, normalize_manifest_digest +from ..models import NodeHeartbeat, ResourceQuantity +from ..placement_accounting import PlacementRecord +from .placement import has_resource_values, node_can_fit +from .registry_refs import ( + managed_registry_build_tag, + managed_registry_worker_reference, +) +from .request_parsing import prepared_resources_from_payload, strict_positive_integer + + +def is_builder_heartbeat(heartbeat: NodeHeartbeat) -> bool: + """Return whether a ready heartbeat represents a dedicated builder node.""" + return ( + "image-build" in heartbeat.capabilities + and "sandbox" not in heartbeat.capabilities + ) + + +def merge_refreshed_builder_heartbeat( + cached: NodeHeartbeat, + current: NodeHeartbeat | None, +) -> NodeHeartbeat | None: + """Validate a freshly polled builder heartbeat and merge live scheduling fields. + + Preserves gateway-owned metadata (e.g. quarantine labels) while taking + active build count, free physical disk, and admission capacity hint from + the live sample. + """ + if ( + current is None + or current.job_id != cached.job_id + or current.node_id != cached.node_id + or current.deployment_id != cached.deployment_id + or current.node_epoch != cached.node_epoch + or current.draining + or not current.admission_open + ): + return None + labels = dict(cached.labels) + labels.pop(BUILD_ADMISSION_CAPACITY_LABEL, None) + if BUILD_ADMISSION_CAPACITY_LABEL in current.labels: + labels[BUILD_ADMISSION_CAPACITY_LABEL] = current.labels[ + BUILD_ADMISSION_CAPACITY_LABEL + ] + return replace( + cached, + active_image_builds=current.active_image_builds, + physical_disk_free_mb=current.physical_disk_free_mb, + labels=labels, + ) + + +def builder_owns_active_build(build: Any) -> bool: + """Return whether a builder's build record still owns an active or finishing build.""" + if not isinstance(build, dict) or build.get("status") not in { + "running", + "succeeded", + "failed", + }: + return False + return bool( + build["status"] == "running" + or build.get("admission_phase") in {"preparing_solving", "finishing"} + ) + + +def image_build_response_is_terminal( + status: int, + payload: dict[str, Any], +) -> bool: + """Return whether a builder HTTP response settles the pending build record.""" + if 200 <= status < 300: + return True + build = payload.get("build") + if isinstance(build, dict) and build.get("status") in {"succeeded", "failed"}: + return True + return status < 500 and status not in {408, 425, 429} + + +def normalize_build_spec( + raw: dict[str, Any], + *, + registry_url: str | None, + registry_worker_url: str | None, +) -> tuple[dict[str, Any], ImageBuildSpec, bool]: + """Validate and rewrite a gateway image-build request onto the managed registry.""" + cleaned = dict(raw) + cleaned.pop("base_contexts", None) + spec = ImageBuildSpec.from_dict(cleaned) + push = bool(cleaned.get("push", False)) + if not spec.tag.strip(): + if not str(cleaned.get("id") or "").strip(): + raise ValueError("gateway-managed image builds require an image id") + spec = replace( + spec, + tag=managed_registry_build_tag(spec.id, registry_worker_url or ""), + ) + push = True + elif registry_url and registry_worker_url: + spec = replace( + spec, + tag=managed_registry_worker_reference( + spec.tag, registry_url, registry_worker_url + ), + ) + spec.validate() + cleaned["tag"] = spec.tag + cleaned["push"] = push + return cleaned, spec, push + + +def rank_image_cache_candidates( + ready_heartbeats: Iterable[NodeHeartbeat], + routes: list[PlacementRecord], + *, + resources: ResourceQuantity, + sandbox_nodes_only: bool, +) -> list[NodeHeartbeat]: + """Rank ready image-cache nodes by role, free disk/memory/CPU, and node id.""" + candidates: list[NodeHeartbeat] = [] + for heartbeat in ready_heartbeats: + if "image-cache" not in heartbeat.capabilities: + continue + if sandbox_nodes_only and "sandbox" not in heartbeat.capabilities: + continue + if has_resource_values(resources) and "sandbox" in heartbeat.capabilities: + if not node_can_fit(heartbeat, resources, routes): + continue + candidates.append(heartbeat) + return sorted( + candidates, + key=lambda heartbeat: ( + 0 if "sandbox" in heartbeat.capabilities else 1, + -heartbeat.free_resources.disk_mb, + -heartbeat.free_resources.memory_mb, + -heartbeat.free_resources.vcpu, + heartbeat.node_id, + ), + ) + + +def select_builder_candidate( + candidates: Iterable[NodeHeartbeat], + *, + effective_load: Callable[[NodeHeartbeat], int], + allow_full: bool = False, +) -> NodeHeartbeat | None: + """Choose the best eligible builder using pipeline-aware load ranking. + + Consolidates a trickle up to two active builds per builder, then spreads + to idle peers before queuing additional output behind publication workers. + """ + eligible = [ + heartbeat + for heartbeat in candidates + if allow_full or effective_load(heartbeat) < build_admission_capacity(heartbeat.labels) + ] + if not eligible: + return None + + def rank(heartbeat: NodeHeartbeat): + active = effective_load(heartbeat) + saturated = active >= 2 + return ( + int(saturated), + active if saturated else -active, + consolidation_rank(heartbeat), + -heartbeat.physical_disk_free_mb, + heartbeat.node_id, + ) + + return min(eligible, key=rank) + + +def image_build_payload_is_terminal(payload: dict[str, Any]) -> bool: + """Return whether a build JSON payload represents a terminal build state.""" + build = payload.get("build") + if not isinstance(build, dict): + return "image" in payload + return str(build.get("status") or "").lower() in {"succeeded", "failed"} + + +def select_latest_build_record( + builds: Iterable[dict[str, Any]], + build_key: str, +) -> dict[str, Any] | None: + """Return the latest build record matching ``build_key`` by build_id or image_id.""" + matches = [ + build + for build in builds + if build.get("build_id") == build_key or build.get("image_id") == build_key + ] + if not matches: + return None + return sorted( + matches, + key=lambda item: ( + str(item.get("created_at") or ""), + str(item.get("build_id") or ""), + ), + )[-1] + + +def build_terminal_metrics_summary( + build: dict[str, Any], +) -> tuple[tuple[str, str], dict[str, Any]] | None: + """Extract deduplication key and sanitized timings summary for a terminal build.""" + if build.get("status") not in {"succeeded", "failed"} or not build.get("build_id"): + return None + timings = build.get("timings") or {} + if not isinstance(timings, dict): + return None + key = (str(build["build_id"]), str(build.get("updated_at", ""))) + summary: dict[str, Any] = { + name: build.get(name, "") + for name in ( + "build_id", + "image_id", + "status", + "created_at", + "started_at", + "finished_at", + "location", + ) + } + summary["timings"] = { + "total_ms": timings.get("total_ms"), + **{ + name: timings[name] + for name in ("preparation_ms", "queue_wait_ms", "end_to_end_ms") + if type(timings.get(name)) in {int, float} + }, + **{ + name: { + k: v + for k, v in (timings.get(name) or {}).items() + if type(v) in {int, float} + } + for name in ("phases", "environment") + if isinstance(timings.get(name), dict) + }, + } + return key, summary + + +def parse_image_pull_request( + raw: Any, +) -> tuple[str, int, ResourceQuantity, bool, str]: + """Validate a ``POST /v1/images/pull`` payload.""" + if not isinstance(raw, dict): + raise ValueError("image pull payload must be a JSON object") + unsupported = sorted( + set(raw) + - { + "count", + "cpus", + "disk_mb", + "id", + "image", + "memory_mb", + "sandbox_nodes_only", + } + ) + if unsupported: + raise ValueError("unsupported image pull fields: " + ", ".join(unsupported)) + image = str(raw.get("image") or "") + if not image.strip(): + raise ValueError("image is required.") + count = strict_positive_integer(raw.get("count", 1), "count") + resources = prepared_resources_from_payload(raw) + sandbox_nodes_only = raw.get("sandbox_nodes_only", True) + if not isinstance(sandbox_nodes_only, bool): + raise ValueError("sandbox_nodes_only must be a boolean.") + if count <= 0: + raise ValueError("count must be positive.") + return image, count, resources, sandbox_nodes_only, str(raw.get("id") or "").strip() + + +def image_record_cache_keys(record: dict[str, Any]) -> set[str]: + """Return the set of lookup keys (tag, id, canonical digest ref) for an image record.""" + tag = str(record.get("tag") or "") + image_id = str(record.get("id") or "") + digest = normalize_manifest_digest(str(record.get("manifest_digest") or "")) + digest_ref = canonical_image_digest_ref(tag, digest) + return {item for item in (tag, image_id, digest_ref) if item} + + +def retryable_image_pull_payload(status: int, payload: dict[str, Any]) -> bool: + """Return whether an image pull response indicates a transient retryable failure.""" + return bool( + status == HTTPStatus.SERVICE_UNAVAILABLE + and payload.get("retryable") is True + and payload.get("error_code") == "image_pull_failed" + ) diff --git a/sandboxes/gateway/create.py b/sandboxes/gateway/create.py index a60cd2c3..8488d853 100644 --- a/sandboxes/gateway/create.py +++ b/sandboxes/gateway/create.py @@ -31,11 +31,11 @@ from ..sandbox import SandboxSpec, sandbox_spec_fingerprint from ..telemetry import Telemetry from ..worker_receipts import ( - _route_with_sandbox_record, _sandbox_create_request_body, _sandbox_record_matches_route, + route_with_sandbox_record, sandbox_create_request_body, sandbox_record_matches_route, ) from .exchange import Exchange from .node_rpc import ProxiedResponse -from .placement import _sandbox_required_capabilities, migration_reservations +from .placement import sandbox_required_capabilities, migration_reservations from .registry_refs import RegistryImageReferenceUnavailable, RegistryReferences # Creation includes quota allocation, rootfs preparation, networking, and @@ -100,7 +100,7 @@ def create( ) -> None: spec_dict = spec.to_dict() request = PlacementRequest( - spec.requested_resources(), capabilities=_sandbox_required_capabilities(spec_dict), + spec.requested_resources(), capabilities=sandbox_required_capabilities(spec_dict), image=spec.image, spec=spec_dict, ) spec_hash = sandbox_spec_fingerprint(spec) @@ -178,7 +178,7 @@ def release_hold(): self._ensure_reference(spec, route) finally: self.registry_refs.release_route_reference(previous) - self.overlay.reserve(shared, _incarnation(route), request) + self.overlay.reserve(shared, sandbox_incarnation(route), request) release_hold() rejected = self._attempt( ex, spec, route, heartbeat, pending, root, @@ -186,7 +186,7 @@ def release_hold(): ) if rejected is None: return - self.overlay.release(route.job_id, _incarnation(route)) + self.overlay.release(route.job_id, sandbox_incarnation(route)) reason, rejections = rejected, rejections + 1 root.set_attribute("rejected_jobs", rejections) finally: @@ -233,7 +233,7 @@ def _attempt( ex._send_proxied_response(image_response) return None if image_response.status >= 400: - rejected = _image_check_rejection_reason(image_response) + rejected = image_check_rejection_reason(image_response) if rejected is not None: return rejected # No create was dispatched. self._abandon(spec, route, f"image_pull_http_{image_response.status}") @@ -247,7 +247,7 @@ def _attempt( }) as span: response = ex._proxy_request( heartbeat.node_url or "", "/v1/sandboxes", method="POST", - body=_sandbox_create_request_body(spec, route), + body=sandbox_create_request_body(spec, route), timeout_seconds=SANDBOX_CREATE_PROXY_TIMEOUT_SECONDS, extra_headers=None if wait is None else {ADMISSION_WAIT_HEADER: f"{wait:g}"}, ) @@ -255,20 +255,20 @@ def _attempt( payload = response.json() if isinstance(payload.get("timings"), dict): span.add_event("node.timings", payload["timings"]) - if _is_duplicate_sandbox_response(response, spec.id) and ex._send_existing_sandbox_response( + if is_duplicate_sandbox_response(response, spec.id) and ex._send_existing_sandbox_response( route, spec, status=HTTPStatus.CREATED, pending=pending, ): root.set_attribute("outcome", "recovered_duplicate") return None if 200 <= response.status < 300: record = payload.get("sandbox") - if not isinstance(record, dict) or not _sandbox_record_matches_route(record, route, spec): + if not isinstance(record, dict) or not sandbox_record_matches_route(record, route, spec): root.status = "error" root.set_attribute("outcome", "invalid_create_confirmation") ex._write_invalid_create_confirmation() return None confirmed = ex._confirm_sandbox_observation( - _route_with_sandbox_record(route, record), self.routing_store.confirm_create, + route_with_sandbox_record(route, record), self.routing_store.confirm_create, ) if confirmed is None: return None @@ -281,16 +281,16 @@ def _attempt( root.set_attribute("node_id", heartbeat.node_id) ex._send_proxied_response(response) return None - rejected = _node_create_rejection_reason(response) + rejected = node_create_rejection_reason(response) if rejected is not None: return rejected root.status = "error" root.set_attribute("outcome", "node_create_failed") root.set_attribute("status_code", int(response.status)) - if _node_create_may_still_be_running(response): + if node_create_may_still_be_running(response): root.set_attribute("kept_durable_route", True) else: - self.overlay.release(route.job_id, _incarnation(route)) + self.overlay.release(route.job_id, sandbox_incarnation(route)) removed = self.routing_store.delete_sandbox_if_current( spec.id, generation=route.generation, create_operation_id=route.create_operation_id, ) @@ -309,7 +309,7 @@ def _ensure_reference(self, spec: SandboxSpec, route: SandboxRoute) -> None: raise def _abandon(self, spec: SandboxSpec, route: SandboxRoute, reason: str) -> SandboxRoute | None: - self.overlay.release(route.job_id, _incarnation(route)) + self.overlay.release(route.job_id, sandbox_incarnation(route)) removed = self.routing_store.delete_sandbox_if_current( spec.id, generation=route.generation, create_operation_id=route.create_operation_id, ) @@ -323,20 +323,20 @@ def _abandon(self, spec: SandboxSpec, route: SandboxRoute, reason: str) -> Sandb return removed -def _incarnation(route: SandboxRoute) -> SandboxIncarnation: +def sandbox_incarnation(route: SandboxRoute) -> SandboxIncarnation: return SandboxIncarnation( route.sandbox_id, route.generation, route.spec_hash, route.create_operation_id, ) -def _is_duplicate_sandbox_response(response: ProxiedResponse, sandbox_id: str) -> bool: +def is_duplicate_sandbox_response(response: ProxiedResponse, sandbox_id: str) -> bool: if response.status not in {HTTPStatus.BAD_REQUEST, HTTPStatus.CONFLICT}: return False error_message = str(response.json().get("error") or "").lower() return "already exists" in error_message and sandbox_id.lower() in error_message -def _node_create_may_still_be_running(response: ProxiedResponse) -> bool: +def node_create_may_still_be_running(response: ProxiedResponse) -> bool: if response.transport_error_kind == "dns": # DNS lookup failed before an HTTP connection could be established, so # the node cannot have received or persisted this create operation. @@ -344,7 +344,7 @@ def _node_create_may_still_be_running(response: ProxiedResponse) -> bool: return response.status in {408, 425, 429, 500, 502, 503, 504} -def _node_create_rejection_reason(response: ProxiedResponse) -> str | None: +def node_create_rejection_reason(response: ProxiedResponse) -> str | None: if response.status != HTTPStatus.SERVICE_UNAVAILABLE: return None payload = response.json() @@ -357,12 +357,12 @@ def _node_create_rejection_reason(response: ProxiedResponse) -> str | None: return None -def _image_check_rejection_reason(response: ProxiedResponse) -> str | None: +def image_check_rejection_reason(response: ProxiedResponse) -> str | None: """The image check runs before any create is dispatched, so a refusal there, explicit or retryable (the worker unreachable, timed out, busy), moves the create to another worker or back to pending. Other errors fail it.""" - reason = _node_create_rejection_reason(response) + reason = node_create_rejection_reason(response) if reason is not None: return reason payload = response.json() diff --git a/sandboxes/gateway/fleet.py b/sandboxes/gateway/fleet.py index 0e523336..3b366fb4 100644 --- a/sandboxes/gateway/fleet.py +++ b/sandboxes/gateway/fleet.py @@ -70,7 +70,7 @@ def nodes_with_cached_image( """Nodes whose heartbeat cache proves the image; unknown caches are absent.""" if not image.strip() and not image_id.strip(): return set() - image_keys = _requested_image_cache_keys( + image_keys = requested_image_cache_keys( image, image_id, require_digest=self.registry_refs.requires_digest_identity(image), ) return { @@ -81,7 +81,7 @@ def nodes_with_cached_image( } -def _node_metadata(heartbeat: NodeHeartbeat) -> dict[str, Any]: +def node_metadata(heartbeat: NodeHeartbeat) -> dict[str, Any]: return { "node_id": heartbeat.node_id, "job_id": heartbeat.job_id, @@ -90,7 +90,7 @@ def _node_metadata(heartbeat: NodeHeartbeat) -> dict[str, Any]: } -def _heartbeat_has_image( +def heartbeat_has_image( heartbeat: NodeHeartbeat, image: str, image_id: str = "", @@ -99,7 +99,7 @@ def _heartbeat_has_image( ) -> bool: if not heartbeat.cached_images_known: return False - image_keys = _requested_image_cache_keys( + image_keys = requested_image_cache_keys( image, image_id, require_digest=require_digest, @@ -107,7 +107,7 @@ def _heartbeat_has_image( return bool(image_keys.intersection(heartbeat.cached_images)) -def _requested_image_cache_keys( +def requested_image_cache_keys( image: str, image_id: str = "", *, diff --git a/sandboxes/gateway/groups.py b/sandboxes/gateway/groups.py index 66ecf6f0..107bdecb 100644 --- a/sandboxes/gateway/groups.py +++ b/sandboxes/gateway/groups.py @@ -30,15 +30,15 @@ ) from ..sandbox import SandboxSpec, sandbox_spec_fingerprint from ..worker_receipts import ( - _route_with_sandbox_record, _sandbox_create_request_body, _sandbox_record_matches_route, + route_with_sandbox_record, sandbox_create_request_body, sandbox_record_matches_route, ) from .create import ( - SANDBOX_CREATE_PROXY_TIMEOUT_SECONDS, CreateExchange, CreatePlacement, _incarnation, - _image_check_rejection_reason, _is_duplicate_sandbox_response, _node_create_may_still_be_running, - _node_create_rejection_reason, + SANDBOX_CREATE_PROXY_TIMEOUT_SECONDS, CreateExchange, CreatePlacement, sandbox_incarnation, + image_check_rejection_reason, is_duplicate_sandbox_response, node_create_may_still_be_running, + node_create_rejection_reason, ) -from .fleet import _heartbeat_has_image -from .placement import _sandbox_required_capabilities +from .fleet import heartbeat_has_image +from .placement import sandbox_required_capabilities GROUP_PATH = "/v1/sandboxes:batch" # A member id appends "-dddd", within the 64 characters of a sandbox id. @@ -158,7 +158,7 @@ def create( results[spec.id] = _result(spec.id, route.state.lower(), route) spec_dict = specs[0].to_dict() request = PlacementRequest( - specs[0].requested_resources(), capabilities=_sandbox_required_capabilities(spec_dict), + specs[0].requested_resources(), capabilities=sandbox_required_capabilities(spec_dict), image=specs[0].image, spec=spec_dict, ) root.set_attribute("sandbox.group.unplaced", len(unplaced)) @@ -178,7 +178,7 @@ def create( except SandboxGroupDeletedError: for member in unplaced: # Intents written before the delete are its to remove. if member.route is not None: - self.creates.overlay.release(member.route.job_id, _incarnation(member.route)) + self.creates.overlay.release(member.route.job_id, sandbox_incarnation(member.route)) results.update({m.id: _result(m.id, "deleted") for m in unplaced}) planned, unplaced = [], [] if not batches + planned: @@ -232,7 +232,7 @@ def _plan( require_digest = self.creates.registry_refs.requires_digest_identity(request.image) resident = frozenset( node.job_id for node in view.nodes - if _heartbeat_has_image(node, request.image, require_digest=require_digest) + if heartbeat_has_image(node, request.image, require_digest=require_digest) ) with self.creates.chooser.planning: # The plan and its holds at once: concurrent groups see them. slices = self.creates.chooser.plan_group( @@ -289,7 +289,7 @@ def _write_plan( self.creates.registry_refs.release_route_reference(previous) placed.append(member) for member in placed: - self.creates.overlay.reserve(item.heartbeat, _incarnation(member.route), request) + self.creates.overlay.reserve(item.heartbeat, sandbox_incarnation(member.route), request) if placed: batches.append((item.heartbeat, placed)) return batches, remaining @@ -310,7 +310,7 @@ def _run(self, ex: GroupExchange, group: SandboxGroup, request: PlacementRequest width = min(MAX_GROUP_DISPATCH, sum(len(members) for _node, members in batches)) with ThreadPoolExecutor(len(batches)) as workers, ThreadPoolExecutor(width) as posts: return [future.result() for future in [ - workers.submit(_in_context(self._run_batch), ex, group, request, shared, members, posts) + workers.submit(in_context(self._run_batch), ex, group, request, shared, members, posts) for shared, members in batches ]] @@ -329,10 +329,10 @@ def _run_batch( return {m.id: _result(m.id, "creating", m.route, error_code="image_warmup_pending") for m in members}, [] if image_response is not None and image_response.status >= 400: - reason = _image_check_rejection_reason(image_response) + reason = image_check_rejection_reason(image_response) for member in members: if reason is not None: - self.creates.overlay.release(member.route.job_id, _incarnation(member.route)) + self.creates.overlay.release(member.route.job_id, sandbox_incarnation(member.route)) rejected.append((member, reason)) else: self.creates._abandon(member.spec, member.route, f"image_pull_http_{image_response.status}") @@ -340,28 +340,28 @@ def _run_batch( pull=image_response.json()) return results, rejected responses = [posts.submit( - _in_context(ex._proxy_request), node_url, "/v1/sandboxes", method="POST", - body=_sandbox_create_request_body(member.spec, member.route), + in_context(ex._proxy_request), node_url, "/v1/sandboxes", method="POST", + body=sandbox_create_request_body(member.spec, member.route), timeout_seconds=SANDBOX_CREATE_PROXY_TIMEOUT_SECONDS, ) for member in members] accepted: list[tuple[_Member, dict[str, Any]]] = [] for member, future in zip(members, responses): response, route = future.result(), member.route - duplicate = _is_duplicate_sandbox_response(response, member.id) + duplicate = is_duplicate_sandbox_response(response, member.id) record = (ex._sandbox_record_on_node(node_url, member.id) if duplicate else response.json().get("sandbox") if 200 <= response.status < 300 else None) - reason = _node_create_rejection_reason(response) - if isinstance(record, dict) and _sandbox_record_matches_route(record, route, member.spec): + reason = node_create_rejection_reason(response) + if isinstance(record, dict) and sandbox_record_matches_route(record, route, member.spec): accepted.append((member, record)) elif reason is not None: - self.creates.overlay.release(route.job_id, _incarnation(route)) + self.creates.overlay.release(route.job_id, sandbox_incarnation(route)) rejected.append((member, reason)) - elif duplicate or 200 <= response.status < 300 or _node_create_may_still_be_running(response): + elif duplicate or 200 <= response.status < 300 or node_create_may_still_be_running(response): # The worker may hold this incarnation: keep its route and charge. results[member.id] = _result(member.id, "creating", route, error_code=str(response.json().get("error_code") or "")) else: - self.creates.overlay.release(route.job_id, _incarnation(route)) + self.creates.overlay.release(route.job_id, sandbox_incarnation(route)) removed = self.store.delete_sandbox_if_current( member.id, generation=route.generation, create_operation_id=route.create_operation_id) if removed is not None: @@ -369,12 +369,12 @@ def _run_batch( results[member.id] = _result(member.id, "failed", status_code=int(response.status), error=response.json().get("error") or "node create failed") confirmed = self.store.confirm_creates( - [_route_with_sandbox_record(member.route, record) for member, record in accepted], + [route_with_sandbox_record(member.route, record) for member, record in accepted], group_id=group.group_id, ) if accepted else [] for (member, record), route in zip(accepted, confirmed): if route is None: # Deleted while it was being created. - ex._delete_unowned_create(_route_with_sandbox_record(member.route, record)) + ex._delete_unowned_create(route_with_sandbox_record(member.route, record)) results[member.id] = _result(member.id, "deleted") continue record_sandbox_scheduled( @@ -423,7 +423,7 @@ def delete(self, ex: GroupExchange, group_id: str) -> tuple[int, dict[str, Any], for member in set(group.member_ids()) - set(routed): self.store.clear_pending(member) with ThreadPoolExecutor(MEMBER_DELETE_CONCURRENCY) as pool: - answers = list(pool.map(_in_context(ex._loopback_delete), routed)) + answers = list(pool.map(in_context(ex._loopback_delete), routed)) outcomes = [{"id": member, "status_code": status, **({"error": body.get("error")} if status >= 300 else {})} for member, (status, body) in zip(routed, answers)] payload = {**self._members(group), "deleted": outcomes} @@ -433,7 +433,7 @@ def delete(self, ex: GroupExchange, group_id: str) -> tuple[int, dict[str, Any], return HTTPStatus.OK, payload, {} -def _in_context(function: Callable[..., Any]) -> Callable[..., Any]: +def in_context(function: Callable[..., Any]) -> Callable[..., Any]: """Run on a pool thread in a copy of the caller's context: its trace span and, on the placement worker, the durable command claim.""" diff --git a/sandboxes/gateway/heartbeats.py b/sandboxes/gateway/heartbeats.py index ba552ded..74956fad 100644 --- a/sandboxes/gateway/heartbeats.py +++ b/sandboxes/gateway/heartbeats.py @@ -21,10 +21,10 @@ from ..routing import ( RoutingStore, SandboxRoute, SandboxRouteConflictError, route_with_inventory_snapshot, ) -from ..worker_receipts import _record_generation +from ..worker_receipts import record_generation from .job_reads import parked_job_record from .registry_refs import ( - RegistryImageReferenceUnavailable, RegistryReferences, _portable_snapshot_for_route, + RegistryImageReferenceUnavailable, RegistryReferences, portable_snapshot_for_route, ) # A pull stands in for a late push on a request thread: one bounded worker RPC, @@ -124,7 +124,7 @@ def _run(self, job_id: str, node_url: str, reaps: list[RebootReap]) -> None: try: status, payload = self.delete_on_worker( node_url, reap.sandbox_id, reap.generation, reap.operation_id) - confirmed = 200 <= status < 300 and _record_generation( + confirmed = 200 <= status < 300 and record_generation( payload.get("deleted")) in {None, reap.generation} if confirmed and reap.route is not None: # The same commit as a client-driven delete of this intent. @@ -331,7 +331,7 @@ def _apply(self, heartbeat: NodeHeartbeat, *, first: bool) -> None: if route is None: raise ValueError("inventory snapshot has no assigned route") candidate = route_with_inventory_snapshot(route, item) - snapshot = _portable_snapshot_for_route(candidate) + snapshot = portable_snapshot_for_route(candidate) # The permanent Registry reference must be durable # before the portable route becomes durable. self.registry_refs.ensure_snapshot_reference( diff --git a/sandboxes/gateway/image_resolution.py b/sandboxes/gateway/image_resolution.py index 22c93354..fae5e88a 100644 --- a/sandboxes/gateway/image_resolution.py +++ b/sandboxes/gateway/image_resolution.py @@ -19,9 +19,9 @@ ) from ..registry_disk import RegistryDiskMonitor, RegistryDiskUsage from .exchange import Exchange -from .fleet import FleetView, _node_metadata -from .node_rpc import _header_value -from .registry_refs import _managed_registry_image_coordinates, _managed_registry_worker_reference +from .fleet import FleetView, node_metadata +from .node_rpc import header_value +from .registry_refs import managed_registry_image_coordinates, managed_registry_worker_reference IMAGE_REFERENCE_KIND_HEADER = "X-UCloud-Image-Reference-Kind" MANAGED_REGISTRY_DIGEST_PROTECTION_UNAVAILABLE_ERROR_CODE = ( @@ -128,7 +128,7 @@ def __init__( def is_managed(self, image_ref: str) -> bool: """Whether the reference targets this deployment's managed Registry.""" - return bool(self.registry_url and _managed_registry_image_coordinates( + return bool(self.registry_url and managed_registry_image_coordinates( image_ref, self.registry_url, self.registry_worker_url or "") is not None) def inventory(self, ex: Exchange) -> dict[str, Any]: @@ -163,7 +163,7 @@ def load_raw_inventory(self, ex: Exchange) -> ImageInventorySnapshot: complete = False continue raw = dict(record) - raw["node"] = _node_metadata(heartbeat) + raw["node"] = node_metadata(heartbeat) images.append(raw) return ImageInventorySnapshot.from_records(images, complete=complete) @@ -232,7 +232,7 @@ def resolve_and_protect_manifest(self, image_ref: str) -> str: existing = manifest_digest_from_image_ref(image_ref) if not self.registry_url: return existing - coordinates = _managed_registry_image_coordinates( + coordinates = managed_registry_image_coordinates( image_ref, self.registry_url, self.registry_worker_url or "", ) if coordinates is None: @@ -352,7 +352,7 @@ def resolve( # Read that exact row before discovering copies across the fleet. local = self.image_manager.get_image(image) local_matches = [] - if local is not None and _image_record_available_to_sandboxes(local.to_dict()): + if local is not None and image_record_available_to_sandboxes(local.to_dict()): local_matches = self.enrich_records( ({**local.to_dict(), "location": "control-plane"},), image_id=image, ) @@ -378,7 +378,7 @@ def resolve( available = [ record for record in matches - if _image_record_available_to_sandboxes(record) + if image_record_available_to_sandboxes(record) and isinstance(record.get("tag"), str) and record.get("tag") ] @@ -415,7 +415,7 @@ def resolve( def worker_reference(self, image_ref: str) -> str: if not self.registry_url: return image_ref - return _managed_registry_worker_reference( + return managed_registry_worker_reference( image_ref, self.registry_url, self.registry_worker_url or "", ) @@ -455,8 +455,8 @@ def _digest_protection_unavailable(**identity: str) -> dict[str, Any]: } -def _image_reference_kind_from_headers(headers: Any) -> str: - raw = _header_value(headers, IMAGE_REFERENCE_KIND_HEADER).strip().lower() +def image_reference_kind_from_headers(headers: Any) -> str: + raw = header_value(headers, IMAGE_REFERENCE_KIND_HEADER).strip().lower() if not raw: return "auto" if raw not in {"auto", "name", "registry"}: @@ -486,7 +486,7 @@ def _looks_like_image_id_reference(image: str) -> bool: ) -def _image_record_available_to_sandboxes(record: dict[str, Any]) -> bool: +def image_record_available_to_sandboxes(record: dict[str, Any]) -> bool: return bool( record.get("available_to_sandboxes") or record.get("pushed") @@ -499,7 +499,7 @@ def _image_record_requires_registry_manifest( registry_url: str, registry_worker_url: str = "", ) -> bool: - if not _image_record_available_to_sandboxes(record): + if not image_record_available_to_sandboxes(record): return False source = str(record.get("source") or "") if not source.startswith("build:"): @@ -521,7 +521,7 @@ def _image_record_summary(record: dict[str, Any]) -> dict[str, Any]: "tag": record.get("tag"), "source": record.get("source"), "pushed": bool(record.get("pushed")), - "available_to_sandboxes": _image_record_available_to_sandboxes(record), + "available_to_sandboxes": image_record_available_to_sandboxes(record), } if record.get("manifest_digest"): summary["manifest_digest"] = record.get("manifest_digest") diff --git a/sandboxes/gateway/migration_service.py b/sandboxes/gateway/migration_service.py new file mode 100644 index 00000000..7925de4d --- /dev/null +++ b/sandboxes/gateway/migration_service.py @@ -0,0 +1,1081 @@ +"""Gateway imperative shell for sandbox worker detach and live migrations.""" + +from __future__ import annotations + +from http import HTTPStatus +import json +import sqlite3 +import time +from typing import Any, Callable, Protocol +from urllib.parse import parse_qs, quote, urlparse +from uuid import uuid4 + +from ..exec_routing import heartbeat_proves_route_absent +from ..host_locks import HOST_LOCKS +from ..lifecycle_commit import route_with_snapshot_payload +from ..models import NodeHeartbeat, ResourceQuantity, utc_now +from ..routing import ( + RoutingStore, + SandboxRoute, + SandboxRouteConflictError, + cold_offload_fence, + is_portable_parked_route, + is_worker_detachable_parked_route, +) +from ..storage_native_migration import ( + STORAGE_NATIVE_MIGRATION_SCHEMA, + SUPPORTED_STORAGE_NATIVE_MIGRATION_SCHEMAS, + StorageNativeMigration, +) +from ..wake_admission import WakeAdmission +from ..wake_placement import WakePlacementStopped, WakeUnavailable +from .fleet import FleetView +from .migrations import ( + build_migration_destination_route, + cold_offload_fence_matches, + migration_pending_demand_id, + parse_detach_request, + parse_migration_request, + select_migration_destination, + validate_prepared_migration_metadata, + validate_staged_migration_metadata, +) +from .node_rpc import ProxiedResponse +from .placement import Placement +from .registry_refs import ( + RegistryImageReferenceUnavailable, + RegistryReferences, + portable_snapshot_for_route, +) + + +RETRY_AFTER_SECONDS = 5 +MIGRATION_RPC_TIMEOUT_SECONDS = 3600 + + +def migration_operation_lock(migration_id: str): + """Serialize one migration's worker export and stage calls across processes. + + Phase commits are compare-and-set in PostgreSQL, but the worker calls between + them are not; the public gateways and the placement worker all advance + migrations. + """ + return HOST_LOCKS.hold("migration", migration_id.strip()) + + +def precise_elapsed_ms(started: float) -> float: + return round(max(0.0, (time.monotonic() - started) * 1000), 3) + + +class MigrationExchange(Protocol): + """Request-scoped I/O surface required by SandboxMigrations.""" + + path: str + + def _read_json_body(self) -> Any: ... + def _write_json( + self, + payload: dict[str, Any], + *, + status: int = ..., + headers: dict[str, str] | None = None, + ) -> None: ... + def _proxy_request( + self, + node_url: str, + path: str, + *, + method: str, + body: Any = None, + timeout_seconds: float = ..., + extra_headers: dict[str, str] | None = None, + ) -> ProxiedResponse: ... + def _heartbeat_for_route( + self, + *, + job_id: str, + include_inventory: bool = True, + ) -> NodeHeartbeat | None: ... + def _ensure_image_on_node( + self, + heartbeat: NodeHeartbeat, + image: str, + environment_root: str | None = None, + ) -> ProxiedResponse | None: ... + def _write_missing_sandbox_route(self, sandbox_id: str) -> None: ... + def _write_registry_lease_unavailable( + self, exc: RegistryImageReferenceUnavailable + ) -> None: ... + def _write_routing_store_unavailable( + self, exc: sqlite3.DatabaseError + ) -> None: ... + def _write_wake_unavailable(self, outcome: WakeUnavailable) -> None: ... + + +class SandboxMigrations: + """Imperative orchestration for sandbox worker detach and parked migrations.""" + + def __init__( + self, + *, + routing_store: RoutingStore | None, + registry_refs: RegistryReferences, + fleet: FleetView, + placement: Placement, + operation_lock: Callable[[str], Any] = migration_operation_lock, + ) -> None: + self.routing_store = routing_store + self.registry_refs = registry_refs + self.fleet = fleet + self.placement = placement + self.operation_lock = operation_lock + + def _routing(self, ex: Any) -> RoutingStore: + if self.routing_store is not None: + return self.routing_store + return ex.routing_store + + def detach_sandbox( + self, + ex: MigrationExchange, + sandbox_id: str, + *, + publish_for_detach: Callable[[SandboxRoute], tuple[SandboxRoute | None, str]] | None = None, + finish_detach: Callable[[SandboxRoute], tuple[SandboxRoute | None, str]] | None = None, + ) -> None: + routing = self._routing(ex) + publish = publish_for_detach or (lambda route: self.publish_route_for_detach(ex, route)) + finish = finish_detach or (lambda route: self.finish_sandbox_detach(ex, route)) + retry_headers = { + "Retry-After": str(RETRY_AFTER_SECONDS), + "X-UCloud-Sandbox-Retryable": "true", + } + try: + require_cold, if_cold = parse_detach_request(ex._read_json_body()) + route = routing.get_sandbox_readonly(sandbox_id) + if route is None: + ex._write_missing_sandbox_route(sandbox_id) + return + if require_cold: + assert if_cold is not None + if not cold_offload_fence_matches(cold_offload_fence(route), if_cold): + raise SandboxRouteConflictError( + "cold offload observation no longer owns the snapshot" + ) + if route.worker_state == "detached": + ex._write_json({"ok": True, "sandbox": route.to_dict()}) + return + if route.worker_state == "attached" and not is_portable_parked_route(route): + if not is_worker_detachable_parked_route(route): + raise SandboxRouteConflictError( + "only a parked sandbox can detach from a worker" + ) + route, publication_error = publish(route) + if route is None: + ex._write_json( + { + "error": publication_error + or "parked snapshot publication is incomplete", + "retryable": True, + }, + status=HTTPStatus.SERVICE_UNAVAILABLE, + headers=retry_headers, + ) + return + if not is_portable_parked_route(route): + raise SandboxRouteConflictError( + "only a fully published parked sandbox can detach from a worker" + ) + portable_snapshot_for_route(route) + self.registry_refs.ensure_route_reference(route, touch=True) + fenced = routing.begin_sandbox_detach(route, require_cold=require_cold) + if fenced is None: + raise SandboxRouteConflictError( + "sandbox route changed before worker detach began" + ) + detached, error_message = finish(fenced) + if detached is None: + ex._write_json( + { + "error": error_message or "worker detach is incomplete", + "retryable": True, + }, + status=HTTPStatus.SERVICE_UNAVAILABLE, + headers=retry_headers, + ) + return + ex._write_json({"ok": True, "sandbox": detached.to_dict()}) + except RegistryImageReferenceUnavailable as exc: + ex._write_registry_lease_unavailable(exc) + except (SandboxRouteConflictError, ValueError) as exc: + ex._write_json({"error": str(exc)}, status=HTTPStatus.CONFLICT) + + def publish_route_for_detach( + self, + ex: MigrationExchange, + route: SandboxRoute, + ) -> tuple[SandboxRoute | None, str]: + routing = self._routing(ex) + response = ex._proxy_request( + route.node_url, + f"/v1/sandboxes/{quote(route.sandbox_id, safe='')}/publish-parked", + method="POST", + body=json.dumps( + { + "generation": route.generation, + "create_operation_id": route.create_operation_id, + "spec_hash": route.spec_hash, + }, + separators=(",", ":"), + ).encode("utf-8"), + extra_headers={"Content-Type": "application/json"}, + timeout_seconds=MIGRATION_RPC_TIMEOUT_SECONDS, + ) + if response.status >= 400: + error_message = str(response.json().get("error") or "").strip() + return ( + None, + error_message + or f"worker parked publication returned HTTP {response.status}", + ) + try: + payload = response.json() + candidate = route_with_snapshot_payload(route, payload) + except (TypeError, ValueError, json.JSONDecodeError) as exc: + return None, f"worker returned invalid parked publication: {exc}" + self.registry_refs.ensure_snapshot_reference( + candidate, + repository=candidate.snapshot_repository, + tag=candidate.snapshot_tag, + digest=candidate.snapshot_manifest_digest, + ) + try: + stored = routing.set_sandbox_state_if_current( + route, + expected_states={"parked"}, + state="parked", + storage_schema=candidate.storage_schema, + snapshot_manifest_digest=candidate.snapshot_manifest_digest, + snapshot_repository=candidate.snapshot_repository, + snapshot_tag=candidate.snapshot_tag, + storage_snapshot=candidate.storage_snapshot, + ) + except BaseException: + # Commit acknowledgement can fail after the candidate became + # durable. Reconcile against a successful read-back and otherwise + # retain the candidate reference conservatively. + try: + current = routing.get_sandbox_readonly(route.sandbox_id) + except BaseException: + raise + self.registry_refs.release_snapshot_reference( + candidate, + keep_route=current, + ) + raise + if stored is None: + self.registry_refs.release_snapshot_reference( + candidate, + keep_route=routing.get_sandbox_readonly(route.sandbox_id), + ) + return None, "sandbox route changed while its parked snapshot published" + self.registry_refs.release_snapshot_reference(route, keep_route=stored) + return stored, "" + + def finish_sandbox_detach( + self, + ex: MigrationExchange, + route: SandboxRoute, + ) -> tuple[SandboxRoute | None, str]: + routing = self._routing(ex) + current = routing.get_sandbox_readonly(route.sandbox_id) + if current is None: + return None, "sandbox route disappeared during worker detach" + if not WakeAdmission.same_incarnation(current, route) or current.delete_operation_id: + return None, "sandbox route changed during worker detach" + if current.worker_state == "detached": + return current, "" + if current.worker_state != "detaching" or not is_portable_parked_route(current): + return None, "sandbox route changed during worker detach" + heartbeat = ex._heartbeat_for_route(job_id=current.job_id) + if heartbeat_proves_route_absent( + heartbeat, + sandbox_id=current.sandbox_id, + route_created_at=current.created_at, + route_updated_at=current.updated_at, + heartbeat_ttl_seconds=self.fleet.heartbeat_ttl_seconds, + ): + completed = routing.complete_sandbox_detach(current) + return completed, "" if completed is not None else "detach fence changed" + response = ex._proxy_request( + current.node_url, + f"/v1/sandboxes/{quote(current.sandbox_id, safe='')}/evict-published", + method="POST", + body=json.dumps( + { + "generation": current.generation, + "snapshot_manifest_digest": current.snapshot_manifest_digest, + }, + separators=(",", ":"), + ).encode("utf-8"), + extra_headers={"Content-Type": "application/json"}, + ) + if response.status >= 400: + error_message = str(response.json().get("error") or "").strip() + return ( + None, + error_message + or f"worker published eviction returned HTTP {response.status}", + ) + completed = routing.complete_sandbox_detach(current) + if completed is None: + return None, "sandbox route changed before worker detach committed" + return completed, "" + + def _ensure_soft_drain_published( + self, + routing: RoutingStore, + sandbox_id: str, + *, + publish: Callable[[SandboxRoute], tuple[SandboxRoute | None, str]], + ) -> WakeUnavailable | None: + source = routing.get_sandbox_readonly(sandbox_id) + if ( + source is None + or source.state.lower() != "parked" + or source.worker_state != "attached" + or source.delete_operation_id + or is_portable_parked_route(source) + ): + return None + published, error = publish(source) + if published is None: + return WakeUnavailable( + error or "sandbox is no longer a parked sandbox", + error_code="migration_source_not_parked", + retry_after=1, + ) + return None + + def _reserve_migration( + self, + routing: RoutingStore, + *, + sandbox_id: str, + migration_id: str, + requested_destination: str, + soft_drain: bool, + select_destination: Callable[..., NodeHeartbeat | None], + ): + def reserve(): + existing = routing.get_sandbox_migration(migration_id) + if existing is not None: + if existing.sandbox_id != sandbox_id: + raise SandboxRouteConflictError("migration id belongs to another sandbox") + return existing + source = routing.get_sandbox_readonly(sandbox_id) + if source is None: + return WakeUnavailable("sandbox route not found", missing_sandbox_id=sandbox_id) + if soft_drain and not is_portable_parked_route(source): + return WakeUnavailable( + "sandbox is no longer a published park", + error_code="migration_source_not_parked", + retry_after=1, + ) + destination = select_destination(source, requested_node_id=requested_destination) + if destination is None and soft_drain: + return WakeUnavailable( + "no ready destination for soft-drain move", + error_code="migration_destination_unavailable", + retry_after=1, + ) + if destination is None: + _, demand = routing.upsert_pending_with_demand( + migration_pending_demand_id(sandbox_id), + ResourceQuantity(disk_mb=source.resources.disk_mb), + failure_reason="migration_destination_unavailable", + ) + return WakeUnavailable( + "no ready destination has disk capacity for parked sandbox migration", + error_code="migration_destination_unavailable", + retry_after=1, + pending_resources=demand.pending_resources, + ) + return routing.begin_sandbox_migration( + source, + migration_id=migration_id, + destination_node_id=destination.node_id, + destination_job_id=destination.job_id, + destination_node_url=destination.node_url or "", + ) + + return self.placement.atomic(reserve) + + def migrate_sandbox( + self, + ex: MigrationExchange, + sandbox_id: str, + *, + publish_for_detach: Callable[[SandboxRoute], tuple[SandboxRoute | None, str]] | None = None, + select_destination: Callable[..., NodeHeartbeat | None] | None = None, + prepare_and_advance: Callable[..., Any] | None = None, + abort_migration: Callable[[Any], tuple[Any, str]] | None = None, + ) -> None: + routing = self._routing(ex) + publish = publish_for_detach or (lambda route: self.publish_route_for_detach(ex, route)) + choose_destination = select_destination or ( + lambda source, *, requested_node_id: self.select_destination( + ex, source, requested_node_id=requested_node_id + ) + ) + run_migration = prepare_and_advance or ( + lambda migration, *, timings_ms=None: self.prepare_and_advance( + ex, migration, timings_ms=timings_ms + ) + ) + abort = abort_migration or (lambda migration: self.abort_migration(ex, migration)) + try: + migration_id, requested_destination, soft_drain = parse_migration_request( + ex._read_json_body(), + default_migration_id=f"migration-{uuid4().hex}", + ) + migration = routing.get_sandbox_migration(migration_id) + if migration is not None and migration.sandbox_id != sandbox_id: + raise SandboxRouteConflictError("migration id belongs to another sandbox") + if migration is None and soft_drain: + # The gateway learns a worker's publication from its next + # heartbeat; agents that wake every few seconds are rarely seen + # as published parks. Ask the owner now, outside the placement + # lock (the worker reuses an existing publication). + unavailable = self._ensure_soft_drain_published( + routing, sandbox_id, publish=publish + ) + if unavailable is not None: + ex._write_wake_unavailable(unavailable) + return + if migration is None: + reserved = self._reserve_migration( + routing, + sandbox_id=sandbox_id, + migration_id=migration_id, + requested_destination=requested_destination, + soft_drain=soft_drain, + select_destination=choose_destination, + ) + if isinstance(reserved, WakeUnavailable): + ex._write_wake_unavailable(reserved) + return + migration = reserved + assert migration is not None + routing.clear_pending(migration_pending_demand_id(sandbox_id)) + migration_timings_ms: dict[str, float] = {} + migration = run_migration(migration, timings_ms=migration_timings_ms) + if migration is None: + return + except WakePlacementStopped as stopped: + ex._write_wake_unavailable(stopped.outcome) + return + except (SandboxRouteConflictError, ValueError) as exc: + ex._write_json({"error": str(exc)}, status=HTTPStatus.CONFLICT) + return + except sqlite3.DatabaseError as exc: + ex._write_routing_store_unavailable(exc) + return + if migration.phase != "complete": + aborted = False + if soft_drain and migration.phase in {"planned", "prepared", "staged"}: + # A drain move is optional: roll it back at once so the source + # is never left fenced (unable to wake) by a failed import. + migration, abort_error = abort(migration) + aborted = not abort_error + ex._write_json( + { + "error": migration.error or "sandbox migration is incomplete", + "migration": migration.to_dict(), + "retryable": True, + "aborted": aborted, + "timings_ms": migration_timings_ms, + }, + status=HTTPStatus.SERVICE_UNAVAILABLE, + ) + return + route = routing.get_sandbox_readonly(sandbox_id) + ex._write_json( + { + "migration": migration.to_dict(), + "sandbox": route.to_dict() if route is not None else None, + "timings_ms": migration_timings_ms, + } + ) + + def select_destination( + self, + ex: MigrationExchange, + source: SandboxRoute, + *, + requested_node_id: str, + require_active_resources: bool = False, + ) -> NodeHeartbeat | None: + routing = self._routing(ex) + routes = self.placement.routes() + active_migrations = routing.sandbox_migrations(active_only=True) + ready_heartbeats = self.fleet.ready_sandbox_heartbeats() + source_heartbeat = next( + ( + heartbeat + for heartbeat in ready_heartbeats + if heartbeat.node_id == source.node_id + or ( + source.node_url + and heartbeat.node_url + and heartbeat.node_url.rstrip("/") == source.node_url.rstrip("/") + ) + ), + None, + ) + if source_heartbeat is None and source.worker_state == "attached": + # Closed admission/draining excludes a destination, not a source. + # Busy workers must still be able to export their parked state. + owner = ex._heartbeat_for_route(job_id=source.job_id) + if ( + owner is not None + and owner.node_id == source.node_id + and owner.is_fresh(utc_now(), self.fleet.heartbeat_ttl_seconds) + ): + source_heartbeat = owner + return select_migration_destination( + source, + ready_heartbeats=ready_heartbeats, + routes=routes, + active_migrations=active_migrations, + source_heartbeat=source_heartbeat, + requested_node_id=requested_node_id, + require_active_resources=require_active_resources, + ) + + def prepare_destination_image( + self, + ex: MigrationExchange, + source: SandboxRoute, + destination: NodeHeartbeat, + ) -> None: + image = str(source.spec.get("image") or "").strip() + response = ex._ensure_image_on_node( + destination, image, source.spec.get("environment_root") + ) + if response is not None and response.status >= 400: + error = response.json() + raise WakePlacementStopped( + WakeUnavailable( + "migration destination could not prepare the sandbox image", + details={ + "image": image, + "node_id": destination.node_id, + "node_error": error.get("error") or error, + }, + ) + ) + + def prepare_and_advance( + self, + ex: MigrationExchange, + migration: Any, + *, + timings_ms: dict[str, float] | None = None, + wake_on_complete: bool = False, + prepare_destination_image: Callable[[SandboxRoute, NodeHeartbeat], None] | None = None, + advance: Callable[..., Any] | None = None, + ): + """Existing migration authority, with domain failures rather than HTTP writes.""" + routing = self._routing(ex) + prepare_image = prepare_destination_image or ( + lambda source, destination: self.prepare_destination_image(ex, source, destination) + ) + advance_fn = advance or ( + lambda current, *, timings_ms=None, wake_on_complete=False: self.advance( + ex, current, timings_ms=timings_ms, wake_on_complete=wake_on_complete + ) + ) + with self.operation_lock(migration.migration_id): + current = routing.get_sandbox_migration(migration.migration_id) + if current is None: + raise WakePlacementStopped(WakeUnavailable("sandbox migration disappeared")) + if current.phase == "complete": + return ( + routing.complete_sandbox_migration( + current.migration_id, wake_destination=wake_on_complete + ) + or current + ) + if current.phase == "planned": + source = routing.get_sandbox_readonly(current.sandbox_id) + destination = next( + ( + heartbeat + for heartbeat in self.fleet.ready_sandbox_heartbeats() + if heartbeat.node_id == current.destination_node_id + and heartbeat.job_id == current.destination_job_id + and (heartbeat.node_url or "").rstrip("/") + == current.destination_node_url.rstrip("/") + ), + None, + ) + if source is None or destination is None: + raise WakePlacementStopped( + WakeUnavailable( + "migration source or destination is unavailable", + migration=current, + ) + ) + prepare_image(source, destination) + return advance_fn( + current, timings_ms=timings_ms, wake_on_complete=wake_on_complete + ) + + def _record_error( + self, + routing: RoutingStore, + migration: Any, + response: ProxiedResponse | None = None, + *, + error_message: str = "", + ): + detail = error_message + if response is not None: + payload = response.json() + detail = str(payload.get("error") or "").strip() + if not detail: + detail = f"node migration request returned HTTP {response.status}" + return ( + routing.advance_sandbox_migration( + migration.migration_id, + expected_phases={migration.phase}, + phase=migration.phase, + error=detail, + ) + or migration + ) + + def _advance_planned( + self, + ex: MigrationExchange, + routing: RoutingStore, + migration: Any, + measured: dict[str, float], + ): + source_route = routing.get_sandbox_readonly(migration.sandbox_id) + route_snapshot: StorageNativeMigration | None = None + if source_route is not None and is_portable_parked_route(source_route): + try: + route_snapshot = portable_snapshot_for_route(source_route) + except ValueError: + route_snapshot = None + phase_started = time.monotonic() + if source_route is None: + return self._record_error( + routing, migration, error_message="migration source route disappeared" + ) + if source_route.worker_state == "detached": + if route_snapshot is None: + return self._record_error( + routing, + migration, + error_message="detached route has no valid published snapshot", + ) + migration = ( + routing.advance_sandbox_migration( + migration.migration_id, + expected_phases={"planned"}, + phase="prepared", + storage_schema=route_snapshot.schema, + snapshot_sha256=route_snapshot.sha256, + storage_snapshot=route_snapshot.to_dict(), + source_fenced=False, + error="", + ) + or migration + ) + elif source_route.worker_state == "attached": + response = ex._proxy_request( + migration.source_node_url, + f"/v1/sandboxes/{quote(migration.sandbox_id, safe='')}/migration/prepare", + method="POST", + body=json.dumps( + { + "migration_id": migration.migration_id, + "format": STORAGE_NATIVE_MIGRATION_SCHEMA, + } + ).encode("utf-8"), + extra_headers={"Content-Type": "application/json"}, + timeout_seconds=MIGRATION_RPC_TIMEOUT_SECONDS, + ) + if response.status >= 400: + return self._record_error(routing, migration, response) + prepared = response.json().get("migration") + if not isinstance(prepared, dict): + return self._record_error( + routing, + migration, + error_message="source returned invalid migration metadata", + ) + try: + storage_schema, snapshot_sha256, snapshot_dict = ( + validate_prepared_migration_metadata(prepared) + ) + except ValueError as exc: + return self._record_error( + routing, + migration, + error_message=f"source returned invalid snapshot: {exc}", + ) + migration = ( + routing.advance_sandbox_migration( + migration.migration_id, + expected_phases={"planned"}, + phase="prepared", + storage_schema=storage_schema, + snapshot_sha256=snapshot_sha256, + storage_snapshot=snapshot_dict, + source_fenced=True, + error="", + ) + or migration + ) + else: + return self._record_error( + routing, migration, error_message="migration source is still detaching" + ) + measured["prepare_export"] = precise_elapsed_ms(phase_started) + return migration + + def _advance_prepared( + self, + ex: MigrationExchange, + routing: RoutingStore, + migration: Any, + measured: dict[str, float], + ): + phase_started = time.monotonic() + if migration.storage_schema not in SUPPORTED_STORAGE_NATIVE_MIGRATION_SCHEMAS: + return self._record_error( + routing, + migration, + error_message="migration is missing storage-native metadata", + ) + import_payload = { + "migration_id": migration.migration_id, + "sandbox_id": migration.sandbox_id, + "snapshot_sha256": migration.snapshot_sha256, + "storage_schema": migration.storage_schema, + "storage_snapshot": migration.storage_snapshot, + } + response = ex._proxy_request( + migration.destination_node_url, + "/v1/migrations/import", + method="POST", + body=json.dumps(import_payload).encode("utf-8"), + extra_headers={"Content-Type": "application/json"}, + timeout_seconds=MIGRATION_RPC_TIMEOUT_SECONDS, + ) + measured["transfer_and_stage"] = precise_elapsed_ms(phase_started) + if response.status >= 400: + return self._record_error(routing, migration, response) + try: + destination_snapshot = validate_staged_migration_metadata( + response.json(), + expected_schema=migration.storage_schema, + source_snapshot=migration.storage_snapshot, + ) + except ValueError as exc: + return self._record_error( + routing, + migration, + error_message=f"destination returned invalid snapshot: {exc}", + ) + return ( + routing.advance_sandbox_migration( + migration.migration_id, + expected_phases={"prepared"}, + phase="staged", + storage_snapshot=destination_snapshot, + error="", + ) + or migration + ) + + def _advance_staged( + self, + routing: RoutingStore, + migration: Any, + measured: dict[str, float], + ): + phase_started = time.monotonic() + source_route = routing.get_sandbox_readonly(migration.sandbox_id) + destination_route: SandboxRoute | None = None + try: + destination_route = build_migration_destination_route(source_route, migration) + # Both the image and portable snapshot must be protected under + # the destination owner before routing can point at it. + self.registry_refs.ensure_route_reference(destination_route, touch=True) + except (RegistryImageReferenceUnavailable, ValueError) as exc: + if destination_route is not None and source_route is not None: + self.registry_refs.release_route_reference( + destination_route, keep_route=source_route + ) + return self._record_error( + routing, + migration, + error_message=( + f"destination registry references could not be persisted: {exc}" + ), + ) + try: + routed = routing.route_sandbox_migration(migration.migration_id) + except BaseException: + try: + current_route = routing.get_sandbox_readonly(migration.sandbox_id) + except BaseException: + raise + self.registry_refs.release_route_reference( + destination_route, keep_route=current_route + ) + raise + measured["route_commit"] = precise_elapsed_ms(phase_started) + if routed is None: + self.registry_refs.release_route_reference( + destination_route, keep_route=source_route + ) + return self._record_error( + routing, + migration, + error_message="sandbox route changed before migration commit", + ) + migration, destination_route = routed + self.registry_refs.release_route_reference( + source_route, keep_route=destination_route + ) + return migration + + def _advance_routed( + self, + ex: MigrationExchange, + routing: RoutingStore, + migration: Any, + measured: dict[str, float], + ): + phase_started = time.monotonic() + response = ex._proxy_request( + migration.destination_node_url, + f"/v1/sandboxes/{quote(migration.sandbox_id, safe='')}/migration/activate", + method="POST", + body=json.dumps( + { + "snapshot_sha256": migration.snapshot_sha256, + "migration_id": migration.migration_id, + } + ).encode("utf-8"), + extra_headers={"Content-Type": "application/json"}, + timeout_seconds=MIGRATION_RPC_TIMEOUT_SECONDS, + ) + measured["activate_destination"] = precise_elapsed_ms(phase_started) + if response.status >= 400: + return self._record_error(routing, migration, response) + return ( + routing.advance_sandbox_migration( + migration.migration_id, + expected_phases={"routed"}, + phase="activated", + error="", + ) + or migration + ) + + def _advance_activated( + self, + ex: MigrationExchange, + routing: RoutingStore, + migration: Any, + measured: dict[str, float], + *, + wake_on_complete: bool, + ): + phase_started = time.monotonic() + if not migration.source_fenced: + measured["finalize_source"] = 0.0 + return ( + routing.complete_sandbox_migration( + migration.migration_id, wake_destination=wake_on_complete + ) + or migration + ) + response = ex._proxy_request( + migration.source_node_url, + f"/v1/sandboxes/{quote(migration.sandbox_id, safe='')}/migration/finalize", + method="POST", + body=json.dumps( + { + "snapshot_sha256": migration.snapshot_sha256, + "migration_id": migration.migration_id, + } + ).encode("utf-8"), + extra_headers={"Content-Type": "application/json"}, + timeout_seconds=MIGRATION_RPC_TIMEOUT_SECONDS, + ) + measured["finalize_source"] = precise_elapsed_ms(phase_started) + if response.status >= 400: + return self._record_error(routing, migration, response) + return ( + routing.complete_sandbox_migration( + migration.migration_id, wake_destination=wake_on_complete + ) + or migration + ) + + def advance( + self, + ex: MigrationExchange, + migration: Any, + *, + timings_ms: dict[str, float] | None = None, + wake_on_complete: bool = False, + ): + routing = self._routing(ex) + advance_started = time.monotonic() + measured = timings_ms if timings_ms is not None else {} + if migration.phase == "planned": + migration = self._advance_planned(ex, routing, migration, measured) + if migration.phase == "prepared": + migration = self._advance_prepared(ex, routing, migration, measured) + if migration.phase == "staged": + migration = self._advance_staged(routing, migration, measured) + if migration.phase == "routed": + migration = self._advance_routed(ex, routing, migration, measured) + if migration.phase == "activated": + migration = self._advance_activated( + ex, routing, migration, measured, wake_on_complete=wake_on_complete + ) + measured["protocol_total"] = precise_elapsed_ms(advance_started) + return migration + + def cancel_migration( + self, + ex: MigrationExchange, + sandbox_id: str, + *, + abort_migration: Callable[[Any], tuple[Any, str]] | None = None, + ) -> None: + routing = self._routing(ex) + abort = abort_migration or (lambda migration: self.abort_migration(ex, migration)) + query = parse_qs(urlparse(ex.path).query, keep_blank_values=True) + migration_id = (query.get("migration_id") or [""])[0].strip() + migration = routing.get_sandbox_migration(migration_id) + if migration is None or migration.sandbox_id != sandbox_id: + ex._write_json( + {"error": "sandbox migration not found"}, + status=HTTPStatus.NOT_FOUND, + ) + return + if migration.phase in {"routed", "activated"}: + ex._write_json( + { + "error": ( + "migration routing is already committed; retry the " + "migration to finish it" + ) + }, + status=HTTPStatus.CONFLICT, + ) + return + if migration.phase == "complete": + ex._write_json({"migration": migration.to_dict()}) + return + migration, error_message = abort(migration) + if error_message: + ex._write_json( + { + "error": error_message, + "migration": migration.to_dict(), + "retryable": True, + }, + status=HTTPStatus.SERVICE_UNAVAILABLE, + ) + return + ex._write_json({"migration": migration.to_dict()}) + + def abort_migration( + self, + ex: MigrationExchange, + migration: Any, + ) -> tuple[Any, str]: + """Roll back an uncommitted migration using its durable journal.""" + routing = self._routing(ex) + payload = json.dumps( + { + "snapshot_sha256": migration.snapshot_sha256, + "migration_id": migration.migration_id, + } + ).encode("utf-8") + headers = {"Content-Type": "application/json"} + if migration.phase in {"prepared", "staged"}: + destination = ex._proxy_request( + migration.destination_node_url, + f"/v1/sandboxes/{quote(migration.sandbox_id, safe='')}/migration/abort-import", + method="POST", + body=payload, + extra_headers=headers, + timeout_seconds=MIGRATION_RPC_TIMEOUT_SECONDS, + ) + if destination.status >= 400: + migration = self._record_error(routing, migration, destination) + return migration, migration.error + source = ex._proxy_request( + migration.source_node_url, + f"/v1/sandboxes/{quote(migration.sandbox_id, safe='')}/migration/abort", + method="POST", + body=payload, + extra_headers=headers, + timeout_seconds=MIGRATION_RPC_TIMEOUT_SECONDS, + ) + if source.status >= 400: + migration = self._record_error(routing, migration, source) + return migration, migration.error + migration = ( + routing.advance_sandbox_migration( + migration.migration_id, + expected_phases={migration.phase}, + phase="complete", + error="cancelled before route commit", + ) + or migration + ) + return migration, "" + + def resolve_for_delete( + self, + ex: MigrationExchange, + sandbox_id: str, + *, + advance: Callable[[Any], Any] | None = None, + abort_migration: Callable[[Any], tuple[Any, str]] | None = None, + ) -> str: + """Finish or roll back migration journals before replaying deletion.""" + routing = self._routing(ex) + advance_fn = advance or (lambda migration: self.advance(ex, migration)) + abort = abort_migration or (lambda migration: self.abort_migration(ex, migration)) + active = [ + migration + for migration in routing.sandbox_migrations(active_only=True) + if migration.sandbox_id == sandbox_id + ] + for migration in active: + if migration.phase in {"routed", "activated"}: + migration = advance_fn(migration) + if migration.phase != "complete": + return ( + migration.error or "committed sandbox migration is incomplete" + ) + continue + migration, error_message = abort(migration) + if error_message: + return error_message + return "" diff --git a/sandboxes/gateway/migrations.py b/sandboxes/gateway/migrations.py new file mode 100644 index 00000000..4b8a450e --- /dev/null +++ b/sandboxes/gateway/migrations.py @@ -0,0 +1,342 @@ +"""Pure migration destination selection and runtime/CPU compatibility checks. + +No database queries, network I/O, or clocks: the gateway shell gathers +``ready_heartbeats``, ``routes``, ``active_migrations``, and the optional +``source_heartbeat`` and passes them into ``select_migration_destination``. +""" + +from __future__ import annotations + +from dataclasses import replace +import re +from typing import Any, Iterable + +from ..capabilities import ( + HOST_EROFS_CAPABILITY, + RUNTIME_COMPATIBILITY_CAPABILITY_PREFIX, + RUNTIME_CPU_CAPABILITY_PREFIX, + SPLIT_CHECKPOINT_CAPABILITY, + STORAGE_NATIVE_CAPABILITY, + STORAGE_NATIVE_MIGRATION_CAPABILITY, +) +from ..models import NodeHeartbeat, ResourceQuantity, is_soft_drained +from ..placement_accounting import ( + PlacementRecord, + node_available_resources, + placement_route_index, +) +from ..routing import SandboxMigration, SandboxRoute, is_portable_parked_route +from ..storage_native_migration import ( + SPLIT_MIGRATION_SCHEMA, + SUPPORTED_STORAGE_NATIVE_MIGRATION_SCHEMAS, + StorageNativeMigration, +) +from .fleet import heartbeat_has_image +from .placement import node_can_fit_available, sandbox_required_capabilities +from .registry_refs import portable_snapshot_for_route + + +def validate_prepared_migration_metadata( + prepared: Any, +) -> tuple[str, str, dict[str, Any]]: + """Validate source /migration/prepare metadata; returns (schema, sha256, snapshot).""" + if not isinstance(prepared, dict): + raise ValueError("source returned invalid migration metadata") + storage_schema = str(prepared.get("storage_schema") or "") + if storage_schema not in SUPPORTED_STORAGE_NATIVE_MIGRATION_SCHEMAS: + raise ValueError("unsupported migration storage schema") + storage_snapshot = StorageNativeMigration.from_dict( + prepared.get("storage_snapshot") + ) + snapshot_sha256 = str(prepared.get("snapshot_sha256") or "") + if storage_snapshot.schema != storage_schema: + raise ValueError("source schema does not match snapshot descriptor") + if storage_snapshot.sha256 != snapshot_sha256: + raise ValueError("source snapshot digest does not match metadata") + return storage_schema, snapshot_sha256, storage_snapshot.to_dict() + + +def validate_staged_migration_metadata( + response_body: dict[str, Any], + *, + expected_schema: str, + source_snapshot: dict[str, Any], +) -> dict[str, Any]: + """Validate destination /v1/migrations/import metadata against source manifest.""" + if str(response_body.get("storage_schema") or "") != expected_schema: + raise ValueError("destination changed the storage schema") + parsed_destination = StorageNativeMigration.from_dict( + response_body.get("storage_snapshot") + ) + if ( + parsed_destination.manifest + != StorageNativeMigration.from_dict(source_snapshot).manifest + ): + raise ValueError("destination changed portable migration metadata") + return parsed_destination.to_dict() + + +def build_migration_destination_route( + source_route: SandboxRoute | None, + migration: SandboxMigration, +) -> SandboxRoute: + """Project the destination SandboxRoute whose registry leases must be ensured.""" + destination_snapshot = StorageNativeMigration.from_dict(migration.storage_snapshot) + destination_publication = destination_snapshot.reference + if source_route is None: + raise ValueError("source route disappeared") + return replace( + source_route, + node_id=migration.destination_node_id, + job_id=migration.destination_job_id, + node_url=migration.destination_node_url, + storage_schema=migration.storage_schema, + snapshot_manifest_digest=destination_publication.manifest_digest, + snapshot_repository=destination_publication.repository, + snapshot_tag=destination_publication.tag, + storage_snapshot=destination_snapshot.to_dict(), + ) + + +def migration_runtime_capability( + route: SandboxRoute, + owner: NodeHeartbeat | None, +) -> str | None: + """Use the same immutable runtime identity that import already validates. + + A detached checkpoint retains this identity without its former worker. + Only an attached, pre-capability Docker source keeps legacy eligibility. + Runtime fingerprints deliberately exclude node-local paths and addresses. + """ + if route.storage_snapshot: + snapshot = portable_snapshot_for_route(route) + return ( + RUNTIME_COMPATIBILITY_CAPABILITY_PREFIX + + snapshot.manifest.runtime.node_compatibility_sha256 + ) + if route.worker_state != "attached" or owner is None: + raise ValueError("migration source runtime is unavailable") + advertised = [ + value + for value in owner.capabilities + if value.startswith(RUNTIME_COMPATIBILITY_CAPABILITY_PREFIX) + ] + if advertised: + if len(advertised) != 1 or not re.fullmatch( + r"[0-9a-f]{64}", + advertised[0][len(RUNTIME_COMPATIBILITY_CAPABILITY_PREFIX) :], + ): + raise ValueError("migration source advertises an invalid runtime") + return advertised[0] + if HOST_EROFS_CAPABILITY in owner.capabilities: + raise ValueError("immutable environment source lacks its runtime identity") + return None + + +def migration_cpu_capability( + route: SandboxRoute, + owner: NodeHeartbeat | None, +) -> str | None: + """The CPU feature identity a destination's import will require, if known.""" + if route.storage_snapshot: + try: + snapshot = portable_snapshot_for_route(route) + except ValueError: + return None + return ( + RUNTIME_CPU_CAPABILITY_PREFIX + + snapshot.manifest.runtime.cpu_features_sha256 + ) + if owner is None: + return None + advertised = [ + value + for value in owner.capabilities + if value.startswith(RUNTIME_CPU_CAPABILITY_PREFIX) + ] + return advertised[0] if len(advertised) == 1 else None + + +def cpu_compatible(destination: NodeHeartbeat, required: str | None) -> bool: + """Workers predating CPU capabilities stay eligible; import validates full fingerprint.""" + if required is None: + return True + advertised = [ + value + for value in destination.capabilities + if value.startswith(RUNTIME_CPU_CAPABILITY_PREFIX) + ] + return not advertised or required in advertised + + +def select_migration_destination( + source: SandboxRoute, + *, + ready_heartbeats: Iterable[NodeHeartbeat], + routes: Iterable[PlacementRecord], + active_migrations: Iterable[SandboxMigration], + source_heartbeat: NodeHeartbeat | None = None, + requested_node_id: str = "", + require_active_resources: bool = False, +) -> NodeHeartbeat | None: + """Choose the best eligible destination worker for a sandbox migration.""" + ready_list = list(ready_heartbeats) + if source_heartbeat is None: + source_heartbeat = next( + ( + heartbeat + for heartbeat in ready_list + if heartbeat.node_id == source.node_id + or ( + source.node_url + and heartbeat.node_url + and heartbeat.node_url.rstrip("/") == source.node_url.rstrip("/") + ) + ), + None, + ) + + source_storage_native = bool( + source_heartbeat is not None + and STORAGE_NATIVE_CAPABILITY in source_heartbeat.capabilities + and STORAGE_NATIVE_MIGRATION_CAPABILITY in source_heartbeat.capabilities + ) + source_is_attached = source.worker_state == "attached" + if source_is_attached: + if not source_storage_native: + return None + elif source.worker_state != "detached" or not is_portable_parked_route(source): + return None + + try: + runtime_capability = migration_runtime_capability(source, source_heartbeat) + except ValueError: + return None + source_cpu = migration_cpu_capability(source, source_heartbeat) + + required_destination_capabilities = sandbox_required_capabilities(source.spec) + if runtime_capability is not None: + required_destination_capabilities = ( + *required_destination_capabilities, + runtime_capability, + ) + if source.storage_schema == SPLIT_MIGRATION_SCHEMA or ( + source_is_attached + and source_heartbeat is not None + and SPLIT_CHECKPOINT_CAPABILITY in source_heartbeat.capabilities + ): + required_destination_capabilities = ( + *required_destination_capabilities, + SPLIT_CHECKPOINT_CAPABILITY, + ) + + route_list = list(routes) + routes_by_id = { + route.sandbox_id: route + for route in route_list + if isinstance(route, SandboxRoute) + } + reservations: dict[str, int] = {} + for migration in active_migrations: + if migration.phase in {"routed", "activated"}: + continue + route = routes_by_id.get(migration.sandbox_id) + if route is None: + continue + reservations[migration.destination_node_id] = ( + reservations.get(migration.destination_node_id, 0) + + route.resources.disk_mb + ) + + route_index = placement_route_index(route_list) + available_by_node: dict[str, ResourceQuantity] = {} + candidates: list[NodeHeartbeat] = [] + for heartbeat in ready_list: + if ( + heartbeat.node_id == source.node_id + or any(item.sandbox_id == source.sandbox_id for item in heartbeat.inventory) + or STORAGE_NATIVE_CAPABILITY not in heartbeat.capabilities + or STORAGE_NATIVE_MIGRATION_CAPABILITY not in heartbeat.capabilities + or ( + runtime_capability is None + and HOST_EROFS_CAPABILITY in heartbeat.capabilities + ) + or any( + capability not in heartbeat.capabilities + for capability in required_destination_capabilities + ) + or (requested_node_id and heartbeat.node_id != requested_node_id) + or not cpu_compatible(heartbeat, source_cpu) + ): + continue + node_routes = route_index.routes_for(heartbeat) + available = node_available_resources(heartbeat, node_routes) + requested = ( + source.resources + if require_active_resources + else ResourceQuantity(disk_mb=source.resources.disk_mb) + ) + if requested.disk_mb <= 0 or not node_can_fit_available( + heartbeat, requested, available + ): + continue + available_by_node[heartbeat.node_id] = available + candidates.append(heartbeat) + + undrained = [item for item in candidates if not is_soft_drained(item)] + # Moves (plain migrations) never target a soft-drained worker. A wake + # falls back to it rather than failing. + if undrained or not require_active_resources: + candidates = undrained + if not candidates: + return None + image = str(source.spec.get("image") or "") + return min( + candidates, + key=lambda heartbeat: ( + 0 if heartbeat_has_image(heartbeat, image) else 1, + reservations.get(heartbeat.node_id, 0), + -available_by_node[heartbeat.node_id].disk_mb, + heartbeat.node_id, + ), + ) + + +def migration_pending_demand_id(sandbox_id: str) -> str: + return f"__migration__:{sandbox_id}" + + +def parse_detach_request(raw: Any) -> tuple[bool, dict[str, Any] | None]: + """Validate a worker-detach JSON payload and return ``(require_cold, if_cold)``.""" + if not isinstance(raw, dict) or (raw and set(raw) != {"if_cold"}): + raise ValueError("sandbox detach payload must be empty or contain if_cold") + if not raw: + return False, None + if_cold = raw["if_cold"] + if not isinstance(if_cold, dict): + raise ValueError("conditional detach requires an owner observation") + return True, if_cold + + +def cold_offload_fence_matches( + expected: dict[str, Any], + provided: dict[str, Any], +) -> bool: + """Return whether a client's conditional detach observation matches the route fence.""" + return provided == expected and all( + type(provided[key]) is type(value) for key, value in expected.items() + ) + + +def parse_migration_request( + raw: Any, + *, + default_migration_id: str, +) -> tuple[str, str, bool]: + """Validate a migration POST payload and return ``(migration_id, destination, soft_drain)``.""" + if not isinstance(raw, dict): + raise ValueError("migration payload must be a JSON object") + migration_id = str(raw.get("migration_id") or default_migration_id).strip() + requested_destination = str(raw.get("destination_node_id") or "").strip() + soft_drain = raw.get("soft_drain") is True + return migration_id, requested_destination, soft_drain diff --git a/sandboxes/gateway/node_rpc.py b/sandboxes/gateway/node_rpc.py index 9e8fcd88..38f10dba 100644 --- a/sandboxes/gateway/node_rpc.py +++ b/sandboxes/gateway/node_rpc.py @@ -81,7 +81,7 @@ def json(self) -> dict[str, Any]: ) -def _node_request_headers(req, *, allow_body_keep_alive=False): +def node_request_headers(req, *, allow_body_keep_alive=False): headers = dict(req.header_items()) if req.data is not None and ( not allow_body_keep_alive or isinstance(req.data, RequestBodyStream) @@ -104,7 +104,7 @@ def _open_node_request( # redirect target selected by a compromised node endpoint. if authenticated: try: - headers = _node_request_headers(req, allow_body_keep_alive=allow_body_keep_alive) + headers = node_request_headers(req, allow_body_keep_alive=allow_body_keep_alive) path = urlparse(req.full_url).path if buffer_response_bytes is not None and not isinstance(req.data, RequestBodyStream): from ..node_http_async import node_http_pool @@ -207,22 +207,22 @@ def proxy( with telemetry.span("gateway.node_response_body", attributes={ **proxy_attributes, "http.response.status_code": response.status, }) as body_span: - response_body = _read_bounded_proxy_body( + response_body = read_bounded_proxy_body( response, max_bytes=DEFAULT_MAX_PROXY_RESPONSE_BYTES) body_span.set_attribute("http.response.body.size", len(response_body)) except ProxyResponseTooLargeError: - return _proxy_response_too_large(DEFAULT_MAX_PROXY_RESPONSE_BYTES) + return proxy_response_too_large(DEFAULT_MAX_PROXY_RESPONSE_BYTES) return ProxiedResponse(response.status, response.headers, response_body) except error.HTTPError as exc: try: with telemetry.span("gateway.node_response_body", attributes={ **proxy_attributes, "http.response.status_code": exc.code, }) as body_span: - response_body = _read_bounded_proxy_body( + response_body = read_bounded_proxy_body( exc, max_bytes=DEFAULT_MAX_PROXY_ERROR_BYTES) body_span.set_attribute("http.response.body.size", len(response_body)) except ProxyResponseTooLargeError: - return _proxy_response_too_large(DEFAULT_MAX_PROXY_ERROR_BYTES) + return proxy_response_too_large(DEFAULT_MAX_PROXY_ERROR_BYTES) return ProxiedResponse(exc.code, exc.headers, response_body) except ValueError as exc: if not isinstance(body, RequestBodyStream): @@ -233,24 +233,24 @@ def proxy( json.dumps({"error": str(exc)}).encode(), ) except error.URLError as exc: - return _node_transport_error_response(exc.reason) + return node_transport_error_response(exc.reason) except (OSError, Urllib3HTTPError) as exc: # With preload_content=False, read/protocol failures can occur # after headers, outside _open_node_request's exception wrapper. - return _node_transport_error_response(exc) + return node_transport_error_response(exc) -def _async_proxy_response(response, transport_error): +def async_proxy_response(response, transport_error): """Apply the normal bounded/error contract to a completed async RPC.""" if transport_error is not None: - proxied = _node_transport_error_response(transport_error) + proxied = node_transport_error_response(transport_error) else: with response: body = response.read() - proxied = (_proxy_response_too_large(DEFAULT_MAX_PROXY_RESPONSE_BYTES) + proxied = (proxy_response_too_large(DEFAULT_MAX_PROXY_RESPONSE_BYTES) if len(body) > DEFAULT_MAX_PROXY_RESPONSE_BYTES else ProxiedResponse(response.status, response.headers, body)) - structured = _structured_proxy_error(proxied) + structured = structured_proxy_error(proxied) if structured is not None: return proxied.status, {"Content-Type": "application/json"}, json.dumps(structured).encode() return proxied.status, proxied.headers, proxied.body @@ -281,7 +281,7 @@ def _node_proxy_span_attributes( } -def _node_transport_error_response(reason: object) -> ProxiedResponse: +def node_transport_error_response(reason: object) -> ProxiedResponse: if isinstance(reason, EmptyPoolError): # urllib3 failed to acquire a connection: no request bytes were sent. # Preserve that certainty so mutations can retry safely. @@ -336,7 +336,7 @@ def _node_transport_error_response(reason: object) -> ProxiedResponse: ) -def _proxy_response_too_large(max_bytes: int) -> ProxiedResponse: +def proxy_response_too_large(max_bytes: int) -> ProxiedResponse: body = json.dumps( { "error": "upstream sandbox node response exceeded the gateway limit", @@ -351,8 +351,8 @@ def _proxy_response_too_large(max_bytes: int) -> ProxiedResponse: ) -def _proxy_content_length(headers: Any) -> int | None: - raw = _header_value(headers, "Content-Length").strip() +def proxy_content_length(headers: Any) -> int | None: + raw = header_value(headers, "Content-Length").strip() if not raw: return None try: @@ -364,8 +364,8 @@ def _proxy_content_length(headers: Any) -> int | None: return length -def _read_bounded_proxy_body(response: Any, *, max_bytes: int) -> bytes: - content_length = _proxy_content_length(response.headers) +def read_bounded_proxy_body(response: Any, *, max_bytes: int) -> bytes: + content_length = proxy_content_length(response.headers) if content_length is not None and content_length > max_bytes: raise ProxyResponseTooLargeError( f"upstream response exceeds the {max_bytes} byte limit" @@ -385,7 +385,7 @@ def _read_bounded_proxy_body(response: Any, *, max_bytes: int) -> bytes: return b"".join(chunks) -def _structured_proxy_error(response: ProxiedResponse) -> dict[str, Any] | None: +def structured_proxy_error(response: ProxiedResponse) -> dict[str, Any] | None: if response.status < 400 or _response_looks_json(response): return None preview = response.body[:500].decode("utf-8", errors="replace").strip() @@ -393,20 +393,20 @@ def _structured_proxy_error(response: ProxiedResponse) -> dict[str, Any] | None: "error": "upstream sandbox node returned a non-JSON error response", "status": int(response.status), "retryable": response.status in {408, 425, 429, 500, 502, 503, 504}, - "upstream_content_type": _header_value(response.headers, "Content-Type"), + "upstream_content_type": header_value(response.headers, "Content-Type"), "upstream_body_preview": preview, } def _response_looks_json(response: ProxiedResponse) -> bool: - content_type = _header_value(response.headers, "Content-Type").lower() + content_type = header_value(response.headers, "Content-Type").lower() if "json" in content_type: return True stripped = response.body.lstrip() return stripped.startswith(b"{") or stripped.startswith(b"[") -def _header_value(headers: Any, key: str) -> str: +def header_value(headers: Any, key: str) -> str: try: value = headers.get(key, "") except AttributeError: diff --git a/sandboxes/gateway/operator.py b/sandboxes/gateway/operator.py index e4f97c05..0906459c 100644 --- a/sandboxes/gateway/operator.py +++ b/sandboxes/gateway/operator.py @@ -21,7 +21,7 @@ from urllib.parse import unquote from ..models import is_operator_drained, utc_now -from .groups import MEMBER_DELETE_CONCURRENCY, _in_context +from .groups import MEMBER_DELETE_CONCURRENCY, in_context _DRAIN_PATH = re.compile(r"^/v1/nodes/([^/]+)/drain$") @@ -52,7 +52,7 @@ def drain(self, ex: DrainExchange, job_id: str, *, evict: bool) -> tuple[int, di node_id=heartbeat.node_id, job_id=job_id, node_url=heartbeat.node_url or "") sandbox_ids = sorted({route.sandbox_id for route in routes}) with ThreadPoolExecutor(MEMBER_DELETE_CONCURRENCY) as pool: - answers = list(pool.map(_in_context(ex._loopback_delete), sandbox_ids)) + answers = list(pool.map(in_context(ex._loopback_delete), sandbox_ids)) payload["evicted"] = [ {"id": sandbox_id, "status_code": status, **({"error": body.get("error")} if status >= 300 else {})} for sandbox_id, (status, body) in zip(sandbox_ids, answers) diff --git a/sandboxes/gateway/placement.py b/sandboxes/gateway/placement.py index eac1c4ba..66ee976a 100644 --- a/sandboxes/gateway/placement.py +++ b/sandboxes/gateway/placement.py @@ -13,7 +13,7 @@ from ..models import NodeHeartbeat, ResourceQuantity from ..network_policy import SandboxNetworkPolicy from ..placement_accounting import ( - PlacementRecord, PlacementReservation, _node_available_resources, _route_targets_node, + PlacementRecord, PlacementReservation, node_available_resources, route_targets_node, ) from ..resource_admission import node_accepts_dynamic_request from ..routing import RoutingStore, SandboxRoute @@ -62,7 +62,7 @@ def routes_for_node(self, heartbeat: NodeHeartbeat) -> list[PlacementRecord]: node_url=migration.destination_node_url, resources=ResourceQuantity(), image="", ) - if not _route_targets_node(destination, heartbeat): + if not route_targets_node(destination, heartbeat): continue source = by_id.get(migration.sandbox_id) if source is None: @@ -117,7 +117,7 @@ def migration_reservations( return reservations -def _sandbox_required_capabilities(spec: dict[str, Any]) -> tuple[str, ...]: +def sandbox_required_capabilities(spec: dict[str, Any]) -> tuple[str, ...]: capabilities = [] policy = SandboxNetworkPolicy.from_dict(spec.get("network_policy", {})) if policy.egress == "relay": @@ -147,19 +147,19 @@ def _sandbox_required_capabilities(spec: dict[str, Any]) -> tuple[str, ...]: return tuple(capabilities) -def _node_can_fit( +def node_can_fit( heartbeat: NodeHeartbeat, requested: ResourceQuantity, routes: list[PlacementRecord], ) -> bool: - return _node_can_fit_available( + return node_can_fit_available( heartbeat, requested, - _node_available_resources(heartbeat, routes), + node_available_resources(heartbeat, routes), ) -def _node_can_fit_available( +def node_can_fit_available( heartbeat: NodeHeartbeat, requested: ResourceQuantity, available: ResourceQuantity, @@ -167,5 +167,5 @@ def _node_can_fit_available( return node_accepts_dynamic_request(heartbeat, requested, available) -def _has_resource_values(resources: ResourceQuantity) -> bool: +def has_resource_values(resources: ResourceQuantity) -> bool: return resources.vcpu > 0 or resources.memory_mb > 0 or resources.disk_mb > 0 diff --git a/sandboxes/gateway/registry_refs.py b/sandboxes/gateway/registry_refs.py index 5a9fc47a..89043dd8 100644 --- a/sandboxes/gateway/registry_refs.py +++ b/sandboxes/gateway/registry_refs.py @@ -57,12 +57,12 @@ def usage_health_error(self) -> str: return "" def managed_coordinates(self, image_ref: str) -> tuple[str, str] | None: - return _managed_registry_image_coordinates( + return managed_registry_image_coordinates( image_ref, self.registry_url or "", self.registry_worker_url or "") def requires_digest_identity(self, image: str) -> bool: """A managed tag can move under a heartbeat, so only a digest is a hit.""" - return bool(self.registry_url and _managed_registry_image_coordinates( + return bool(self.registry_url and managed_registry_image_coordinates( image, self.registry_url, self.registry_worker_url or "") is not None) def record_image_used(self, image_ref: str) -> None: @@ -82,7 +82,7 @@ def ensure_image_lease(self, image_ref: str, owner: str, *, touch: bool) -> None if self.managed_coordinates(image_ref) is None: return try: - _persist_registry_image_protection( + persist_registry_image_protection( store, image_ref, owner, touch=touch, persistent=False, dependency_resolver=self.dependency_resolver, ) @@ -104,7 +104,7 @@ def ensure_image_reference(self, image_ref: str, owner: str) -> None: if existing is not None and existing.digest != manifest_digest_from_image_ref(image_ref): store.release_owner(owner) store.release_owner(owner + ":environment") - _persist_registry_image_protection( + persist_registry_image_protection( store, image_ref, owner, touch=True, persistent=True, dependency_resolver=self.dependency_resolver, ) @@ -120,7 +120,7 @@ def ensure_route_reference(self, route: SandboxRoute, *, touch: bool) -> None: return if image_ref and self.managed_coordinates(image_ref) is not None: try: - _persist_registry_image_protection( + persist_registry_image_protection( store, image_ref, _registry_route_reference_owner( route, deployment_id=self.deployment_id, route_generation=route.generation), @@ -141,7 +141,7 @@ def protect_build_target(self, spec: ImageBuildSpec, *, push: bool) -> None: not push or self.usage_store is None or not self.registry_url - or _managed_registry_image_coordinates( + or managed_registry_image_coordinates( spec.tag, self.registry_url, self.registry_worker_url or "") is None ): return @@ -201,7 +201,7 @@ def release_snapshot_reference( store, route, deployment_id=self.deployment_id, keep_route=keep_route) -def _portable_snapshot_for_route(route: SandboxRoute) -> StorageNativeMigration: +def portable_snapshot_for_route(route: SandboxRoute) -> StorageNativeMigration: if not is_portable_parked_route(route): raise ValueError("sandbox route is not a fully published park") snapshot = StorageNativeMigration.from_dict(route.storage_snapshot) @@ -241,7 +241,7 @@ def _private_registry_image_coordinates( return registry_repository_tag_from_image_ref(image_ref) -def _managed_registry_image_coordinates( +def managed_registry_image_coordinates( image_ref: str, registry_url: str, registry_worker_url: str = "", @@ -261,7 +261,7 @@ def _managed_registry_image_coordinates( return registry_repository_tag_from_image_ref(image_ref) -def _managed_registry_build_tag(image_id: str, registry_worker_url: str) -> str: +def managed_registry_build_tag(image_id: str, registry_worker_url: str) -> str: """Allocate a stable internal tag without exposing registry naming to clients.""" host = urlparse(registry_worker_url).netloc @@ -276,7 +276,7 @@ def _managed_registry_build_tag(image_id: str, registry_worker_url: str) -> str: return f"{host}/ucloud-managed/{component}-{suffix}:latest" -def _managed_registry_worker_reference( +def managed_registry_worker_reference( image_ref: str, registry_url: str, registry_worker_url: str, @@ -285,7 +285,7 @@ def _managed_registry_worker_reference( if not registry_worker_url: return image_ref - coordinates = _managed_registry_image_coordinates( + coordinates = managed_registry_image_coordinates( image_ref, registry_url, registry_worker_url, @@ -299,7 +299,7 @@ def _managed_registry_worker_reference( return image_ref_with_manifest_digest(rewritten, digest) if digest else rewritten -def _persist_registry_image_protection( +def persist_registry_image_protection( store: RegistryUsageStore, image_ref: str, owner: str, @@ -329,7 +329,7 @@ def _persist_registry_image_protection( dependency_owner = owner + ":environment" if store.get_lease(dependency_repository, dependency_tag, dependency_owner, now=now) is None: dependency_resolver.ensure_reference(dependency_repository, dependency_tag, dependency_digest) - _persist_registry_image_protection( + persist_registry_image_protection( store, f"{registry_host_from_image_ref(image_ref)}/{dependency_repository}:{dependency_tag}@{dependency_digest}", dependency_owner, touch=touch, persistent=persistent, now=now, ttl_seconds=ttl_seconds, lease_key=lease_key, @@ -409,7 +409,7 @@ def _registry_route_reference_owner( "route_created_at": route.created_at, "image": str(route.spec.get("image") or ""), } - return _registry_operation_lease_owner("sandbox-route", identity) + return registry_operation_lease_owner("sandbox-route", identity) def _registry_snapshot_reference_owner( @@ -417,7 +417,7 @@ def _registry_snapshot_reference_owner( *, deployment_id: str, ) -> str: - return _registry_operation_lease_owner( + return registry_operation_lease_owner( "sandbox-snapshot", { "version": 1, @@ -553,7 +553,7 @@ def release_registry_route_references( _release_registry_reference_keys(store, references, image_owners=image_owners) -def _registry_operation_lease_owner(kind: str, identity: object) -> str: +def registry_operation_lease_owner(kind: str, identity: object) -> str: encoded = json.dumps( {"kind": kind, "identity": identity}, sort_keys=True, diff --git a/sandboxes/gateway/request_parsing.py b/sandboxes/gateway/request_parsing.py index 48b80c99..b87a6740 100644 --- a/sandboxes/gateway/request_parsing.py +++ b/sandboxes/gateway/request_parsing.py @@ -20,11 +20,11 @@ def _collection_id_from_path(path: str, prefix: str) -> str | None: return unquote(rest.split("/", 1)[0]) -def _sandbox_id_from_path(path: str) -> str | None: +def sandbox_id_from_path(path: str) -> str | None: return _collection_id_from_path(path, "/v1/sandboxes/") -def _sandbox_migration_id_from_path(path: str) -> str | None: +def sandbox_migration_id_from_path(path: str) -> str | None: prefix = "/v1/sandboxes/" suffix = "/migration" if not path.startswith(prefix) or not path.endswith(suffix): @@ -36,7 +36,7 @@ def _sandbox_migration_id_from_path(path: str) -> str | None: return sandbox_id -def _sandbox_detach_id_from_path(path: str) -> str | None: +def sandbox_detach_id_from_path(path: str) -> str | None: prefix = "/v1/sandboxes/" suffix = "/detach" if not path.startswith(prefix) or not path.endswith(suffix): @@ -48,38 +48,38 @@ def _sandbox_detach_id_from_path(path: str) -> str | None: return sandbox_id -def _image_build_key_from_path(path: str) -> str | None: +def image_build_key_from_path(path: str) -> str | None: return _collection_id_from_path(path, "/v1/images/builds/") -def _image_build_cancel_key_from_path(path: str) -> str | None: +def image_build_cancel_key_from_path(path: str) -> str | None: """The build id of POST /v1/images/builds/:cancel, else None.""" - key = _image_build_key_from_path(path) + key = image_build_key_from_path(path) if key is None or not key.endswith(":cancel") or "/" in path[len("/v1/images/builds/"):]: return None return key[: -len(":cancel")] or None -def _exec_session_id_from_path(path: str) -> str | None: +def exec_session_id_from_path(path: str) -> str | None: return _collection_id_from_path(path, "/v1/exec/") -def _prepare_id_from_path(path: str) -> str | None: +def prepare_id_from_path(path: str) -> str | None: return _collection_id_from_path(path, "/v1/capacity/prepare/") -def _builder_prepare_id_from_path(path: str) -> str | None: +def builder_prepare_id_from_path(path: str) -> str | None: return _collection_id_from_path(path, "/v1/builders/prepare/") -def _truthy_query_param(parsed: Any, name: str) -> bool: +def truthy_query_param(parsed: Any, name: str) -> bool: values = parse_qs(str(getattr(parsed, "query", ""))).get(name, []) return any( str(value).lower() in {"1", "true", "yes", "on", "full"} for value in values ) -def _prepared_resources_from_payload(raw: dict[str, Any]) -> ResourceQuantity: +def prepared_resources_from_payload(raw: dict[str, Any]) -> ResourceQuantity: resources = { "vcpu": raw.get("cpus", 0), "memory_mb": raw.get("memory_mb", 0), @@ -116,13 +116,13 @@ def _prepared_resources_from_payload(raw: dict[str, Any]) -> ResourceQuantity: ) -def _strict_positive_integer(value: object, label: str) -> int: +def strict_positive_integer(value: object, label: str) -> int: if isinstance(value, bool) or not isinstance(value, int) or value <= 0: raise ValueError(f"{label} must be a positive integer.") return value -def _validate_prepared_resources(resources: ResourceQuantity) -> None: +def validate_prepared_resources(resources: ResourceQuantity) -> None: if resources.vcpu < 0: raise ValueError("vcpu must be non-negative.") if resources.memory_mb < 0: diff --git a/sandboxes/gateway/sandbox_proxy.py b/sandboxes/gateway/sandbox_proxy.py new file mode 100644 index 00000000..2a33c4c6 --- /dev/null +++ b/sandboxes/gateway/sandbox_proxy.py @@ -0,0 +1,1780 @@ +"""Gateway sandbox request routing, lifecycle proxying, and wake placement. + +Pure validation, header/payload construction, and transport-epoch hashing live +at the top of the module; ``SandboxProxy`` is the imperative shell wired into +``GatewayServices`` and driven per-request through a ``SandboxProxyExchange``. +""" + +from __future__ import annotations + +from concurrent.futures import Future +from contextlib import nullcontext +from datetime import datetime, timezone +import hashlib +from http import HTTPStatus +import json +import math +from pathlib import Path +import sqlite3 +from threading import RLock, Thread +from typing import Any, Callable, Protocol +from urllib import error +from urllib.parse import quote +from uuid import uuid4 + +from ..exec_routing import ExecRouteUnavailable +from ..exec_session_routes import EXEC_SESSION_PREFIX_HEADER +from ..http_contract import UPLOAD_ACTIONS, SandboxHttpRoute, match_sandbox_http_route +from ..http_server import ( + DEFAULT_MAX_JSON_BODY_BYTES, + RequestBodyStream, + TRANSFER_CHUNK_BYTES, +) +from ..lifecycle_commit import ( + InvalidLifecycleReceipt, + LifecycleCommitter, + LifecycleRouteChanged, + SnapshotReferences, +) +from ..metrics import MetricsStore, record_sandbox_pending_deleted +from ..models import ( + NodeHeartbeat, + sandbox_route_state_from_observation, + utc_now, +) +from ..placement_accounting import node_available_resources, node_has_storage_device_capacity +from ..routing import ( + ProgramRequestState, + RoutingStore, + SandboxRoute, + SandboxRouteConflictError, +) +from ..sandbox import SandboxSpec +from ..telemetry import Telemetry +from ..wake_admission import WakeAdmission +from ..wake_placement import WakePlaced, WakePlacement, WakePlacementPorts, WakeUnavailable +from ..worker_receipts import ( + record_generation, + route_with_sandbox_record, + sandbox_record_matches_route, +) +from .fleet import FleetView +from .heartbeats import HeartbeatIngest, PULL_TIMEOUT_SECONDS +from .job_reads import ( + cache_parked_job, + cached_job_logs_response, + cached_job_status_response, + job_read_timeout_seconds, + job_read_wait_ms, + project_job_response, + record_job_response, +) +from .migration_service import SandboxMigrations +from .node_rpc import ( + ProxiedResponse, + node_request_headers, + node_transport_error_response, +) +from .placement import Placement, node_can_fit_available +from .registry_refs import RegistryImageReferenceUnavailable, RegistryReferences + + +DEFAULT_MAX_PROXY_BODY_BYTES = 256 * 1024 * 1024 +SANDBOX_GENERATION_HEADER = "X-UCloud-Sandbox-Generation" +SANDBOX_OPERATION_ID_HEADER = "X-UCloud-Sandbox-Operation-Id" +SANDBOX_TRANSPORT_RESET_HEADER = "X-UCloud-Sandbox-Transport-Reset" +SANDBOX_TRANSPORT_EPOCH_HEADER = "X-UCloud-Sandbox-Transport-Epoch" + + +# --------------------------------------------------------------------------- +# Functional core (pure functions, no I/O or clocks) +# --------------------------------------------------------------------------- + + +def is_warm_wake_route( + route: SandboxRoute | None, + generation: int | None = None, +) -> bool: + """A resident owner needs no placement; its worker fences the wake itself.""" + return bool( + route is not None + and not route.delete_operation_id + and route.worker_state == "attached" + and (route.state or "").lower() in {"running", "waking"} + and (generation is None or route.generation == generation) + ) + + +def sandbox_supports_managed_lifecycle(spec: dict[str, Any]) -> bool: + """Return whether request-bound relay park/wake is valid for this spec.""" + try: + parsed = SandboxSpec.from_dict(spec) + except (TypeError, ValueError): + return False + return parsed.parkable and parsed.managed_process + + +def sandbox_transport_epoch( + route: SandboxRoute, + migrations: list[Any], +) -> str: + """Hash every committed route handoff for this sandbox incarnation.""" + committed = sorted( + migration.migration_id + for migration in migrations + if migration.sandbox_id == route.sandbox_id + and migration.generation == route.generation + and migration.create_operation_id == route.create_operation_id + and migration.phase in {"routed", "activated", "complete"} + ) + return hashlib.sha256( + "\0".join( + ( + route.sandbox_id, + str(route.generation), + route.create_operation_id, + *committed, + ) + ).encode("utf-8") + ).hexdigest() + + +def sandbox_record_is_ready(record: dict[str, Any]) -> bool: + """Return true only for externally usable lifecycle states.""" + return sandbox_route_state_from_observation(record.get("state")) is not None + + +def lifecycle_node_payload( + generation: int, + action: str, + payload: dict[str, Any], +) -> dict[str, Any]: + """The worker's body for a parsed park or wake request on this route generation.""" + node_payload: dict[str, Any] = {"operation_id": str(payload["operation_id"]).strip()} + if payload.get("durable_lifecycle"): + node_payload["relay_request_id"] = payload["request_id"] + node_payload["generation"] = generation + if action == "wake": + node_payload["generation"] = generation + elif "background" in payload: + if not isinstance(payload["background"], bool): + raise ValueError("park background must be a boolean") + node_payload["background"] = payload["background"] + return node_payload + + +def lifecycle_proxy_error(response: ProxiedResponse) -> str: + detail = "" + try: + payload = response.json() + if isinstance(payload, dict): + detail = str(payload.get("error") or "").strip() + except (TypeError, ValueError, json.JSONDecodeError): + pass + if not detail: + detail = response.body[:500].decode("utf-8", errors="replace").strip() + prefix = f"HTTP {int(response.status)}" + return f"{prefix}: {detail}" if detail else prefix + + +def classify_buffered_bulk_request( + method: str, + weight: int, + action: SandboxHttpRoute | None, +) -> bool: + """Return whether a sandbox request body must wait for bulk upload admission.""" + return ( + method in {"POST", "PUT", "PATCH"} + and (weight > 64 * 1024 or (action is not None and action.action == "files")) + and not (method == "PUT" and action is not None and action.action in UPLOAD_ACTIONS) + ) + + +def validate_lifecycle_payload( + route: SandboxRoute, + action: str, + body: bytes | None, +) -> tuple[dict[str, Any] | None, tuple[int, dict[str, Any]] | None]: + """Pure parser and validator for explicit park/wake payloads. + + Returns ``(payload, None)`` on success or ``(None, (http_status, body))`` + when the request is malformed or does not match the current route. + """ + try: + payload = json.loads((body or b"{}").decode("utf-8")) + if not isinstance(payload, dict): + raise ValueError("sandbox lifecycle payload must be an object") + request_id = str(payload.get("request_id") or "").strip() + rollout_id = str(payload.get("rollout_id") or "").strip() + if "durable_lifecycle" in payload and ( + payload["durable_lifecycle"] is not True or not request_id + ): + raise ValueError("durable lifecycle requires a request binding") + if bool(request_id) != bool(rollout_id): + raise ValueError("program lifecycle requires both request_id and rollout_id") + generation = payload.get("generation") + operation_id = str(payload.get("operation_id") or "").strip() + if not operation_id: + raise ValueError("sandbox lifecycle operation_id is required") + if action == "wake" and generation is None: + raise ValueError("wake generation is required") + if generation is not None and int(generation) != route.generation: + return ( + None, + ( + HTTPStatus.CONFLICT, + { + "error": ( + f"{action} generation does not own the current " + "sandbox route" + ), + "retryable": False, + }, + ), + ) + except (TypeError, UnicodeDecodeError, json.JSONDecodeError, ValueError) as exc: + return None, (HTTPStatus.BAD_REQUEST, {"error": str(exc)}) + if request_id and not sandbox_supports_managed_lifecycle(route.spec): + return ( + None, + ( + HTTPStatus.CONFLICT, + { + "error": ( + f"request-bound {action} requires a parkable " + "managed_process sandbox" + ), + "retryable": False, + }, + ), + ) + return payload, None + + +def build_program_request_transition_args( + route: SandboxRoute, + lifecycle_payload: dict[str, Any], + *, + state: str, + now_iso: str, + warm_observation: tuple[str, str, int, str] | None = None, + parked_at: str | None = None, + response_ready: bool = False, + last_error: str = "", + clear_error: bool = False, +) -> dict[str, Any] | None: + """Build keyword arguments for ``upsert_program_request_transition_with_change``.""" + request_id = str(lifecycle_payload.get("request_id") or "").strip() + rollout_id = str(lifecycle_payload.get("rollout_id") or "").strip() + if not request_id or not rollout_id: + return None + warm_started_at = ( + warm_observation[3] + if warm_observation is not None + and warm_observation[:3] == (request_id, route.sandbox_id, route.generation) + and state in {"waking", "acting"} + else None + ) + accepted_at = "" + try: + raw_created_at = float(lifecycle_payload.get("request_created_at")) + if math.isfinite(raw_created_at) and raw_created_at >= 0: + accepted_at = datetime.fromtimestamp( + raw_created_at, + tz=timezone.utc, + ).isoformat() + except (TypeError, ValueError, OverflowError, OSError): + pass + return dict( + request_id=request_id, + rollout_id=rollout_id, + state=state, + accepted_at=accepted_at or None, + parked_at=parked_at, + response_ready_at=warm_started_at or (now_iso if response_ready else None), + **({"wake_started_at": warm_started_at} if warm_started_at else {}), + last_error=last_error, + clear_error=clear_error, + ) + + +def build_wake_unavailable_response( + outcome: WakeUnavailable, +) -> tuple[dict[str, Any], dict[str, str]]: + """Build JSON payload and retry headers for a ``WakeUnavailable`` outcome.""" + payload: dict[str, Any] = { + "error": outcome.message, + "retryable": True, + **outcome.details, + } + if outcome.error_code: + payload["error_code"] = outcome.error_code + if outcome.pending_resources is not None: + payload["pending_resources"] = outcome.pending_resources.to_dict() + if outcome.migration is not None: + payload["migration"] = outcome.migration.to_dict() + headers = { + "Retry-After": str(outcome.retry_after), + "X-UCloud-Sandbox-Retryable": "true", + } + return payload, headers + + +# --------------------------------------------------------------------------- +# Local wake batcher (coalesces concurrent local wake admissions per owner) +# --------------------------------------------------------------------------- + + +class LocalWakeBatcher: + """Coalesce waiting local admissions without a timer or a concurrency cap.""" + + def __init__(self) -> None: + self.lock = RLock() + self.pending: list[tuple[Any, SandboxRoute, Future]] = [] + self.running = False + + def reserve(self, handler: Any, route: SandboxRoute): + future: Future = Future() + with self.lock: + self.pending.append((handler, route, future)) + if not self.running: + self.running = True + Thread( + target=self._drain, + name="local-wake-admission", + daemon=True, + ).start() + observation = ( + handler.telemetry.span("gateway.wake.await_admission") + if getattr(handler, "telemetry", None) is not None + else nullcontext() + ) + with observation: + return future.result() + + def _drain(self) -> None: + while True: + with self.lock: + if not self.pending: + self.running = False + return + leader = self.pending[0][0] + batch: list[tuple[Any, SandboxRoute, Future]] = [] + try: + with self.lock: + batch, self.pending = self.pending, [] + results = leader.services.placement.atomic( + lambda: leader._reserve_local_wake_batch(batch), + worker_id=batch[0][1].job_id, + ) + for (_, _, future), result in zip(batch, results, strict=True): + future.set_result(result) + except BaseException as exc: + if not batch: + with self.lock: + batch, self.pending = self.pending, [] + for _, _, future in batch: + if not future.done(): + future.set_exception(exc) + + +class LocalWakeBatcherPool: + def __init__(self) -> None: + self._lock = RLock() + self._batchers: dict[tuple[Path, str], LocalWakeBatcher] = {} + + def for_owner(self, path: Path, *, owner: str = "") -> LocalWakeBatcher: + key = (path.resolve(), owner) + with self._lock: + return self._batchers.setdefault(key, LocalWakeBatcher()) + + +# --------------------------------------------------------------------------- +# Imperative shell +# --------------------------------------------------------------------------- + + +class SandboxProxyExchange(Protocol): + """Request-scoped I/O surface required by SandboxProxy.""" + + command: str + path: str + headers: Any + rfile: Any + request: Any + server: Any + close_connection: bool + async_responses: Any + exec_routing: Any + telemetry: Telemetry + + def _read_raw_body(self, *, max_bytes: int) -> bytes: ... + def _request_content_length(self, *, max_bytes: int) -> int: ... + def _write_json( + self, + payload: dict[str, Any], + *, + status: int = ..., + headers: dict[str, str] | None = None, + ) -> None: ... + def _send_proxied_response( + self, + response: ProxiedResponse, + *, + extra_headers: dict[str, str] | None = None, + ) -> None: ... + def _stream_proxy_request( + self, + node_url: str, + path: str, + *, + method: str, + body: Any = None, + timeout_seconds: float = ..., + extra_headers: dict[str, str] | None = None, + on_success: Callable[[], None] | None = None, + ) -> None: ... + def _defer_node_response( + self, + node_url: str, + path: str, + *, + method: str, + body: Any = None, + extra_headers: dict[str, str] | None = None, + event_poll: bool = False, + ) -> bool: ... + def _defer_placement( + self, kind: str, sandbox_id: str, path: str, body: bytes + ) -> None: ... + def _proxy_request( + self, + node_url: str, + path: str, + *, + method: str, + body: Any = None, + timeout_seconds: float = ..., + extra_headers: dict[str, str] | None = None, + ) -> ProxiedResponse: ... + def _build_proxy_request( + self, + node_url: str, + path: str, + *, + method: str, + body: Any = None, + extra_headers: dict[str, str] | None = None, + ) -> Any: ... + def _heartbeat_for_route( + self, *, job_id: str, include_inventory: bool = True + ) -> NodeHeartbeat | None: ... + def _startup_request_admission( + self, *, creating: bool = False, weight: int = 1 + ) -> Any: ... + def _route_worker_is_fresh( + self, route: SandboxRoute, *, pull: bool = False + ) -> bool: ... + def _write_route_worker_unreachable(self, route: SandboxRoute) -> None: ... + def _write_create_in_progress_response(self, sandbox_id: str) -> None: ... + def _write_registry_lease_unavailable( + self, exc: RegistryImageReferenceUnavailable + ) -> None: ... + def _sandbox_record_on_node( + self, node_url: str, sandbox_id: str + ) -> dict[str, Any] | None: ... + def _confirm_sandbox_observation( + self, route: SandboxRoute + ) -> SandboxRoute: ... + + +class SandboxProxy: + """Imperative shell for sandbox traffic routing, lifecycle proxying, and wake placement.""" + + def __init__( + self, + *, + routing_store: RoutingStore | None, + fleet: FleetView, + placement: Placement, + registry_refs: RegistryReferences, + metrics_store: MetricsStore | None, + heartbeats: HeartbeatIngest, + migrations: SandboxMigrations, + batchers: LocalWakeBatcherPool | None = None, + ) -> None: + self.routing_store = routing_store + self.fleet = fleet + self.placement = placement + self.registry_refs = registry_refs + self.metrics_store = metrics_store + self.heartbeats = heartbeats + self.migrations = migrations + self.batchers = batchers or LocalWakeBatcherPool() + + def _routing(self, ex: Any) -> RoutingStore: + return self.routing_store if self.routing_store is not None else ex.routing_store + + def _metrics(self, ex: Any) -> MetricsStore: + return self.metrics_store if self.metrics_store is not None else ex.metrics_store + + def route_sandbox_request( + self, + ex: Any, + sandbox_id: str, + path: str, + *, + warm_wake_route: Callable[[str, int], bool] | None = None, + route_admitted: Callable[[str, str], None] | None = None, + ) -> None: + routing = self._routing(ex) + check_warm = warm_wake_route or ( + lambda sid, gen: self.warm_wake_route(ex, sid, gen) + ) + run_admitted = route_admitted or ( + lambda sid, p: self.route_sandbox_request_admitted(ex, sid, p) + ) + action = match_sandbox_http_route(ex.command, path) + if action and action.action == "delete": + routing.cancel_create_commands(sandbox_id) + if action and action.action == "wake" and getattr(ex, "placement_queue", None) is not None: + try: + body = ex._read_raw_body(max_bytes=DEFAULT_MAX_JSON_BODY_BYTES) + raw = json.loads(body) + if ( + not isinstance(raw, dict) + or not raw.get("operation_id") + or int(raw.get("generation", 0)) < 1 + ): + raise ValueError("wake requires operation_id and generation") + except (ValueError, TypeError) as exc: + ex._write_json({"error": str(exc)}, status=400) + return + if not check_warm(sandbox_id, int(raw["generation"])): + ex._prefetched_route = None + ex._defer_placement("wake", sandbox_id, path, body) + return + ex._placement_request_body = body + ex._warm_wake_fallback = (path, body) + try: + weight = max(1, int(ex.headers.get("Content-Length", "0"))) + if weight > DEFAULT_MAX_PROXY_BODY_BYTES: + raise ValueError("request exceeds gateway body limit") + except ValueError as exc: + ex.close_connection = True + ex._write_json({"error": str(exc)}, status=HTTPStatus.BAD_REQUEST) + return + if classify_buffered_bulk_request(ex.command, weight, action): + with ex._startup_request_admission(weight=weight) as admitted: + if admitted: + run_admitted(sandbox_id, path) + else: + run_admitted(sandbox_id, path) + + def warm_wake_route(self, ex: Any, sandbox_id: str, generation: int) -> bool: + try: + route = self._routing(ex).get_sandbox_readonly(sandbox_id) + except sqlite3.DatabaseError: + return False + ex._prefetched_route = (sandbox_id, route) + return is_warm_wake_route(route, generation) + + def write_missing_sandbox_route(self, ex: Any, sandbox_id: str) -> None: + loss = self._routing(ex).get_sandbox_loss(sandbox_id) + if loss is not None: + ex._write_json( + { + "error": "sandbox worker was lost; this sandbox incarnation cannot resume", + "error_code": "node_lost", + "reason": loss["reason"], + "retryable": False, + "sandbox_id": sandbox_id, + "sandbox_generation": loss["generation"], + "lost_at": loss["lost_at"], + }, + status=HTTPStatus.GONE, + ) + return + ex._write_json({"error": "sandbox route not found"}, status=HTTPStatus.NOT_FOUND) + + def write_absent_route(self, ex: Any, sandbox_id: str) -> None: + if ex.command == "DELETE": + routing = self._routing(ex) + pending_before = routing.get_pending(sandbox_id) + routing.delete_sandbox(sandbox_id) + record_sandbox_pending_deleted( + self._metrics(ex), + sandbox_id=sandbox_id, + pending=pending_before, + ) + ex._write_json({"ok": True, "deleted": False}) + return + self.write_missing_sandbox_route(ex, sandbox_id) + + def resolve_admitted_route(self, ex: Any, sandbox_id: str) -> SandboxRoute | None: + routing = self._routing(ex) + prefetched, ex._prefetched_route = getattr(ex, "_prefetched_route", None), None + if prefetched is not None and prefetched[0] == sandbox_id: + route = prefetched[1] + else: + route = routing.get_sandbox(sandbox_id) + fallback, ex._warm_wake_fallback = getattr(ex, "_warm_wake_fallback", None), None + if fallback is not None and not is_warm_wake_route(route): + ex._placement_request_body = None + ex._defer_placement("wake", sandbox_id, *fallback) + return None + if route is None: + self.write_absent_route(ex, sandbox_id) + return None + if ex.command != "DELETE" and route.delete_operation_id: + ex._write_json( + { + "error": "sandbox deletion is in progress", + "error_code": "sandbox_delete_pending", + "retryable": False, + }, + status=HTTPStatus.CONFLICT, + ) + return None + if ex.command != "DELETE": + return self.reconcile_routable_sandbox(ex, route) + return route + + def read_admitted_proxy_body( + self, + ex: Any, + sandbox_http_route: SandboxHttpRoute | None, + ) -> tuple[bool, bytes | RequestBodyStream | None]: + try: + if ( + ex.command == "PUT" + and sandbox_http_route is not None + and sandbox_http_route.action in UPLOAD_ACTIONS + ): + length = ex._request_content_length(max_bytes=DEFAULT_MAX_PROXY_BODY_BYTES) + body: bytes | RequestBodyStream | None = ( + ex._read_raw_body(max_bytes=TRANSFER_CHUNK_BYTES) + if length <= TRANSFER_CHUNK_BYTES + else RequestBodyStream(ex.rfile, length) + ) + else: + body = ( + ex._read_raw_body(max_bytes=DEFAULT_MAX_PROXY_BODY_BYTES) + if ex.command in {"POST", "PUT", "PATCH"} + else None + ) + except ValueError as exc: + ex._write_json({"error": str(exc)}, status=HTTPStatus.BAD_REQUEST) + return False, None + return True, body + + def try_serve_parked_job_read( + self, + ex: Any, + route: SandboxRoute, + sandbox_http_route: SandboxHttpRoute | None, + ) -> bool: + if (route.state or "unknown").lower() not in { + "parking", + "parked", + "moving", + "restoring", + "waking", + }: + return False + if sandbox_http_route is not None and sandbox_http_route.action == "job_status": + self.serve_cached_job_status( + ex, + route, + sandbox_http_route, + missing_status=HTTPStatus.NOT_FOUND, + ) + return True + return bool(self.serve_cached_job_logs(ex, route, sandbox_http_route)) + + def prepare_route_for_forwarding( + self, + ex: Any, + sandbox_id: str, + route: SandboxRoute, + sandbox_http_route: SandboxHttpRoute | None, + lifecycle_action: str, + lifecycle_payload: dict[str, Any], + *, + prepare_wake_placement: Callable[[SandboxRoute], tuple[SandboxRoute, bool] | None] | None = None, + record_program_transition: Callable[..., tuple[ProgramRequestState | None, bool]] | None = None, + prepare_delete: Callable[[SandboxRoute], SandboxRoute | None] | None = None, + perform_implicit_wake: Callable[[SandboxRoute], SandboxRoute | None] | None = None, + ) -> tuple[SandboxRoute, bool] | None: + place_wake = prepare_wake_placement or ( + lambda r: self.prepare_wake_placement(ex, r) + ) + record_transition = record_program_transition or ( + lambda r, p, **kw: self.record_program_request_transition(ex, r, p, **kw) + ) + prep_delete = prepare_delete or (lambda r: self.prepare_delete_route(ex, r)) + implicit_wake_fn = perform_implicit_wake or ( + lambda r: self.perform_implicit_wake(ex, r) + ) + request_wakes = bool( + sandbox_http_route is not None and sandbox_http_route.wakes + ) + transport_reset = False + implicit_wake = bool( + not lifecycle_action + and request_wakes + and (route.state or "unknown").lower() in {"parked", "waking"} + ) + if (route.state or "unknown").lower() == "parked" and request_wakes: + placed = place_wake(route) + if placed is None: + return None + route, transport_reset = placed + if ( + lifecycle_action == "wake" + and lifecycle_payload.get("request_id") + and not getattr(ex, "_program_wake_started", False) + ): + record_transition(route, lifecycle_payload, state="waking") + if ex.command == "DELETE": + prepared_delete = prep_delete(route) + if prepared_delete is None: + return None + route = prepared_delete + if not ex._route_worker_is_fresh(route, pull=True): + if self._routing(ex).get_sandbox_readonly(sandbox_id) is None: + self.write_absent_route(ex, sandbox_id) + return None + if self.serve_cached_job_status(ex, route, sandbox_http_route): + return None + ex._write_route_worker_unreachable(route) + return None + if implicit_wake: + completed_wake = implicit_wake_fn(route) + if completed_wake is None: + return None + route = completed_wake + return route, transport_reset + + def build_sandbox_proxy_headers( + self, + ex: Any, + route: SandboxRoute, + sandbox_http_route: SandboxHttpRoute | None, + body: bytes | RequestBodyStream | None, + ) -> tuple[bool, dict[str, str] | None]: + extra_headers: dict[str, str] | None = ( + { + SANDBOX_GENERATION_HEADER: str(route.generation), + SANDBOX_OPERATION_ID_HEADER: route.delete_operation_id, + } + if ex.command == "DELETE" + else None + ) + if ( + ex.command == "PUT" + and sandbox_http_route is not None + and sandbox_http_route.action in UPLOAD_ACTIONS + ): + assert body is not None + extra_headers = { + "Content-Length": str( + body.length if isinstance(body, RequestBodyStream) else len(body) + ), + SANDBOX_GENERATION_HEADER: str(route.generation), + } + if sandbox_http_route is not None and sandbox_http_route.action == "exec": + try: + extra_headers = { + EXEC_SESSION_PREFIX_HEADER: ex.exec_routing.signed_prefix(route) + } + except ExecRouteUnavailable as exc: + ex._write_json(exc.payload, status=exc.status, headers=exc.headers) + return False, None + return True, extra_headers + + def finalize_sandbox_proxy_response( + self, + ex: Any, + route: SandboxRoute, + sandbox_http_route: SandboxHttpRoute | None, + lifecycle_action: str, + lifecycle_payload: dict[str, Any], + transport_reset: bool, + response: ProxiedResponse, + *, + handle_lifecycle_response: Callable[..., SandboxRoute | None] | None = None, + ) -> None: + handle_lifecycle = handle_lifecycle_response or ( + lambda r, a, p, resp: self.handle_lifecycle_proxy_response(ex, r, a, p, resp) + ) + if self.serve_cached_transition_job_read(ex, route, sandbox_http_route, response): + return + if not self.record_successful_sandbox_proxy_state( + ex, route, sandbox_http_route, response + ): + return + if lifecycle_action == "park" and response.status == HTTPStatus.ACCEPTED: + self.cache_parked_job(ex, route, response.json().get("sandbox")) + ex._send_proxied_response(response) + return + if lifecycle_action: + lifecycle_route = handle_lifecycle( + route, lifecycle_action, lifecycle_payload, response + ) + if lifecycle_route is None: + return + route = lifecycle_route + if ex.command == "DELETE" and 200 <= response.status < 300: + if not self.commit_successful_worker_delete(ex, route, response): + return + response_headers: dict[str, str] | None = None + if lifecycle_action: + response_headers = { + SANDBOX_TRANSPORT_EPOCH_HEADER: sandbox_transport_epoch( + route, + self._routing(ex).sandbox_migrations( + active_only=False, sandbox_id=route.sandbox_id + ), + ) + } + if transport_reset: + response_headers[SANDBOX_TRANSPORT_RESET_HEADER] = "true" + ex._send_proxied_response(response, extra_headers=response_headers) + + def route_sandbox_request_admitted( + self, + ex: Any, + sandbox_id: str, + path: str, + *, + parse_lifecycle: Callable[[SandboxRoute, str, bytes | None], dict[str, Any] | None] | None = None, + prepare_program: Callable[[SandboxRoute, str, dict[str, Any]], None] | None = None, + prepare_forwarding: Callable[..., tuple[SandboxRoute, bool] | None] | None = None, + lifecycle_body: Callable[[SandboxRoute, str, dict[str, Any]], bytes | None] | None = None, + finalize_response: Callable[..., None] | None = None, + ) -> None: + parse_lc = parse_lifecycle or ( + lambda r, a, b: self.parse_lifecycle_request(ex, r, a, b) + ) + prep_prog = prepare_program or ( + lambda r, a, p: self.prepare_program_lifecycle(ex, r, a, p) + ) + prep_fwd = prepare_forwarding or ( + lambda sid, r, hr, la, lp: self.prepare_route_for_forwarding( + ex, sid, r, hr, la, lp + ) + ) + lc_body = lifecycle_body or ( + lambda r, a, p: self.lifecycle_proxy_body(ex, r, a, p) + ) + finalize = finalize_response or ( + lambda r, hr, la, lp, tr, resp: self.finalize_sandbox_proxy_response( + ex, r, hr, la, lp, tr, resp + ) + ) + route = self.resolve_admitted_route(ex, sandbox_id) + if route is None: + return + sandbox_http_route = match_sandbox_http_route(ex.command, path) + body_ok, body = self.read_admitted_proxy_body(ex, sandbox_http_route) + if not body_ok: + return + lifecycle_payload: dict[str, Any] = {} + lifecycle_action = ( + sandbox_http_route.action + if sandbox_http_route is not None + and sandbox_http_route.action in {"park", "wake"} + else "" + ) + if lifecycle_action: + parsed_lifecycle = parse_lc(route, lifecycle_action, body) + if parsed_lifecycle is None: + return + lifecycle_payload = parsed_lifecycle + job_read_wait = job_read_wait_ms(sandbox_http_route, ex.path) + if self.try_serve_parked_job_read(ex, route, sandbox_http_route): + return + prep_prog(route, lifecycle_action, lifecycle_payload) + prepared = prep_fwd( + sandbox_id, route, sandbox_http_route, lifecycle_action, lifecycle_payload + ) + if prepared is None: + return + route, transport_reset = prepared + headers_ok, extra_headers = self.build_sandbox_proxy_headers( + ex, route, sandbox_http_route, body + ) + if not headers_ok: + return + if ( + sandbox_http_route is not None + and sandbox_http_route.action == "files" + and ex.command == "GET" + ): + ex._stream_proxy_request( + route.node_url, + ex.path, + method=ex.command, + extra_headers=extra_headers, + ) + return + proxy_body = body + if lifecycle_action: + proxy_body = lc_body(route, lifecycle_action, lifecycle_payload) + if proxy_body is None: + return + if ( + ex.command == "PUT" + and sandbox_http_route is not None + and sandbox_http_route.action in UPLOAD_ACTIONS + and isinstance(proxy_body, bytes) + and len(proxy_body) <= TRANSFER_CHUNK_BYTES + and ex._defer_node_response( + route.node_url, + ex.path, + method="PUT", + body=proxy_body, + extra_headers=extra_headers, + ) + ): + return + if job_read_wait is not None and self.defer_job_read( + ex, route, sandbox_http_route, job_read_wait + ): + return + response = ex._proxy_request( + route.node_url, + ex.path, + method=ex.command, + body=proxy_body, + extra_headers=extra_headers, + timeout_seconds=job_read_timeout_seconds(job_read_wait), + ) + finalize( + route, + sandbox_http_route, + lifecycle_action, + lifecycle_payload, + transport_reset, + response, + ) + + def reconcile_routable_sandbox( + self, + ex: Any, + route: SandboxRoute, + ) -> SandboxRoute | None: + """Promote a completed create before forwarding sandbox traffic.""" + if route.state.lower() not in { + "creating", + "unknown", + "planned", + "quota_ready", + "rootfs_ready", + }: + return route + try: + routed_spec = SandboxSpec.from_dict(route.spec) + except (TypeError, ValueError): + routed_spec = None + if not ex._route_worker_is_fresh(route): + ex._write_create_in_progress_response(route.sandbox_id) + return None + record = ex._sandbox_record_on_node(route.node_url, route.sandbox_id) + if ( + routed_spec is None + or record is None + or not sandbox_record_matches_route(record, route, routed_spec) + or not sandbox_record_is_ready(record) + ): + ex._write_create_in_progress_response(route.sandbox_id) + return None + return ex._confirm_sandbox_observation(route_with_sandbox_record(route, record)) + + def prepare_program_lifecycle( + self, + ex: Any, + route: SandboxRoute, + action: str, + payload: dict[str, Any], + *, + record_program_transition: Callable[..., tuple[ProgramRequestState | None, bool]] | None = None, + ) -> None: + record_transition = record_program_transition or ( + lambda r, p, **kw: self.record_program_request_transition(ex, r, p, **kw) + ) + ex._program_wake_started = False + ex._warm_program_wake_observation = None + request_id = str(payload.get("request_id") or "").strip() + if not action or not request_id: + return + if ( + action == "wake" + and route.state.lower() == "running" + and payload.get("durable_lifecycle") + ): + ex._warm_program_wake_observation = ( + request_id, + route.sandbox_id, + route.generation, + utc_now().isoformat(), + ) + ex._program_wake_started = True + return + warm_wake = action == "wake" and route.state.lower() in {"running", "waking"} + transition = {"response_ready": True} if warm_wake else {} + program, _changed = record_transition( + route, + payload, + state=( + "waking" + if warm_wake + else "model_wait" + if action == "park" + else "ready_to_wake" + ), + **transition, + ) + ex._program_wake_started = warm_wake and program is not None + + def prepare_wake_placement( + self, + ex: Any, + route: SandboxRoute, + *, + wake_placement: Callable[[], WakePlacement] | None = None, + write_wake_unavailable: Callable[[WakeUnavailable], None] | None = None, + ) -> tuple[SandboxRoute, bool] | None: + wp = (wake_placement or (lambda: self.wake_placement(ex)))() + write_unavail = write_wake_unavailable or ( + lambda out: self.write_wake_unavailable(ex, out) + ) + outcome = wp.place(route) + if isinstance(outcome, WakePlaced): + return outcome.route, outcome.owner_changed + write_unavail(outcome) + return None + + def lifecycle_proxy_body( + self, + ex: Any, + route: SandboxRoute, + action: str, + payload: dict[str, Any], + ) -> bytes | None: + try: + node_payload = lifecycle_node_payload(route.generation, action, payload) + except ValueError as exc: + ex._write_json({"error": str(exc)}, status=HTTPStatus.BAD_REQUEST) + return None + return json.dumps(node_payload, separators=(",", ":")).encode("utf-8") + + def parse_lifecycle_request( + self, + ex: Any, + route: SandboxRoute, + action: str, + body: bytes | None, + ) -> dict[str, Any] | None: + """Parse and authorize one explicit lifecycle request.""" + payload, error_response = validate_lifecycle_payload(route, action, body) + if error_response is not None: + status, error_payload = error_response + ex._write_json(error_payload, status=status) + return None + assert payload is not None + request_id = str(payload.get("request_id") or "").strip() + rollout_id = str(payload.get("rollout_id") or "").strip() + if action == "park" and payload.get("durable_lifecycle"): + program = self._routing(ex).program_request_readonly(request_id) + if ( + program is not None + and program.sandbox_id == route.sandbox_id + and program.sandbox_generation == route.generation + and program.rollout_id == rollout_id + and program.state != "model_wait" + ): + ex._write_json({"skipped": True, "reason": "model_result_ready"}) + return None + return payload + + def prepare_delete_route( + self, + ex: Any, + route: SandboxRoute, + *, + resolve_migrations: Callable[[str], str] | None = None, + finish_detach: Callable[[SandboxRoute], tuple[SandboxRoute | None, str]] | None = None, + ) -> SandboxRoute | None: + """Resolve detach/migration state before proxying a durable delete.""" + routing = self._routing(ex) + resolve_migs = resolve_migrations or ( + lambda sid: self.migrations.resolve_for_delete(ex, sid) + ) + finish = finish_detach or ( + lambda r: self.migrations.finish_sandbox_detach(ex, r) + ) + sandbox_id = route.sandbox_id + route = routing.prepare_sandbox_delete(sandbox_id) or route + if route.worker_state != "detached": + migration_error = resolve_migs(sandbox_id) + if migration_error: + ex._write_json( + {"error": migration_error, "retryable": True}, + status=HTTPStatus.SERVICE_UNAVAILABLE, + headers={"X-UCloud-Sandbox-Retryable": "true"}, + ) + return None + current = routing.get_sandbox_readonly(sandbox_id) + if current is None: + ex._write_json({"deleted": None}) + return None + route = current + if route.worker_state == "detaching": + detached, error_message = finish(route) + if detached is None: + ex._write_json( + { + "error": error_message or "worker detach is incomplete", + "retryable": True, + }, + status=HTTPStatus.SERVICE_UNAVAILABLE, + headers={"X-UCloud-Sandbox-Retryable": "true"}, + ) + return None + route = detached + if route.worker_state != "detached": + return route + route = routing.prepare_sandbox_delete(sandbox_id) or route + removed = routing.delete_sandbox_if_current( + sandbox_id, + generation=route.generation, + delete_operation_id=route.delete_operation_id, + ) + if removed is not None: + self.registry_refs.release_route_reference(removed) + ex._write_json({"deleted": removed.to_dict() if removed is not None else None}) + return None + + def serve_cached_job_status( + self, + ex: Any, + route: SandboxRoute, + http_route: SandboxHttpRoute | None, + *, + missing_status: HTTPStatus | None = None, + ) -> bool: + cached = cached_job_status_response( + self._routing(ex), + route, + http_route, + wait_ms=job_read_wait_ms(http_route, ex.path), + missing_status=missing_status, + ) + if cached is None: + return False + ex._send_proxied_response(cached) + return True + + def serve_cached_job_logs( + self, + ex: Any, + route: SandboxRoute, + http_route: SandboxHttpRoute | None, + ) -> bool: + cached = cached_job_logs_response( + self._routing(ex), + route, + http_route, + ex.path, + wait_ms=job_read_wait_ms(http_route, ex.path), + ) + if cached is None: + return False + ex._send_proxied_response(cached) + return True + + def defer_job_read( + self, + ex: Any, + route: SandboxRoute, + http_route: SandboxHttpRoute | None, + wait_ms: int, + ) -> bool: + if ex.async_responses is None or ( + ex.headers.get("Transfer-Encoding") + or ex.headers.get("Content-Length", "0") != "0" + ): + return False + routing_store, path = self._routing(ex), ex.path + + def project(status, headers, body): + response = ProxiedResponse(status, headers, body) + try: + projected = project_job_response( + routing_store, + route, + http_route, + path, + response, + wait_ms=wait_ms, + ) + except sqlite3.DatabaseError: + return ( + HTTPStatus.SERVICE_UNAVAILABLE, + {"Content-Type": "application/json"}, + b'{"error":"routing state unavailable","retryable":true}', + ) + if projected is None: + return status, headers, body + return projected.status, projected.headers, projected.body + + try: + proxied = ex._build_proxy_request(route.node_url, path, method="GET") + ex.server.defer_proxy_response( + ex.request, + url=proxied.full_url, + headers=node_request_headers(proxied), + trace_headers=ex.telemetry.current_trace_headers(), + telemetry=ex.telemetry, + method="GET", + event_poll=False, + timeout=job_read_timeout_seconds(wait_ms), + held_read=True, + project=project, + ) + except (OSError, error.URLError, RuntimeError) as exc: + ex._send_proxied_response(node_transport_error_response(exc)) + return True + ex.close_connection = True + return True + + def perform_implicit_wake( + self, + ex: Any, + route: SandboxRoute, + *, + commit_lifecycle: Callable[..., SandboxRoute | None] | None = None, + ) -> SandboxRoute | None: + commit_fn = commit_lifecycle or ( + lambda r, a, resp: self.commit_lifecycle_response(ex, r, a, resp) + ) + response = ex._proxy_request( + route.node_url, + f"/v1/sandboxes/{quote(route.sandbox_id, safe='')}/wake", + method="POST", + body=json.dumps( + { + "generation": route.generation, + "operation_id": f"activity-wake:{uuid4().hex}", + }, + separators=(",", ":"), + ).encode("utf-8"), + extra_headers={"Content-Type": "application/json"}, + ) + if response.status < 300: + return commit_fn(route, "wake", response) + if str(response.json().get("lifecycle_state") or "").lower() == "parked": + rolled_back = self._routing(ex).set_sandbox_state_if_current( + route, + expected_states={"waking"}, + state="parked", + ) + if rolled_back is not None: + self.cache_parked_job(ex, rolled_back, response.json().get("sandbox")) + if response.transport_error_kind: + ex._write_json( + { + "error": "sandbox wake is unavailable; requested operation has not started", + "error_code": "node_restore_busy", + "cause_code": response.json().get("code", "node_transport_error"), + "retryable": True, + }, + status=HTTPStatus.SERVICE_UNAVAILABLE, + headers={"Retry-After": "1", "X-UCloud-Sandbox-Retryable": "true"}, + ) + return None + ex._send_proxied_response(response) + return None + + def serve_cached_transition_job_read( + self, + ex: Any, + route: SandboxRoute, + http_route: SandboxHttpRoute | None, + response: ProxiedResponse, + ) -> bool: + if not 400 <= response.status < 500: + return False + cached = project_job_response( + self._routing(ex), + route, + http_route, + ex.path, + response, + wait_ms=job_read_wait_ms(http_route, ex.path), + ) + if cached is None: + return False + ex._send_proxied_response(cached) + return True + + def record_successful_sandbox_proxy_state( + self, + ex: Any, + route: SandboxRoute, + http_route: SandboxHttpRoute | None, + response: ProxiedResponse, + ) -> bool: + if http_route is None or not 200 <= response.status < 300: + return True + if http_route.action in {"job_create", "job_status", "job_signal", "job_logs"}: + invalid = record_job_response(self._routing(ex), route, http_route, response) + if invalid is not None: + ex._send_proxied_response(invalid) + return False + return True + + def handle_lifecycle_proxy_response( + self, + ex: Any, + route: SandboxRoute, + action: str, + payload: dict[str, Any], + response: ProxiedResponse, + *, + record_program_transition: Callable[..., tuple[ProgramRequestState | None, bool]] | None = None, + commit_lifecycle: Callable[..., SandboxRoute | None] | None = None, + record_completed: Callable[..., None] | None = None, + ) -> SandboxRoute | None: + record_transition = record_program_transition or ( + lambda r, p, **kw: self.record_program_request_transition(ex, r, p, **kw) + ) + commit_fn = commit_lifecycle or ( + lambda r, a, resp, *, lifecycle_payload=None: self.commit_lifecycle_response( + ex, r, a, resp, lifecycle_payload=lifecycle_payload + ) + ) + record_done = record_completed or ( + lambda r, a, p: self.record_completed_program_lifecycle(ex, r, a, p) + ) + if response.status >= 300: + if action == "park" and response.status == HTTPStatus.CONFLICT: + try: + deferred = response.json() + except (TypeError, ValueError): + deferred = {} + if ( + isinstance(deferred, dict) + and deferred.get("error_code") == "park_deferred" + and deferred.get("retryable") is True + ): + return route + if action == "wake": + try: + failed_state = str( + response.json().get("lifecycle_state") or "" + ).lower() + except (TypeError, ValueError, json.JSONDecodeError): + failed_state = "" + if failed_state == "parked": + rolled_back = self._routing(ex).set_sandbox_state_if_current( + route, + expected_states={"waking"}, + state="parked", + ) + if rolled_back is not None: + route = rolled_back + self.cache_parked_job(ex, route, response.json().get("sandbox")) + record_transition( + route, + payload, + state=("waking" if action == "wake" else "model_wait"), + last_error=lifecycle_proxy_error(response), + ) + return route + if not 200 <= response.status < 300: + return route + updated = commit_fn( + route, + action, + response, + lifecycle_payload=payload if action == "wake" else None, + ) + if updated is None: + return None + if action != "wake": + record_done(updated, action, payload) + return updated + + def commit_lifecycle_response( + self, + ex: Any, + route: SandboxRoute, + action: str, + response: ProxiedResponse, + *, + lifecycle_payload: dict[str, Any] | None = None, + record_completed: Callable[..., None] | None = None, + ) -> SandboxRoute | None: + record_done = record_completed or ( + lambda r, a, p, *, committed=None: self.record_completed_program_lifecycle( + ex, r, a, p, committed=committed + ) + ) + commit = LifecycleCommitter( + self._routing(ex), + heartbeat=lambda job_id: ex._heartbeat_for_route( + job_id=job_id, include_inventory=False + ), + snapshots=SnapshotReferences( + protect=lambda candidate: self.registry_refs.ensure_snapshot_reference( + candidate, + repository=candidate.snapshot_repository, + tag=candidate.snapshot_tag, + digest=candidate.snapshot_manifest_digest, + ), + release=self.registry_refs.release_snapshot_reference, + ), + ) + try: + try: + receipt = response.json() + except (ValueError, TypeError) as exc: + raise InvalidLifecycleReceipt( + "invalid node lifecycle response: expected JSON object" + ) from exc + if not isinstance(receipt, dict): + raise InvalidLifecycleReceipt( + "invalid node lifecycle response: expected JSON object" + ) + if action == "wake": + outcome = commit.wake( + route, + receipt, + program_transition=( + self.program_request_transition_args( + ex, + route, + lifecycle_payload, + state="acting", + clear_error=True, + ) + if lifecycle_payload is not None + else None + ), + ) + else: + outcome = commit.park(route, receipt) + except InvalidLifecycleReceipt as exc: + ex._write_json({"error": str(exc)}, status=HTTPStatus.BAD_GATEWAY) + return None + except LifecycleRouteChanged as exc: + ex._write_json( + {"error": str(exc), "retryable": True}, + status=HTTPStatus.SERVICE_UNAVAILABLE, + headers={"X-UCloud-Sandbox-Retryable": "true"}, + ) + return None + except RegistryImageReferenceUnavailable as exc: + ex._write_registry_lease_unavailable(exc) + return None + if action != "wake": + self.cache_parked_job(ex, outcome.route, receipt.get("sandbox")) + if action == "wake" and lifecycle_payload is not None: + record_done( + outcome.route, + action, + lifecycle_payload, + committed=outcome.program_transition, + ) + return outcome.route + + def cache_parked_job( + self, + ex: Any, + route: SandboxRoute, + sandbox_record: object, + ) -> None: + cache_parked_job(self._routing(ex), route, sandbox_record) + + def record_completed_program_lifecycle( + self, + ex: Any, + route: SandboxRoute, + action: str, + payload: dict[str, Any], + *, + committed=None, + record_program_transition: Callable[..., tuple[ProgramRequestState | None, bool]] | None = None, + ) -> None: + record_transition = record_program_transition or ( + lambda r, p, **kw: self.record_program_request_transition(ex, r, p, **kw) + ) + metrics = self._metrics(ex) + if not payload.get("request_id"): + return + if action == "park": + record_transition( + route, + payload, + state="model_wait", + parked_at=utc_now().isoformat(), + clear_error=True, + ) + return + if committed is None: + _program, changed = record_transition( + route, payload, state="acting", clear_error=True + ) + else: + _program, changed = committed + if changed: + metrics.append("program_state_transition", _program.to_dict()) + if not changed: + return + metrics.append( + "program_wake_actual", + { + "request_id": str(payload.get("request_id") or "").strip(), + "rollout_id": str(payload.get("rollout_id") or "").strip(), + "sandbox_id": route.sandbox_id, + "sandbox_generation": route.generation, + "node_id": route.node_id, + "job_id": route.job_id, + }, + ) + + def commit_successful_worker_delete( + self, + ex: Any, + route: SandboxRoute, + response: ProxiedResponse, + ) -> bool: + deleted = response.json().get("deleted") + response_generation = record_generation(deleted) + if ( + isinstance(deleted, dict) + and response_generation is not None + and response_generation != route.generation + ): + ex._write_json( + { + "error": "node delete response confirmed a different generation", + "retryable": True, + }, + status=HTTPStatus.BAD_GATEWAY, + ) + return False + removed = self._routing(ex).delete_sandbox_if_current( + route.sandbox_id, + generation=route.generation, + delete_operation_id=route.delete_operation_id, + ) + if removed is not None: + self.registry_refs.release_route_reference(removed) + return True + + def program_request_transition_args( + self, + ex: Any, + route: SandboxRoute, + lifecycle_payload: dict[str, Any], + *, + state: str, + parked_at: str | None = None, + response_ready: bool = False, + last_error: str = "", + clear_error: bool = False, + ) -> dict[str, Any] | None: + return build_program_request_transition_args( + route, + lifecycle_payload, + state=state, + now_iso=utc_now().isoformat(), + warm_observation=getattr(ex, "_warm_program_wake_observation", None), + parked_at=parked_at, + response_ready=response_ready, + last_error=last_error, + clear_error=clear_error, + ) + + def record_program_request_transition( + self, + ex: Any, + route: SandboxRoute, + lifecycle_payload: dict[str, Any], + *, + state: str, + parked_at: str | None = None, + response_ready: bool = False, + last_error: str = "", + clear_error: bool = False, + ) -> tuple[ProgramRequestState | None, bool]: + args = self.program_request_transition_args( + ex, + route, + lifecycle_payload, + state=state, + parked_at=parked_at, + response_ready=response_ready, + last_error=last_error, + clear_error=clear_error, + ) + if args is None: + return None, False + metrics = self._metrics(ex) + try: + program, changed = self._routing( + ex + ).upsert_program_request_transition_with_change(route, **args) + except (OSError, sqlite3.Error, ValueError, SandboxRouteConflictError) as exc: + metrics.append( + "program_state_projection_error", + { + "request_id": args["request_id"], + "rollout_id": args["rollout_id"], + "sandbox_id": route.sandbox_id, + "sandbox_generation": route.generation, + "state": state, + "error": str(exc), + }, + ) + return None, False + if changed: + metrics.append("program_state_transition", program.to_dict()) + return program, changed + + def read_worker_heartbeat(self, ex: Any, node_url: str) -> Any: + response = ex._proxy_request( + node_url, + "/v1/heartbeat", + method="GET", + timeout_seconds=PULL_TIMEOUT_SECONDS, + ) + return ( + response.json().get("heartbeat") + if response.status == HTTPStatus.OK + else None + ) + + def refresh_worker(self, ex: Any, heartbeat: NodeHeartbeat) -> NodeHeartbeat | None: + return self.heartbeats.refresh( + heartbeat, lambda url: self.read_worker_heartbeat(ex, url) + ) + + def refresh_wake_capacity(self, ex: Any, route: SandboxRoute) -> None: + owner = self.fleet.store.get_heartbeat(route.job_id, include_inventory=False) + if owner is not None: + self.refresh_worker(ex, owner) + + def request_wake_publication( + self, + ex: Any, + route: SandboxRoute, + ) -> dict[str, Any] | None: + response = ex._proxy_request( + route.node_url, + f"/v1/sandboxes/{quote(route.sandbox_id, safe='')}/snapshot/publish", + method="POST", + body=json.dumps({"generation": route.generation}).encode(), + timeout_seconds=2.0, + ) + return response.json() if response.status < 400 else None + + def decode_wake_publication( + self, + ex: Any, + route: SandboxRoute, + payload: dict[str, Any], + ) -> SandboxRoute | None: + record = payload.get("sandbox") + if not isinstance(record, dict) or record.get("state") != "parked": + return None + if not sandbox_record_matches_route( + record, route, SandboxSpec.from_dict(route.spec) + ): + return None + self.cache_parked_job(ex, route, record) + return route_with_sandbox_record(route, record) + + def wake_admission(self, ex: Any) -> WakeAdmission: + return WakeAdmission( + self._routing(ex), + read_owner=self.fleet.store.get_heartbeat, + read_placement=self.placement.routes_for_node, + can_admit=lambda owner, routes, requested: ( + node_has_storage_device_capacity(owner, routes) + and node_can_fit_available( + owner, requested, node_available_resources(owner, routes) + ) + ), + heartbeat_ttl_seconds=self.fleet.heartbeat_ttl_seconds, + ) + + def reserve_local_wake(self, ex: Any, route: SandboxRoute): + return self.batchers.for_owner( + self._routing(ex).path, owner=route.job_id + ).reserve(ex, route) + + def reserve_local_wake_batch(self, ex: Any, batch: list[tuple[Any, SandboxRoute, Any]]): + decisions = self.wake_admission(ex).reserve_batch( + [route for _, route, _ in batch] + ) + return [decision.route for decision in decisions] + + def wake_placement( + self, + ex: Any, + *, + select_destination: Callable[..., NodeHeartbeat | None] | None = None, + finish_detach: Callable[[SandboxRoute], tuple[SandboxRoute | None, str]] | None = None, + advance_migration: Callable[..., Any] | None = None, + refresh_capacity: Callable[[SandboxRoute], None] | None = None, + reserve_local: Callable[[SandboxRoute], Any] | None = None, + ) -> WakePlacement: + choose_dest = select_destination or ( + lambda route: self.migrations.select_destination( + ex, route, requested_node_id="", require_active_resources=True + ) + ) + finish = finish_detach or ( + lambda route: self.migrations.finish_sandbox_detach(ex, route) + ) + advance_mig = advance_migration or ( + lambda migration, **kw: self.migrations.prepare_and_advance(ex, migration, **kw) + ) + refresh_cap = refresh_capacity or ( + lambda route: self.refresh_wake_capacity(ex, route) + ) + reserve = reserve_local or (lambda route: self.reserve_local_wake(ex, route)) + return WakePlacement( + self._routing(ex), + self.wake_admission(ex), + WakePlacementPorts( + owner=lambda job_id: ex._heartbeat_for_route(job_id=job_id), + occupants=self.placement.routes_for_node, + destination=choose_dest, + reserve_local=reserve, + finish_detach=finish, + advance_migration=advance_mig, + refresh_capacity=refresh_cap, + publish=lambda route: self.request_wake_publication(ex, route), + decode_publication=lambda route, payload: self.decode_wake_publication( + ex, route, payload + ), + atomic=self.placement.atomic, + ), + ) + + def write_wake_unavailable(self, ex: Any, outcome: WakeUnavailable) -> None: + if outcome.missing_sandbox_id: + self.write_missing_sandbox_route(ex, outcome.missing_sandbox_id) + return + payload, headers = build_wake_unavailable_response(outcome) + ex._write_json( + payload, + status=HTTPStatus.SERVICE_UNAVAILABLE, + headers=headers, + ) diff --git a/sandboxes/gateway/services.py b/sandboxes/gateway/services.py index 35b895cc..86bde37e 100644 --- a/sandboxes/gateway/services.py +++ b/sandboxes/gateway/services.py @@ -12,14 +12,17 @@ from ..registry_disk import RegistryDiskMonitor from ..routing import RoutingStore from ..telemetry import Telemetry +from .build_service import ImageBuilds from .create import CreatePlacement from .fleet import FleetView from .groups import GroupCreate from .heartbeats import HeartbeatIngest, RebootReaper, WorkerDelete from .image_resolution import ImageResolution +from .migration_service import SandboxMigrations from .operator import OperatorDrains, QueuedCreates from .placement import Placement from .registry_refs import RegistryReferences +from .sandbox_proxy import SandboxProxy @dataclass(frozen=True) @@ -39,6 +42,9 @@ class GatewayServices: images: ImageResolution drains: OperatorDrains queued_creates: QueuedCreates + migrations: SandboxMigrations + builds: ImageBuilds + sandbox_proxy: SandboxProxy def build_services( @@ -65,25 +71,53 @@ def build_services( target_creates_per_node=create_target_concurrency_per_node, api_processes=api_processes, ) + placement = Placement(routing_store, telemetry=telemetry) + images = ImageResolution( + image_manager=image_manager, registry_url=registry_url, + registry_worker_url=registry_worker_url, disk_monitor=registry_disk_monitor, + fleet=fleet, image_roots=getattr(dependency_resolver, "image_roots", None), + ) + heartbeats = HeartbeatIngest( + store=store, routing_store=routing_store, metrics_store=metrics_store, + deployment_id=deployment_id, registry_refs=registry_refs, + reaper=RebootReaper( + routing_store=routing_store, registry_refs=registry_refs, + metrics_store=metrics_store, delete_on_worker=delete_on_worker, + ) if delete_on_worker is not None else None, + ) + migrations = SandboxMigrations( + routing_store=routing_store, + registry_refs=registry_refs, + fleet=fleet, + placement=placement, + ) return GatewayServices( registry_refs=registry_refs, fleet=fleet, - heartbeats=HeartbeatIngest( - store=store, routing_store=routing_store, metrics_store=metrics_store, - deployment_id=deployment_id, registry_refs=registry_refs, - reaper=RebootReaper( - routing_store=routing_store, registry_refs=registry_refs, - metrics_store=metrics_store, delete_on_worker=delete_on_worker, - ) if delete_on_worker is not None else None, - ), - placement=Placement(routing_store, telemetry=telemetry), + heartbeats=heartbeats, + placement=placement, creates=creates, groups=GroupCreate(creates, target_creates_per_node=create_target_concurrency_per_node), - images=ImageResolution( - image_manager=image_manager, registry_url=registry_url, - registry_worker_url=registry_worker_url, disk_monitor=registry_disk_monitor, - fleet=fleet, image_roots=getattr(dependency_resolver, "image_roots", None), - ), + images=images, drains=OperatorDrains(store, routing_store), queued_creates=QueuedCreates(routing_store), + migrations=migrations, + builds=ImageBuilds( + routing_store=routing_store, + fleet=fleet, + registry_refs=registry_refs, + images=images, + image_manager=image_manager, + metrics_store=metrics_store, + telemetry=telemetry, + ), + sandbox_proxy=SandboxProxy( + routing_store=routing_store, + fleet=fleet, + placement=placement, + registry_refs=registry_refs, + metrics_store=metrics_store, + heartbeats=heartbeats, + migrations=migrations, + ), ) diff --git a/sandboxes/gateway/state.py b/sandboxes/gateway/state.py new file mode 100644 index 00000000..8ec9c1f2 --- /dev/null +++ b/sandboxes/gateway/state.py @@ -0,0 +1,159 @@ +"""Process-wide in-memory caches and singleflight coalescers for the gateway. + +Replaces raw mutable class attributes (locks, futures, OrderedDicts) on +``ControlPlaneHandler`` with explicit per-server state owned by ``build_server``. +""" + +from __future__ import annotations + +from collections import OrderedDict +from concurrent.futures import Future +from dataclasses import dataclass, field +from threading import RLock +import time +from typing import Callable, Generic, TypeVar + +K = TypeVar("K") +V = TypeVar("V") + +DEFAULT_BUILD_OWNER_CACHE_LIMIT = 4096 + + +class SingleflightCoalescer(Generic[K, V]): + """Coalesce concurrent in-flight computations sharing a key. + + Waiters share the leader's result or exception; once the leader completes, + the slot clears immediately so no stale snapshot or failure is retained. + """ + + def __init__(self, *, future_factory: Callable[[], Future[V]] = Future) -> None: + self._lock = RLock() + self._futures: dict[K, Future[V]] = {} + self._future_factory = future_factory + + @property + def in_flight_count(self) -> int: + with self._lock: + return len(self._futures) + + def has_in_flight(self, key: K) -> bool: + with self._lock: + return key in self._futures + + def run(self, key: K, compute: Callable[[], V]) -> V: + leader = False + with self._lock: + future = self._futures.get(key) + if future is None: + future = self._future_factory() + self._futures[key] = future + leader = True + if not leader: + return future.result() + try: + value = compute() + except BaseException as exc: + future.set_exception(exc) + raise + else: + future.set_result(value) + return value + finally: + with self._lock: + if self._futures.get(key) is future: + del self._futures[key] + + +class MetricsResponseCache: + """Thread-safe TTL cache for rendered metrics responses.""" + + def __init__(self, *, clock: Callable[[], float] = time.monotonic) -> None: + self._lock = RLock() + self._clock = clock + self._cached: bytes | None = None + self._cached_at: float = 0.0 + + def get_or_compute( + self, + *, + ttl_seconds: float, + cacheable: bool, + compute: Callable[[], bytes | tuple[bytes, bytes]], + ) -> bytes: + with self._lock: + now = self._clock() + if ( + cacheable + and self._cached is not None + and now - self._cached_at <= ttl_seconds + ): + return self._cached + result = compute() + if isinstance(result, tuple): + fresh, cached = result + else: + fresh = cached = result + if cacheable: + self._cached = cached + self._cached_at = self._clock() + return fresh + + +class BuildOwnerCache: + """Bounded-LRU cache of builder ownership and recorded terminal build metrics.""" + + def __init__(self, *, max_entries: int = DEFAULT_BUILD_OWNER_CACHE_LIMIT) -> None: + self._lock = RLock() + self._max_entries = max(1, max_entries) + self.owners: OrderedDict[str, tuple[str, str, str]] = OrderedDict() + self.metrics_seen: OrderedDict[tuple[str, str], None] = OrderedDict() + + def get_owner(self, build_key: str) -> tuple[str, str, str] | None: + with self._lock: + return self.owners.get(build_key) + + def record_owner(self, build_key: str, identity: tuple[str, str, str]) -> None: + with self._lock: + self.owners[build_key] = identity + self.owners.move_to_end(build_key) + while len(self.owners) > self._max_entries: + self.owners.popitem(last=False) + + def has_recorded_metric(self, key: tuple[str, str]) -> bool: + with self._lock: + return key in self.metrics_seen + + def mark_metric_recorded(self, key: tuple[str, str]) -> None: + with self._lock: + self.metrics_seen[key] = None + while len(self.metrics_seen) > self._max_entries: + self.metrics_seen.popitem(last=False) + + def record_metric_once( + self, + key: tuple[str, str], + write: Callable[[], None], + ) -> bool: + """Run ``write`` at most once per key; a failing write is not marked seen.""" + with self._lock: + if key in self.metrics_seen: + return False + write() + self.metrics_seen[key] = None + while len(self.metrics_seen) > self._max_entries: + self.metrics_seen.popitem(last=False) + return True + + +@dataclass +class GatewayRuntimeState: + """All process-wide mutable caches and coalescers for one gateway server.""" + + builds: BuildOwnerCache = field(default_factory=BuildOwnerCache) + metrics_cache: MetricsResponseCache = field(default_factory=MetricsResponseCache) + fleet_list: SingleflightCoalescer[None, bytes] = field( + default_factory=SingleflightCoalescer + ) + fleet_status: SingleflightCoalescer[tuple[str, ...], bytes] = field( + default_factory=SingleflightCoalescer + ) diff --git a/sandboxes/gvisor_distribution.py b/sandboxes/gvisor_distribution.py index be86b6ba..867b1994 100644 --- a/sandboxes/gvisor_distribution.py +++ b/sandboxes/gvisor_distribution.py @@ -9,7 +9,6 @@ GVISOR_COMMIT = "50e1502a95d36ad2faf2c7ef33b8bf21fe975293" -REFLINK_RESTORE_PATCH_SHA256 = "17933cd7990ac28c0b9bdb8add8330f242fdd3dcf61621c2a7d3905c984f6619" GVISOR_SIDECARS = ( "checkpointgofer", "gvisor-sentry-prewarmer", @@ -128,17 +127,3 @@ def require_ram_backing_runtime(runsc: Path, commit: str) -> None: raise ValueError( "RAM application memory requires the qualified sparse-capture runtime" ) - - -def require_reflink_restore_runtime(runsc: Path, commit: str) -> None: - """File-backed reflink restores require the full pinned capture ABI.""" - require_ram_backing_runtime(runsc, commit) - manifest = json.loads((runsc.parent / "build-manifest.json").read_text()) - if not any( - entry == { - "name": "20260817/0007-ucloud-reflink-application-memory.patch", - "sha256": REFLINK_RESTORE_PATCH_SHA256, - } - for entry in manifest.get("patches", []) - ): - raise ValueError("reflink memory restore requires the qualified reflink runtime") diff --git a/sandboxes/memory_backing.py b/sandboxes/memory_backing.py index 49827e56..81788e7e 100644 --- a/sandboxes/memory_backing.py +++ b/sandboxes/memory_backing.py @@ -47,13 +47,6 @@ class MemoryBackingBusyError(MemoryBackingError): pass -@dataclass(frozen=True) -class RetainedCheckpointRef: - reference: MemoryBackingRef - hibernation_generation: int - manifest_sha256: str - - class FilesystemTrim: """Coalesce already-unlinked allocations behind a shared physical barrier. @@ -371,31 +364,6 @@ def active_mode(self, sandbox_id: str, generation: int) -> str | None: with self._active_modes_lock: return self._active_modes.get((sandbox_id, generation)) - def configure_reflink_restore(self, enabled: bool) -> None: - """Keep the required reader until all its allocations have drained. - - Placement and checkpoint ownership must never silently revert to the - old destructive restore semantics when a deployment flag is removed. - """ - with self._write_batches.transaction() as conn: - conn.execute("BEGIN IMMEDIATE") - previous = conn.execute( - "SELECT 1 FROM features WHERE name='reflink-restore-v1'" - ).fetchone() - retained = conn.execute( - "SELECT 1 FROM allocations WHERE state!='deleted' LIMIT 1" - ).fetchone() - retained = retained or conn.execute( - "SELECT 1 FROM retained_checkpoints WHERE state!='deleted' LIMIT 1" - ).fetchone() - if previous and not enabled and retained: - raise MemoryBackingError("reflink restore reader is required until retained allocations drain") - if enabled: - conn.execute("INSERT OR IGNORE INTO features VALUES ('reflink-restore-v1')") - else: - conn.execute("DELETE FROM features WHERE name='reflink-restore-v1'") - conn.commit() - def _connect(self): conn = sqlite3.connect(self.journal, timeout=30, check_same_thread=False) conn.execute("PRAGMA journal_mode=WAL") @@ -678,211 +646,6 @@ def _prepare_active(self, lease: MemoryBackingLease) -> None: path.mkdir(mode=0o700, exist_ok=True) self._private_directory(path) - def prepare_file_restore( - self, reference: MemoryBackingRef, *, sandbox_id: str, sandbox_generation: int - ) -> MemoryBackingLease: - """Persist file placement before a fenced parked owner's next launch. - - The Warden must already own PARKED authority. This allocator validates - the retained quota and refuses to abandon any still-present RAM files; - it neither checkpoints nor moves a live mapping. The selection survives - candidate failure and restart, so recovery chooses the same backing. - """ - with self._mutation_lock(reference): - # The owner's mutation lock keeps this row stable until the update. - row = self._reader().execute( - "SELECT * FROM allocations WHERE allocation_id=?", (reference.allocation_id,) - ).fetchone() - if (row is None or row[1:3] != (sandbox_id, sandbox_generation) - or row[4] != reference.quota_bytes or row[5] != "ready"): - raise MemoryBackingError("file restore does not own a retained memory allocation") - lease = MemoryBackingLease(reference, sandbox_id, sandbox_generation, - row[3], self.root / reference.allocation_id, row[6]) - self._validate(lease) - if lease.active_mode == "ram": - active = self.active_root / reference.allocation_id - if any(active.iterdir()): - raise MemoryBackingError("file restore cannot abandon live RAM backing") - with self._write_batches.transaction() as conn: - conn.execute("UPDATE allocations SET active_mode='file' WHERE allocation_id=?", - (reference.allocation_id,)) - conn.commit() - self._remember_mode(sandbox_id, sandbox_generation, "file") - return MemoryBackingLease(reference, sandbox_id, sandbox_generation, - row[3], lease.path, "file") - - def retain_checkpoint( - self, reference: MemoryBackingRef, *, sandbox_id: str, - sandbox_generation: int, hibernation_generation: int, - manifest_sha256: str, allocated_bytes: int, - ) -> None: - """Assign immutable memory its separately admitted temporary quota. - - The caller reserves these bytes in the canonical registry BEFORE this - operation and owns PARKED lifecycle authority. The live project never - receives extra space that a guest could consume before cleanup. - """ - if hibernation_generation < 1 or allocated_bytes < 1: - raise MemoryBackingError("retained checkpoint capacity is invalid") - phase_started = time.monotonic() - lease = self.require(reference, sandbox_id=sandbox_id, - sandbox_generation=sandbox_generation) - path = lease.path / f"hibernate-{hibernation_generation}" / "application_memory.img" - with self._mutation_lock(reference): - self._private_directory(path.parent) - info = path.lstat() - if (not stat.S_ISREG(info.st_mode) or info.st_uid != os.geteuid() - or info.st_mode & 0o077 or info.st_blocks * 512 > allocated_bytes): - raise MemoryBackingError("retained checkpoint identity or capacity differs") - get_current_span().add_event("memory.retain.validate", - {"duration_ms": (time.monotonic() - phase_started) * 1000}) - phase_started = time.monotonic() - # The per-owner mutation lease fences filesystem side effects. - # SQLite serializes counter/row updates; a shared FULL commit lets - # independent owners retain concurrently without a node-wide lock. - with self._write_batches.transaction() as conn: - conn.execute("BEGIN IMMEDIATE") - row = conn.execute( - "SELECT manifest_sha256,allocated_bytes,device,inode,project_id,state " - "FROM retained_checkpoints WHERE allocation_id=? AND hibernation_generation=?", - (reference.allocation_id, hibernation_generation), - ).fetchone() - expected = (manifest_sha256, allocated_bytes, info.st_dev, info.st_ino) - if row is not None and row[5] == "retiring": - raise MemoryBackingBusyError("retained checkpoint physical release is pending") - if row is not None and row[5] == "deleted": - # A parked incarnation can migrate away and return without - # executing or advancing its hibernation generation. The - # old source/project was fully retired; the caller has - # already admitted this new source in the global registry. - # Never recycle a project ID or reinterpret an active row. - conn.execute( - "DELETE FROM retained_checkpoints WHERE allocation_id=? AND hibernation_generation=?", - (reference.allocation_id, hibernation_generation), - ) - row = None - if row is None: - project = conn.execute("SELECT value FROM counter").fetchone()[0] - conn.execute("UPDATE counter SET value=value+1") - conn.execute("INSERT INTO retained_checkpoints VALUES (?,?,?,?,?,?,?,?)", - (reference.allocation_id, hibernation_generation, - *expected, project, "preparing")) - elif row[:4] != expected: - raise MemoryBackingError("retained checkpoint quota identity conflicts") - else: - project = row[4] - conn.commit() - get_current_span().add_event("memory.retain.prepare_journal", - {"duration_ms": (time.monotonic() - phase_started) * 1000}) - # Idempotent through a crash before/after inode reassignment. Only - # this owner's mutation lease is held over filesystem operations. - self.quota.retain_file(path, project, allocated_bytes) - phase_started = time.monotonic() - with self._write_batches.transaction() as conn: - conn.execute("UPDATE retained_checkpoints SET state='ready' " - "WHERE allocation_id=? AND hibernation_generation=?", - (reference.allocation_id, hibernation_generation)) - conn.commit() - - get_current_span().add_event("memory.retain.ready_journal", - {"duration_ms": (time.monotonic() - phase_started) * 1000}) - - def release_retained_checkpoint( - self, reference: MemoryBackingRef, *, hibernation_generation: int, - manifest_sha256: str, - ) -> bool: - """Release only after artifact deletion, closed readers and physical trim.""" - with self._mutation_lock(reference), self._allocation_lock(reference, exclusive=True): - path = self.root / reference.allocation_id / f"hibernate-{hibernation_generation}" - if os.path.lexists(path): - return False - row = self._reader().execute( - "SELECT manifest_sha256,project_id,state FROM retained_checkpoints " - "WHERE allocation_id=? AND hibernation_generation=?", - (reference.allocation_id, hibernation_generation), - ).fetchone() - if row is None: - # A crash may follow the global claim but precede project setup. - return True - if row[0] != manifest_sha256: - raise MemoryBackingError("retained checkpoint release identity conflicts") - if row[2] != "deleted": - self.quota.release(self.root, row[1]) - with self._write_batches.transaction() as conn: - conn.execute("UPDATE retained_checkpoints SET state='deleted' " - "WHERE allocation_id=? AND hibernation_generation=?", - (reference.allocation_id, hibernation_generation)) - conn.commit() - return True - - def release_retained_checkpoints(self, checkpoints, *, release_claim) -> int: - """Batch the physical barrier without holding any lifecycle/owner lock. - - Existing retention rows fence each exact project while trim is outside - the locks. A concurrent deletion can finish that project; final identity - checks prevent the old batch from touching a reimported replacement. - The global claim is always last, after the local deleted commit. - """ - pending = [] - for checkpoint in checkpoints: - ref = checkpoint.reference - identity = (ref.allocation_id, checkpoint.hibernation_generation) - try: - with self._mutation_lock(ref), self._allocation_lock(ref, exclusive=True): - path = self.root / ref.allocation_id / f"hibernate-{checkpoint.hibernation_generation}" - if os.path.lexists(path): - continue - with self._write_batches.transaction() as conn: - conn.execute("BEGIN IMMEDIATE") - row = conn.execute( - "SELECT manifest_sha256,allocated_bytes,device,inode,project_id,state " - "FROM retained_checkpoints WHERE allocation_id=? AND hibernation_generation=?", - identity, - ).fetchone() - if row is not None: - if row[0] != checkpoint.manifest_sha256: - raise MemoryBackingError("retained checkpoint release identity conflicts") - if row[5] not in {"preparing", "ready", "retiring", "deleted"}: - raise MemoryBackingError("retained checkpoint release state is invalid") - if row[5] != "deleted": - conn.execute("UPDATE retained_checkpoints SET state='retiring' " - "WHERE allocation_id=? AND hibernation_generation=?", identity) - conn.commit() - pending.append((checkpoint, row)) - except MemoryBackingBusyError: - continue - projects = [row[4] for _, row in pending if row is not None and row[5] != "deleted"] - self.quota.release_many(self.root, projects) - released = 0 - for checkpoint, before in pending: - ref = checkpoint.reference - identity = (ref.allocation_id, checkpoint.hibernation_generation) - try: - with self._mutation_lock(ref), self._allocation_lock(ref, exclusive=True): - path = self.root / ref.allocation_id / f"hibernate-{checkpoint.hibernation_generation}" - if os.path.lexists(path): - continue - with self._write_batches.transaction() as conn: - conn.execute("BEGIN IMMEDIATE") - current = conn.execute( - "SELECT manifest_sha256,allocated_bytes,device,inode,project_id,state " - "FROM retained_checkpoints WHERE allocation_id=? AND hibernation_generation=?", - identity, - ).fetchone() - if ((before is None and current is not None) - or (before is not None and (current is None or current[:5] != before[:5] - or current[5] not in {"retiring", "deleted"}))): - continue - if current is not None: - conn.execute("UPDATE retained_checkpoints SET state='deleted' " - "WHERE allocation_id=? AND hibernation_generation=?", identity) - conn.commit() - release_claim(checkpoint) - released += 1 - except MemoryBackingBusyError: - continue - return released - @staticmethod def _marker(lease: MemoryBackingLease): return { diff --git a/sandboxes/node_agent.py b/sandboxes/node_agent.py index c45f4096..69aac249 100644 --- a/sandboxes/node_agent.py +++ b/sandboxes/node_agent.py @@ -21,6 +21,7 @@ from .admission import ADMISSION_WAIT_HEADER, CREATE_ADMISSION_WAIT, parse_admission_wait from .agent import build_heartbeat +from .builder_agent import build_builder_node_agent_server as build_builder_node_agent_server from .build_context_store import ( BuildContextBlobStore, BuildContextHttpHandler, @@ -36,7 +37,6 @@ MANAGED_PRIMARY_CAPABILITY, STORAGE_NATIVE_CAPABILITY, SPLIT_CHECKPOINT_CAPABILITY, - REFLINK_MEMORY_RESTORE_CAPABILITY, HOST_EROFS_CAPABILITY, ENVIRONMENT_ROOT_CAPABILITY, ENVIRONMENT_RAFS_CAPABILITY, @@ -62,7 +62,6 @@ ) from .http_contract import UPLOAD_ACTIONS, match_sandbox_http_route from .images import ( - DEFAULT_MAX_ACTIVE_IMAGE_BUILDS, DockerImageRuntime, ImageBuildCapacityError, ImageBuildConflictError, @@ -92,7 +91,7 @@ from .admission_backend import NodedAdmission from .noded_client import NodedClient, NodedLink, noded_socket_path from .pause_handoff import MANAGED_GROWTH_CALLS, parse_escalation, parse_growth_events, parse_managed_growth_call -from .node_runtime import BuilderNodeRuntime, DirectNodeRuntime, NodeStateStore +from .node_runtime import DirectNodeRuntime from .registry import heartbeat_to_dict from .runtime_metrics import ( SingleFlightRuntimeMetricsSampler, @@ -399,7 +398,7 @@ def do_GET(self) -> None: } ) return - build_key = _image_build_key_from_path(parsed.path) + build_key = image_build_key_from_path(parsed.path) if build_key is not None: record = self.image_manager.get_build(build_key) if record is None: @@ -667,7 +666,8 @@ def _create_config(self) -> dict[str, Any]: if cached is None: config = create_config(self.manager.service, node_epoch=self.node_epoch, exec_sessions=self.exec_manager, - rust_admission_enabled=self.noded_link is not None) + rust_admission_enabled=self.noded_link is not None, + max_file_body_bytes=self.max_file_body_bytes) digest = hashlib.sha256(json.dumps(config, sort_keys=True, separators=(",", ":")).encode()).hexdigest() cached = type(self)._create_config_cache = dict(config, config_sha256=digest) return cached @@ -1015,7 +1015,7 @@ def _signal_managed_process(self, sandbox_id: str, job_id: str) -> None: self._write_json({"job": record.to_dict()}) def _park_sandbox(self, path: str) -> None: - sandbox_id = _sandbox_id_from_path(path, suffix="/park") + sandbox_id = sandbox_id_from_path(path, suffix="/park") try: raw = self._read_json_body() if not isinstance(raw, dict): @@ -1098,7 +1098,7 @@ def _request_snapshot_publication(self, path: str) -> None: generation = raw["generation"] if type(generation) is not int or generation <= 0: raise ValueError("publication generation must be a positive integer") - sandbox_id = _sandbox_id_from_path(path, suffix="/snapshot/publish") + sandbox_id = sandbox_id_from_path(path, suffix="/snapshot/publish") self.manager.service.request_storage_publication(sandbox_id, generation=generation) except (RuntimeError, ValueError) as exc: self._write_exception(exc) @@ -1173,7 +1173,7 @@ def _sandbox_inventory_entry( ) def _wake_sandbox(self, path: str) -> None: - sandbox_id = _sandbox_id_from_path(path, suffix="/wake") + sandbox_id = sandbox_id_from_path(path, suffix="/wake") try: raw = self._read_json_body() if not isinstance(raw, dict): @@ -1251,7 +1251,7 @@ def _wake_sandbox(self, path: str) -> None: ) def _prepare_migration(self, path: str) -> None: - sandbox_id = _sandbox_id_from_path(path, suffix="/migration/prepare") + sandbox_id = sandbox_id_from_path(path, suffix="/migration/prepare") try: raw = self._read_json_body() if not isinstance(raw, dict): @@ -1328,7 +1328,7 @@ def _abort_import(self, path: str) -> None: self._complete_migration_action(path, action="abort-import") def _evict_published_sandbox(self, path: str) -> None: - sandbox_id = _sandbox_id_from_path(path, suffix="/evict-published") + sandbox_id = sandbox_id_from_path(path, suffix="/evict-published") try: raw = self._read_json_body() if not isinstance(raw, dict): @@ -1357,7 +1357,7 @@ def _commit_export(self, path: str) -> None: raise CommitRefused("commit_export_unavailable", "commit export is not served here", status=HTTPStatus.NOT_FOUND) status, payload = self.commit_exports.request( - _sandbox_id_from_path(path, suffix="/commit-export"), self._read_json_body()) + sandbox_id_from_path(path, suffix="/commit-export"), self._read_json_body()) except CommitRefused as exc: self._write_json(exc.payload(), status=exc.status, headers={"Retry-After": "1"} if exc.retryable else None) @@ -1368,7 +1368,7 @@ def _commit_export(self, path: str) -> None: self._write_json(payload, status=status) def _publish_parked_sandbox(self, path: str) -> None: - sandbox_id = _sandbox_id_from_path(path, suffix="/publish-parked") + sandbox_id = sandbox_id_from_path(path, suffix="/publish-parked") try: raw = self._read_json_body() if not isinstance(raw, dict): @@ -1405,7 +1405,7 @@ def _publish_parked_sandbox(self, path: str) -> None: ) def _complete_migration_action(self, path: str, *, action: str) -> None: - sandbox_id = _sandbox_id_from_path(path, suffix=f"/migration/{action}") + sandbox_id = sandbox_id_from_path(path, suffix=f"/migration/{action}") try: raw = self._read_json_body() if not isinstance(raw, dict): @@ -1451,7 +1451,7 @@ def _direct_service(self) -> Any: return self.manager.service def _exec_session(self, path: str) -> None: - session_id = self._exec_session_id_from_path(path) + session_id = self.exec_session_id_from_path(path) session = self.exec_manager.get(session_id) if session is None: self._write_json( @@ -1461,7 +1461,7 @@ def _exec_session(self, path: str) -> None: self._write_json({"session": session.to_dict()}) def _exec_events(self, parsed: Any) -> None: - session_id = self._exec_session_id_from_path(parsed.path, suffix="/events") + session_id = self.exec_session_id_from_path(parsed.path, suffix="/events") query = parse_qs(parsed.query) after = _int_query(query, "after", 0) limit = _int_query(query, "limit", 100) @@ -1487,7 +1487,7 @@ def _exec_events(self, parsed: Any) -> None: ) def _write_exec_stdin(self, path: str) -> None: - session_id = self._exec_session_id_from_path(path, suffix="/stdin") + session_id = self.exec_session_id_from_path(path, suffix="/stdin") try: raw = self._read_json_body() if not isinstance(raw, dict): @@ -1502,7 +1502,7 @@ def _write_exec_stdin(self, path: str) -> None: self._write_json({"session": session.to_dict()}) def _close_exec_stdin(self, path: str) -> None: - session_id = self._exec_session_id_from_path(path, suffix="/close-stdin") + session_id = self.exec_session_id_from_path(path, suffix="/close-stdin") try: session = self.exec_manager.close_stdin(session_id) except ValueError as exc: @@ -1511,7 +1511,7 @@ def _close_exec_stdin(self, path: str) -> None: self._write_json({"session": session.to_dict()}) def _signal_exec(self, path: str) -> None: - session_id = self._exec_session_id_from_path(path, suffix="/signal") + session_id = self.exec_session_id_from_path(path, suffix="/signal") try: raw = self._read_json_body() if not isinstance(raw, dict) or set(raw) != {"signal"}: @@ -1550,7 +1550,7 @@ def _sandbox_ssh(self, path: str) -> None: def _upload_file(self, parsed: Any, *, archive: bool = False) -> None: """Write one file, or extract an archive's files below the path (directory).""" - sandbox_id = _sandbox_id_from_path(parsed.path, suffix="/archive" if archive else "/files") + sandbox_id = sandbox_id_from_path(parsed.path, suffix="/archive" if archive else "/files") container_path = _file_path_from_query(parsed) if container_path is None: self._write_json( @@ -1618,7 +1618,7 @@ def write(content: bytes, staged: Any = None) -> None: self._write_json(result) def _download_file(self, parsed: Any) -> None: - sandbox_id = _sandbox_id_from_path(parsed.path, suffix="/files") + sandbox_id = sandbox_id_from_path(parsed.path, suffix="/files") container_path = _file_path_from_query(parsed) if container_path is None: self._write_json( @@ -1890,7 +1890,7 @@ def _runtime_metrics_snapshot(self) -> NodeRuntimeMetrics | None: ), ) - def _exec_session_id_from_path(self, path: str, *, suffix: str = "") -> str: + def exec_session_id_from_path(self, path: str, *, suffix: str = "") -> str: prefix = "/v1/exec/" if suffix: return unquote(path[len(prefix) : -len(suffix)]) @@ -2095,110 +2095,6 @@ def server_close(self) -> None: super().server_close() -def build_builder_node_agent_server( - host: str, - port: int, - *, - state_file: Path, - image_file: Path, - job_id: str, - node_id: str, - node_url: str | None = None, - agent_version: str = "", - deployment_id: str, - init_version: str = "", - total_resources: ResourceQuantity | None = None, - image_runtime: DockerImageRuntime, - node_control_bearer_token: str, - runtime_metrics_provider: Callable[[], NodeRuntimeMetrics | None] | None = None, - max_json_body_bytes: int = DEFAULT_MAX_JSON_BODY_BYTES, - max_file_body_bytes: int = DEFAULT_MAX_FILE_BODY_BYTES, - max_active_image_builds: int = DEFAULT_MAX_ACTIVE_IMAGE_BUILDS, - max_finishing_image_builds: int = 0, - build_execution_timeout_seconds: float = 1800.0, - max_concurrent_image_pulls: int = 8, - physical_disk_path: Path | None = None, - build_context_store_dir: Path | None = None, - node_epoch: str | None = None, - telemetry: Telemetry | None = None, - environment_publisher: Callable[[Any], str] | None = None, - heartbeat: HeartbeatSenderConfig | None = None, -) -> NodeAgentHTTPServer: - token = node_control_bearer_token.strip() - if not token: - raise ValueError("node control bearer token cannot be empty") - if not deployment_id.strip(): - raise ValueError("deployment_id cannot be empty") - if ( - max_json_body_bytes < 1 - or max_file_body_bytes < 1 - or max_active_image_builds < 1 - or max_concurrent_image_pulls < 1 - ): - raise ValueError("node-agent request and build limits must be positive") - if type(max_finishing_image_builds) is not int or not 0 <= max_finishing_image_builds <= 2: - raise ValueError("max finishing image builds must be between 0 and 2") - resources = total_resources or ResourceQuantity() - if not resources.is_valid: - raise ValueError("total_resources cannot contain negative or non-finite values") - - resolved_telemetry = telemetry or Telemetry.disabled("ucloud-sandbox-builder") - runtime = BuilderNodeRuntime(NodeStateStore(state_file)) - image_manager = ImageManager( - ImageStore(image_file), - image_runtime, - max_active_builds=max_active_image_builds, - max_finishing_builds=max_finishing_image_builds, - build_execution_timeout_seconds=build_execution_timeout_seconds, - queue_builds=True, - # Atomically admit only execution capacity, including preparations. - # Excess demand stays at the gateway so another builder can take it; - # stale load samples from different gateway processes cannot queue it - # behind slow work here. The queue still handles brief cleanup handoff. - max_queued_builds=0, - max_concurrent_pulls=max_concurrent_image_pulls, - telemetry=resolved_telemetry, - environment_publisher=environment_publisher, - ) - context_store = BuildContextBlobStore( - build_context_store_dir or image_file.parent / f"{image_file.stem}-contexts", - max_blob_bytes=max_file_body_bytes, - max_total_bytes=DEFAULT_MAX_BUILD_CONTEXT_STORE_BYTES, - max_entries=DEFAULT_MAX_BUILD_CONTEXT_ENTRIES, - max_age_seconds=DEFAULT_MAX_BUILD_CONTEXT_AGE_SECONDS, - ) - - class BuilderHandler(NodeAgentHandler): - pass - - BuilderHandler.manager = runtime - BuilderHandler.exec_manager = None - BuilderHandler.image_manager = image_manager - BuilderHandler.build_context_store = context_store - BuilderHandler.job_id = job_id - BuilderHandler.node_id = node_id - BuilderHandler.node_url = node_url - BuilderHandler.agent_version = agent_version - BuilderHandler.deployment_id = deployment_id - BuilderHandler.init_version = init_version - BuilderHandler.total_resources = resources - BuilderHandler.capabilities = ("image-cache", "image-build", REQUEST_BODY_KEEPALIVE_CAPABILITY) - BuilderHandler.image_builds_enabled = True - BuilderHandler.sandboxes_enabled = False - BuilderHandler.node_epoch = _resolve_node_epoch(node_epoch) - BuilderHandler.physical_disk_path = physical_disk_path or image_file.parent - BuilderHandler.node_control_bearer_token = token - BuilderHandler.max_json_body_bytes = max_json_body_bytes - BuilderHandler.max_file_body_bytes = max_file_body_bytes - BuilderHandler.runtime_metrics_provider = staticmethod( - _host_runtime_metrics_sampler(runtime_metrics_provider) - ) - BuilderHandler.telemetry = resolved_telemetry - server = NodeAgentHTTPServer((host, port), BuilderHandler) - server.attach_heartbeats(heartbeat) - return server - - def build_direct_node_agent_server( host: str, port: int, @@ -2346,8 +2242,6 @@ class DirectBoundHandler(NodeAgentHandler): if (getattr(service.warden, "memory_backing", None) is not None and getattr(service.provisioner, "checkpoint_store", None) is not None): direct_capabilities.append(SPLIT_CHECKPOINT_CAPABILITY) - if getattr(service.warden.config, "reflink_memory_restore", False): - direct_capabilities.append(REFLINK_MEMORY_RESTORE_CAPABILITY) fingerprint = getattr(getattr(service.warden, "config", None), "runtime_fingerprint", None) if fingerprint is not None: direct_capabilities.append(RUNTIME_COMPATIBILITY_CAPABILITY_PREFIX + fingerprint.node_compatibility_sha256) @@ -2534,14 +2428,14 @@ def _elapsed_ms(started: float) -> int: return max(0, int((time.monotonic() - started) * 1000)) -def _sandbox_id_from_path(path: str, *, suffix: str = "") -> str: +def sandbox_id_from_path(path: str, *, suffix: str = "") -> str: prefix = "/v1/sandboxes/" if suffix: return unquote(path[len(prefix) : -len(suffix)]) return unquote(path[len(prefix) :]) -def _image_build_key_from_path(path: str) -> str | None: +def image_build_key_from_path(path: str) -> str | None: prefix = "/v1/images/builds/" if not path.startswith(prefix): return None @@ -2551,7 +2445,7 @@ def _image_build_key_from_path(path: str) -> str | None: def _image_build_cancel_id_from_path(path: str) -> str | None: """The build id of POST /v1/images/builds/:cancel, else None.""" - key = _image_build_key_from_path(path) + key = image_build_key_from_path(path) if key is None or not key.endswith(":cancel"): return None return key[: -len(":cancel")] or None diff --git a/sandboxes/placement_accounting.py b/sandboxes/placement_accounting.py index e2798fb4..92896b37 100644 --- a/sandboxes/placement_accounting.py +++ b/sandboxes/placement_accounting.py @@ -54,14 +54,14 @@ def routes_for(self, heartbeat: NodeHeartbeat) -> list[PlacementRecord]: return matches -def _node_available_resources( +def node_available_resources( heartbeat: NodeHeartbeat, routes: list[PlacementRecord], ) -> ResourceQuantity: - route_reservations = _node_reserved_route_resources(heartbeat, routes) + route_reservations = node_reserved_route_resources(heartbeat, routes) free = heartbeat.free_resources disk_mb = max(0, free.disk_mb - route_reservations.disk_mb) - if not _node_has_storage_device_capacity(heartbeat, routes): + if not node_has_storage_device_capacity(heartbeat, routes): disk_mb = 0 return ResourceQuantity( vcpu=max(0.0, free.vcpu - route_reservations.vcpu), @@ -70,7 +70,7 @@ def _node_available_resources( ) -def _node_has_storage_device_capacity( +def node_has_storage_device_capacity( heartbeat: NodeHeartbeat, routes: list[PlacementRecord], ) -> bool: @@ -83,12 +83,12 @@ def _node_has_storage_device_capacity( return True return ( metrics.storage_ublk_active_devices - + _node_reserved_storage_device_slots(heartbeat, routes) + + node_reserved_storage_device_slots(heartbeat, routes) < metrics.storage_ublk_max_devices ) -def _node_reserved_storage_device_slots( +def node_reserved_storage_device_slots( heartbeat: NodeHeartbeat, routes: list[PlacementRecord], ) -> int: @@ -101,9 +101,9 @@ def _node_reserved_storage_device_slots( seen: set[tuple[str, ...]] = set() reserved = 0 for route in routes: - if not _route_targets_node(route, heartbeat): + if not route_targets_node(route, heartbeat): continue - identity = _placement_identity(route) + identity = placement_identity(route) if identity in seen: continue seen.add(identity) @@ -135,7 +135,7 @@ def _node_reserved_storage_device_slots( return reserved -def _node_reserved_route_resources( +def node_reserved_route_resources( heartbeat: NodeHeartbeat, routes: list[PlacementRecord], ) -> ResourceQuantity: @@ -153,9 +153,9 @@ def _node_reserved_route_resources( item, ) for route in routes: - if not _route_targets_node(route, heartbeat): + if not route_targets_node(route, heartbeat): continue - identity = _placement_identity(route) + identity = placement_identity(route) if identity in seen_routes: continue seen_routes.add(identity) @@ -178,7 +178,7 @@ def _node_reserved_route_resources( and (matching_inventory.state or "unknown").lower() == "parked" ): storage_disk = ( - _route_workspace_claim_mb(route, heartbeat) + route_workspace_claim_mb(route, heartbeat) if route.storage_schema in SUPPORTED_STORAGE_NATIVE_MIGRATION_SCHEMAS and bool(route.snapshot_manifest_digest) @@ -199,7 +199,7 @@ def _node_reserved_route_resources( ): continue resources = resources + replace( - route.resources, disk_mb=_route_initial_claim_mb(route, heartbeat) + route.resources, disk_mb=route_initial_claim_mb(route, heartbeat) ) return resources @@ -218,7 +218,7 @@ def _dynamic_split_spec(route, heartbeat) -> tuple[int, int] | None: return disk_mb, memory_mb -def _route_initial_claim_mb(route, heartbeat) -> int: +def route_initial_claim_mb(route, heartbeat) -> int: """What a create not yet in the heartbeat will charge the worker registry. A node that advertises dynamic claims (docs/architecture.md) charges a new @@ -236,13 +236,13 @@ def _route_initial_claim_mb(route, heartbeat) -> int: return min(full, workspace + memory) -def _route_workspace_claim_mb(route, heartbeat) -> int: +def route_workspace_claim_mb(route, heartbeat) -> int: """A woken published workspace: at most its ceiling, never the full claim.""" split = _dynamic_split_spec(route, heartbeat) return route.resources.disk_mb if split is None else min(route.resources.disk_mb, split[0]) -def _placement_route_index(routes: list[PlacementRecord]) -> PlacementRouteIndex: +def placement_route_index(routes: list[PlacementRecord]) -> PlacementRouteIndex: by_node_id: dict[str, list[PlacementRecord]] = {} by_job_id: dict[str, list[PlacementRecord]] = {} by_node_url: dict[str, list[PlacementRecord]] = {} @@ -260,7 +260,7 @@ def _placement_route_index(routes: list[PlacementRecord]) -> PlacementRouteIndex ) -def _route_targets_node(route: PlacementRecord, heartbeat: NodeHeartbeat) -> bool: +def route_targets_node(route: PlacementRecord, heartbeat: NodeHeartbeat) -> bool: return bool( (route.node_id and route.node_id == heartbeat.node_id) or (route.job_id and route.job_id == heartbeat.job_id) @@ -272,7 +272,7 @@ def _route_targets_node(route: PlacementRecord, heartbeat: NodeHeartbeat) -> boo ) -def _placement_identity(route: PlacementRecord) -> tuple[str, ...]: +def placement_identity(route: PlacementRecord) -> tuple[str, ...]: if isinstance(route, SandboxRoute): return ( "sandbox", diff --git a/sandboxes/placement_choice.py b/sandboxes/placement_choice.py index 3e446580..0ec81d58 100644 --- a/sandboxes/placement_choice.py +++ b/sandboxes/placement_choice.py @@ -30,8 +30,8 @@ from .models import NodeHeartbeat, ResourceQuantity, is_soft_drained from .placement_accounting import ( PlacementRecord, PlacementReservation, PlacementRouteIndex, - _node_available_resources, _node_has_storage_device_capacity, _placement_route_index, - _route_initial_claim_mb, + node_available_resources, node_has_storage_device_capacity, placement_route_index, + route_initial_claim_mb, ) from .resource_admission import node_accepts_dynamic_request, node_pressure_score @@ -62,7 +62,7 @@ class FleetView: migrations) that their heartbeats do not show yet.""" nodes: tuple[NodeHeartbeat, ...] - routes: PlacementRouteIndex = field(default_factory=lambda: _placement_route_index([])) + routes: PlacementRouteIndex = field(default_factory=lambda: placement_route_index([])) @classmethod def ready( @@ -74,7 +74,7 @@ def ready( if heartbeat.node_url and not heartbeat.draining and heartbeat.admission_open and has_capability(heartbeat.capabilities, "sandbox") and heartbeat.is_fresh(now, ttl_seconds) - ), _placement_route_index(list(routes))) + ), placement_route_index(list(routes))) @dataclass(frozen=True) @@ -101,8 +101,8 @@ def node_fits( """The reservation-time fit: each record charges hard disk and a storage device until the heartbeat shows it. CPU is only a ranking signal.""" - return _node_has_storage_device_capacity(heartbeat, records) and node_accepts_dynamic_request( - heartbeat, requested, _node_available_resources(heartbeat, records), check_cpu=False, + return node_has_storage_device_capacity(heartbeat, records) and node_accepts_dynamic_request( + heartbeat, requested, node_available_resources(heartbeat, records), check_cpu=False, ) @@ -116,7 +116,7 @@ def initial_charge(heartbeat: NodeHeartbeat, request: PlacementRequest) -> Resou claim that placement_accounting charges an unobserved route.""" claim = _Claim(request.resources, request.spec) - return replace(request.resources, disk_mb=_route_initial_claim_mb(claim, heartbeat)) + return replace(request.resources, disk_mb=route_initial_claim_mb(claim, heartbeat)) def fit_count( diff --git a/sandboxes/policy.py b/sandboxes/policy.py index b222d56d..7317f88a 100644 --- a/sandboxes/policy.py +++ b/sandboxes/policy.py @@ -32,59 +32,88 @@ ) -def evaluate_scale( +@dataclass(frozen=True) +class _PoolSnapshot: + pool_nodes: tuple[SandboxNode, ...] + capacity_nodes: tuple[SandboxNode, ...] + ready_nodes: tuple[SandboxNode, ...] + provisioning_nodes: tuple[SandboxNode, ...] + unreachable_nodes: tuple[SandboxNode, ...] + unreachable_stop_candidates: tuple[SandboxNode, ...] + retiring_candidates: tuple[SandboxNode, ...] + total_nodes: int + available_pool_nodes: int + oldest_pending_seconds: int + effective_scale_down_idle_seconds: int + effective_policy: ScalePolicy + + +@dataclass(frozen=True) +class _DemandForecast: + placement_requests: tuple[SandboxPlacementRequest, ...] + unschedulable_placements: int + desired_resources: ResourceQuantity + forecast_node_memory: int + pressure_scale_up: bool + backlog_scale_up: bool + create_pressure_scale_up: bool + pending_backlog_nodes: int + + +@dataclass(frozen=True) +class _CapacityAssessment: + projected_free_resources: ResourceQuantity + resource_deficit: ResourceQuantity + placement_nodes: int + soft_drain: SoftDrainPlan + soft_drain_released: bool + + +def _classify_pool( nodes: list[SandboxNode], demand: SandboxDemand, policy: ScalePolicy, - *, - now: datetime | None = None, - live_signals: LiveScaleSignals | None = None, -) -> ScaleDecision: - if now is None: - now = utc_now() + now: datetime, + live_signals: LiveScaleSignals | None, +) -> _PoolSnapshot: stop_budget = max(0, policy.max_stop_per_cycle) - unreachable_stop_candidates = _unreachable_stop_candidates( - nodes, - policy, - now=now, - )[:stop_budget] + unreachable_stop_candidates = tuple( + _unreachable_stop_candidates(nodes, policy, now=now)[:stop_budget] + ) unreachable_job_ids = {node.job_id for node in unreachable_stop_candidates} - retiring_candidates = retiring_stop_candidates( - [node for node in nodes if node.job_id not in unreachable_job_ids], - now=now, - max_cpu_check_ms=policy.max_cpu_check_ms, - )[: max(0, stop_budget - len(unreachable_stop_candidates))] - pool_nodes = [node for node in nodes if _counts_as_pool_node(node, policy, now, 0)] - capacity_nodes = [ + retiring_candidates = tuple( + retiring_stop_candidates( + [node for node in nodes if node.job_id not in unreachable_job_ids], + now=now, + max_cpu_check_ms=policy.max_cpu_check_ms, + )[: max(0, stop_budget - len(unreachable_stop_candidates))] + ) + pool_nodes = tuple( + node for node in nodes if _counts_as_pool_node(node, policy, now, 0) + ) + capacity_nodes = tuple( node for node in pool_nodes # A retiring host (repeated reboots, a slow VM) keeps serving what it # holds while it retires; demand is planned without it. - if not retiring_reason(node.heartbeat, now, max_cpu_check_ms=policy.max_cpu_check_ms) - ] - ready_nodes = [node for node in capacity_nodes if node.is_schedulable] - + if not retiring_reason( + node.heartbeat, now, max_cpu_check_ms=policy.max_cpu_check_ms + ) + ) + ready_nodes = tuple(node for node in capacity_nodes if node.is_schedulable) oldest_pending_seconds = max(0, demand.oldest_pending_seconds) - provisioning_nodes = [ + provisioning_nodes = tuple( node for node in pool_nodes if _counts_as_active_provisioning( - node, - policy, - now, - oldest_pending_seconds, + node, policy, now, oldest_pending_seconds ) - ] - unreachable_nodes = [ + ) + unreachable_nodes = tuple( node for node in pool_nodes - if _counts_as_unreachable( - node, - policy, - now, - oldest_pending_seconds, - ) - ] + if _counts_as_unreachable(node, policy, now, oldest_pending_seconds) + ) total_nodes = len(pool_nodes) # A RUNNING provider job with an expired worker heartbeat is billable but # not useful capacity. Keep it in total_nodes for accounting and eventual @@ -109,16 +138,39 @@ def evaluate_scale( policy, scale_down_idle_seconds=effective_scale_down_idle_seconds, ) + return _PoolSnapshot( + pool_nodes=pool_nodes, + capacity_nodes=capacity_nodes, + ready_nodes=ready_nodes, + provisioning_nodes=provisioning_nodes, + unreachable_nodes=unreachable_nodes, + unreachable_stop_candidates=unreachable_stop_candidates, + retiring_candidates=retiring_candidates, + total_nodes=total_nodes, + available_pool_nodes=available_pool_nodes, + oldest_pending_seconds=oldest_pending_seconds, + effective_scale_down_idle_seconds=effective_scale_down_idle_seconds, + effective_policy=effective_policy, + ) + + +def _forecast_demand( + nodes: list[SandboxNode], + pool: _PoolSnapshot, + demand: SandboxDemand, + policy: ScalePolicy, + now: datetime, + live_signals: LiveScaleSignals | None, +) -> _DemandForecast: + ready_list = list(pool.ready_nodes) pressure_scale_up = _live_pressure_requires_capacity( - policy, - live_signals, - ) and not any(node.is_idle for node in ready_nodes) + policy, live_signals + ) and not any(node.is_idle for node in pool.ready_nodes) backlog_scale_up = _startup_backlog_requires_capacity( - policy, demand, ready_nodes, live_signals + policy, demand, ready_list, live_signals ) create_pressure_scale_up = backlog_scale_up or _create_pressure_requires_capacity( - policy, - live_signals, + policy, live_signals ) pending_backlog_nodes = ( _ceil_div( @@ -165,56 +217,100 @@ def evaluate_scale( # A pending cold start is future resident demand, not a permanent charge # for its sandbox limit. Once assigned, its transient worker reservation # replaces this promise; once running, measured working memory replaces it. - pending_resources = replace(pending_resources, memory_mb=( - _cold_memory_forecast(demand.placement_requests, maximum_request, policy) - if demand.placement_requests else math.ceil( - pending_resources.memory_mb / policy.target_memory_utilization))) - prepared_resources = replace(prepared_resources, memory_mb= - _cold_memory_forecast(demand.prepared_placement_requests, maximum_request, policy)) - resident_forecast = sum(_resident_memory_forecast(node, policy, now) for node in ready_nodes) + pending_resources = replace( + pending_resources, + memory_mb=( + _cold_memory_forecast(demand.placement_requests, maximum_request, policy) + if demand.placement_requests + else math.ceil( + pending_resources.memory_mb / policy.target_memory_utilization + ) + ), + ) + prepared_resources = replace( + prepared_resources, + memory_mb=_cold_memory_forecast( + demand.prepared_placement_requests, maximum_request, policy + ), + ) + resident_forecast = sum( + _resident_memory_forecast(node, policy, now) for node in pool.ready_nodes + ) demand_resources = _add_resources(pending_resources, prepared_resources) - demand_resources = replace(demand_resources, - memory_mb=demand_resources.memory_mb + resident_forecast) + demand_resources = replace( + demand_resources, + memory_mb=demand_resources.memory_mb + resident_forecast, + ) forecast_node_memory = _forecast_node_memory(nodes, policy) desired_resources = _add_resources(demand_resources, policy.warm_resources) + return _DemandForecast( + placement_requests=placement_requests, + unschedulable_placements=unschedulable_placements, + desired_resources=desired_resources, + forecast_node_memory=forecast_node_memory, + pressure_scale_up=pressure_scale_up, + backlog_scale_up=backlog_scale_up, + create_pressure_scale_up=create_pressure_scale_up, + pending_backlog_nodes=pending_backlog_nodes, + ) + + +def _assess_capacity_and_soft_drain( + nodes: list[SandboxNode], + pool: _PoolSnapshot, + forecast: _DemandForecast, + demand: SandboxDemand, + policy: ScalePolicy, + now: datetime, +) -> _CapacityAssessment: soft_drain = plan_soft_drain( nodes, policy, now, - required_resources=desired_resources, - placement_requests=placement_requests, - oldest_pending_seconds=oldest_pending_seconds, + required_resources=forecast.desired_resources, + placement_requests=forecast.placement_requests, + oldest_pending_seconds=pool.oldest_pending_seconds, pending_count=demand.pending_count, allow_select=False, ) - def scale_up_capacity(withheld: str): + def scale_up_capacity( + withheld: str, + ) -> tuple[ResourceQuantity, ResourceQuantity, int]: # Creates avoid a soft-drained worker, so its capacity must not # hide demand from scale-up either. - scale_nodes = [node for node in capacity_nodes if node.job_id != withheld] + scale_nodes = [ + node for node in pool.capacity_nodes if node.job_id != withheld + ] projected = _projected_free_resources( - scale_nodes, - policy, - now, - oldest_pending_seconds, + scale_nodes, policy, now, pool.oldest_pending_seconds ) - return projected, _subtract_resources(desired_resources, projected), ( + return ( + projected, + _subtract_resources(forecast.desired_resources, projected), _nodes_for_unplaced_requests( scale_nodes, - placement_requests, + forecast.placement_requests, policy, now=now, - oldest_pending_seconds=oldest_pending_seconds, - ) + oldest_pending_seconds=pool.oldest_pending_seconds, + ), ) - projected_free_resources, resource_deficit, placement_nodes = ( - scale_up_capacity(soft_drain.job_id) + projected_free_resources, resource_deficit, placement_nodes = scale_up_capacity( + soft_drain.job_id ) soft_drain_released = False - if soft_drain.job_id and not soft_drain.retiring and ( - placement_nodes > 0 - or (_has_resources(desired_resources) and _has_resources(resource_deficit)) + if ( + soft_drain.job_id + and not soft_drain.retiring + and ( + placement_nodes > 0 + or ( + _has_resources(forecast.desired_resources) + and _has_resources(resource_deficit) + ) + ) ): # Reopening the drained worker is cheaper than buying a new one. soft_drain_released = True @@ -225,186 +321,204 @@ def scale_up_capacity(withheld: str): projected_free_resources, resource_deficit, placement_nodes = ( scale_up_capacity("") ) - reasons: list[str] = [] - actions: list[ScaleAction] = [] - - if unschedulable_placements > 0: - reasons.append( - f"{unschedulable_placements} placement request(s) exceed the " - "configured schedulable node shape and were excluded from create demand" - ) + return _CapacityAssessment( + projected_free_resources=projected_free_resources, + resource_deficit=resource_deficit, + placement_nodes=placement_nodes, + soft_drain=soft_drain, + soft_drain_released=soft_drain_released, + ) - if demand.suppressed_pending_count > 0: - reasons.append( - f"{demand.suppressed_pending_count} non-capacity pending failure(s) " - "excluded from fleet demand" - ) - if unreachable_stop_candidates: - job_ids = tuple(node.job_id for node in unreachable_stop_candidates) +def _plan_mandatory_stops( + pool: _PoolSnapshot, + actions: list[ScaleAction], + reasons: list[str], +) -> None: + if pool.unreachable_stop_candidates: + job_ids = tuple(node.job_id for node in pool.unreachable_stop_candidates) reason = "unreachable empty sandbox node(s) exceeded the eviction lease" actions.append( ScaleAction( - kind="stop", - count=len(job_ids), - job_ids=job_ids, - reason=reason, + kind="stop", count=len(job_ids), job_ids=job_ids, reason=reason ) ) reasons.append(reason) - - if retiring_candidates: - job_ids = tuple(node.job_id for node in retiring_candidates) + if pool.retiring_candidates: + job_ids = tuple(node.job_id for node in pool.retiring_candidates) reason = "idle sandbox node(s) are retiring (repeated reboots or slow CPU)" actions.append( ScaleAction( - kind="stop", - count=len(job_ids), - job_ids=job_ids, - reason=reason, + kind="stop", count=len(job_ids), job_ids=job_ids, reason=reason ) ) reasons.append(reason) - if available_pool_nodes < policy.min_nodes: - missing_nodes = policy.min_nodes - available_pool_nodes - create_count = min( - missing_nodes, - _create_budget( - policy, - available_pool_nodes, - len(provisioning_nodes), - actions, - ), - ) - if create_count > 0: - reason = f"below min_nodes={policy.min_nodes}" - actions.append( - ScaleAction(kind="create", count=create_count, reason=reason) - ) - reasons.append(reason) - else: - reason = _create_limit_reason( - policy, - available_pool_nodes, - len(provisioning_nodes), - actions, - ) - if reason: - reasons.append(f"cannot satisfy min_nodes={policy.min_nodes}: {reason}") - if placement_nodes > 0 or ( - _has_resources(desired_resources) and _has_resources(resource_deficit) - ): - deficit_nodes = ( - _nodes_for_resource_deficit(resource_deficit, policy, memory_capacity_mb=forecast_node_memory) - if _has_resources(resource_deficit) - else 0 - ) - # A node already planned to restore ``min_nodes`` contributes the same - # default schedulable shape as a resource-deficit create. Count it - # once; otherwise loss of the final node produces one replacement for - # the minimum and a second replacement for the exact same demand. - needed_nodes = max( - 0, - max(deficit_nodes, placement_nodes) - _planned_creates(actions), +def _plan_min_nodes_create( + pool: _PoolSnapshot, + policy: ScalePolicy, + actions: list[ScaleAction], + reasons: list[str], +) -> None: + if pool.available_pool_nodes >= policy.min_nodes: + return + missing_nodes = policy.min_nodes - pool.available_pool_nodes + create_count = min( + missing_nodes, + _create_budget( + policy, pool.available_pool_nodes, len(pool.provisioning_nodes), actions + ), + ) + if create_count > 0: + reason = f"below min_nodes={policy.min_nodes}" + actions.append(ScaleAction(kind="create", count=create_count, reason=reason)) + reasons.append(reason) + return + reason = _create_limit_reason( + policy, pool.available_pool_nodes, len(pool.provisioning_nodes), actions + ) + if reason: + reasons.append(f"cannot satisfy min_nodes={policy.min_nodes}: {reason}") + + +def _plan_deficit_create( + pool: _PoolSnapshot, + forecast: _DemandForecast, + capacity: _CapacityAssessment, + policy: ScalePolicy, + actions: list[ScaleAction], + reasons: list[str], +) -> None: + if not ( + capacity.placement_nodes > 0 + or ( + _has_resources(forecast.desired_resources) + and _has_resources(capacity.resource_deficit) ) - create_count = min( - needed_nodes, - _create_budget( - policy, - available_pool_nodes, - len(provisioning_nodes), - actions, - ), + ): + return + deficit_nodes = ( + _nodes_for_resource_deficit( + capacity.resource_deficit, + policy, + memory_capacity_mb=forecast.forecast_node_memory, ) - if create_count > 0: - if placement_nodes > deficit_nodes: - reason = ( - f"{placement_nodes} additional node(s) required because " - "pending sandbox shapes do not fit any single projected node" - ) - else: - reason = ( - "projected free resources " - f"{_resource_label(projected_free_resources)} below desired " - f"{_resource_label(desired_resources)}" - ) - actions.append( - ScaleAction(kind="create", count=create_count, reason=reason) + if _has_resources(capacity.resource_deficit) + else 0 + ) + # A node already planned to restore ``min_nodes`` contributes the same + # default schedulable shape as a resource-deficit create. Count it + # once; otherwise loss of the final node produces one replacement for + # the minimum and a second replacement for the exact same demand. + needed_nodes = max( + 0, max(deficit_nodes, capacity.placement_nodes) - _planned_creates(actions) + ) + create_count = min( + needed_nodes, + _create_budget( + policy, pool.available_pool_nodes, len(pool.provisioning_nodes), actions + ), + ) + if create_count > 0: + if capacity.placement_nodes > deficit_nodes: + reason = ( + f"{capacity.placement_nodes} additional node(s) required because " + "pending sandbox shapes do not fit any single projected node" ) - reasons.append(reason) else: - reason = _create_limit_reason( - policy, - available_pool_nodes, - len(provisioning_nodes), - actions, + reason = ( + "projected free resources " + f"{_resource_label(capacity.projected_free_resources)} below desired " + f"{_resource_label(forecast.desired_resources)}" ) - if reason: - reasons.append( - "cannot create for resource deficit " - f"{_resource_label(resource_deficit)}: {reason}" - ) + actions.append(ScaleAction(kind="create", count=create_count, reason=reason)) + reasons.append(reason) + return + reason = _create_limit_reason( + policy, pool.available_pool_nodes, len(pool.provisioning_nodes), actions + ) + if reason: + reasons.append( + "cannot create for resource deficit " + f"{_resource_label(capacity.resource_deficit)}: {reason}" + ) + - if pending_backlog_nodes > 0: +def _plan_pressure_creates( + pool: _PoolSnapshot, + forecast: _DemandForecast, + demand: SandboxDemand, + policy: ScalePolicy, + live_signals: LiveScaleSignals | None, + actions: list[ScaleAction], + reasons: list[str], +) -> None: + if forecast.pending_backlog_nodes > 0: # Pending create/wake rows are requests that the current fleet already # failed to admit. Nominal CPU and RAM limits remain reusable; only a # simultaneous real-pressure signal turns the retry backlog into # additional pipeline capacity. target_nodes = min( policy.max_nodes, - available_pool_nodes + pending_backlog_nodes, + pool.available_pool_nodes + forecast.pending_backlog_nodes, ) needed_nodes = max( 0, - target_nodes - available_pool_nodes - _planned_creates(actions), + target_nodes - pool.available_pool_nodes - _planned_creates(actions), ) create_count = min( needed_nodes, _create_budget( policy, - available_pool_nodes, - len(provisioning_nodes), + pool.available_pool_nodes, + len(pool.provisioning_nodes), actions, ), ) if create_count > 0: reason = ( f"{demand.pending_count} pressure-confirmed pending request(s) " - f"require {pending_backlog_nodes} additional create pipeline " + f"require {forecast.pending_backlog_nodes} additional create pipeline " f"node(s); targeting {target_nodes} node(s)" ) actions.append( ScaleAction(kind="create", count=create_count, reason=reason) ) reasons.append(reason) - elif target_nodes > available_pool_nodes + _planned_creates(actions): + elif target_nodes > pool.available_pool_nodes + _planned_creates(actions): reason = _create_limit_reason( policy, - available_pool_nodes, - len(provisioning_nodes), + pool.available_pool_nodes, + len(pool.provisioning_nodes), actions, ) if reason: reasons.append("cannot create for pending request backlog: " + reason) if ( - pressure_scale_up + forecast.pressure_scale_up # Create saturation is a more specific interpretation of this same # live-pressure sample and owns its rejection-wave calculation below. # Letting the generic branch act first would undercount a sustained # gateway backlog on every later cycle. - and not create_pressure_scale_up - and ready_nodes + and not forecast.create_pressure_scale_up + and pool.ready_nodes ): - pressure_target = min(policy.max_nodes, len(ready_nodes) + policy.max_create_per_cycle) + pressure_target = min( + policy.max_nodes, len(pool.ready_nodes) + policy.max_create_per_cycle + ) create_count = min( - max(0, pressure_target - available_pool_nodes - _planned_creates(actions)), + max( + 0, + pressure_target + - pool.available_pool_nodes + - _planned_creates(actions), + ), _create_budget( policy, - available_pool_nodes, - len(provisioning_nodes), + pool.available_pool_nodes, + len(pool.provisioning_nodes), actions, ), ) @@ -416,193 +530,264 @@ def scale_up_capacity(withheld: str): reasons.append(reason) else: reason = _create_limit_reason( - policy, available_pool_nodes, len(provisioning_nodes), actions + policy, + pool.available_pool_nodes, + len(pool.provisioning_nodes), + actions, ) if reason: reasons.append("cannot create for live pressure: " + reason) - if create_pressure_scale_up and not any(node.is_idle for node in ready_nodes): - assert live_signals is not None - baseline_nodes = max(len(ready_nodes), policy.min_nodes) - if _has_resources(desired_resources): - baseline_nodes = max( - baseline_nodes, - _nodes_for_resource_deficit(desired_resources, policy, memory_capacity_mb=forecast_node_memory), - ) - elif available_pool_nodes > 0: - baseline_nodes = max(baseline_nodes, 1) - pipeline_nodes = _ceil_div( - max(1, live_signals.sandbox_create_limit), - max(1, policy.create_target_concurrency_per_node), + if forecast.create_pressure_scale_up and not any( + node.is_idle for node in pool.ready_nodes + ): + _plan_create_pipeline_headroom( + pool, forecast, demand, policy, live_signals, actions, reasons ) - if backlog_scale_up: - pipeline_nodes = max( - pipeline_nodes, - len(ready_nodes) - + _ceil_div( - demand.pending_count, - max(1, policy.create_target_concurrency_per_node), - ), - ) - # Saturation on an already larger fleet still warrants its configured - # headroom; an absolute pipeline count must not suppress live pressure. - pipeline_nodes = max(pipeline_nodes, baseline_nodes + min( - policy.max_create_per_cycle, policy.create_pressure_max_headroom_nodes)) - target_nodes = min( - policy.max_nodes, - max( - baseline_nodes, - min( - pipeline_nodes, - baseline_nodes + max(0, policy.create_pressure_max_headroom_nodes), - ), + + +def _plan_create_pipeline_headroom( + pool: _PoolSnapshot, + forecast: _DemandForecast, + demand: SandboxDemand, + policy: ScalePolicy, + live_signals: LiveScaleSignals | None, + actions: list[ScaleAction], + reasons: list[str], +) -> None: + assert live_signals is not None + baseline_nodes = max(len(pool.ready_nodes), policy.min_nodes) + if _has_resources(forecast.desired_resources): + baseline_nodes = max( + baseline_nodes, + _nodes_for_resource_deficit( + forecast.desired_resources, + policy, + memory_capacity_mb=forecast.forecast_node_memory, ), ) - needed_nodes = max( - 0, - target_nodes - available_pool_nodes - _planned_creates(actions), - ) - create_count = min( - needed_nodes, - _create_budget( - policy, - available_pool_nodes, - len(provisioning_nodes), - actions, + elif pool.available_pool_nodes > 0: + baseline_nodes = max(baseline_nodes, 1) + pipeline_nodes = _ceil_div( + max(1, live_signals.sandbox_create_limit), + max(1, policy.create_target_concurrency_per_node), + ) + if forecast.backlog_scale_up: + pipeline_nodes = max( + pipeline_nodes, + len(pool.ready_nodes) + + _ceil_div( + demand.pending_count, + max(1, policy.create_target_concurrency_per_node), ), ) - if create_count > 0: - reason = ( - ( - f"{demand.pending_count} capacity request(s) queued for " - f"{demand.oldest_capacity_pending_seconds}s; targeting " - f"{target_nodes} temporary startup node(s)" - ) - if backlog_scale_up - else ( - "sandbox create pipeline saturated at " - f"{live_signals.sandbox_create_limit} concurrent request(s); " - f"targeting {target_nodes} temporary node(s) after " - f"{live_signals.sandbox_create_rejections} recent rejection(s)" - ) + # Saturation on an already larger fleet still warrants its configured + # headroom; an absolute pipeline count must not suppress live pressure. + pipeline_nodes = max( + pipeline_nodes, + baseline_nodes + + min(policy.max_create_per_cycle, policy.create_pressure_max_headroom_nodes), + ) + target_nodes = min( + policy.max_nodes, + max( + baseline_nodes, + min( + pipeline_nodes, + baseline_nodes + max(0, policy.create_pressure_max_headroom_nodes), + ), + ), + ) + needed_nodes = max( + 0, + target_nodes - pool.available_pool_nodes - _planned_creates(actions), + ) + create_count = min( + needed_nodes, + _create_budget( + policy, pool.available_pool_nodes, len(pool.provisioning_nodes), actions + ), + ) + if create_count > 0: + reason = ( + ( + f"{demand.pending_count} capacity request(s) queued for " + f"{demand.oldest_capacity_pending_seconds}s; targeting " + f"{target_nodes} temporary startup node(s)" ) - actions.append( - ScaleAction(kind="create", count=create_count, reason=reason) + if forecast.backlog_scale_up + else ( + "sandbox create pipeline saturated at " + f"{live_signals.sandbox_create_limit} concurrent request(s); " + f"targeting {target_nodes} temporary node(s) after " + f"{live_signals.sandbox_create_rejections} recent rejection(s)" ) - reasons.append(reason) - elif target_nodes > available_pool_nodes + _planned_creates(actions): - reason = _create_limit_reason( + ) + actions.append(ScaleAction(kind="create", count=create_count, reason=reason)) + reasons.append(reason) + elif target_nodes > pool.available_pool_nodes + _planned_creates(actions): + reason = _create_limit_reason( + policy, pool.available_pool_nodes, len(pool.provisioning_nodes), actions + ) + if reason: + reasons.append( + "cannot create temporary sandbox-create headroom: " + reason + ) + + +def _plan_scale_down_and_soft_drain( + nodes: list[SandboxNode], + pool: _PoolSnapshot, + forecast: _DemandForecast, + capacity: _CapacityAssessment, + demand: SandboxDemand, + policy: ScalePolicy, + now: datetime, + live_signals: LiveScaleSignals | None, + actions: list[ScaleAction], + reasons: list[str], +) -> SoftDrainPlan: + soft_drain = capacity.soft_drain + if ( + _planned_creates(actions) != 0 + or _has_resources(capacity.resource_deficit) + or capacity.placement_nodes != 0 + ): + return soft_drain + excess_nodes = pool.total_nodes - policy.min_nodes + stop_budget = max(0, policy.max_stop_per_cycle - planned_stops(actions)) + latest_capacity_pressure_age = _latest_capacity_pressure_age(policy, live_signals) + pressure_cooldown = bool( + (policy.live_pressure_enabled or policy.create_pressure_enabled) + and live_signals is not None + and latest_capacity_pressure_age is not None + and latest_capacity_pressure_age < policy.pressure_scale_down_cooldown_seconds + ) + if pressure_cooldown: + reasons.append("recent live pressure retains ready capacity during cooldown") + elif excess_nodes > 0 and stop_budget > 0: + ready_list = list(pool.ready_nodes) + stop_candidates = _stop_candidates( + ready_list, + pool.effective_policy, + now, + required_resources=forecast.desired_resources, + max_count=min(excess_nodes, stop_budget), + placement_nodes=list(pool.capacity_nodes), + placement_requests=forecast.placement_requests, + oldest_pending_seconds=pool.oldest_pending_seconds, + ) + if stop_candidates: + job_ids = tuple(node.job_id for node in stop_candidates) + reason = _stop_reason( + ready_list, policy, - available_pool_nodes, - len(provisioning_nodes), - actions, + required_resources=forecast.desired_resources, + job_ids=job_ids, ) - if reason: - reasons.append( - "cannot create temporary sandbox-create headroom: " + reason + actions.append( + ScaleAction( + kind="stop", count=len(job_ids), job_ids=job_ids, reason=reason ) - - planned_creates = _planned_creates(actions) + ) + reasons.append(reason) + # A busy worker is surplus by memory claims long before it is surplus + # for create throughput. Consolidating it in a rollout step's tail left + # the next step one worker short until a new one provisioned, so new + # creates hold selection off for the same idle time that stops wait. + recent_creates = bool( + live_signals is not None + and live_signals.latest_schedule_age_seconds is not None + and live_signals.latest_schedule_age_seconds + < pool.effective_policy.scale_down_idle_seconds + ) if ( - planned_creates == 0 - and not _has_resources(resource_deficit) - and placement_nodes == 0 + not pressure_cooldown + and not recent_creates + and not soft_drain.job_id + and not capacity.soft_drain_released ): - excess_nodes = total_nodes - policy.min_nodes - stop_budget = max(0, policy.max_stop_per_cycle - planned_stops(actions)) - latest_capacity_pressure_age = _latest_capacity_pressure_age( + selected = plan_soft_drain( + nodes, policy, - live_signals, + now, + required_resources=forecast.desired_resources, + placement_requests=forecast.placement_requests, + oldest_pending_seconds=pool.oldest_pending_seconds, + pending_count=demand.pending_count, + excluded_job_ids=_planned_stop_job_ids(actions), ) - pressure_cooldown = bool( - (policy.live_pressure_enabled or policy.create_pressure_enabled) - and live_signals is not None - and latest_capacity_pressure_age is not None - and latest_capacity_pressure_age - < policy.pressure_scale_down_cooldown_seconds + soft_drain = replace( + selected, + clear_job_ids=tuple( + dict.fromkeys((*soft_drain.clear_job_ids, *selected.clear_job_ids)) + ), ) - if pressure_cooldown: - reasons.append( - "recent live pressure retains ready capacity during cooldown" - ) - elif excess_nodes > 0 and stop_budget > 0: - stop_candidates = _stop_candidates( - ready_nodes, - effective_policy, - now, - required_resources=desired_resources, - max_count=min(excess_nodes, stop_budget), - placement_nodes=capacity_nodes, - placement_requests=placement_requests, - oldest_pending_seconds=oldest_pending_seconds, - ) - if stop_candidates: - job_ids = tuple(node.job_id for node in stop_candidates) - reason = _stop_reason( - ready_nodes, - policy, - required_resources=desired_resources, - job_ids=job_ids, - ) - actions.append( - ScaleAction( - kind="stop", - count=len(job_ids), - job_ids=job_ids, - reason=reason, - ) - ) - reasons.append(reason) - # A busy worker is surplus by memory claims long before it is surplus - # for create throughput. Consolidating it in a rollout step's tail left - # the next step one worker short until a new one provisioned, so new - # creates hold selection off for the same idle time that stops wait. - recent_creates = bool( - live_signals is not None and live_signals.latest_schedule_age_seconds is not None - and live_signals.latest_schedule_age_seconds < effective_policy.scale_down_idle_seconds + return soft_drain + + +def evaluate_scale( + nodes: list[SandboxNode], + demand: SandboxDemand, + policy: ScalePolicy, + *, + now: datetime | None = None, + live_signals: LiveScaleSignals | None = None, +) -> ScaleDecision: + if now is None: + now = utc_now() + pool = _classify_pool(nodes, demand, policy, now, live_signals) + forecast = _forecast_demand(nodes, pool, demand, policy, now, live_signals) + capacity = _assess_capacity_and_soft_drain( + nodes, pool, forecast, demand, policy, now + ) + + reasons: list[str] = [] + actions: list[ScaleAction] = [] + if forecast.unschedulable_placements > 0: + reasons.append( + f"{forecast.unschedulable_placements} placement request(s) exceed the " + "configured schedulable node shape and were excluded from create demand" ) - if not pressure_cooldown and not recent_creates and not soft_drain.job_id and not soft_drain_released: - selected = plan_soft_drain( - nodes, - policy, - now, - required_resources=desired_resources, - placement_requests=placement_requests, - oldest_pending_seconds=oldest_pending_seconds, - pending_count=demand.pending_count, - excluded_job_ids=_planned_stop_job_ids(actions), - ) - soft_drain = replace( - selected, - clear_job_ids=tuple( - dict.fromkeys((*soft_drain.clear_job_ids, *selected.clear_job_ids)) - ), - ) + if demand.suppressed_pending_count > 0: + reasons.append( + f"{demand.suppressed_pending_count} non-capacity pending failure(s) " + "excluded from fleet demand" + ) + + _plan_mandatory_stops(pool, actions, reasons) + _plan_min_nodes_create(pool, policy, actions, reasons) + _plan_deficit_create(pool, forecast, capacity, policy, actions, reasons) + _plan_pressure_creates( + pool, forecast, demand, policy, live_signals, actions, reasons + ) + soft_drain = _plan_scale_down_and_soft_drain( + nodes, pool, forecast, capacity, demand, policy, now, live_signals, actions, reasons + ) if soft_drain.reason: reasons.append(f"soft-drain: {soft_drain.reason}") - if not actions and not reasons: reasons.append("current pool matches demand and policy") return ScaleDecision( actions=tuple(actions), - ready_nodes=len(ready_nodes), - provisioning_nodes=len(provisioning_nodes), - total_nodes=total_nodes, - unreachable_nodes=len(unreachable_nodes), + ready_nodes=len(pool.ready_nodes), + provisioning_nodes=len(pool.provisioning_nodes), + total_nodes=pool.total_nodes, + unreachable_nodes=len(pool.unreachable_nodes), pending_resources=demand.pending_resources, suppressed_pending_resources=demand.suppressed_pending_resources, pending_count=demand.pending_count, suppressed_pending_count=demand.suppressed_pending_count, prepared_resources=demand.prepared_resources, - desired_resources=desired_resources, - projected_free_resources=projected_free_resources, - resource_deficit=resource_deficit, + desired_resources=forecast.desired_resources, + projected_free_resources=capacity.projected_free_resources, + resource_deficit=capacity.resource_deficit, reasons=tuple(reasons), live_signals=live_signals, - pressure_scale_up=pressure_scale_up, - create_pressure_scale_up=create_pressure_scale_up, - effective_scale_down_idle_seconds=effective_scale_down_idle_seconds, + pressure_scale_up=forecast.pressure_scale_up, + create_pressure_scale_up=forecast.create_pressure_scale_up, + effective_scale_down_idle_seconds=pool.effective_scale_down_idle_seconds, soft_drain_job_id=soft_drain.job_id, soft_drain_selected=soft_drain.selected, soft_drain_clear_job_ids=soft_drain.clear_job_ids, diff --git a/sandboxes/registry_disk.py b/sandboxes/registry_disk.py index 73d10160..0d24a819 100644 --- a/sandboxes/registry_disk.py +++ b/sandboxes/registry_disk.py @@ -89,9 +89,9 @@ def to_dict(self) -> dict[str, Any]: def registry_disk_paths(config: DeploymentConfig) -> tuple[str, ...]: - """Candidate paths on the registry volume; empty for non-filesystem stores.""" + """Candidate paths on the registry volume; empty when disabled or non-filesystem.""" - if config.registry_store.kind != "filesystem": + if not config.registry_disk_guard_enabled or config.registry_store.kind != "filesystem": return () # The data directory is root-only (0750); the unprivileged gateway can # still statvfs it, but fall back to the mount point if lookup fails. diff --git a/sandboxes/registry_prune.py b/sandboxes/registry_prune.py new file mode 100644 index 00000000..24283e2b --- /dev/null +++ b/sandboxes/registry_prune.py @@ -0,0 +1,563 @@ +"""Registry retention, LRU eviction, and stale image-record pruning workflow. + +Extracted from ``sandboxes.cli`` with explicit I/O factories (``client_factory``, +``disk_usage_fn``) so callers and tests can inject registry transport and disk +probes without patching CLI module globals. +""" + +from __future__ import annotations + +from dataclasses import replace +from datetime import timedelta +from pathlib import Path +import sys +from typing import Any, Callable +from urllib.parse import urlparse + +from .config import DeploymentConfig +from .images import ImageRecord, ImageStore +from .managed_registry import ( + RegistryClient, + RegistryRequestError, + RegistryTag, + RegistryUsageGenerationChanged, + RegistryUsageStore, + apply_registry_usage, + execute_registry_prune, + list_registry_tags, + registry_host_from_image_ref, + registry_prune_plan, + registry_repository_tag_from_image_ref, + select_prune_candidates, +) +from .models import utc_now +from .registry_disk import ( + RegistryDiskUsage, + record_image_evictions, + record_registry_prune, + registry_disk_usage, +) +from .registry_retention import ( + ENVIRONMENT_REASON, + SNAPSHOT_REASON, + EnvironmentBlobIndex, + ImageEnvironmentIndex, + ManagedImage, + ReferenceRetentionDecision, + RegistryTagClock, + environment_live_identities, + execute_reference_prune, + hold_unrecorded_conversions, + image_is_referenced, + list_repository_tags, + managed_images, + manifest_blob_sizes, + manifest_layer_bytes, + routing_image_identities, + select_lru_evictions, + select_unreferenced, + snapshot_live_identities, + still_unreferenced_environment, +) +from .routing import open_routing_store + + +def reference_retained_repositories(config: DeploymentConfig) -> dict[str, str]: + repositories: dict[str, str] = {} + if config.snapshot_store.kind == "registry": + repositories[SNAPSHOT_REASON] = config.sandbox.storage_native_repository + if config.immutable_environments is not None: + repositories[ENVIRONMENT_REASON] = config.immutable_environments.repository + return repositories + + +def image_ref_uses_private_registry(image_ref: str, registry_url: str) -> bool: + host = registry_host_from_image_ref(image_ref) + if not host: + return False + registry_host = urlparse(registry_url).netloc + allowed = { + "ucloud-sandbox-registry:5000", + "localhost:5000", + "127.0.0.1:5000", + } + if registry_host: + allowed.add(registry_host) + return host in allowed + + +def image_record_is_pushed_private_build( + record: ImageRecord, + registry_url: str, +) -> bool: + return bool( + record.pushed + and record.source.startswith("build:") + and image_ref_uses_private_registry(record.tag, registry_url) + ) + + +def dedupe_image_records(records: list[ImageRecord]) -> list[ImageRecord]: + deduped: dict[str, ImageRecord] = {} + for record in records: + deduped[record.id] = record + return [deduped[key] for key in sorted(deduped)] + + +def remove_image_records_for_registry_tags( + image_file: Path, + registry_tags: set[tuple[str, str]], +) -> list[ImageRecord]: + if not registry_tags: + return [] + store = ImageStore(image_file) + records = store.load() + tags_to_remove = [ + record.tag + for record in records.values() + if registry_repository_tag_from_image_ref(record.tag) in registry_tags + ] + return store.delete_by_tags(tags_to_remove) + + +def remove_stale_private_build_image_records( + image_file: Path, + client: RegistryClient, +) -> list[ImageRecord]: + from .gateway.image_roots import released_lookup + + store = ImageStore(image_file) + records = store.load() + tags_to_remove: list[str] = [] + released = released_lookup(image_file) + for record in records.values(): + if not image_record_is_pushed_private_build(record, client.base_url): + continue + parsed = registry_repository_tag_from_image_ref(record.tag) + if parsed is None: + continue + try: + exists = client.tag_exists(*parsed) + except (OSError, ValueError, RegistryRequestError): + continue + # Chunk store M2: OCI release deleted a released image's tags, not the image. + if not exists and not released(parsed[0], parsed[1], record.manifest_digest): + tags_to_remove.append(record.tag) + return store.delete_by_tags(tags_to_remove) + + +def run_lru_eviction( + config: DeploymentConfig, + client: RegistryClient, + usage_store: RegistryUsageStore, + *, + images: list[RegistryTag], + usage: RegistryDiskUsage, + execute: bool, +) -> tuple[dict[str, Any], list[RegistryTag], list[ImageRecord]]: + """Evict managed images, oldest use first, down to the target usage.""" + + grace = config.registry_reference_grace_seconds + usage_snapshot = usage_store.snapshot() + data_dir = ( + config.registry_data_dir() + if config.registry_store.kind == "filesystem" + and config.registry_data_dir().is_dir() + else None + ) + routing_store = open_routing_store(config.routing_file()) + environments = ( + ( + ImageEnvironmentIndex(client), + EnvironmentBlobIndex(client, config.immutable_environments.repository), + ) + if config.immutable_environments is not None + else None + ) + + def blobs(repository: str, digest: str) -> dict[str, int]: + result = manifest_blob_sizes(client, repository, digest) + if environments is not None: + roots, environment_blobs = environments + try: + result.update(environment_blobs.blobs(roots.root(repository, digest))) + except (RegistryRequestError, ValueError): + pass + return result + + from .gateway.image_roots import retention_view + + _mapped_roots, dispatched = retention_view(config.image_file()) + now = utc_now() + plan = select_lru_evictions( + managed_images( + [ + record + for record in images + if (record.repository, record.digest) not in dispatched + ], + tag_time=RegistryTagClock(data_dir, usage_snapshot.records), + blobs=blobs, + ), + used_bytes=usage.used_bytes, + target_used_bytes=usage.target_used_bytes, + grace_seconds=grace, + live=routing_image_identities(routing_store), + leased_digests=usage_snapshot.active_lease_digests(), + now=now, + ) + summary = plan.to_dict() + summary["evict_sample_all"] = [ + {"repository": image.repository, "tags": [tag.tag for tag in image.tags]} + for image in plan.evict + ] + if not execute or not plan.evict: + return summary, [], [] + fresh = routing_image_identities(routing_store) + evicted = execute_reference_prune( + client, + plan.records, + usage_store=usage_store, + still_unreferenced=lambda record: not image_is_referenced( + ManagedImage(record.repository, record.digest, (record,), None), fresh + ), + unused_since=now - timedelta(seconds=grace), + ) + removed = remove_image_records_for_registry_tags( + config.image_file(), + {(record.repository, record.tag) for record in evicted}, + ) + if evicted: + try: + record_image_evictions( + config.registry_maintenance_state_file(), + [{"image_id": item.id, "tag": item.tag} for item in removed], + ) + except OSError as exc: + summary["tombstone_error"] = str(exc) + summary["evicted_images"] = len( + {(item.repository, item.digest) for item in evicted} + ) + summary["evicted_tags"] = len(evicted) + print( + "registry disk pressure evicted " + f"{summary['evicted_images']} least-recently-used managed images", + file=sys.stderr, + ) + return summary, evicted, removed + + +def run_reference_retention( + config: DeploymentConfig, + client: RegistryClient, + usage_store: RegistryUsageStore, + *, + repositories: dict[str, str], + remaining_images: list[RegistryTag], + repository_prefix: str, + execute: bool, +) -> dict[str, Any]: + grace = config.registry_reference_grace_seconds + result: dict[str, Any] = {"grace_seconds": grace, "decisions": []} + if not repositories: + return result + catalog = set(client.catalog()) + usage_snapshot = usage_store.snapshot() + leased = usage_snapshot.active_lease_digests() + data_dir = ( + config.registry_data_dir() + if config.registry_store.kind == "filesystem" + and config.registry_data_dir().is_dir() + else None + ) + tag_time = RegistryTagClock(data_dir, usage_snapshot.records) + now = utc_now() + + def present(reason: str) -> bool: + repository = repositories.get(reason, "") + return repository in catalog and repository.startswith(repository_prefix) + + def decide(reason: str, live: set[str]) -> ReferenceRetentionDecision: + return select_unreferenced( + list_repository_tags(client, repositories[reason]), + reason=reason, + repository=repositories[reason], + live=live, + grace_seconds=grace, + tag_time=tag_time, + leased_digests=leased, + now=now, + ) + + def skip(reason: str, message: str) -> ReferenceRetentionDecision: + return ReferenceRetentionDecision( + reason=reason, repository=repositories[reason], skipped=message + ) + + outcomes: list[tuple[ReferenceRetentionDecision, list[RegistryTag]]] = [] + if present(SNAPSHOT_REASON): + routing_store = open_routing_store(config.routing_file()) + try: + decision = decide(SNAPSHOT_REASON, snapshot_live_identities(routing_store)) + except ValueError as exc: + decision = skip(SNAPSHOT_REASON, f"snapshot liveness unknown: {exc}") + deleted_snapshots: list[RegistryTag] = [] + if execute and decision.delete: + fresh = snapshot_live_identities(routing_store) + deleted_snapshots = execute_reference_prune( + client, + decision, + usage_store=usage_store, + still_unreferenced=lambda record: ( + record.digest not in fresh and record.tag not in fresh + ), + ) + outcomes.append((decision, deleted_snapshots)) + + if present(ENVIRONMENT_REASON): + environment_repository = repositories[ENVIRONMENT_REASON] + excluded = set(repositories.values()) + index = ImageEnvironmentIndex(client) + from .gateway.image_roots import retention_view + + mapped_roots, dispatched = retention_view(config.image_file()) + if repository_prefix: + decision = skip( + ENVIRONMENT_REASON, + "a repository prefix limits the managed image scan", + ) + else: + try: + live = environment_live_identities( + client, + environment_repository, + index.roots( + record + for record in remaining_images + if record.repository not in excluded + and (record.repository, record.digest) not in dispatched + ) + | mapped_roots, + ) + decision = hold_unrecorded_conversions( + decide(ENVIRONMENT_REASON, live), tag_time, now + ) + if decision.delete: + decision = replace( + decision, + delete_layer_bytes=manifest_layer_bytes( + client, + environment_repository, + (record.digest for record in decision.delete), + ), + ) + except (RegistryRequestError, ValueError) as exc: + decision = skip( + ENVIRONMENT_REASON, f"environment liveness unknown: {exc}" + ) + deleted_environments: list[RegistryTag] = [] + if execute and decision.delete: + mapped_roots, dispatched = retention_view(config.image_file()) + fresh = environment_live_identities( + client, + environment_repository, + index.roots( + record + for repository in client.catalog() + if repository not in excluded + for record in list_repository_tags(client, repository) + if (record.repository, record.digest) not in dispatched + ) + | mapped_roots, + ) + deleted_environments = execute_reference_prune( + client, + decision, + usage_store=usage_store, + still_unreferenced=still_unreferenced_environment( + fresh, tag_time, now - timedelta(seconds=grace) + ), + ) + outcomes.append((decision, deleted_environments)) + + for decision, deleted in outcomes: + item = decision.to_dict() + if execute: + item["deleted_manifests"] = len({record.digest for record in deleted}) + item["deleted_tags"] = len(deleted) + result["decisions"].append(item) + return result + + +def run_registry_prune( + config: DeploymentConfig, + *, + execute: bool, + repository_prefix: str = "", + evict_lru: bool = False, + client_factory: Callable[[str], RegistryClient] = RegistryClient, + disk_usage_fn: Callable[[DeploymentConfig], RegistryDiskUsage | None] = registry_disk_usage, +) -> dict[str, Any]: + """Age retention for image repositories, reference retention for the rest.""" + + client = client_factory(config.registry_url) + usage_store = RegistryUsageStore(config.registry_usage_file()) + usage_snapshot = usage_store.snapshot() + usage_records = usage_snapshot.records + reference_repositories = reference_retained_repositories(config) + cache_policy = None + excluded_repositories = list(reference_repositories.values()) + if config.builder.buildx_cache_ref: + from .build_cache import RegistryBuildCache + + cache_policy = RegistryBuildCache( + config.builder.buildx_cache_ref, + registry_url=config.registry_url, + max_bytes=config.builder.buildx_cache_max_bytes, + max_entries=config.builder.buildx_cache_max_entries, + max_age_seconds=config.builder.buildx_cache_max_age_seconds, + ) + excluded_repositories.append(cache_policy.repository) + + plan = registry_prune_plan( + client, + keep_per_repository=config.registry_keep_per_repository, + repository_prefix=repository_prefix, + max_age_days=config.registry_retention_days, + usage_records=usage_records, + active_leases=usage_snapshot.leases, + usage_generation=usage_snapshot.generation, + exclude_repositories=excluded_repositories, + ) + plan["execute"] = bool(execute) + plan["usage_file"] = str(config.registry_usage_file()) + plan["image_file"] = str(config.image_file()) + image_records = [RegistryTag(**item) for item in plan["tags"]] + removed_images = {(item["repository"], item["tag"]) for item in plan["delete"]} + deleted: list[RegistryTag] = [] + if execute: + records = image_records + for attempt in range(3): + usage_snapshot = usage_store.snapshot() + usage_records = usage_snapshot.records + records = list_registry_tags( + client, + repository_prefix=repository_prefix, + exclude_repositories=excluded_repositories, + ) + records = apply_registry_usage(records, usage_records) + candidates = select_prune_candidates( + records, + keep_per_repository=config.registry_keep_per_repository, + max_age_days=config.registry_retention_days, + use_last_used_at=True, + active_leases=usage_snapshot.leases, + ) + try: + deleted = execute_registry_prune( + client, + candidates, + usage_store=usage_store, + expected_usage_generation=usage_snapshot.generation, + all_records=records, + ) + break + except RegistryUsageGenerationChanged: + if attempt == 2: + raise + continue + image_records = records + removed_images = {(item.repository, item.tag) for item in deleted} + plan["deleted"] = [item.to_dict() for item in deleted] + plan["usage_generation"] = usage_snapshot.generation + plan["active_lease_count"] = len(usage_snapshot.leases) + removed = remove_image_records_for_registry_tags( + config.image_file(), + {(record.repository, record.tag) for record in deleted}, + ) + removed.extend( + remove_stale_private_build_image_records(config.image_file(), client) + ) + plan["removed_image_records"] = [ + item.to_dict() for item in dedupe_image_records(removed) + ] + + evicted: list[RegistryTag] = [] + usage = disk_usage_fn(config) if evict_lru else None + if usage is not None and usage.cleanup_needed and not repository_prefix: + eviction, evicted, evicted_records = run_lru_eviction( + config, + client, + usage_store, + images=[ + record + for record in image_records + if (record.repository, record.tag) not in removed_images + ], + usage=usage, + execute=execute, + ) + plan["lru_eviction"] = eviction + if execute: + removed_images |= {(item.repository, item.tag) for item in evicted} + plan.setdefault("removed_image_records", []).extend( + item.to_dict() for item in evicted_records + ) + else: + removed_images |= { + (item["repository"], tag) + for item in eviction["evict_sample_all"] + for tag in item["tags"] + } + eviction.pop("evict_sample_all", None) + + reference = run_reference_retention( + config, + client, + usage_store, + repositories=reference_repositories, + remaining_images=[ + record + for record in image_records + if (record.repository, record.tag) not in removed_images + ], + repository_prefix=repository_prefix, + execute=execute, + ) + plan["reference_retention"] = reference + + cache_deleted = 0 + if cache_policy is not None and ( + not repository_prefix + or cache_policy.repository.startswith(repository_prefix) + ): + try: + plan["build_cache"] = cache_policy.prune(execute=execute) + cache_deleted = plan["build_cache"].get("deleted_manifests", 0) + except (OSError, ValueError, RuntimeError) as exc: + plan["build_cache"] = { + "error": type(exc).__name__, + "deleted_manifests": 0, + } + + if execute: + deleted_manifests = len( + {(item.repository, item.digest) for item in (*deleted, *evicted)} + ) + deleted_manifests += sum( + item["deleted_manifests"] for item in reference["decisions"] + ) + deleted_manifests += cache_deleted + plan["deleted_manifest_count"] = deleted_manifests + try: + state = record_registry_prune( + config.registry_maintenance_state_file(), deleted=deleted_manifests + ) + state.pop("evicted_images", None) + plan["maintenance_state"] = state + except OSError as exc: + plan["maintenance_state_error"] = str(exc) + + usage = disk_usage_fn(config) + plan["registry_disk"] = usage.to_dict() if usage is not None else None + return plan diff --git a/sandboxes/routing.py b/sandboxes/routing.py index 28ff2dc1..ed7b50c2 100644 --- a/sandboxes/routing.py +++ b/sandboxes/routing.py @@ -22,8 +22,18 @@ utc_now, ) from .managed_process import ManagedProcessRecord +from .routing_transitions import ( + PROGRAM_REQUEST_STATES, + PROGRAM_STATE_RANK as _PROGRAM_STATE_RANK, + classify_absent_node_routes, + plan_node_epoch_retirement, + plan_observed_route_updates, + plan_sandbox_state_transition, + project_program_request_transition, + validate_program_transition_args, + validate_sandbox_state_transition_args, +) from .sandbox import OPERATION_ID_RE -from .storage_native_registry import StorageSnapshotPublication _POSTGRES_ROUTING_STORES_GUARD = Lock() @@ -105,16 +115,6 @@ def close_routing_store(path: Path) -> None: SANDBOX_WORKER_STATES = ("attached", "detaching", "detached") -PROGRAM_REQUEST_STATES = ( - "model_wait", - "ready_to_wake", - "waking", - "acting", - "terminal", -) -_PROGRAM_STATE_RANK = { - state: index for index, state in enumerate(PROGRAM_REQUEST_STATES) -} class SandboxRouteConflictError(RuntimeError): @@ -1112,83 +1112,28 @@ def upsert_program_request_transition_with_change( clear_error: bool = False, _connection=None, ) -> tuple[ProgramRequestState, bool]: - request_id = request_id.strip() - rollout_id = rollout_id.strip() - if not request_id or not rollout_id: - raise ValueError("program request and rollout ids are required") - if state not in _PROGRAM_STATE_RANK: - raise ValueError(f"unsupported program request state: {state}") + request_id, rollout_id = validate_program_transition_args( + request_id=request_id, rollout_id=rollout_id, state=state + ) transition_at = transition_at or utc_now().isoformat() def project(existing): - if existing is not None and ( - existing.rollout_id != rollout_id - or existing.sandbox_id != route.sandbox_id - or existing.sandbox_generation != route.generation - ): - raise SandboxRouteConflictError( - "program request id belongs to another rollout or sandbox" - ) - effective_state = state - if ( - existing is not None - and _PROGRAM_STATE_RANK[existing.state] > _PROGRAM_STATE_RANK[state] - ): - effective_state = existing.state - timestamps = { - "accepted_at": existing.accepted_at if existing else "", - "parked_at": existing.parked_at if existing else "", - "response_ready_at": ( - existing.response_ready_at if existing else "" - ), - "wake_started_at": existing.wake_started_at if existing else "", - "wake_completed_at": ( - existing.wake_completed_at if existing else "" - ), - } - if accepted_at and not timestamps["accepted_at"]: - timestamps["accepted_at"] = accepted_at - if not timestamps["accepted_at"]: - timestamps["accepted_at"] = transition_at - if parked_at and not timestamps["parked_at"]: - timestamps["parked_at"] = parked_at - if response_ready_at and not timestamps["response_ready_at"]: - timestamps["response_ready_at"] = response_ready_at - if wake_started_at and not timestamps["wake_started_at"]: - timestamps["wake_started_at"] = wake_started_at - transition_field = { - "ready_to_wake": "response_ready_at", - "waking": "wake_started_at", - "acting": "wake_completed_at", - }.get(state) - if transition_field and not timestamps[transition_field]: - timestamps[transition_field] = transition_at - advanced = bool( - existing is not None - and _PROGRAM_STATE_RANK[effective_state] - > _PROGRAM_STATE_RANK[existing.state] - ) - error = ( - last_error - if last_error - else ( - "" - if clear_error or advanced - else (existing.last_error if existing else "") - ) + return project_program_request_transition( + existing, + route, + request_id=request_id, + rollout_id=rollout_id, + state=state, + transition_at=transition_at, + accepted_at=accepted_at, + parked_at=parked_at, + response_ready_at=response_ready_at, + wake_started_at=wake_started_at, + last_error=last_error, + clear_error=clear_error, + state_cls=ProgramRequestState, + conflict_error_cls=SandboxRouteConflictError, ) - if existing is not None and ( - existing.state == effective_state - and existing.resources == route.resources - and existing.accepted_at == timestamps["accepted_at"] - and existing.parked_at == timestamps["parked_at"] - and existing.response_ready_at == timestamps["response_ready_at"] - and existing.wake_started_at == timestamps["wake_started_at"] - and existing.wake_completed_at == timestamps["wake_completed_at"] - and existing.last_error == error - ): - return effective_state, timestamps, error, True - return effective_state, timestamps, error, False def read_current(conn): snapshot = conn.execute( @@ -1201,19 +1146,28 @@ def read_current(conn): raise SandboxRouteConflictError( "program transition does not own the current sandbox generation" ) - return _program_request_from_row(snapshot) if snapshot["request_id"] is not None else None + return ( + _program_request_from_row(snapshot) + if snapshot["request_id"] is not None + else None + ) # Retries are observational. Changed projections recheck both request # identity and generation in one joined read inside the transaction. - with (self._connect() if _connection is None else nullcontext(_connection)) as conn: + with ( + self._connect() if _connection is None else nullcontext(_connection) + ) as conn: previous = read_current(conn) - if previous is not None and project(previous)[3]: + if previous is not None and not project(previous).changed: return previous, False - with (self._transaction() if _connection is None else nullcontext(_connection)) as conn: + with ( + self._transaction() if _connection is None else nullcontext(_connection) + ) as conn: existing = read_current(conn) if _connection is None else previous - effective_state, timestamps, error, unchanged = project(existing) - if unchanged: + outcome = project(existing) + if not outcome.changed: return existing, False + projected = outcome.state conn.execute( """ INSERT INTO program_requests ( @@ -1235,31 +1189,22 @@ def read_current(conn): last_error = excluded.last_error """, ( - request_id, - rollout_id, - route.sandbox_id, - route.generation, - effective_state, + projected.request_id, + projected.rollout_id, + projected.sandbox_id, + projected.sandbox_generation, + projected.state, _resources_json(route.resources), - timestamps["accepted_at"], - timestamps["parked_at"], - timestamps["response_ready_at"], - timestamps["wake_started_at"], - timestamps["wake_completed_at"], - transition_at, - error, + projected.accepted_at, + projected.parked_at, + projected.response_ready_at, + projected.wake_started_at, + projected.wake_completed_at, + projected.updated_at, + projected.last_error, ), ) - # These are the exact values just committed; there are no SQL - # defaults/triggers to read back. The context still waits for FULL - # commit before returning them to the caller. - return ProgramRequestState( - request_id=request_id, rollout_id=rollout_id, - sandbox_id=route.sandbox_id, sandbox_generation=route.generation, - state=effective_state, - resources=ResourceQuantity.from_dict(route.resources.to_dict()), - **timestamps, updated_at=transition_at, last_error=error, - ), True + return projected, True def program_request_readonly(self, request_id: str) -> ProgramRequestState | None: with self._read() as conn: @@ -1323,89 +1268,30 @@ def set_sandbox_state_if_current( route behind a heartbeat that has already been reconciled. """ - expected = {str(item or "unknown").strip().lower() for item in expected_states} - cleaned_state = str(state).strip() - if not expected or not cleaned_state: - raise ValueError("expected and destination sandbox states are required") - if (node_epoch is None) != (activity_epoch is None): - raise ValueError("node_epoch and activity_epoch must be supplied together") - lifecycle_node_epoch: str | None = None - lifecycle_activity_epoch: int | None = None - if node_epoch is not None: - lifecycle_node_epoch = node_epoch.strip() - if not lifecycle_node_epoch: - raise ValueError("lifecycle node_epoch must be nonempty") - if isinstance(activity_epoch, bool) or not isinstance(activity_epoch, int): - raise ValueError("lifecycle activity_epoch must be an integer") - if activity_epoch < 0: - raise ValueError("lifecycle activity_epoch must be non-negative") - lifecycle_activity_epoch = activity_epoch + proof = validate_sandbox_state_transition_args( + expected_states=expected_states, + state=state, + node_epoch=node_epoch, + activity_epoch=activity_epoch, + ) # The transaction serializes this database-only mutation. Inventory # projection must not block lifecycle progress. with (self._transaction() if _connection is None else nullcontext(_connection)) as conn: current = self._get_sandbox_unlocked(conn, route.sandbox_id) - if ( - current is None - or (current.state or "unknown").lower() not in expected - or not _same_sandbox_route_incarnation(current, route) - or current.worker_state != route.worker_state - or bool(current.delete_operation_id) - or ( - lifecycle_node_epoch is not None - and ( - lifecycle_activity_epoch is None - or lifecycle_activity_epoch <= route.activity_epoch - or bool( - route.node_epoch - and route.node_epoch != lifecycle_node_epoch - ) - or bool( - current.node_epoch - and current.node_epoch != lifecycle_node_epoch - ) - or current.activity_epoch > lifecycle_activity_epoch - ) - ) - ): - return None - stored = replace( + stored = plan_sandbox_state_transition( current, - state=cleaned_state, - node_epoch=( - current.node_epoch - if lifecycle_node_epoch is None - else lifecycle_node_epoch - ), - activity_epoch=( - current.activity_epoch - if lifecycle_activity_epoch is None - else lifecycle_activity_epoch - ), - storage_schema=( - current.storage_schema - if storage_schema is None - else storage_schema - ), - snapshot_manifest_digest=( - current.snapshot_manifest_digest - if snapshot_manifest_digest is None - else snapshot_manifest_digest - ), - snapshot_repository=( - current.snapshot_repository - if snapshot_repository is None - else snapshot_repository - ), - snapshot_tag=( - current.snapshot_tag if snapshot_tag is None else snapshot_tag - ), - storage_snapshot=( - current.storage_snapshot - if storage_snapshot is None - else dict(storage_snapshot) - ), + route, + proof, + same_incarnation=_same_sandbox_route_incarnation, updated_at=utc_now().isoformat(), + storage_schema=storage_schema, + snapshot_manifest_digest=snapshot_manifest_digest, + snapshot_repository=snapshot_repository, + snapshot_tag=snapshot_tag, + storage_snapshot=storage_snapshot, ) + if stored is None: + return None self._write_sandbox_lifecycle(conn, stored) return stored @@ -2354,12 +2240,8 @@ def reconcile_sandboxes_for_node( reported_ids.update(item.sandbox_id for item in observed) observed_at_dt = parse_iso_datetime(observed_at) # The SQL transaction serializes all incarnation and ownership checks. - removed_sandbox_ids: list[str] = [] removed_routes: list[SandboxRoute] = [] - stale_snapshot_routes: list[SandboxRoute] = [] with self._transaction() as conn: - # One snapshot under the writer transaction preserves the same - # incarnation fences without a SELECT for every inventory entry. existing_by_id = { route.sandbox_id: route for row in conn.execute( @@ -2368,135 +2250,53 @@ def reconcile_sandboxes_for_node( ) if (route := _sandbox_route_from_row(row)) is not None } - touched_ids: set[str] = set() - accepted_ids: set[str] = set() - dependencies = [] - unique_observations = len({item.sandbox_id for item in observed}) == len(observed) - - def write_dependencies(): - if not dependencies: - return - self._write_storage_dependencies(conn, dependencies) - dependencies.clear() - - for item in observed: - existing = existing_by_id.get(item.sandbox_id) - if existing is None: - continue - observed_state = item.route_state - # Heartbeats are sampled independently of synchronous - # lifecycle requests. Registration, transition, recovery, - # unavailable, and unrecognised samples still prove - # presence through ``reported_ids``, but none may become - # durable gateway routing state. The next stable - # RUNNING/PARKED observation remains authoritative. - if observed_state is None: - continue - parked = observed_state == "parked" - published_snapshot = bool(parked and item.storage_snapshot) - validated_snapshot: SandboxRoute | None = None - if published_snapshot: - try: - validated_snapshot = route_with_inventory_snapshot( - existing, - item, - ) - except ValueError: - # Presence and stable lifecycle state remain useful, - # but malformed publication metadata can never grant - # portable authority. - published_snapshot = False - candidate = replace( - existing, - node_id=node_id, - job_id=job_id, - node_url=node_url, - resources=( - item.resources - if item.resources != ResourceQuantity() - else existing.resources - ), - state=observed_state, - generation=item.generation, - create_operation_id=item.operation_id, - spec_hash=item.spec_hash, - node_epoch=node_epoch, - # Activity counters are scoped to a node epoch. Do not - # carry the old epoch's high water into a proven restart. - activity_epoch=max(0, activity_epoch), - storage_schema=( - validated_snapshot.storage_schema - if published_snapshot - else (existing.storage_schema if parked else "") - ), - snapshot_manifest_digest=( - validated_snapshot.snapshot_manifest_digest - if published_snapshot - else (existing.snapshot_manifest_digest if parked else "") - ), - snapshot_repository=( - validated_snapshot.snapshot_repository - if published_snapshot - else (existing.snapshot_repository if parked else "") - ), - snapshot_tag=( - validated_snapshot.snapshot_tag - if published_snapshot - else (existing.snapshot_tag if parked else "") - ), - storage_snapshot=( - dict(validated_snapshot.storage_snapshot) - if published_snapshot - else (dict(existing.storage_snapshot) if parked else {}) - ), - updated_at=observed_at, - ) - if candidate.generation != existing.generation: - continue - if not _route_update_is_current( - existing, candidate, allow_node_epoch_adoption=False, - ): - continue - if existing.snapshot_manifest_digest and ( - existing.snapshot_manifest_digest - != candidate.snapshot_manifest_digest - or existing.snapshot_repository != candidate.snapshot_repository - or existing.snapshot_tag != candidate.snapshot_tag - ): - stale_snapshot_routes.append(existing) - if replace( - candidate, activity_epoch=existing.activity_epoch, - updated_at=existing.updated_at, - ) == existing: - # Only the observation watermark changed. Rewriting the - # full spec, snapshot and generation HWM for every running - # guest turns startup heartbeats into quadratic SQL work. - touched_ids.add(candidate.sandbox_id) + updates = plan_observed_route_updates( + existing_by_id, + observed, + node_id=node_id, + job_id=job_id, + node_url=node_url, + observed_at=observed_at, + node_epoch=node_epoch, + activity_epoch=activity_epoch, + route_with_inventory_snapshot=route_with_inventory_snapshot, + route_update_is_current=_route_update_is_current, + ) + for candidate in updates.writes: + self._write_sandbox(conn, candidate) + if updates.storage_dependencies: + if updates.unique_observations: + self._write_storage_dependencies( + conn, + [ + [ + dep.sandbox_id, + dep.generation, + _object_json({"publication": dep.publication}) + if dep.publication + else "{}", + ] + for dep in updates.storage_dependencies + ], + ) else: - self._write_sandbox(conn, candidate) - existing_by_id[candidate.sandbox_id] = candidate - accepted_ids.add(candidate.sandbox_id) - if item.storage_dependency is not None: - # This metadata conveys liveness only, never permission - # to restore a running sandbox from an old checkpoint. - dependency = item.storage_dependency - if dependency: - dependency = StorageSnapshotPublication.from_dict( - dependency - ).to_dict() - dependencies.append([ - candidate.sandbox_id, candidate.generation, - _object_json({"publication": dependency}) if dependency else "{}", - ]) - if not unique_observations: - # Preserve per-entry ordering if a malformed inventory - # repeats an identity with different snapshot metadata. - write_dependencies() - write_dependencies() - if accepted_ids: + for dep in updates.storage_dependencies: + self._write_storage_dependencies( + conn, + [ + [ + dep.sandbox_id, + dep.generation, + _object_json({"publication": dep.publication}) + if dep.publication + else "{}", + ] + ], + ) + if updates.accepted_ids: conn.execute( f"DELETE FROM pending WHERE sandbox_id IN ({self._json_values_query})", - (json.dumps(sorted(accepted_ids)),), + (json.dumps(sorted(updates.accepted_ids)),), ) current_routes = self._sandbox_routes_for_node_url_unlocked( @@ -2504,57 +2304,37 @@ def write_dependencies(): node_url, excluded_ids=reported_ids, ) - for route in current_routes: - sandbox_id = route.sandbox_id - if sandbox_id in reported_ids or not inventory_complete: - continue - if route.node_epoch and route.node_epoch != node_epoch: - # Only retire_node_epochs settles another boot's routes. - # Inventory proves state for its own boot alone, and an - # unversioned observation for none. - continue - if (route.state or "unknown").lower() in {"creating", "unknown"}: - # An empty inventory does not distinguish "create never - # arrived" from "create is still in progress" with the - # current node protocol. Preserve the reservation until a - # later generation-aware reconciliation can prove absence. - continue - if route.activity_epoch > max(0, activity_epoch): - continue - route_updated_at = parse_iso_datetime( - route.updated_at - ) or parse_iso_datetime(route.created_at) - if not ( - observed_at_dt is None - or route_updated_at is None - or route_updated_at <= observed_at_dt - ): - continue - if ( - sandbox_owner_loss_disposition(route) - is SandboxOwnerLossDisposition.RECOVER_DETACHED - ): - self._detach_owner_lost_route_unlocked( - conn, - route, - updated_at=observed_at, - ) - removed_sandbox_ids.append(sandbox_id) - continue - if not self._delete_sandbox_unlocked(conn, route): - continue - removed_routes.append(route) - removed_sandbox_ids.append(sandbox_id) - if touched_ids: + absences = classify_absent_node_routes( + current_routes, + reported_ids=reported_ids, + inventory_complete=inventory_complete, + node_epoch=node_epoch, + activity_epoch=activity_epoch, + observed_at_dt=observed_at_dt, + owner_loss_disposition=sandbox_owner_loss_disposition, + recover_detached_value=SandboxOwnerLossDisposition.RECOVER_DETACHED, + ) + for route in absences.detach: + self._detach_owner_lost_route_unlocked( + conn, route, updated_at=observed_at + ) + for route in absences.delete: + if self._delete_sandbox_unlocked(conn, route): + removed_routes.append(route) + if updates.touched_ids: # Last statement: these row locks conflict with wake and # placement writes, so hold them only until commit. Absence # processing above never reads a reported (touched) route. conn.execute( f"""UPDATE sandboxes SET activity_epoch = ?, updated_at = ? WHERE sandbox_id IN ({self._json_values_query})""", - (max(0, activity_epoch), observed_at, json.dumps(sorted(touched_ids))), + ( + max(0, activity_epoch), + observed_at, + json.dumps(sorted(updates.touched_ids)), + ), ) - return removed_routes, stale_snapshot_routes + return removed_routes, list(updates.stale_snapshot_routes) def delete_sandbox(self, sandbox_id: str) -> None: with self._transaction() as conn: @@ -2576,38 +2356,41 @@ def retire_node_epochs( retired = {str(epoch) for epoch in retired_node_epochs} - {"", node_epoch} if not job_id or not node_epoch or not retired: return NodeEpochRetirement((), ()) - parked = { - (item.sandbox_id, item.generation, item.operation_id, item.spec_hash) - for item in inventory or () if item.route_state == "parked" - } lost: list[SandboxRoute] = [] - pending_deletes: list[SandboxRoute] = [] with self._transaction() as conn: - for row in conn.execute( - "SELECT * FROM sandboxes WHERE job_id = ? ORDER BY sandbox_id", (job_id,), - ).fetchall(): - route = _sandbox_route_from_row(row) - if route is None or route.node_epoch not in retired: - continue - disposition = sandbox_owner_loss_disposition(route) - deleting = disposition is SandboxOwnerLossDisposition.TERMINAL_DELETE - if deleting or route.worker_state == "attached" and ( - route.sandbox_id, route.generation, route.create_operation_id, route.spec_hash, - ) in parked: - if deleting: - pending_deletes.append(route) - else: - self._write_sandbox(conn, replace( - route, state="parked", node_epoch=node_epoch, - activity_epoch=max(0, activity_epoch), updated_at=observed_at, - )) - elif disposition is SandboxOwnerLossDisposition.RECOVER_DETACHED: - self._detach_owner_lost_route_unlocked(conn, route, updated_at=observed_at) - elif self._delete_sandbox_unlocked( - conn, route, terminal_error="node_lost", loss_reason=REBOOTED_LOSS_REASON, + routes = [ + _sandbox_route_from_row(row) + for row in conn.execute( + "SELECT * FROM sandboxes WHERE job_id = ? ORDER BY sandbox_id", + (job_id,), + ).fetchall() + ] + plan = plan_node_epoch_retirement( + routes, + retired, + node_epoch=node_epoch, + activity_epoch=activity_epoch, + inventory=inventory, + observed_at=observed_at, + owner_loss_disposition=sandbox_owner_loss_disposition, + terminal_delete_value=SandboxOwnerLossDisposition.TERMINAL_DELETE, + recover_detached_value=SandboxOwnerLossDisposition.RECOVER_DETACHED, + ) + for route in plan.readopted_routes: + self._write_sandbox(conn, route) + for route in plan.detach_routes: + self._detach_owner_lost_route_unlocked( + conn, route, updated_at=observed_at + ) + for route in plan.lost_routes: + if self._delete_sandbox_unlocked( + conn, + route, + terminal_error="node_lost", + loss_reason=REBOOTED_LOSS_REASON, ): lost.append(route) - return NodeEpochRetirement(tuple(lost), tuple(pending_deletes)) + return NodeEpochRetirement(tuple(lost), plan.pending_deletes) def reboot_lost_incarnations( self, job_id: str, incarnations: Iterable[tuple[str, int]], diff --git a/sandboxes/routing_transitions.py b/sandboxes/routing_transitions.py new file mode 100644 index 00000000..e02593cb --- /dev/null +++ b/sandboxes/routing_transitions.py @@ -0,0 +1,525 @@ +"""Pure routing state-transition and reconciliation rules (no SQL or clocks). + +``RoutingStore`` loads rows inside a PostgreSQL transaction, calls these +functions with explicit timestamps, and writes the returned deltas. Keeping +incarnation fencing, reboot retirement, and lifecycle proofs pure lets the +invariants be tested directly without a database. +""" + +from __future__ import annotations + +from dataclasses import dataclass, replace +from datetime import datetime +from typing import Any, Iterable + +from .models import ( + ResourceQuantity, + SandboxInventoryEntry, + parse_iso_datetime, +) +from .storage_native_registry import StorageSnapshotPublication + +PROGRAM_REQUEST_STATES: tuple[str, ...] = ( + "model_wait", + "ready_to_wake", + "waking", + "acting", + "terminal", +) +PROGRAM_STATE_RANK: dict[str, int] = { + state: index for index, state in enumerate(PROGRAM_REQUEST_STATES) +} + + +@dataclass(frozen=True) +class ProgramTransitionResult: + state: Any # ProgramRequestState + changed: bool + + +@dataclass(frozen=True) +class ValidatedLifecycleProof: + expected_states: frozenset[str] + destination_state: str + node_epoch: str | None + activity_epoch: int | None + + +@dataclass(frozen=True) +class StorageDependencyWrite: + sandbox_id: str + generation: int + publication: dict[str, Any] | None + + +@dataclass(frozen=True) +class ObservedRouteUpdates: + """Result of applying a node heartbeat's observed inventory against routes.""" + + writes: tuple[Any, ...] # SandboxRoute rows whose full state changed + touched_ids: frozenset[str] # IDs where only activity_epoch/updated_at changed + accepted_ids: frozenset[str] + stale_snapshot_routes: tuple[Any, ...] # prior SandboxRoute rows with replaced snapshots + storage_dependencies: tuple[StorageDependencyWrite, ...] + unique_observations: bool + + +@dataclass(frozen=True) +class AbsentRoutePlan: + """Disposition of routes missing from a complete same-boot node inventory.""" + + detach: tuple[Any, ...] # SandboxRoute rows to detach (portable parks) + delete: tuple[Any, ...] # SandboxRoute rows to delete + + +@dataclass(frozen=True) +class EpochRetirementPlan: + """Settlement plan for routes owned by retired boot epochs of a worker.""" + + pending_deletes: tuple[Any, ...] + readopted_routes: tuple[Any, ...] + detach_routes: tuple[Any, ...] + lost_routes: tuple[Any, ...] + + +def validate_program_transition_args( + *, + request_id: str, + rollout_id: str, + state: str, +) -> tuple[str, str]: + cleaned_request_id = request_id.strip() + cleaned_rollout_id = rollout_id.strip() + if not cleaned_request_id or not cleaned_rollout_id: + raise ValueError("program request and rollout ids are required") + if state not in PROGRAM_STATE_RANK: + raise ValueError(f"unsupported program request state: {state}") + return cleaned_request_id, cleaned_rollout_id + + +def project_program_request_transition( + existing: Any | None, + route: Any, + *, + request_id: str, + rollout_id: str, + state: str, + transition_at: str, + accepted_at: str | None = None, + parked_at: str | None = None, + response_ready_at: str | None = None, + wake_started_at: str | None = None, + last_error: str = "", + clear_error: bool = False, + state_cls: type, + conflict_error_cls: type[Exception], +) -> ProgramTransitionResult: + """Project a monotonic program-request lifecycle transition.""" + if existing is not None and ( + existing.rollout_id != rollout_id + or existing.sandbox_id != route.sandbox_id + or existing.sandbox_generation != route.generation + ): + raise conflict_error_cls( + "program request id belongs to another rollout or sandbox" + ) + effective_state = state + if ( + existing is not None + and PROGRAM_STATE_RANK[existing.state] > PROGRAM_STATE_RANK[state] + ): + effective_state = existing.state + timestamps = { + "accepted_at": existing.accepted_at if existing else "", + "parked_at": existing.parked_at if existing else "", + "response_ready_at": existing.response_ready_at if existing else "", + "wake_started_at": existing.wake_started_at if existing else "", + "wake_completed_at": existing.wake_completed_at if existing else "", + } + if accepted_at and not timestamps["accepted_at"]: + timestamps["accepted_at"] = accepted_at + if not timestamps["accepted_at"]: + timestamps["accepted_at"] = transition_at + if parked_at and not timestamps["parked_at"]: + timestamps["parked_at"] = parked_at + if response_ready_at and not timestamps["response_ready_at"]: + timestamps["response_ready_at"] = response_ready_at + if wake_started_at and not timestamps["wake_started_at"]: + timestamps["wake_started_at"] = wake_started_at + transition_field = { + "ready_to_wake": "response_ready_at", + "waking": "wake_started_at", + "acting": "wake_completed_at", + }.get(state) + if transition_field and not timestamps[transition_field]: + timestamps[transition_field] = transition_at + advanced = bool( + existing is not None + and PROGRAM_STATE_RANK[effective_state] > PROGRAM_STATE_RANK[existing.state] + ) + error = ( + last_error + if last_error + else ( + "" + if clear_error or advanced + else (existing.last_error if existing else "") + ) + ) + if existing is not None and ( + existing.state == effective_state + and existing.resources == route.resources + and existing.accepted_at == timestamps["accepted_at"] + and existing.parked_at == timestamps["parked_at"] + and existing.response_ready_at == timestamps["response_ready_at"] + and existing.wake_started_at == timestamps["wake_started_at"] + and existing.wake_completed_at == timestamps["wake_completed_at"] + and existing.last_error == error + ): + return ProgramTransitionResult(state=existing, changed=False) + projected = state_cls( + request_id=request_id, + rollout_id=rollout_id, + sandbox_id=route.sandbox_id, + sandbox_generation=route.generation, + state=effective_state, + resources=ResourceQuantity.from_dict(route.resources.to_dict()), + **timestamps, + updated_at=transition_at, + last_error=error, + ) + return ProgramTransitionResult(state=projected, changed=True) + + +def validate_sandbox_state_transition_args( + *, + expected_states: Iterable[str], + state: str, + node_epoch: str | None = None, + activity_epoch: int | None = None, +) -> ValidatedLifecycleProof: + expected = frozenset( + str(item or "unknown").strip().lower() for item in expected_states + ) + cleaned_state = str(state).strip() + if not expected or not cleaned_state: + raise ValueError("expected and destination sandbox states are required") + if (node_epoch is None) != (activity_epoch is None): + raise ValueError("node_epoch and activity_epoch must be supplied together") + lifecycle_node_epoch: str | None = None + lifecycle_activity_epoch: int | None = None + if node_epoch is not None: + lifecycle_node_epoch = node_epoch.strip() + if not lifecycle_node_epoch: + raise ValueError("lifecycle node_epoch must be nonempty") + if isinstance(activity_epoch, bool) or not isinstance(activity_epoch, int): + raise ValueError("lifecycle activity_epoch must be an integer") + if activity_epoch < 0: + raise ValueError("lifecycle activity_epoch must be non-negative") + lifecycle_activity_epoch = activity_epoch + return ValidatedLifecycleProof( + expected_states=expected, + destination_state=cleaned_state, + node_epoch=lifecycle_node_epoch, + activity_epoch=lifecycle_activity_epoch, + ) + + +def plan_sandbox_state_transition( + current: Any | None, + route: Any, + proof: ValidatedLifecycleProof, + *, + same_incarnation: Any, + updated_at: str, + storage_schema: str | None = None, + snapshot_manifest_digest: str | None = None, + snapshot_repository: str | None = None, + snapshot_tag: str | None = None, + storage_snapshot: dict[str, Any] | None = None, +) -> Any | None: + """Return the updated SandboxRoute if the lifecycle proof is current, else None.""" + if ( + current is None + or (current.state or "unknown").lower() not in proof.expected_states + or not same_incarnation(current, route) + or current.worker_state != route.worker_state + or bool(current.delete_operation_id) + or ( + proof.node_epoch is not None + and ( + proof.activity_epoch is None + or proof.activity_epoch <= route.activity_epoch + or bool(route.node_epoch and route.node_epoch != proof.node_epoch) + or bool(current.node_epoch and current.node_epoch != proof.node_epoch) + or current.activity_epoch > proof.activity_epoch + ) + ) + ): + return None + return replace( + current, + state=proof.destination_state, + node_epoch=( + current.node_epoch if proof.node_epoch is None else proof.node_epoch + ), + activity_epoch=( + current.activity_epoch + if proof.activity_epoch is None + else proof.activity_epoch + ), + storage_schema=( + current.storage_schema if storage_schema is None else storage_schema + ), + snapshot_manifest_digest=( + current.snapshot_manifest_digest + if snapshot_manifest_digest is None + else snapshot_manifest_digest + ), + snapshot_repository=( + current.snapshot_repository + if snapshot_repository is None + else snapshot_repository + ), + snapshot_tag=current.snapshot_tag if snapshot_tag is None else snapshot_tag, + storage_snapshot=( + current.storage_snapshot + if storage_snapshot is None + else dict(storage_snapshot) + ), + updated_at=updated_at, + ) + + +def plan_observed_route_updates( + existing_by_id: dict[str, Any], + observations: tuple[SandboxInventoryEntry, ...], + *, + node_id: str, + job_id: str, + node_url: str, + observed_at: str, + node_epoch: str, + activity_epoch: int, + route_with_inventory_snapshot: Any, + route_update_is_current: Any, +) -> ObservedRouteUpdates: + """Compute route writes, touch-only updates, and dependency records from inventory.""" + working = dict(existing_by_id) + writes: list[Any] = [] + touched_ids: set[str] = set() + accepted_ids: set[str] = set() + stale_snapshot_routes: list[Any] = [] + dependencies: list[StorageDependencyWrite] = [] + unique_observations = len({item.sandbox_id for item in observations}) == len( + observations + ) + + for item in observations: + existing = working.get(item.sandbox_id) + if existing is None: + continue + observed_state = item.route_state + if observed_state is None: + continue + parked = observed_state == "parked" + published_snapshot = bool(parked and item.storage_snapshot) + validated_snapshot = None + if published_snapshot: + try: + validated_snapshot = route_with_inventory_snapshot(existing, item) + except ValueError: + published_snapshot = False + candidate = replace( + existing, + node_id=node_id, + job_id=job_id, + node_url=node_url, + resources=( + item.resources + if item.resources != ResourceQuantity() + else existing.resources + ), + state=observed_state, + generation=item.generation, + create_operation_id=item.operation_id, + spec_hash=item.spec_hash, + node_epoch=node_epoch, + activity_epoch=max(0, activity_epoch), + storage_schema=( + validated_snapshot.storage_schema + if published_snapshot + else (existing.storage_schema if parked else "") + ), + snapshot_manifest_digest=( + validated_snapshot.snapshot_manifest_digest + if published_snapshot + else (existing.snapshot_manifest_digest if parked else "") + ), + snapshot_repository=( + validated_snapshot.snapshot_repository + if published_snapshot + else (existing.snapshot_repository if parked else "") + ), + snapshot_tag=( + validated_snapshot.snapshot_tag + if published_snapshot + else (existing.snapshot_tag if parked else "") + ), + storage_snapshot=( + dict(validated_snapshot.storage_snapshot) + if published_snapshot + else (dict(existing.storage_snapshot) if parked else {}) + ), + updated_at=observed_at, + ) + if candidate.generation != existing.generation: + continue + if not route_update_is_current( + existing, candidate, allow_node_epoch_adoption=False + ): + continue + if existing.snapshot_manifest_digest and ( + existing.snapshot_manifest_digest != candidate.snapshot_manifest_digest + or existing.snapshot_repository != candidate.snapshot_repository + or existing.snapshot_tag != candidate.snapshot_tag + ): + stale_snapshot_routes.append(existing) + if ( + replace( + candidate, + activity_epoch=existing.activity_epoch, + updated_at=existing.updated_at, + ) + == existing + ): + touched_ids.add(candidate.sandbox_id) + else: + writes.append(candidate) + working[candidate.sandbox_id] = candidate + accepted_ids.add(candidate.sandbox_id) + if item.storage_dependency is not None: + dependency = item.storage_dependency + if dependency: + dependency = StorageSnapshotPublication.from_dict(dependency).to_dict() + dependencies.append( + StorageDependencyWrite( + sandbox_id=candidate.sandbox_id, + generation=candidate.generation, + publication=dependency if dependency else None, + ) + ) + + return ObservedRouteUpdates( + writes=tuple(writes), + touched_ids=frozenset(touched_ids), + accepted_ids=frozenset(accepted_ids), + stale_snapshot_routes=tuple(stale_snapshot_routes), + storage_dependencies=tuple(dependencies), + unique_observations=unique_observations, + ) + + +def classify_absent_node_routes( + current_routes: Iterable[Any], + *, + reported_ids: set[str] | frozenset[str], + inventory_complete: bool, + node_epoch: str, + activity_epoch: int, + observed_at_dt: datetime | None, + owner_loss_disposition: Any, + recover_detached_value: Any, +) -> AbsentRoutePlan: + """Classify routes absent from a node's inventory into detaches vs deletes.""" + detach: list[Any] = [] + delete: list[Any] = [] + clamped_activity = max(0, activity_epoch) + for route in current_routes: + if route.sandbox_id in reported_ids or not inventory_complete: + continue + if route.node_epoch and route.node_epoch != node_epoch: + continue + if (route.state or "unknown").lower() in {"creating", "unknown"}: + continue + if route.activity_epoch > clamped_activity: + continue + route_updated_at = parse_iso_datetime(route.updated_at) or parse_iso_datetime( + route.created_at + ) + if not ( + observed_at_dt is None + or route_updated_at is None + or route_updated_at <= observed_at_dt + ): + continue + if owner_loss_disposition(route) is recover_detached_value: + detach.append(route) + else: + delete.append(route) + return AbsentRoutePlan(detach=tuple(detach), delete=tuple(delete)) + + +def plan_node_epoch_retirement( + routes: Iterable[Any], + retired_node_epochs: Iterable[str], + *, + node_epoch: str, + activity_epoch: int, + inventory: Iterable[SandboxInventoryEntry] | None, + observed_at: str, + owner_loss_disposition: Any, + terminal_delete_value: Any, + recover_detached_value: Any, +) -> EpochRetirementPlan: + """Settle routes owned by retired boot epochs of a worker.""" + retired = {str(epoch) for epoch in retired_node_epochs} - {"", node_epoch} + if not node_epoch or not retired: + return EpochRetirementPlan((), (), (), ()) + parked = { + (item.sandbox_id, item.generation, item.operation_id, item.spec_hash) + for item in inventory or () + if item.route_state == "parked" + } + pending_deletes: list[Any] = [] + readopted_routes: list[Any] = [] + detach_routes: list[Any] = [] + lost_routes: list[Any] = [] + clamped_activity = max(0, activity_epoch) + + for route in routes: + if route is None or route.node_epoch not in retired: + continue + disposition = owner_loss_disposition(route) + if disposition is terminal_delete_value: + pending_deletes.append(route) + elif ( + route.worker_state == "attached" + and ( + route.sandbox_id, + route.generation, + route.create_operation_id, + route.spec_hash, + ) + in parked + ): + readopted_routes.append( + replace( + route, + state="parked", + node_epoch=node_epoch, + activity_epoch=clamped_activity, + updated_at=observed_at, + ) + ) + elif disposition is recover_detached_value: + detach_routes.append(route) + else: + lost_routes.append(route) + + return EpochRetirementPlan( + pending_deletes=tuple(pending_deletes), + readopted_routes=tuple(readopted_routes), + detach_routes=tuple(detach_routes), + lost_routes=tuple(lost_routes), + ) diff --git a/sandboxes/sandbox.py b/sandboxes/sandbox.py index 2ca28d7b..6d09d546 100644 --- a/sandboxes/sandbox.py +++ b/sandboxes/sandbox.py @@ -620,7 +620,7 @@ def from_dict(cls, raw: dict[str, Any]) -> "SandboxSpec": toolkits=_json_string_list(raw.get("toolkits", []), "toolkits"), ) - def validate(self) -> None: + def _validate_identity_and_env(self) -> None: if not SANDBOX_ID_RE.match(self.id): raise ValueError( "sandbox id must be 1-64 characters of letters, digits, _, . or - " @@ -628,11 +628,16 @@ def validate(self) -> None: ) if not self.image.strip() or "\0" in self.image: raise ValueError("sandbox image is required.") - if self.environment_root is not None and not ENVIRONMENT_ROOT_RE.fullmatch(self.environment_root): + if self.environment_root is not None and not ENVIRONMENT_ROOT_RE.fullmatch( + self.environment_root + ): raise ValueError("environment_root must be a sha256 digest.") if len(self.toolkits) > MAX_TOOLKITS: raise ValueError(f"at most {MAX_TOOLKITS} toolkits are supported.") - names = [match[1] if (match := TOOLKIT_REF_RE.fullmatch(ref)) else None for ref in self.toolkits] + names = [ + match[1] if (match := TOOLKIT_REF_RE.fullmatch(ref)) else None + for ref in self.toolkits + ] if None in names: raise ValueError("toolkits must be name:tag or name@sha256:.") if len(set(names)) != len(names): @@ -656,6 +661,8 @@ def validate(self) -> None: "sandbox labels must not use the reserved " f"{SANDBOX_RESERVED_LABEL_PREFIX!r} prefix: {reserved_labels[0]!r}" ) + + def _validate_resources_and_lifecycle(self) -> None: if self.memory_mb is not None and self.memory_mb <= 0: raise ValueError("memory_mb must be positive.") if self.cpus is not None and self.cpus <= 0: @@ -693,6 +700,12 @@ def validate(self) -> None: raise ValueError( "profile must be one of: " + ", ".join(sorted(SANDBOX_PROFILES)) ) + if self.managed_process and self.security.supplementary_groups: + raise ValueError( + "managed_process does not yet support supplementary groups" + ) + + def _validate_networking_and_subspecs(self) -> None: if not isinstance(self.network_policy, SandboxNetworkPolicy): raise ValueError("network_policy must be a SandboxNetworkPolicy") if self.network_policy.egress == "relay": @@ -704,10 +717,6 @@ def validate(self) -> None: ) if self.network not in {"none", "bridge"}: raise ValueError("network must be either 'none' or 'bridge'.") - if self.managed_process and self.security.supplementary_groups: - raise ValueError( - "managed_process does not yet support supplementary groups" - ) from .environment_contract import validate_requirements if len(self.required_features) > 64 or any( @@ -731,6 +740,11 @@ def validate(self) -> None: if self.ssh.enabled and self.network != "bridge": raise ValueError("ssh-enabled sandboxes must use bridge networking.") + def validate(self) -> None: + self._validate_identity_and_env() + self._validate_resources_and_lifecycle() + self._validate_networking_and_subspecs() + def to_dict(self) -> dict[str, Any]: raw = asdict(self) if self.network_policy.egress == "direct": diff --git a/sandboxes/shared_control/relay.py b/sandboxes/shared_control/relay.py index cf5552a4..4384a3c4 100644 --- a/sandboxes/shared_control/relay.py +++ b/sandboxes/shared_control/relay.py @@ -28,6 +28,12 @@ from ..telemetry import Telemetry from .database import PostgresDatabase from .model import cancel_until_done +from .relay_transitions import ( + RetryLifecycle, + canonicalize_relay_request, + classify_wait_mode, + plan_lifecycle_dispatch_outcome, +) LOGGER = logging.getLogger(__name__) # Reserve response space BEFORE accepting work. This is a durable-storage safety @@ -617,32 +623,17 @@ async def enqueue( ) if idempotency_key is not None: api.validate_idempotency_key(idempotency_key) - identity_headers = { - k: v - for k, v in headers.items() - if k.lower() - not in { - "baggage", - "traceparent", - "tracestate", - "x-correlation-id", - "x-request-id", - "x-stainless-read-timeout", - "x-stainless-retry-count", - } - } - metadata = json.dumps( - dict(endpoint=endpoint, method=method, headers=identity_headers), - sort_keys=True, - separators=(",", ":"), - ensure_ascii=False, - ).encode() - digest = hashlib.sha256( - b"\0".join( - (rollout_id.encode(), endpoint.encode(), method.encode(), metadata, raw) - ) - ).hexdigest() - size = len(raw) + len(metadata) + canonical = canonicalize_relay_request( + rollout_id=rollout_id, + endpoint=endpoint, + method=method, + headers=headers, + raw_body=raw, + response_reservation=RESPONSE_RESERVATION, + ) + digest = canonical.digest + size = canonical.payload_bytes + reserved = canonical.reserved_bytes async with self.store.transaction("relay_enqueue") as conn: reg = await self._registration(conn, rollout_id, expected_registration_token) token = reg["registration_token"] @@ -664,12 +655,15 @@ async def enqueue( text="idempotency key was already used for a different relay request" ) return await self._load(conn, existing["request_id"]) - reserved = size + RESPONSE_RESERVATION now = await self._now(conn) request_id = uuid4().hex sandbox_id = api._registration_sandbox_id(reg) - local = bool(local_wait and self.local_model_waits and sandbox_id) - park = bool(sandbox_id and self.notifiers["park"] and not local) + local, park = classify_wait_mode( + sandbox_id=sandbox_id, + local_wait_requested=local_wait, + local_model_waits_enabled=bool(self.local_model_waits), + has_park_notifier=bool(self.notifiers["park"]), + ) await conn.execute( """INSERT INTO relay_requests(deployment_id,request_id,rollout_id,registration_token,endpoint,method, created_at,expires_at,payload_bytes,reserved_bytes,state,idempotency_key,request_digest,reattachable,sandbox_id,sandbox_generation, @@ -1638,22 +1632,32 @@ async def _dispatch_claimed(self, work): or current["claim_token"] != work["claim_token"] ): return - if failure or deferred is not None: - if action == 'park' and epoch is not None: - # A retained sandbox can park locally as pressure changes. - # The worker accepted ownership of the local park decision. - # Publish that receipt with its original transport as one - # monotonic pair; SDK lease renewal observes this state. - # This is not a claim that checkpointing has completed. + plan = plan_lifecycle_dispatch_outcome( + action=action, + attempts=work["attempts"], + parked_transport_epoch=row["parked_transport_epoch"], + wake_transport_epoch=row["wake_transport_epoch"], + result_epoch=epoch, + unavailable=unavailable, + failure=failure, + deferred=deferred, + ) + if isinstance(plan, RetryLifecycle): + if plan.record_park_epoch is not None: await conn.execute( "UPDATE relay_requests SET accepted_notified_at=COALESCE(accepted_notified_at,%s),parked_transport_epoch=COALESCE(parked_transport_epoch,%s) WHERE deployment_id=%s AND request_id=%s", - (await self._now(conn), epoch, self.deployment, request_id), + ( + await self._now(conn), + plan.record_park_epoch, + self.deployment, + request_id, + ), ) await conn.execute( "UPDATE relay_lifecycle SET claim_token=NULL,claim_until=NULL,last_error=%s,next_attempt_at=clock_timestamp()+%s*interval '1 second' WHERE deployment_id=%s AND request_id=%s AND action=%s", ( - failure, - deferred if deferred is not None else min(5, 0.05 * 2 ** min(work["attempts"], 7)), + plan.last_error, + plan.delay_seconds, self.deployment, request_id, action, @@ -1661,41 +1665,31 @@ async def _dispatch_claimed(self, work): ) return now = await self._now(conn) - if action == "wake": - # Response remains available even if its caller definitively died. + if plan.action == "wake": await conn.execute( "UPDATE relay_requests SET wake_notified_at=%s,wake_transport_epoch=%s,delivery_pending=false,delivery_released_at=%s WHERE deployment_id=%s AND request_id=%s", ( - None if unavailable else now, - epoch, + now if plan.wake_notified else None, + plan.epoch, now, self.deployment, request_id, ), ) - if ( - epoch is not None - and row["parked_transport_epoch"] is not None - and epoch != row["parked_transport_epoch"] - ): + if plan.reattach_required: await self._reattach(conn, row) await self._notify(conn, "r:" + request_id) else: await conn.execute( "UPDATE relay_requests SET accepted_notified_at=COALESCE(accepted_notified_at,%s),parked_transport_epoch=COALESCE(parked_transport_epoch,%s) WHERE deployment_id=%s AND request_id=%s", - (now, epoch, self.deployment, request_id), + (now, plan.epoch, self.deployment, request_id), ) - original_epoch = row["parked_transport_epoch"] or epoch - if ( - original_epoch is not None - and row["wake_transport_epoch"] is not None - and original_epoch != row["wake_transport_epoch"] - ): + if plan.reattach_required: await self._reattach(conn, row) await conn.execute( "UPDATE relay_lifecycle SET done=true,claim_token=NULL,claim_until=NULL,last_error=%s WHERE deployment_id=%s AND request_id=%s AND action=%s", ( - "caller_unavailable" if unavailable else None, + plan.last_error, self.deployment, request_id, action, diff --git a/sandboxes/shared_control/relay_transitions.py b/sandboxes/shared_control/relay_transitions.py new file mode 100644 index 00000000..5e0d5681 --- /dev/null +++ b/sandboxes/shared_control/relay_transitions.py @@ -0,0 +1,158 @@ +"""Pure relay request canonicalization and lifecycle-dispatch state transitions. + +No PostgreSQL, aiohttp, or wall clocks: ``PostgresRelayState`` loads rows, +calls these functions, and applies the resulting SQL mutations. +""" + +from __future__ import annotations + +from dataclasses import dataclass +import hashlib +import json +from typing import Mapping + +TRANSIENT_IDENTITY_HEADERS: frozenset[str] = frozenset( + { + "baggage", + "traceparent", + "tracestate", + "x-correlation-id", + "x-request-id", + "x-stainless-read-timeout", + "x-stainless-retry-count", + } +) + + +@dataclass(frozen=True) +class CanonicalRelayRequest: + endpoint: str + method: str + digest: str + payload_bytes: int + reserved_bytes: int + + +@dataclass(frozen=True) +class RetryLifecycle: + delay_seconds: float + last_error: str | None + record_park_epoch: str | None + + +@dataclass(frozen=True) +class CompleteLifecycle: + action: str + wake_notified: bool + epoch: str | None + reattach_required: bool + last_error: str | None + + +LifecycleDispatchPlan = RetryLifecycle | CompleteLifecycle + + +def canonicalize_relay_request( + *, + rollout_id: str, + endpoint: str, + method: str, + headers: Mapping[str, str], + raw_body: bytes, + response_reservation: int, +) -> CanonicalRelayRequest: + """Compute canonical identity digest and durable byte accounting for a relay request.""" + identity_headers = { + key: value + for key, value in headers.items() + if key.lower() not in TRANSIENT_IDENTITY_HEADERS + } + metadata = json.dumps( + dict(endpoint=endpoint, method=method, headers=identity_headers), + sort_keys=True, + separators=(",", ":"), + ensure_ascii=False, + ).encode() + digest = hashlib.sha256( + b"\0".join( + (rollout_id.encode(), endpoint.encode(), method.encode(), metadata, raw_body) + ) + ).hexdigest() + size = len(raw_body) + len(metadata) + return CanonicalRelayRequest( + endpoint=endpoint, + method=method, + digest=digest, + payload_bytes=size, + reserved_bytes=size + response_reservation, + ) + + +def classify_wait_mode( + *, + sandbox_id: str | None, + local_wait_requested: bool, + local_model_waits_enabled: bool, + has_park_notifier: bool, +) -> tuple[bool, bool]: + """Return (use_local_wait, enqueue_park_obligation) for an accepted relay call.""" + local = bool(local_wait_requested and local_model_waits_enabled and sandbox_id) + park = bool(sandbox_id and has_park_notifier and not local) + return local, park + + +def lifecycle_retry_delay_seconds( + attempts: int, + *, + deferred: float | None = None, +) -> float: + """Bounded exponential retry delay unless the worker asked for a specific deferral.""" + if deferred is not None: + return deferred + return min(5.0, 0.05 * (2 ** min(max(0, attempts), 7))) + + +def plan_lifecycle_dispatch_outcome( + *, + action: str, + attempts: int, + parked_transport_epoch: str | None, + wake_transport_epoch: str | None, + result_epoch: str | None, + unavailable: bool, + failure: str | None, + deferred: float | None, +) -> LifecycleDispatchPlan: + """Decide whether a dispatched park/wake obligation retries or completes (+ reattach).""" + if failure or deferred is not None: + return RetryLifecycle( + delay_seconds=lifecycle_retry_delay_seconds(attempts, deferred=deferred), + last_error=failure, + record_park_epoch=result_epoch if action == "park" else None, + ) + if action == "wake": + reattach = bool( + result_epoch is not None + and parked_transport_epoch is not None + and result_epoch != parked_transport_epoch + ) + return CompleteLifecycle( + action="wake", + wake_notified=not unavailable, + epoch=result_epoch, + reattach_required=reattach, + last_error="caller_unavailable" if unavailable else None, + ) + original_epoch = parked_transport_epoch or result_epoch + reattach = bool( + original_epoch is not None + and wake_transport_epoch is not None + and original_epoch != wake_transport_epoch + ) + return CompleteLifecycle( + action="park", + wake_notified=False, + epoch=result_epoch, + reattach_required=reattach, + last_error="caller_unavailable" if unavailable else None, + ) diff --git a/sandboxes/standalone_noded_config.py b/sandboxes/standalone_noded_config.py new file mode 100644 index 00000000..7d15a1b3 --- /dev/null +++ b/sandboxes/standalone_noded_config.py @@ -0,0 +1,406 @@ +"""Render the JSON configuration consumed by standalone Rust `ucloud-noded` +(`ucloud-noded --standalone-config /etc/ucloud-sandboxes/noded-standalone.json`). + +Matches `runtime/noded/src/standalone.rs::StandaloneConfig`, +`runtime/noded/src/pipeline.rs::CreateConfig`, and +`runtime/noded/src/heartbeat.rs::HeartbeatConfig` field-for-field. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import sys +from pathlib import Path +from typing import Any +from uuid import UUID, uuid4 + +from .admission_decision import PHYSICAL_MEMORY_FLOOR_MB, RETRY_SECONDS +from .capabilities import ( + ARCHIVE_UPLOAD_CAPABILITY, + COMMIT_EXPORT_CAPABILITY, + DISK_QUOTA_CAPABILITY, + ENVIRONMENT_CONTRACT_CAPABILITY, + ENVIRONMENT_RAFS_CAPABILITY, + ENVIRONMENT_ROOT_CAPABILITY, + HIBERNATE_LOCAL_CAPABILITY, + HOST_EROFS_CAPABILITY, + MANAGED_PRIMARY_CAPABILITY, + RELAY_WAKE_FENCE_CAPABILITY, + REQUEST_BODY_KEEPALIVE_CAPABILITY, + RUNTIME_COMPATIBILITY_CAPABILITY_PREFIX, + RUNTIME_CPU_CAPABILITY_PREFIX, + SPLIT_CHECKPOINT_CAPABILITY, + STATIC_FILE_MANAGEMENT_CAPABILITY, + STORAGE_NATIVE_CAPABILITY, + STORAGE_NATIVE_DETACH_CAPABILITY, + STORAGE_NATIVE_MIGRATION_CAPABILITY, +) +from .direct_network import DirectNetworkTcpEgress +from .pause_tier import PREFETCH_MAX_BYTES +from .relay_network import parse_network_relays + +DEFAULT_STANDALONE_NODED_CONFIG_PATH = "/etc/ucloud-sandboxes/noded-standalone.json" +_GROWTH_OBSERVATION_MAX_AGE_SECONDS = 30.0 +_PUBLICATION_LANES = 16 + + +def _host_boot_epoch(boot_id_path: Path = Path("/proc/sys/kernel/random/boot_id")) -> str: + try: + raw = boot_id_path.read_text(encoding="utf-8").strip() + return UUID(raw).hex + except (OSError, ValueError): + return uuid4().hex + + +def build_standalone_noded_config( + *, + job_id: str, + node_id: str, + node_url: str, + deployment_id: str, + agent_version: str, + init_version: str, + state_root: str, + image_cache_root: str, + volume_mount_root: str, + storage_native_socket: str, + runsc: str, + runsc_commit: str = "", + init_binary: str, + managed_init_binary: str, + network: str, + total_vcpu: float, + total_memory_mb: int, + total_disk_mb: int, + memory_backing_hard_capacity_bytes: int, + application_memory_root: str | None = None, + workspace_initial_grant_mb: int = 512, + max_concurrent_startups: int = 8, + max_concurrent_restores: int = 8, + max_concurrent_image_pulls: int = 8, + idle_park_seconds: float = 0.0, + direct_network_allow_tcp: tuple[str, ...] = (), + network_relays: dict[str, str] | None = None, + environment_registry_url: str = "", + environment_registry_repository: str = "", + environment_backend_socket: str = "", + environment_rafs: bool = False, + trusted_keys_file: str | None = None, + checkpoint_registry_url: str | None = None, + checkpoint_registry_repository: str | None = None, + heartbeat_url: str | None = None, + heartbeat_bearer_token: str | None = None, + heartbeat_interval_seconds: float = 20.0, + labels: dict[str, str] | None = None, + node_epoch: str | None = None, + runtime_compatibility_sha256: str = "", + cpu_features_sha256: str = "", +) -> dict[str, Any]: + state_path = Path(state_root) + runtime_root = str(state_path / "runsc-root") + bundle_root = str(state_path / "bundles") + journal_root = str(state_path / "journals") + resolved_epoch = (node_epoch or "").strip() or _host_boot_epoch() + + resolved_compat = runtime_compatibility_sha256 + resolved_cpu = cpu_features_sha256 + if not resolved_compat and runsc_commit and Path(runsc).is_file(): + import os + + from .direct_runtime import _cpu_features_sha256, _sha256_file, boot_config_sha256 + from .hibernation import HibernationRuntimeFingerprint + + runsc_path = Path(runsc) + fp = HibernationRuntimeFingerprint( + runsc_sha256=_sha256_file(runsc_path), + runsc_commit=runsc_commit, + platform="systrap", + architecture=os.uname().machine, + page_size=os.sysconf("SC_PAGE_SIZE"), + cpu_features_sha256=_cpu_features_sha256(), + boot_config_sha256=boot_config_sha256( + runsc_path, + runsc_commit, + network=network, + ram_backing=bool(application_memory_root), + ), + rootfs_sha256="0" * 64, + ) + resolved_compat = fp.node_compatibility_sha256 + resolved_cpu = resolved_cpu or fp.cpu_features_sha256 + if not resolved_compat: + resolved_compat = hashlib.sha256(f"{runsc}:{agent_version}".encode("utf-8")).hexdigest() + + allow_tcp_entries = [] + for raw_ep in direct_network_allow_tcp: + parsed = DirectNetworkTcpEgress.parse(raw_ep) + if not parsed.is_dynamic: + allow_tcp_entries.append({"ip": parsed.address, "port": parsed.port}) + + parsed_relays = parse_network_relays(network_relays or {}) + relay_hosts = { + f"{name}.relay.internal": relay.virtual_ip + for name, relay in sorted(parsed_relays.items()) + } + local_wait_endpoints = [] + for relay in parsed_relays.values(): + try: + import ipaddress + + ipaddress.IPv4Address(relay.host) + except ValueError: + continue + local_wait_endpoints.append({"ip": relay.host, "port": relay.port}) + + environment_cfg: dict[str, Any] | None = None + if environment_registry_url and environment_backend_socket: + environment_cfg = { + "registry_url": environment_registry_url, + "registry_repository": environment_registry_repository, + "backend_socket": environment_backend_socket, + "rafs": bool(environment_rafs), + } + + capabilities = [ + REQUEST_BODY_KEEPALIVE_CAPABILITY, + ENVIRONMENT_CONTRACT_CAPABILITY, + "sandbox", + "image-cache", + DISK_QUOTA_CAPABILITY, + HIBERNATE_LOCAL_CAPABILITY, + RELAY_WAKE_FENCE_CAPABILITY, + ARCHIVE_UPLOAD_CAPABILITY, + "direct-runsc-v1", + *(relay.capability for relay in parsed_relays.values()), + MANAGED_PRIMARY_CAPABILITY, + STATIC_FILE_MANAGEMENT_CAPABILITY, + STORAGE_NATIVE_CAPABILITY, + STORAGE_NATIVE_DETACH_CAPABILITY, + STORAGE_NATIVE_MIGRATION_CAPABILITY, + ] + if memory_backing_hard_capacity_bytes > 0 and checkpoint_registry_url: + capabilities.append(SPLIT_CHECKPOINT_CAPABILITY) + if resolved_compat: + capabilities.append(RUNTIME_COMPATIBILITY_CAPABILITY_PREFIX + resolved_compat) + if resolved_cpu: + capabilities.append(RUNTIME_CPU_CAPABILITY_PREFIX + resolved_cpu) + if environment_cfg is not None: + capabilities.extend((HOST_EROFS_CAPABILITY, ENVIRONMENT_ROOT_CAPABILITY)) + if environment_rafs: + capabilities.append(ENVIRONMENT_RAFS_CAPABILITY) + if checkpoint_registry_url: + capabilities.append(COMMIT_EXPORT_CAPABILITY) + + create_cfg: dict[str, Any] = { + "state_root": state_root, + "image_cache_root": image_cache_root, + "volume_mount_root": volume_mount_root, + "storage_native_socket": storage_native_socket, + "runsc": runsc, + "runtime_root": runtime_root, + "bundle_root": bundle_root, + "journal_root": journal_root, + "network": network, + "network_mtu": 1420, + "network_pool_size": 0 if network == "none" else 16, + "direct_network_allow_tcp": allow_tcp_entries, + "dns_named_egress": False, + "relays_configured": bool(parsed_relays), + "relay_hosts": relay_hosts, + "split_memory_backing": memory_backing_hard_capacity_bytes > 0, + "memory_backing_hard_capacity_bytes": int(memory_backing_hard_capacity_bytes), + "application_memory_root": application_memory_root or None, + "workspace_initial_grant_mb": int(workspace_initial_grant_mb), + "demonstrated_memory": True, + "init_binary": init_binary, + "managed_init_binary": managed_init_binary, + "environment": environment_cfg, + "runtime_compatibility_sha256": resolved_compat, + "node_epoch": resolved_epoch, + "exec": { + "runsc": runsc, + "runtime_root": runtime_root, + "warden_locks_dir": str(Path(runtime_root) / "warden-locks"), + "warden_paused_dir": str(Path(runtime_root) / "warden-paused"), + "active_capacity_configured": total_vcpu > 0 and total_memory_mb > 0, + "memory_floor_mib": PHYSICAL_MEMORY_FLOOR_MB, + "sessions": { + "max_sessions": 1024, + "max_events_per_session": 512, + "completed_retention_seconds": 30.0, + "delivered_grace_seconds": 2.0, + "output_idle_timeout_seconds": 300.0, + }, + "admission_wait_seconds": 30.0, + }, + "pause": { + "idle_park_seconds": float(idle_park_seconds), + "local_waits": { + "enabled": bool(local_wait_endpoints), + "endpoints": local_wait_endpoints, + }, + }, + "admission": { + "rust_admission_enabled": True, + "max_concurrent_startups": int(max_concurrent_startups), + "max_concurrent_restores": int(max_concurrent_restores), + "admission_wait_seconds": 30.0, + "active_capacity": ( + {"vcpu": float(total_vcpu), "memory_mb": int(total_memory_mb)} + if total_vcpu > 0 and total_memory_mb > 0 + else None + ), + "physical_memory_floor_mb": PHYSICAL_MEMORY_FLOOR_MB, + "growth_observation_max_age_seconds": _GROWTH_OBSERVATION_MAX_AGE_SECONDS, + "prefetch_max_bytes": PREFETCH_MAX_BYTES, + "publication_lanes": _PUBLICATION_LANES, + "retry_seconds": RETRY_SECONDS, + }, + "max_file_body_bytes": 256 * 1024 * 1024, + "config_sha256": "", + } + digest = hashlib.sha256( + json.dumps(create_cfg, sort_keys=True, separators=(",", ":")).encode("utf-8") + ).hexdigest() + create_cfg["config_sha256"] = digest + + heartbeat_cfg: dict[str, Any] = { + "job_id": job_id, + "node_id": node_id, + "node_url": node_url, + "agent_version": agent_version, + "deployment_id": deployment_id, + "init_version": init_version, + "node_epoch": resolved_epoch, + "capabilities": capabilities, + "total_vcpu": float(total_vcpu), + "total_memory_mb": int(total_memory_mb), + "total_disk_mb": int(total_disk_mb), + "physical_disk_path": volume_mount_root, + "labels": dict(labels or {}), + "push_url": heartbeat_url or None, + "push_bearer_token": heartbeat_bearer_token or None, + "push_interval_secs": float(heartbeat_interval_seconds), + } + + return { + "create": create_cfg, + "heartbeat": heartbeat_cfg, + "trusted_keys_file": trusted_keys_file or None, + "image_catalog_path": str(state_path / "images.json"), + "max_concurrent_image_pulls": int(max_concurrent_image_pulls), + "checkpoint_registry_url": checkpoint_registry_url or None, + "checkpoint_registry_repository": checkpoint_registry_repository or None, + "reconcile_interval_secs": 15.0, + } + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Write standalone ucloud-noded JSON configuration") + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--job-id", required=True) + parser.add_argument("--node-id", required=True) + parser.add_argument("--node-url", required=True) + parser.add_argument("--deployment-id", required=True) + parser.add_argument("--agent-version", default="") + parser.add_argument("--init-version", default="") + parser.add_argument("--state-root", required=True) + parser.add_argument("--image-cache-root", required=True) + parser.add_argument("--volume-mount-root", required=True) + parser.add_argument("--storage-native-socket", required=True) + parser.add_argument("--runsc", required=True) + parser.add_argument("--runsc-commit", default="") + parser.add_argument("--init-binary", required=True) + parser.add_argument("--managed-init-binary", required=True) + parser.add_argument("--network", default="none") + parser.add_argument("--total-vcpu", type=float, required=True) + parser.add_argument("--total-memory-mb", type=int, required=True) + parser.add_argument("--total-disk-mb", type=int, required=True) + parser.add_argument("--memory-backing-hard-capacity-bytes", type=int, default=0) + parser.add_argument("--application-memory-root", default="") + parser.add_argument("--workspace-initial-grant-mb", type=int, default=512) + parser.add_argument("--max-concurrent-startups", type=int, default=8) + parser.add_argument("--max-concurrent-restores", type=int, default=8) + parser.add_argument("--max-concurrent-image-pulls", type=int, default=8) + parser.add_argument("--idle-park-seconds", type=float, default=0.0) + parser.add_argument("--direct-network-allow-tcp", action="append", default=[]) + parser.add_argument("--network-relays-json", default="") + parser.add_argument("--environment-registry-url", default="") + parser.add_argument("--environment-registry-repository", default="") + parser.add_argument("--environment-backend-socket", default="") + parser.add_argument("--environment-rafs", action="store_true") + parser.add_argument("--trusted-keys-file", default="") + parser.add_argument("--checkpoint-registry-url", default="") + parser.add_argument("--checkpoint-registry-repository", default="") + parser.add_argument("--heartbeat-url", default="") + parser.add_argument("--heartbeat-bearer-token-file", default="") + parser.add_argument("--heartbeat-interval-seconds", type=float, default=20.0) + parser.add_argument("--heartbeat-label", action="append", default=[]) + args = parser.parse_args(argv) + + hb_token = "" + if args.heartbeat_bearer_token_file: + hb_token = Path(args.heartbeat_bearer_token_file).read_text(encoding="utf-8").strip() + + labels: dict[str, str] = {} + for entry in args.heartbeat_label: + if "=" in entry: + k, v = entry.split("=", 1) + labels[k] = v + + relays: dict[str, str] | None = None + if args.network_relays_json: + relays = json.loads(args.network_relays_json) + + payload = build_standalone_noded_config( + job_id=args.job_id, + node_id=args.node_id, + node_url=args.node_url, + deployment_id=args.deployment_id, + agent_version=args.agent_version, + init_version=args.init_version, + state_root=args.state_root, + image_cache_root=args.image_cache_root, + volume_mount_root=args.volume_mount_root, + storage_native_socket=args.storage_native_socket, + runsc=args.runsc, + runsc_commit=args.runsc_commit, + init_binary=args.init_binary, + managed_init_binary=args.managed_init_binary, + network=args.network, + total_vcpu=args.total_vcpu, + total_memory_mb=args.total_memory_mb, + total_disk_mb=args.total_disk_mb, + memory_backing_hard_capacity_bytes=args.memory_backing_hard_capacity_bytes, + application_memory_root=args.application_memory_root or None, + workspace_initial_grant_mb=args.workspace_initial_grant_mb, + max_concurrent_startups=args.max_concurrent_startups, + max_concurrent_restores=args.max_concurrent_restores, + max_concurrent_image_pulls=args.max_concurrent_image_pulls, + idle_park_seconds=args.idle_park_seconds, + direct_network_allow_tcp=tuple(args.direct_network_allow_tcp), + network_relays=relays, + environment_registry_url=args.environment_registry_url, + environment_registry_repository=args.environment_registry_repository, + environment_backend_socket=args.environment_backend_socket, + environment_rafs=args.environment_rafs, + trusted_keys_file=args.trusted_keys_file or None, + checkpoint_registry_url=args.checkpoint_registry_url or None, + checkpoint_registry_repository=args.checkpoint_registry_repository or None, + heartbeat_url=args.heartbeat_url or None, + heartbeat_bearer_token=hb_token or None, + heartbeat_interval_seconds=args.heartbeat_interval_seconds, + labels=labels, + ) + args.output.parent.mkdir(parents=True, exist_ok=True) + tmp = args.output.with_suffix(".tmp") + tmp.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8") + tmp.chmod(0o600) + tmp.replace(args.output) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/sandboxes/vm_init.py b/sandboxes/vm_init.py index 015ba5b9..a4e116d5 100644 --- a/sandboxes/vm_init.py +++ b/sandboxes/vm_init.py @@ -250,9 +250,9 @@ class VmInitOptions: direct_max_concurrent_startups: int = 8 direct_idle_park_seconds: float = 0.0 direct_ram_memory_backing: bool = False - direct_reflink_memory_restore: bool = False direct_pause_tier_zswap: bool = False direct_node_rust_admission: bool = False + direct_node_standalone_rust: bool = False direct_workspace_initial_grant_mb: int = 0 environment_registry_url: str = "" environment_repository: str = "" @@ -450,11 +450,63 @@ def _buildkit_setup_script(options: VmInitOptions, service_user: str) -> str: ''' -def render_vm_init_script(options: VmInitOptions) -> str: - validate_vm_init_options(options) - if options.role == "store": - from .chunk_store_node import store_init_script - return store_init_script(options) +@dataclass(frozen=True) +class _VmInitRenderContext: + options: VmInitOptions + work_dir: str + agent_bin: str + storage_agent_bin: str + docker_data_root: str + docker_quota_image: str + docker_quota_root: str + swap_file: str + state_dir: str + package_cache_dir: str + static_runtime_receipt: str + cached_agent_runtime_dir: str + direct_runsc: str + storage_native_backend: str + storage_native_backend_socket: str + storage_native_service_socket: str + storage_native_root: str + storage_native_cache_root: str + storage_native_backend_config: str + storage_native_resize_backend_config: str + env_file: str + node_service: str + storage_backend_service: str + storage_service: str + authorized_keys_shell: str + runtime_role: str + runtime_packages_python: str + runtime_kernel_modules_python: str + runtime_kernel_modules_shell: str + storage_publication_args: str + telemetry_args: str + writable_disk_mb: int + direct_agent_command: str + node_service_user: str + node_service_group: str + node_service_supplementary_groups: str + node_service_exec_start_pre: str + node_service_wants: str + node_service_after: str + node_service_requires: str + noded_setup: str + noded_start: str + environment_setup: str + environment_start: str + chunk_store_environment: str + buildkit_setup: str + buildkit_service_environment: str + memory_filesystem_prestart: str + storage_runtime_root: str + docker_registry_mirrors: list[str] + docker_insecure_registries: list[str] + nydusd_pin_check: str + + +def _build_vm_init_render_context(options: VmInitOptions) -> _VmInitRenderContext: work_dir = _clean_posix_path(options.work_dir) agent_bin = str(PurePosixPath(work_dir) / "bin" / "sandboxes") storage_agent_bin = str( @@ -583,8 +635,6 @@ def render_vm_init_script(options: VmInitOptions) -> str: ) if options.direct_ram_memory_backing: split_memory_flags += " --application-memory-root ${UCLOUD_APPLICATION_MEMORY_ROOT}" - if options.direct_reflink_memory_restore: - split_memory_flags += " --reflink-memory-restore" if options.direct_workspace_initial_grant_mb: split_memory_flags += ( f" --workspace-initial-grant-mb {options.direct_workspace_initial_grant_mb}" @@ -656,7 +706,93 @@ def render_vm_init_script(options: VmInitOptions) -> str: node_service_after = "network-online.target docker.service" node_service_requires = "docker.service" - if options.role == "sandbox": + if options.role == "sandbox" and options.direct_node_standalone_rust: + from .environment_bootstrap import SOCKET as ENV_SOCKET, TRUST_FILE as ENV_TRUST_FILE + from .standalone_noded_config import DEFAULT_STANDALONE_NODED_CONFIG_PATH + + host = options.node_agent_host + listen = f"[{host}]:{options.node_agent_port}" if ":" in host else f"{host}:{options.node_agent_port}" + env_backend_socket = ENV_SOCKET if options.environment_registry_url else "" + env_trusted_keys = ENV_TRUST_FILE if options.environment_registry_url else "" + standalone_cfg_cmd = ( + "env PYTHONPATH=\"$UCLOUD_AGENT_RUNTIME_DIR/site-packages\" /usr/bin/python3 -m sandboxes.standalone_noded_config" + f" --output {shlex.quote(DEFAULT_STANDALONE_NODED_CONFIG_PATH)}" + " --job-id \"${UCLOUD_JOB_ID}\"" + " --node-id \"${UCLOUD_NODE_ID}\"" + " --node-url \"${UCLOUD_NODE_URL}\"" + " --deployment-id \"${UCLOUD_DEPLOYMENT_ID}\"" + " --agent-version \"${UCLOUD_AGENT_VERSION}\"" + " --init-version \"${UCLOUD_INIT_VERSION}\"" + " --state-root \"${UCLOUD_STATE_DIR}/direct-runtime\"" + " --image-cache-root \"${UCLOUD_DIRECT_IMAGE_CACHE_ROOT}\"" + " --volume-mount-root \"${UCLOUD_STORAGE_NATIVE_MOUNT_ROOT}\"" + " --storage-native-socket \"${UCLOUD_STORAGE_NATIVE_SERVICE_SOCKET}\"" + " --runsc \"${UCLOUD_DIRECT_RUNSC}\"" + " --runsc-commit \"${UCLOUD_DIRECT_RUNSC_COMMIT}\"" + " --init-binary \"${UCLOUD_DIRECT_INIT_BINARY}\"" + " --managed-init-binary \"${UCLOUD_MANAGED_INIT}\"" + " --network \"${UCLOUD_DIRECT_NETWORK}\"" + " --total-vcpu \"${UCLOUD_TOTAL_VCPU}\"" + " --total-memory-mb \"${UCLOUD_TOTAL_MEMORY_MB}\"" + " --total-disk-mb \"${UCLOUD_DIRECT_WRITABLE_DISK_MB}\"" + " --memory-backing-hard-capacity-bytes \"${UCLOUD_STORAGE_NATIVE_HARD_CAPACITY_BYTES}\"" + + (" --application-memory-root \"${UCLOUD_APPLICATION_MEMORY_ROOT}\"" if options.direct_ram_memory_backing else "") + + (f" --workspace-initial-grant-mb {options.direct_workspace_initial_grant_mb}" if options.direct_workspace_initial_grant_mb else "") + + " --max-concurrent-startups \"${UCLOUD_DIRECT_MAX_CONCURRENT_STARTUPS}\"" + " --max-concurrent-restores \"${UCLOUD_DIRECT_MAX_CONCURRENT_RESTORES}\"" + " --max-concurrent-image-pulls \"${UCLOUD_MAX_CONCURRENT_IMAGE_PULLS}\"" + " --idle-park-seconds \"${UCLOUD_DIRECT_IDLE_PARK_SECONDS}\"" + + direct_network_allow_flags + + ( + f" --environment-registry-url {shlex.quote(options.environment_registry_url)}" + f" --environment-registry-repository {shlex.quote(options.environment_repository)}" + f" --environment-backend-socket {shlex.quote(env_backend_socket)}" + f" --trusted-keys-file {shlex.quote(env_trusted_keys)}" + if options.environment_registry_url + else "" + ) + + (" --environment-rafs" if options.environment_chunk_store_url else "") + + " --checkpoint-registry-url \"${UCLOUD_STORAGE_NATIVE_REGISTRY_URL}\"" + " --checkpoint-registry-repository \"${UCLOUD_STORAGE_NATIVE_REPOSITORY}\"" + f"{heartbeat_flags}" + ) + noded_requires = "ucloud-storage-native.service" + noded_after = "network-online.target ucloud-storage-native.service" + if options.environment_registry_url: + noded_requires += " ucloud-environment-io.service" + noded_after += " ucloud-environment-io.service" + noded_setup = f"""echo "Writing standalone Rust ucloud-noded configuration and systemd service" +$SUDO {standalone_cfg_cmd} +$SUDO tee {shlex.quote(noded_service)} >/dev/null <<'NODED_SERVICE' +[Unit] +Description=UCloud sandbox node daemon (standalone Rust ucloud-noded) +Wants=network-online.target {noded_requires} +After={noded_after} +Requires={noded_requires} + +[Service] +Type=simple +User=root +Group=root +ExecStart={DEFAULT_NODED} --listen {listen} --standalone-config {DEFAULT_STANDALONE_NODED_CONFIG_PATH} --node-control-token-file {shlex.quote(options.node_control_bearer_token_file)} +LimitNOFILE=65536 +Restart=always +RestartSec=1 + +[Install] +WantedBy=multi-user.target +NODED_SERVICE +if [ -e {shlex.quote(node_service)} ]; then + $SUDO systemctl disable --now ucloud-sandbox-node.service || true + $SUDO rm -f {shlex.quote(node_service)} +fi +""" + noded_start = ( + "$SUDO systemctl reset-failed ucloud-sandbox-noded.service || true\n" + "$SUDO systemctl enable ucloud-sandbox-noded.service\n" + "$SUDO systemctl restart ucloud-sandbox-noded.service\n" + ) + elif options.role == "sandbox": node_service_wants += " ucloud-sandbox-noded.service" node_service_after += " ucloud-sandbox-noded.service" host = options.node_agent_host @@ -746,7 +882,89 @@ def render_vm_init_script(options: VmInitOptions) -> str: nydusd_pin_check = ( ' [ "${UCLOUD_BUNDLED_NYDUSD_SHA256:-}" = ' + options.environment_chunk_nydusd_sha256 + ' ] || ' '{ echo "chunk_store.nydusd pins a nydusd this bundle does not carry" >&2; exit 1; }\n') - script = f"""#!/usr/bin/env bash + return _VmInitRenderContext( + options=options, + work_dir=work_dir, + agent_bin=agent_bin, + storage_agent_bin=storage_agent_bin, + docker_data_root=docker_data_root, + docker_quota_image=docker_quota_image, + docker_quota_root=docker_quota_root, + swap_file=swap_file, + state_dir=state_dir, + package_cache_dir=package_cache_dir, + static_runtime_receipt=static_runtime_receipt, + cached_agent_runtime_dir=cached_agent_runtime_dir, + direct_runsc=direct_runsc, + storage_native_backend=storage_native_backend, + storage_native_backend_socket=storage_native_backend_socket, + storage_native_service_socket=storage_native_service_socket, + storage_native_root=storage_native_root, + storage_native_cache_root=storage_native_cache_root, + storage_native_backend_config=storage_native_backend_config, + storage_native_resize_backend_config=storage_native_resize_backend_config, + env_file=env_file, + node_service=node_service, + storage_backend_service=storage_backend_service, + storage_service=storage_service, + authorized_keys_shell=authorized_keys_shell, + runtime_role=runtime_role, + runtime_packages_python=runtime_packages_python, + runtime_kernel_modules_python=runtime_kernel_modules_python, + runtime_kernel_modules_shell=runtime_kernel_modules_shell, + storage_publication_args=storage_publication_args, + telemetry_args=telemetry_args, + writable_disk_mb=writable_disk_mb, + direct_agent_command=direct_agent_command, + node_service_user=node_service_user, + node_service_group=node_service_group, + node_service_supplementary_groups=node_service_supplementary_groups, + node_service_exec_start_pre=node_service_exec_start_pre, + node_service_wants=node_service_wants, + node_service_after=node_service_after, + node_service_requires=node_service_requires, + noded_setup=noded_setup, + noded_start=noded_start, + environment_setup=environment_setup, + environment_start=environment_start, + chunk_store_environment=chunk_store_environment, + buildkit_setup=buildkit_setup, + buildkit_service_environment=buildkit_service_environment, + memory_filesystem_prestart=memory_filesystem_prestart, + storage_runtime_root=storage_runtime_root, + docker_registry_mirrors=docker_registry_mirrors, + docker_insecure_registries=docker_insecure_registries, + nydusd_pin_check=nydusd_pin_check, + ) + + +def _render_vm_init_header_and_env(ctx: _VmInitRenderContext) -> str: + options = ctx.options + work_dir = ctx.work_dir + agent_bin = ctx.agent_bin + storage_agent_bin = ctx.storage_agent_bin + docker_data_root = ctx.docker_data_root + docker_quota_image = ctx.docker_quota_image + docker_quota_root = ctx.docker_quota_root + swap_file = ctx.swap_file + state_dir = ctx.state_dir + package_cache_dir = ctx.package_cache_dir + static_runtime_receipt = ctx.static_runtime_receipt + cached_agent_runtime_dir = ctx.cached_agent_runtime_dir + direct_runsc = ctx.direct_runsc + storage_native_backend = ctx.storage_native_backend + storage_native_backend_socket = ctx.storage_native_backend_socket + storage_native_service_socket = ctx.storage_native_service_socket + storage_native_root = ctx.storage_native_root + storage_native_cache_root = ctx.storage_native_cache_root + storage_native_backend_config = ctx.storage_native_backend_config + storage_native_resize_backend_config = ctx.storage_native_resize_backend_config + authorized_keys_shell = ctx.authorized_keys_shell + runtime_role = ctx.runtime_role + writable_disk_mb = ctx.writable_disk_mb + docker_registry_mirrors = ctx.docker_registry_mirrors + docker_insecure_registries = ctx.docker_insecure_registries + return f"""#!/usr/bin/env bash set -euo pipefail if [ "$(id -u)" -eq 0 ]; then @@ -823,7 +1041,6 @@ def render_vm_init_script(options: VmInitOptions) -> str: UCLOUD_STORAGE_NATIVE_ROOT={shlex.quote(storage_native_root)} UCLOUD_STORAGE_NATIVE_MOUNT_ROOT=$UCLOUD_STORAGE_NATIVE_ROOT/mounts UCLOUD_DIRECT_RAM_MEMORY_BACKING={int(options.direct_ram_memory_backing)} -UCLOUD_DIRECT_REFLINK_MEMORY_RESTORE={int(options.direct_reflink_memory_restore)} UCLOUD_DIRECT_PAUSE_TIER_ZSWAP={int(options.direct_pause_tier_zswap)} UCLOUD_APPLICATION_MEMORY_ROOT=/run/ucloud-sandboxes/application-memory UCLOUD_APPLICATION_MEMORY_CAPACITY_BYTES={int(options.total_resources.memory_mb) * 1024**2} @@ -910,7 +1127,15 @@ def render_vm_init_script(options: VmInitOptions) -> str: $SUDO chmod 600 "$UCLOUD_NODE_CONTROL_BEARER_TOKEN_FILE" fi log_init_phase "users-and-secrets" +""" + +def _render_vm_init_packages_and_runtime(ctx: _VmInitRenderContext) -> str: + options = ctx.options + runtime_role = ctx.runtime_role + runtime_packages_python = ctx.runtime_packages_python + runtime_kernel_modules_python = ctx.runtime_kernel_modules_python + return f""" wait_for_base_image_initialization() {{ local cloud_init_status if ! command -v cloud-init >/dev/null 2>&1; then @@ -1433,7 +1658,13 @@ def verified_artifact(metadata: dict, file_name: str, label: str) -> str: fi command -v docker >/dev/null 2>&1 log_init_phase "runtime-bundle" +""" + +def _render_vm_init_host_and_storage(ctx: _VmInitRenderContext) -> str: + nydusd_pin_check = ctx.nydusd_pin_check + runtime_kernel_modules_shell = ctx.runtime_kernel_modules_shell + return f""" if [ "$UCLOUD_HOST_ALIASES_JSON" != "[]" ]; then echo "Installing host aliases" export UCLOUD_HOST_ALIASES_JSON @@ -1906,7 +2137,77 @@ def verified_artifact(metadata: dict, file_name: str, label: str) -> str: fi $SUDO usermod -aG docker "$UCLOUD_SERVICE_USER" log_init_phase "docker-daemon" +""" + +def _render_vm_init_python_and_services(ctx: _VmInitRenderContext) -> str: + work_dir = ctx.work_dir + env_file = ctx.env_file + node_service = ctx.node_service + storage_backend_service = ctx.storage_backend_service + storage_service = ctx.storage_service + storage_publication_args = ctx.storage_publication_args + telemetry_args = ctx.telemetry_args + direct_agent_command = ctx.direct_agent_command + node_service_user = ctx.node_service_user + node_service_group = ctx.node_service_group + node_service_supplementary_groups = ctx.node_service_supplementary_groups + node_service_exec_start_pre = ctx.node_service_exec_start_pre + node_service_wants = ctx.node_service_wants + node_service_after = ctx.node_service_after + node_service_requires = ctx.node_service_requires + noded_setup = ctx.noded_setup + noded_start = ctx.noded_start + environment_setup = ctx.environment_setup + environment_start = ctx.environment_start + chunk_store_environment = ctx.chunk_store_environment + buildkit_setup = ctx.buildkit_setup + buildkit_service_environment = ctx.buildkit_service_environment + memory_filesystem_prestart = ctx.memory_filesystem_prestart + storage_runtime_root = ctx.storage_runtime_root + standalone_rust = ctx.options.role == "sandbox" and ctx.options.direct_node_standalone_rust + node_unit_block = ( + "" + if standalone_rust + else f"""echo "Writing node-agent systemd service" +$SUDO tee {shlex.quote(node_service)} >/dev/null < str: STORAGE_SERVICE fi -{noded_setup}echo "Writing node-agent systemd service" -$SUDO tee {shlex.quote(node_service)} >/dev/null < str: $SUDO systemctl restart ucloud-storage-native-backend.service $SUDO systemctl restart ucloud-storage-native.service fi -{noded_start}$SUDO systemctl enable ucloud-sandbox-node.service -$SUDO systemctl restart ucloud-sandbox-node.service -NODE_AGENT_READY=0 +{noded_start}{node_start_block}NODE_AGENT_READY=0 for _ in $(seq 1 100); do if curl -fsS "http://127.0.0.1:${{UCLOUD_NODE_AGENT_PORT}}/healthz" >/dev/null; then NODE_AGENT_READY=1 @@ -2132,7 +2404,7 @@ def verified_artifact(metadata: dict, file_name: str, label: str) -> str: sleep 0.1 done if [ "$NODE_AGENT_READY" -ne 1 ]; then - $SUDO systemctl status ucloud-sandbox-node.service --no-pager -l || true + $SUDO systemctl status {health_failed_unit} --no-pager -l || true echo "Node agent did not become healthy after service start" >&2 exit 1 fi @@ -2140,12 +2412,25 @@ def verified_artifact(metadata: dict, file_name: str, label: str) -> str: echo "UCloud sandbox node init complete. Waiting for heartbeat readiness in the control plane." log_init_phase "systemd-services" """ - return script -def validate_vm_init_options(options: VmInitOptions) -> None: # noqa: C901 - from .environment_bootstrap import validate as validate_environment_bootstrap - validate_environment_bootstrap(options) +def render_vm_init_script(options: VmInitOptions) -> str: + validate_vm_init_options(options) + if options.role == "store": + from .chunk_store_node import store_init_script + return store_init_script(options) + ctx = _build_vm_init_render_context(options) + return "".join( + ( + _render_vm_init_header_and_env(ctx), + _render_vm_init_packages_and_runtime(ctx), + _render_vm_init_host_and_storage(ctx), + _render_vm_init_python_and_services(ctx), + ) + ) + + +def _validate_core_vm_init_options(options: VmInitOptions) -> None: if not options.job_id: raise ValueError("job id is required.") if not options.heartbeat_url: @@ -2165,134 +2450,158 @@ def validate_vm_init_options(options: VmInitOptions) -> None: # noqa: C901 if options.role not in {"sandbox", "builder", "store"}: raise ValueError("node role must be sandbox, builder or store") from .chunk_store_node import validate_store_options + validate_store_options(options) - for name in ("direct_ram_memory_backing", "direct_reflink_memory_restore", - "direct_pause_tier_zswap", "direct_node_rust_admission"): + for name in ( + "direct_ram_memory_backing", + "direct_pause_tier_zswap", + "direct_node_rust_admission", + "direct_node_standalone_rust", + ): if not isinstance(getattr(options, name), bool): raise ValueError(f"{name} must be a boolean") - if options.role != "sandbox" and (options.direct_ram_memory_backing or options.direct_reflink_memory_restore): + if options.role != "sandbox" and options.direct_ram_memory_backing: raise ValueError("split memory backing is only supported by sandbox workers") grant = options.direct_workspace_initial_grant_mb if isinstance(grant, bool) or not isinstance(grant, int) or (grant and grant < 512): raise ValueError("direct_workspace_initial_grant_mb must be 0 or at least 512") - if options.role == "sandbox": - if options.storage_native_snapshot_backend != "registry": - raise ValueError("split memory backing requires registry checkpoint publication; " - "S3 split checkpoints are unsupported") - if not re.fullmatch(r"[0-9a-f]{40}", options.direct_runsc_commit): - raise ValueError( - "direct runtime requires an exact 40-character runsc commit" - ) - if options.direct_network not in {"none", "sandbox"}: - raise ValueError( - "direct runtime network must be either 'none' or 'sandbox'." - ) - from .relay_network import parse_network_relays - - parse_network_relays(options.network_relays or {}) - if options.network_relays and options.direct_network != "sandbox": - raise ValueError("network relays require sandbox networking") - for endpoint in options.direct_network_allow_tcp: - DirectNetworkTcpEgress.parse(endpoint) - if options.direct_network == "none" and options.direct_network_allow_tcp: - raise ValueError("direct network TCP egress requires sandbox networking.") - if options.docker_quota_image_gb < 1: - raise ValueError( - "direct runtime requires bounded Docker image infrastructure." - ) - if not re.fullmatch(r"https?://[^/\s]+", options.storage_native_registry_url): - raise ValueError( - "direct runtime requires an HTTP(S) storage-native Registry origin" - ) - if options.storage_native_snapshot_backend not in {"registry", "s3"}: - raise ValueError("storage-native snapshot backend must be registry or s3") - if options.storage_native_snapshot_backend == "s3": - if not re.fullmatch(r"https?://[^\s]+", options.storage_native_s3_endpoint): - raise ValueError("storage-native S3 endpoint must be HTTP(S)") - if ( - not options.storage_native_s3_bucket - or "/" in options.storage_native_s3_bucket - or not options.storage_native_s3_region - or not options.storage_native_s3_prefix.strip("/") - ): - raise ValueError( - "storage-native S3 bucket, region, and prefix are required" - ) - if ( - not options.storage_native_s3_access_key_id - or not options.storage_native_s3_secret_access_key - ): - raise ValueError("storage-native S3 credentials are required") - if ( - not options.storage_native_repository - or options.storage_native_repository.startswith("/") - or options.storage_native_repository.endswith("/") - or not re.fullmatch( - r"[a-z0-9]+(?:[._/-][a-z0-9]+)*", - options.storage_native_repository, - ) - ): - raise ValueError("invalid storage-native repository") - if options.storage_native_cache_gb < 1: - raise ValueError("storage-native cache size must be positive.") - if options.storage_native_pool_low_watermark < 0: - raise ValueError("storage-native pool low watermark cannot be negative.") - if options.storage_native_pool_high_watermark < 1: - raise ValueError("storage-native pool high watermark must be positive.") + + +def _validate_sandbox_role_storage_options(options: VmInitOptions) -> None: + if options.storage_native_snapshot_backend not in {"registry", "s3"}: + raise ValueError("storage-native snapshot backend must be registry or s3") + if options.storage_native_snapshot_backend == "s3": + if not re.fullmatch(r"https?://[^\s]+", options.storage_native_s3_endpoint): + raise ValueError("storage-native S3 endpoint must be HTTP(S)") if ( - options.storage_native_pool_low_watermark - > options.storage_native_pool_high_watermark + not options.storage_native_s3_bucket + or "/" in options.storage_native_s3_bucket + or not options.storage_native_s3_region + or not options.storage_native_s3_prefix.strip("/") ): raise ValueError( - "storage-native pool low watermark cannot exceed high watermark." + "storage-native S3 bucket, region, and prefix are required" ) - if options.storage_native_max_ublk_devices < 0: - raise ValueError("storage-native maximum ublk devices cannot be negative.") if ( - options.storage_native_max_ublk_devices > 0 - and options.storage_native_pool_high_watermark - > options.storage_native_max_ublk_devices + not options.storage_native_s3_access_key_id + or not options.storage_native_s3_secret_access_key ): - raise ValueError( - "storage-native pool high watermark cannot exceed maximum ublk devices." - ) - if options.storage_native_max_concurrent_publications < 1: - raise ValueError( - "storage-native publication concurrency must be positive." - ) - if (options.storage_native_max_concurrent_prepares < 0 - or options.storage_native_prepare_concurrency() < 1): - raise ValueError("storage-native prepare concurrency must be positive.") - if options.direct_disk_headroom_mb < 1: - raise ValueError("direct runtime disk headroom must be positive.") - guaranteed_mb = ( - int(options.total_resources.disk_mb) - - options.docker_quota_image_gb * 1024 - - options.swap_gb * 1024 - - options.storage_native_cache_gb * 1024 - - options.direct_disk_headroom_mb + raise ValueError("storage-native S3 credentials are required") + if ( + not options.storage_native_repository + or options.storage_native_repository.startswith("/") + or options.storage_native_repository.endswith("/") + or not re.fullmatch( + r"[a-z0-9]+(?:[._/-][a-z0-9]+)*", + options.storage_native_repository, ) - if guaranteed_mb < 1: - raise ValueError( - "direct runtime physical disk cannot guarantee Docker, swap, " - "cache, headroom, and one writable MiB" - ) - if options.direct_max_concurrent_startups < 1: - raise ValueError("direct max concurrent startups must be positive.") - if options.direct_max_concurrent_restores < 1: - raise ValueError("direct max concurrent restores must be positive.") + ): + raise ValueError("invalid storage-native repository") + if options.storage_native_cache_gb < 1: + raise ValueError("storage-native cache size must be positive.") + if options.storage_native_pool_low_watermark < 0: + raise ValueError("storage-native pool low watermark cannot be negative.") + if options.storage_native_pool_high_watermark < 1: + raise ValueError("storage-native pool high watermark must be positive.") + if ( + options.storage_native_pool_low_watermark + > options.storage_native_pool_high_watermark + ): + raise ValueError( + "storage-native pool low watermark cannot exceed high watermark." + ) + if options.storage_native_max_ublk_devices < 0: + raise ValueError("storage-native maximum ublk devices cannot be negative.") + if ( + options.storage_native_max_ublk_devices > 0 + and options.storage_native_pool_high_watermark + > options.storage_native_max_ublk_devices + ): + raise ValueError( + "storage-native pool high watermark cannot exceed maximum ublk devices." + ) + if options.storage_native_max_concurrent_publications < 1: + raise ValueError( + "storage-native publication concurrency must be positive." + ) + if ( + options.storage_native_max_concurrent_prepares < 0 + or options.storage_native_prepare_concurrency() < 1 + ): + raise ValueError("storage-native prepare concurrency must be positive.") + + +def _validate_sandbox_role_options(options: VmInitOptions) -> None: + if options.storage_native_snapshot_backend != "registry": + raise ValueError( + "split memory backing requires registry checkpoint publication; " + "S3 split checkpoints are unsupported" + ) + if not re.fullmatch(r"[0-9a-f]{40}", options.direct_runsc_commit): + raise ValueError( + "direct runtime requires an exact 40-character runsc commit" + ) + if options.direct_network not in {"none", "sandbox"}: + raise ValueError( + "direct runtime network must be either 'none' or 'sandbox'." + ) + from .relay_network import parse_network_relays + + parse_network_relays(options.network_relays or {}) + if options.network_relays and options.direct_network != "sandbox": + raise ValueError("network relays require sandbox networking") + for endpoint in options.direct_network_allow_tcp: + DirectNetworkTcpEgress.parse(endpoint) + if options.direct_network == "none" and options.direct_network_allow_tcp: + raise ValueError("direct network TCP egress requires sandbox networking.") + if options.docker_quota_image_gb < 1: + raise ValueError( + "direct runtime requires bounded Docker image infrastructure." + ) + if not re.fullmatch(r"https?://[^/\s]+", options.storage_native_registry_url): + raise ValueError( + "direct runtime requires an HTTP(S) storage-native Registry origin" + ) + _validate_sandbox_role_storage_options(options) + if options.direct_disk_headroom_mb < 1: + raise ValueError("direct runtime disk headroom must be positive.") + guaranteed_mb = ( + int(options.total_resources.disk_mb) + - options.docker_quota_image_gb * 1024 + - options.swap_gb * 1024 + - options.storage_native_cache_gb * 1024 + - options.direct_disk_headroom_mb + ) + if guaranteed_mb < 1: + raise ValueError( + "direct runtime physical disk cannot guarantee Docker, swap, " + "cache, headroom, and one writable MiB" + ) + if options.direct_max_concurrent_startups < 1: + raise ValueError("direct max concurrent startups must be positive.") + if options.direct_max_concurrent_restores < 1: + raise ValueError("direct max concurrent restores must be positive.") + + +def _validate_vm_init_limits_and_strings(options: VmInitOptions) -> None: if options.docker_quota_image_gb < 0: raise ValueError("docker quota image size cannot be negative.") if options.swap_gb < 0: raise ValueError("swap size cannot be negative.") if options.max_concurrent_image_pulls < 1: raise ValueError("max concurrent image pulls must be positive.") - if (type(options.max_finishing_image_builds) is not int - or not 0 <= options.max_finishing_image_builds <= 2): - raise ValueError("max finishing image builds must be an integer between 0 and 2.") - if (type(options.build_execution_timeout_seconds) not in {int, float} - or not math.isfinite(options.build_execution_timeout_seconds) - or options.build_execution_timeout_seconds <= 0): + if ( + type(options.max_finishing_image_builds) is not int + or not 0 <= options.max_finishing_image_builds <= 2 + ): + raise ValueError( + "max finishing image builds must be an integer between 0 and 2." + ) + if ( + type(options.build_execution_timeout_seconds) not in {int, float} + or not math.isfinite(options.build_execution_timeout_seconds) + or options.build_execution_timeout_seconds <= 0 + ): raise ValueError("build execution timeout must be positive and finite.") _validate_service_user(options.service_user) for value_name, value in { @@ -2334,6 +2643,9 @@ def validate_vm_init_options(options: VmInitOptions) -> None: # noqa: C901 ): if not value.strip(): raise ValueError(f"{name} is required") + + +def _validate_vm_init_lists_and_buildx(options: VmInitOptions) -> None: for registry in options.docker_insecure_registries: if not registry.strip(): raise ValueError("docker insecure registry cannot be empty.") @@ -2360,13 +2672,24 @@ def validate_vm_init_options(options: VmInitOptions) -> None: # noqa: C901 _reject_newline("buildx cache registry URL", options.buildx_cache_registry_url) if options.buildx_cache_registry_url: cache_url = urlsplit(options.buildx_cache_registry_url) - if (not options.buildx_cache_ref or cache_url.scheme not in {"http", "https"} - or not cache_url.hostname or cache_url.username is not None - or cache_url.password is not None or cache_url.path not in {"", "/"} - or cache_url.query or cache_url.fragment or any(c.isspace() for c in cache_url.netloc)): - raise ValueError("buildx cache registry URL requires a cache ref and an HTTP(S) registry authority") + if ( + not options.buildx_cache_ref + or cache_url.scheme not in {"http", "https"} + or not cache_url.hostname + or cache_url.username is not None + or cache_url.password is not None + or cache_url.path not in {"", "/"} + or cache_url.query + or cache_url.fragment + or any(c.isspace() for c in cache_url.netloc) + ): + raise ValueError( + "buildx cache registry URL requires a cache ref and an HTTP(S) registry authority" + ) if options.buildx_cache_ref.split("/", 1)[0] != cache_url.netloc: - raise ValueError("buildx cache registry URL must match the cache ref registry") + raise ValueError( + "buildx cache registry URL must match the cache ref registry" + ) for key in options.init_authorized_keys: if not key.strip(): raise ValueError("init authorized keys cannot contain empty keys.") @@ -2375,6 +2698,17 @@ def validate_vm_init_options(options: VmInitOptions) -> None: # noqa: C901 raise ValueError("init authorized key cannot contain NUL.") +def validate_vm_init_options(options: VmInitOptions) -> None: + from .environment_bootstrap import validate as validate_environment_bootstrap + + validate_environment_bootstrap(options) + _validate_core_vm_init_options(options) + if options.role == "sandbox": + _validate_sandbox_role_options(options) + _validate_vm_init_limits_and_strings(options) + _validate_vm_init_lists_and_buildx(options) + + def ssh_init_command( ssh_command: str, *, diff --git a/sandboxes/worker_receipts.py b/sandboxes/worker_receipts.py index a0812a9c..b23bfb6f 100644 --- a/sandboxes/worker_receipts.py +++ b/sandboxes/worker_receipts.py @@ -10,13 +10,13 @@ from .routing import SandboxRoute from .sandbox import SandboxSpec, sandbox_spec_fingerprint, sandbox_specs_match -def _sandbox_inventory_from_record(record: dict[str, Any]) -> SandboxInventoryEntry: +def sandbox_inventory_from_record(record: dict[str, Any]) -> SandboxInventoryEntry: spec = record.get("spec") if not isinstance(spec, dict): raise ValueError("sandbox record is missing its spec") parsed_spec = SandboxSpec.from_dict(spec) parsed_spec.validate() - generation = _record_generation(record) + generation = record_generation(record) operation_id = record.get("operation_id") spec_hash = record.get("spec_hash") state = record.get("state") @@ -36,11 +36,11 @@ def _sandbox_inventory_from_record(record: dict[str, Any]) -> SandboxInventoryEn ) -def _route_with_sandbox_record( +def route_with_sandbox_record( route: SandboxRoute, record: dict[str, Any], ) -> SandboxRoute: - observation = _sandbox_inventory_from_record(record) + observation = sandbox_inventory_from_record(record) if observation.sandbox_id != route.sandbox_id: raise ValueError("sandbox record id does not match its route") route_state = observation.route_state @@ -99,7 +99,7 @@ def _route_with_sandbox_record( ) -def _sandbox_record_matches_spec( +def sandbox_record_matches_spec( record: dict[str, Any], requested: SandboxSpec ) -> bool: raw_spec = record.get("spec") @@ -112,7 +112,7 @@ def _sandbox_record_matches_spec( return sandbox_specs_match(existing, requested) -def _record_generation(record: object) -> int | None: +def record_generation(record: object) -> int | None: if not isinstance(record, dict): return None try: @@ -131,15 +131,15 @@ def create_incarnation_unowned(current: SandboxRoute | None, created: SandboxRou return current is None or bool(current.delete_operation_id) or current.generation > created.generation -def _sandbox_record_matches_route( +def sandbox_record_matches_route( record: dict[str, Any], route: SandboxRoute, requested: SandboxSpec, ) -> bool: - if not _sandbox_record_matches_spec(record, requested): + if not sandbox_record_matches_spec(record, requested): return False try: - confirmed = _route_with_sandbox_record(route, record) + confirmed = route_with_sandbox_record(route, record) except (TypeError, ValueError): return False return ( @@ -150,7 +150,7 @@ def _sandbox_record_matches_route( ) -def _sandbox_create_request_body(spec: SandboxSpec, route: SandboxRoute) -> bytes: +def sandbox_create_request_body(spec: SandboxSpec, route: SandboxRoute) -> bytes: payload = spec.to_dict() payload["_ucloud_operation"] = { "operation_id": route.create_operation_id, diff --git a/scripts/images/prepare_image_foundations.py b/scripts/images/prepare_image_foundations.py index ba03a4a7..0ebdb1f3 100644 --- a/scripts/images/prepare_image_foundations.py +++ b/scripts/images/prepare_image_foundations.py @@ -147,7 +147,7 @@ def main(): # noqa: C901 sys.path.insert(0, str(args.sdk_wheel)) import ucloud_sandboxes_sdk as sdk from sandboxes.config import DeploymentConfig - from sandboxes.gateway.registry_refs import _persist_registry_image_protection + from sandboxes.gateway.registry_refs import persist_registry_image_protection from sandboxes.environment_artifact import load_image_environment from sandboxes.environment_config import environment_registry_from_deployment from sandboxes.environment_dependencies import EnvironmentDependencyResolver @@ -296,7 +296,7 @@ def prepare(item, reservation): environment_root, environment = load_image_environment(registry, repository, digest) components = [registry.load(d) for d in environment.components] owner = "image-foundation:" + item["key"] - if not _persist_registry_image_protection(usage, reference, owner, touch=True, persistent=True, + if not persist_registry_image_protection(usage, reference, owner, touch=True, persistent=True, dependency_resolver=dependencies): raise RuntimeError("foundation artifact closure was not retained") record = ImageRecord.from_dict({k: v for k, v in published.items() if k in ImageRecord.__dataclass_fields__}) diff --git a/scripts/images/prepare_image_pool.py b/scripts/images/prepare_image_pool.py index 2d694074..08f735c4 100644 --- a/scripts/images/prepare_image_pool.py +++ b/scripts/images/prepare_image_pool.py @@ -445,7 +445,7 @@ def main(): # noqa: C901 sys.path.insert(0, str(args.sdk_wheel)) import ucloud_sandboxes_sdk as sdk from sandboxes.config import DeploymentConfig - from sandboxes.gateway.registry_refs import _persist_registry_image_protection + from sandboxes.gateway.registry_refs import persist_registry_image_protection from sandboxes.environment_artifact import load_image_environment from sandboxes.environment_config import environment_registry_from_deployment from sandboxes.environment_dependencies import EnvironmentDependencyResolver @@ -589,7 +589,7 @@ def prepare(item): build_source = stage_source(resolved, registry.client, claim_root, publication_url=config.registry_worker_url, metrics=staging_metrics, blob_sources=blob_sources, mirrors=mirrors, - protect=lambda ref, owner: _persist_registry_image_protection( + protect=lambda ref, owner: persist_registry_image_protection( usage, ref, owner, touch=True, persistent=True)) receipt["staged_source"] = build_source receipt["staging"] = staging_metrics @@ -630,7 +630,7 @@ def prepare(item): environment_root, environment = load_image_environment(registry, repository, published["manifest_digest"]) components = [registry.load(d) for d in environment.components] owner = "image-pool:" + key - if not _persist_registry_image_protection(usage, reference, owner, touch=True, persistent=True, + if not persist_registry_image_protection(usage, reference, owner, touch=True, persistent=True, dependency_resolver=dependencies): raise RuntimeError("image closure was not retained") with guard: diff --git a/scripts/images/stage_source_image.py b/scripts/images/stage_source_image.py index 5edbf641..c61bf166 100644 --- a/scripts/images/stage_source_image.py +++ b/scripts/images/stage_source_image.py @@ -20,9 +20,9 @@ def publication_repositories(image_id, registry_url, cache_ref=""): - from sandboxes.gateway.registry_refs import _managed_registry_build_tag + from sandboxes.gateway.registry_refs import managed_registry_build_tag from sandboxes.managed_registry import registry_repository_tag_from_image_ref - target, _ = registry_repository_tag_from_image_ref(_managed_registry_build_tag(image_id, registry_url)) + target, _ = registry_repository_tag_from_image_ref(managed_registry_build_tag(image_id, registry_url)) repositories = [target] if cache_ref: authority = parse.urlparse(registry_url).netloc diff --git a/tests/test_builder_agent.py b/tests/test_builder_agent.py new file mode 100644 index 00000000..3caa7b07 --- /dev/null +++ b/tests/test_builder_agent.py @@ -0,0 +1,101 @@ +from __future__ import annotations + +import ast +import json +import threading +import unittest +from pathlib import Path +from tempfile import TemporaryDirectory +from urllib.error import HTTPError +from urllib.request import Request, urlopen + +from sandboxes.builder_agent import build_builder_node_agent_server +from sandboxes.images import DockerImageRuntime +from sandboxes.models import ResourceQuantity + +TEST_TIER = "unit" + + +class BuilderAgentTest(unittest.TestCase): + def test_builder_agent_has_no_sandbox_worker_imports(self) -> None: + source = Path("sandboxes/builder_agent.py").read_text(encoding="utf-8") + tree = ast.parse(source) + imported = set() + for node in ast.walk(tree): + if isinstance(node, ast.ImportFrom) and node.module: + imported.add(node.module) + forbidden = { + "direct_service", + "direct_warden", + "direct_provisioner", + "direct_registry", + "direct_oci", + "direct_network", + "hibernation", + "transition_admission", + } + self.assertEqual(imported & forbidden, set()) + + def test_builder_agent_serves_builder_routes_and_rejects_sandboxes(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + server = build_builder_node_agent_server( + "127.0.0.1", + 0, + state_file=root / "builder.json", + image_file=root / "images.sqlite", + job_id="job-builder-1", + node_id="builder-1", + node_url="http://127.0.0.1:8090", + agent_version="0.1.0", + deployment_id="dep-1", + init_version="init-1", + total_resources=ResourceQuantity(vcpu=8.0, memory_mb=16384, disk_mb=50000), + image_runtime=DockerImageRuntime(dry_run=True), + node_control_bearer_token="builder-secret", + node_epoch="epoch-builder-1", + ) + port = server.server_address[1] + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + base = f"http://127.0.0.1:{port}" + with urlopen(f"{base}/healthz") as resp: + self.assertEqual(resp.status, 200) + self.assertTrue(json.loads(resp.read())["ok"]) + + headers = {"Authorization": "Bearer builder-secret"} + with urlopen(Request(f"{base}/v1/heartbeat", headers=headers)) as resp: + hb = json.loads(resp.read())["heartbeat"] + self.assertEqual(hb["node_id"], "builder-1") + self.assertIn("image-build", hb["capabilities"]) + self.assertNotIn("sandbox", hb["capabilities"]) + + with urlopen(Request(f"{base}/v1/images", headers=headers)) as resp: + self.assertEqual(json.loads(resp.read())["images"], []) + + with urlopen(Request(f"{base}/v1/images/builds", headers=headers)) as resp: + self.assertEqual(json.loads(resp.read())["builds"], []) + + drain_req = Request( + f"{base}/v1/drain", + data=json.dumps({"draining": True, "token": "drain-b1"}).encode("utf-8"), + headers={**headers, "Content-Type": "application/json"}, + method="POST", + ) + with urlopen(drain_req) as resp: + drain = json.loads(resp.read())["drain"] + self.assertTrue(drain["draining"]) + self.assertFalse(drain["admission_open"]) + + with self.assertRaises(HTTPError) as ctx: + urlopen(Request(f"{base}/v1/sandboxes", headers=headers)) + self.assertEqual(ctx.exception.code, 404) + ctx.exception.close() + finally: + server.shutdown() + server.server_close() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_control_plane.py b/tests/test_control_plane.py index 085b3853..6290d611 100644 --- a/tests/test_control_plane.py +++ b/tests/test_control_plane.py @@ -26,8 +26,11 @@ ) from sandboxes import control_plane from sandboxes.control_state import ControlStateStore -from sandboxes.capabilities import HIBERNATE_LOCAL_CAPABILITY -from sandboxes.gateway import image_resolution, node_rpc, placement, registry_refs +from sandboxes.capabilities import ( + HIBERNATE_LOCAL_CAPABILITY, + RUNTIME_COMPATIBILITY_CAPABILITY_PREFIX, +) +from sandboxes.gateway import build_service, image_resolution, node_rpc, placement, registry_refs from sandboxes.gateway.groups import group_budget from sandboxes.image_inventory_cache import ImageInventoryCache, ImageInventorySnapshot from tests.gateway_support import gateway_services @@ -359,6 +362,7 @@ def _prepare_wake_route(handler, route): class ControlPlaneTests(unittest.TestCase): def test_expected_park_deferral_does_not_write_program_error(self): handler = object.__new__(control_plane.ControlPlaneHandler) + handler.services = gateway_services() route = _sandbox_route(sandbox_id="warm", node_id="node", job_id="job", node_url="http://node.invalid") for code, retryable, expected in (("park_deferred", True, 0), ("park_deferred", False, 1), ("other_conflict", True, 1)): with self.subTest(code=code, retryable=retryable): @@ -560,7 +564,7 @@ def test_create_confirmation_survives_delayed_absent_inventory(self) -> None: record = dict(spec=spec.to_dict(), state="running", generation=route.generation, operation_id=route.create_operation_id, spec_hash=route.spec_hash, node_epoch="boot-1", activity_epoch=21) - routing.upsert_sandbox(control_plane._route_with_sandbox_record(route, record)) + routing.upsert_sandbox(control_plane.route_with_sandbox_record(route, record)) # Sampled while create was pending (revision 20), received after # confirmation. Receipt timestamps alone cannot prove absence. removed, _ = routing.reconcile_sandboxes_for_node( @@ -578,7 +582,7 @@ def test_create_confirmation_survives_delayed_absent_inventory(self) -> None: ) self.assertEqual([r.sandbox_id for r in removed], [spec.id]) with self.assertRaisesRegex(ValueError, "another node boot"): - control_plane._route_with_sandbox_record(route, dict(record, node_epoch="retired-boot")) + control_plane.route_with_sandbox_record(route, dict(record, node_epoch="retired-boot")) def test_relay_lifecycle_persists_program_request_transitions(self) -> None: with _temporary_root() as root: @@ -1684,7 +1688,7 @@ def test_detached_park_wakes_without_contacting_former_worker(self) -> None: capabilities=( *legacy_destination.capabilities, HIBERNATE_LOCAL_CAPABILITY, - control_plane.RUNTIME_COMPATIBILITY_CAPABILITY_PREFIX + RUNTIME_COMPATIBILITY_CAPABILITY_PREFIX + snapshot.manifest.runtime.node_compatibility_sha256, ), ) @@ -2066,10 +2070,10 @@ def test_ublk_device_limit_accounts_for_inflight_route_reservations(self) -> Non state="creating", ) - self.assertTrue(placement._node_can_fit(heartbeat, requested, [])) - self.assertFalse(placement._node_can_fit(heartbeat, requested, [inflight])) + self.assertTrue(placement.node_can_fit(heartbeat, requested, [])) + self.assertFalse(placement.node_can_fit(heartbeat, requested, [inflight])) self.assertFalse( - placement._node_can_fit( + placement.node_can_fit( replace( heartbeat, runtime_metrics=replace( @@ -3736,7 +3740,7 @@ def proxy(*args, **kwargs): sleeper = Mock() clock = SimpleNamespace(**{name: getattr(time, name) for name in dir(time) if not name.startswith("_")}) clock.sleep = sleeper - with patch.object(control_plane, "time", clock): + with patch.object(build_service, "time", clock): response = handler._pull_image_on_node(heartbeat, "image") self.assertEqual(response.status, 200) diff --git a/tests/test_direct_runtime_assembly.py b/tests/test_direct_runtime_assembly.py index 1f4ec513..2b32a0bb 100644 --- a/tests/test_direct_runtime_assembly.py +++ b/tests/test_direct_runtime_assembly.py @@ -44,9 +44,9 @@ def test_a_worker_without_immutable_environments_refuses_to_start(self): def test_split_and_ram_runtime_start_over_real_storage_wire(self): fingerprints = {} - for ram, reflink in ((False, False), (True, False), (False, True), (True, True)): + for ram in (False, True): with ( - self.subTest(ram=ram, reflink=reflink), + self.subTest(ram=ram), TemporaryDirectory(prefix="assembly-", dir="/tmp") as raw, ExitStack() as stack, ): @@ -82,9 +82,6 @@ def test_split_and_ram_runtime_start_over_real_storage_wire(self): stack.enter_context( patch("sandboxes.direct_runtime.require_ram_backing_runtime") ) - reflink_gate = stack.enter_context( - patch("sandboxes.direct_runtime.require_reflink_restore_runtime") - ) stack.enter_context( patch( "sandboxes.direct_runtime.installed_sidecar_fingerprints", @@ -127,7 +124,6 @@ def filesystem_probe(args, *a, **kw): storage_native_socket=socket, memory_backing_hard_capacity_bytes=capacity, application_memory_root=active, - reflink_memory_restore=reflink, checkpoint_registry_url="http://127.0.0.1:5000", checkpoint_registry_repository="qualification", # Nothing is attached: the empty image cache never reads either. @@ -136,9 +132,7 @@ def filesystem_probe(args, *a, **kw): environment_backend_socket=root / "environment-io.sock", ) stack.callback(service.stop) - self.assertEqual(reflink_gate.call_count, int(reflink)) - self.assertEqual(service.warden.config.reflink_memory_restore, reflink) - fingerprints[ram, reflink] = service.warden.config.runtime_fingerprint.node_compatibility_sha256 + fingerprints[ram] = service.warden.config.runtime_fingerprint.node_compatibility_sha256 self.assertEqual( service.warden.storage.get_metrics()["hard_capacity_bytes"], capacity, @@ -156,9 +150,9 @@ def filesystem_probe(args, *a, **kw): runtime_metrics_provider=lambda: None, ) stack.callback(server.server_close) - self.assertEqual( - "sandbox-memory-reflink-restore-v1" in server.RequestHandlerClass.capabilities, - reflink, + self.assertNotIn( + "sandbox-memory-reflink-restore-v1", + server.RequestHandlerClass.capabilities, ) stack.callback(server.RequestHandlerClass.manager.stop) thread = Thread(target=server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True) @@ -221,10 +215,7 @@ def filesystem_probe(args, *a, **kw): heartbeat = json.load(response) self.assertEqual(heartbeat["heartbeat"]["job_id"], "job") self.assertIsNotNone(service.provisioner.checkpoint_store) - self.assertEqual(fingerprints[False, True], fingerprints[True, True]) - self.assertNotEqual(fingerprints[False, False], fingerprints[True, False]) - self.assertNotEqual(fingerprints[False, True], fingerprints[False, False]) - self.assertNotEqual(fingerprints[True, True], fingerprints[True, False]) + self.assertNotEqual(fingerprints[False], fingerprints[True]) if __name__ == "__main__": diff --git a/tests/test_environment_contract.py b/tests/test_environment_contract.py index 1de58590..b5490947 100644 --- a/tests/test_environment_contract.py +++ b/tests/test_environment_contract.py @@ -16,13 +16,13 @@ def spec(self, **kw): ) def test_new_contracts_require_capable_nodes_during_placement(self): - from sandboxes.gateway.placement import _sandbox_required_capabilities + from sandboxes.gateway.placement import sandbox_required_capabilities from sandboxes.capabilities import ( ENVIRONMENT_CONTRACT_CAPABILITY, STATIC_FILE_MANAGEMENT_CAPABILITY, ) - self.assertEqual(_sandbox_required_capabilities(self.spec().to_dict()), ()) + self.assertEqual(sandbox_required_capabilities(self.spec().to_dict()), ()) for overrides in ( {"dns_servers": ["9.9.9.9"]}, {"profile": "linux_session"}, @@ -30,9 +30,9 @@ def test_new_contracts_require_capable_nodes_during_placement(self): ): self.assertIn( ENVIRONMENT_CONTRACT_CAPABILITY, - _sandbox_required_capabilities(self.spec(**overrides).to_dict()), + sandbox_required_capabilities(self.spec(**overrides).to_dict()), ) - required = _sandbox_required_capabilities( + required = sandbox_required_capabilities( self.spec(filesystem={"management_helper": "static"}).to_dict() ) self.assertIn(STATIC_FILE_MANAGEMENT_CAPABILITY, required) diff --git a/tests/test_fleet_read_coalescing.py b/tests/test_fleet_read_coalescing.py index 6bb0e9a0..e948db46 100644 --- a/tests/test_fleet_read_coalescing.py +++ b/tests/test_fleet_read_coalescing.py @@ -1,9 +1,10 @@ from concurrent.futures import Future, ThreadPoolExecutor -from threading import Event, Lock, RLock +from threading import Event, Lock import unittest from unittest.mock import patch from sandboxes.control_plane import ControlPlaneHandler +from sandboxes.gateway.state import GatewayRuntimeState, SingleflightCoalescer class FleetReadCoalescingTests(unittest.TestCase): @@ -23,8 +24,9 @@ def result(self, *args, **kwargs): return super().result(*args, **kwargs) class Handler(ControlPlaneHandler): - fleet_response_lock = RLock() - fleet_response_future = None + runtime_state = GatewayRuntimeState( + fleet_list=SingleflightCoalescer(future_factory=ObservedFuture) + ) def _sandbox_list_response(self): calls.append(True) @@ -43,24 +45,23 @@ def read(): handler._list_sandboxes_from_cache() return handler.response - with patch('sandboxes.control_plane.Future', ObservedFuture): - with ThreadPoolExecutor(max_workers=24) as pool: - first = pool.submit(read) - self.assertTrue(entered.wait(3)) - others = [pool.submit(read) for _ in range(23)] - try: - self.assertTrue(joined.wait(3)) - self.assertEqual(len(calls), 1) - finally: - release.set() - for future in [first, *others]: - if fail: - with self.assertRaisesRegex(ValueError, 'injected scan failure'): - future.result(3) - else: - self.assertEqual(future.result(3), (b'first', 'application/json')) + with ThreadPoolExecutor(max_workers=24) as pool: + first = pool.submit(read) + self.assertTrue(entered.wait(3)) + others = [pool.submit(read) for _ in range(23)] + try: + self.assertTrue(joined.wait(3)) + self.assertEqual(len(calls), 1) + finally: + release.set() + for future in [first, *others]: + if fail: + with self.assertRaisesRegex(ValueError, 'injected scan failure'): + future.result(3) + else: + self.assertEqual(future.result(3), (b'first', 'application/json')) # No old snapshot or exception is retained after the concurrent wave. - self.assertIsNone(Handler.fleet_response_future) + self.assertEqual(Handler.runtime_state.fleet_list.in_flight_count, 0) with patch.object(Handler, '_sandbox_list_response', return_value=b'fresh') as scan: self.assertEqual(read(), (b'fresh', 'application/json')) scan.assert_called_once() diff --git a/tests/test_fleet_status.py b/tests/test_fleet_status.py index ab1d68dc..8d2d204d 100644 --- a/tests/test_fleet_status.py +++ b/tests/test_fleet_status.py @@ -7,7 +7,7 @@ import json from pathlib import Path from tempfile import TemporaryDirectory -from threading import Event, RLock +from threading import Event import unittest from unittest.mock import patch from urllib.error import HTTPError @@ -198,9 +198,12 @@ def read_status(self, ids): raise TimeoutError("test reader not released") return json.dumps(ids).encode() + from sandboxes.gateway.state import GatewayRuntimeState, SingleflightCoalescer + class Handler(ControlPlaneHandler): - fleet_response_lock = RLock() - fleet_status_futures = {} + runtime_state = GatewayRuntimeState( + fleet_status=SingleflightCoalescer(future_factory=ObservedFuture) + ) fleet_snapshot_reader = Reader() def _write_bytes(self, body, content_type): @@ -211,8 +214,7 @@ def read(ids): handler._list_sandbox_statuses(ids) return handler.response - with (patch("sandboxes.control_plane.Future", ObservedFuture), - ThreadPoolExecutor(max_workers=2) as pool): + with ThreadPoolExecutor(max_workers=2) as pool: first = pool.submit(read, ("a",)) self.assertTrue(entered.wait(3)) try: @@ -224,10 +226,10 @@ def read(ids): release.set() self.assertEqual(first.result(2), b'["a"]') self.assertEqual(same.result(2), b'["a"]') - self.assertEqual(Handler.fleet_status_futures, {}) + self.assertEqual(Handler.runtime_state.fleet_status.in_flight_count, 0) with patch.object(Handler.fleet_snapshot_reader, "read_status", side_effect=ValueError("failed")): with self.assertRaisesRegex(ValueError, "failed"): read(("a",)) - self.assertEqual(Handler.fleet_status_futures, {}) + self.assertEqual(Handler.runtime_state.fleet_status.in_flight_count, 0) self.assertEqual(read(("a",)), b'["a"]') diff --git a/tests/test_gateway_builds.py b/tests/test_gateway_builds.py new file mode 100644 index 00000000..919b5539 --- /dev/null +++ b/tests/test_gateway_builds.py @@ -0,0 +1,229 @@ +"""Pure decision tests for gateway build normalization and builder refresh logic.""" + +from __future__ import annotations + +from datetime import datetime, timezone +import unittest + +from sandboxes.build_admission import BUILD_ADMISSION_CAPACITY_LABEL +from sandboxes.gateway.builds import ( + build_terminal_metrics_summary, + builder_owns_active_build, + image_build_payload_is_terminal, + image_build_response_is_terminal, + image_record_cache_keys, + is_builder_heartbeat, + merge_refreshed_builder_heartbeat, + normalize_build_spec, + parse_image_pull_request, + rank_image_cache_candidates, + retryable_image_pull_payload, + select_builder_candidate, + select_latest_build_record, +) +from sandboxes.models import NodeHeartbeat, ResourceQuantity + +TEST_TIER = "unit" + +_NOW = datetime(2026, 10, 18, 0, 0, tzinfo=timezone.utc) + + +def _hb( + node_id: str, + *, + capabilities: tuple[str, ...] = ("image-build",), + active_image_builds: int = 0, + physical_disk_free_mb: int = 10_000, + disk_mb: int = 20_000, + labels: dict[str, str] | None = None, + draining: bool = False, + admission_open: bool = True, + node_epoch: str = "boot-1", +) -> NodeHeartbeat: + return NodeHeartbeat( + node_id=node_id, + job_id=f"job-{node_id}", + deployment_id="dep-1", + updated_at=_NOW, + active_sandboxes=0, + active_image_builds=active_image_builds, + node_url=f"http://{node_id}:8090", + capabilities=capabilities, + total_resources=ResourceQuantity(vcpu=8.0, memory_mb=16_384, disk_mb=disk_mb), + resources_known=True, + used_resources=ResourceQuantity(), + labels=labels or {}, + draining=draining, + admission_open=admission_open, + node_epoch=node_epoch, + physical_disk_free_mb=physical_disk_free_mb, + ) + + +class GatewayBuildsCoreTests(unittest.TestCase): + def test_builder_heartbeat_classification_and_refresh_merge(self) -> None: + builder = _hb( + "b1", + labels={"quarantine": "keep-me", BUILD_ADMISSION_CAPACITY_LABEL: "old"}, + ) + sandbox = _hb("s1", capabilities=("image-build", "sandbox")) + self.assertTrue(is_builder_heartbeat(builder)) + self.assertFalse(is_builder_heartbeat(sandbox)) + + # Draining or epoch-mismatched live sample is rejected. + self.assertIsNone( + merge_refreshed_builder_heartbeat(builder, _hb("b1", draining=True)) + ) + self.assertIsNone( + merge_refreshed_builder_heartbeat(builder, _hb("b1", node_epoch="boot-2")) + ) + + # Live sample updates counts and admission hint while preserving gateway labels. + live = _hb( + "b1", + active_image_builds=3, + physical_disk_free_mb=42_000, + labels={BUILD_ADMISSION_CAPACITY_LABEL: "new"}, + ) + merged = merge_refreshed_builder_heartbeat(builder, live) + self.assertIsNotNone(merged) + assert merged is not None + self.assertEqual(merged.active_image_builds, 3) + self.assertEqual(merged.physical_disk_free_mb, 42_000) + self.assertEqual(merged.labels["quarantine"], "keep-me") + self.assertEqual(merged.labels[BUILD_ADMISSION_CAPACITY_LABEL], "new") + + # Missing capacity hint in live sample clears stale cached hint. + no_hint = merge_refreshed_builder_heartbeat(builder, _hb("b1", labels={})) + assert no_hint is not None + self.assertNotIn(BUILD_ADMISSION_CAPACITY_LABEL, no_hint.labels) + + def test_builder_ownership_and_terminal_response_rules(self) -> None: + self.assertTrue(builder_owns_active_build({"status": "running"})) + self.assertTrue( + builder_owns_active_build( + {"status": "succeeded", "admission_phase": "finishing"} + ) + ) + self.assertFalse(builder_owns_active_build({"status": "succeeded"})) + self.assertFalse(builder_owns_active_build({"status": "unknown"})) + + self.assertTrue(image_build_response_is_terminal(200, {})) + self.assertTrue(image_build_response_is_terminal(400, {})) + self.assertFalse(image_build_response_is_terminal(429, {})) + self.assertFalse(image_build_response_is_terminal(503, {})) + self.assertTrue( + image_build_response_is_terminal(500, {"build": {"status": "failed"}}) + ) + + def test_normalize_build_spec_strips_base_contexts_and_sets_managed_tag(self) -> None: + raw, spec, push = normalize_build_spec( + { + "id": "img-1", + "dockerfile": "Dockerfile", + "context_archive_digest": "sha256:" + "a" * 64, + "base_contexts": {"spoofed": "value"}, + }, + registry_url="http://127.0.0.1:5000", + registry_worker_url="http://registry.internal:5000", + ) + self.assertNotIn("base_contexts", raw) + self.assertTrue(push) + self.assertEqual(spec.id, "img-1") + self.assertIn("registry.internal:5000", spec.tag) + + def test_rank_image_cache_candidates_prefers_sandbox_and_free_disk(self) -> None: + builder_cache = _hb("b-cache", capabilities=("image-cache",), disk_mb=100_000) + sbx_small = _hb("s-small", capabilities=("image-cache", "sandbox"), disk_mb=10_000) + sbx_big = _hb("s-big", capabilities=("image-cache", "sandbox"), disk_mb=50_000) + ranked = rank_image_cache_candidates( + [builder_cache, sbx_small, sbx_big], + [], + resources=ResourceQuantity(), + sandbox_nodes_only=False, + ) + self.assertEqual([h.node_id for h in ranked], ["s-big", "s-small", "b-cache"]) + + def test_select_builder_candidate_consolidates_up_to_two_then_spreads(self) -> None: + b_idle = _hb("b-idle", active_image_builds=0, labels={BUILD_ADMISSION_CAPACITY_LABEL: "4"}) + b_one = _hb("b-one", active_image_builds=1, labels={BUILD_ADMISSION_CAPACITY_LABEL: "4"}) + b_two = _hb("b-two", active_image_builds=2, labels={BUILD_ADMISSION_CAPACITY_LABEL: "4"}) + b_full = _hb("b-full", active_image_builds=4, labels={BUILD_ADMISSION_CAPACITY_LABEL: "4"}) + + # Consolidates onto builder with 1 active build before waking idle peer. + chosen = select_builder_candidate( + [b_idle, b_one, b_two, b_full], + effective_load=lambda h: h.active_image_builds, + ) + assert chosen is not None + self.assertEqual(chosen.node_id, "b-one") + + # Once active peers are saturated (>= 2), prefers idle peer over saturated peer. + chosen_spread = select_builder_candidate( + [b_idle, b_two, b_full], + effective_load=lambda h: h.active_image_builds, + ) + assert chosen_spread is not None + self.assertEqual(chosen_spread.node_id, "b-idle") + + # Full builders are excluded unless allow_full=True. + self.assertIsNone( + select_builder_candidate([b_full], effective_load=lambda h: h.active_image_builds) + ) + forced = select_builder_candidate( + [b_full], effective_load=lambda h: h.active_image_builds, allow_full=True + ) + assert forced is not None + self.assertEqual(forced.node_id, "b-full") + + def test_parse_image_pull_request_and_build_summary_helpers(self) -> None: + image, count, resources, sandbox_only, image_id = parse_image_pull_request( + {"image": "repo/app:v1", "count": 2, "cpus": 2, "memory_mb": 2048, "id": " app "} + ) + self.assertEqual((image, count, sandbox_only, image_id), ("repo/app:v1", 2, True, "app")) + self.assertEqual(resources.vcpu, 2.0) + with self.assertRaises(ValueError): + parse_image_pull_request({"image": "repo/app:v1", "bogus": 1}) + + latest = select_latest_build_record( + [ + {"build_id": "b1", "image_id": "img", "created_at": "2026-10-18T00:00:00Z"}, + {"build_id": "b2", "image_id": "img", "created_at": "2026-10-18T00:01:00Z"}, + ], + "img", + ) + assert latest is not None + self.assertEqual(latest["build_id"], "b2") + self.assertTrue(image_build_payload_is_terminal({"build": {"status": "succeeded"}})) + self.assertFalse(image_build_payload_is_terminal({"build": {"status": "running"}})) + + parsed = build_terminal_metrics_summary( + { + "build_id": "b2", + "image_id": "img", + "status": "succeeded", + "updated_at": "2026-10-18T00:02:00Z", + "timings": { + "total_ms": 1200, + "queue_wait_ms": 50, + "phases": {"solve": 900, "bad": "ignored"}, + }, + } + ) + assert parsed is not None + key, summary = parsed + self.assertEqual(key, ("b2", "2026-10-18T00:02:00Z")) + self.assertEqual(summary["timings"]["phases"], {"solve": 900}) + + self.assertTrue( + retryable_image_pull_payload( + 503, {"retryable": True, "error_code": "image_pull_failed"} + ) + ) + self.assertFalse(retryable_image_pull_payload(500, {"retryable": True})) + keys = image_record_cache_keys({"id": "img", "tag": "reg/img:v1"}) + self.assertEqual(keys, {"img", "reg/img:v1"}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_gateway_state.py b/tests/test_gateway_state.py new file mode 100644 index 00000000..5affa25d --- /dev/null +++ b/tests/test_gateway_state.py @@ -0,0 +1,127 @@ +"""Unit tests for gateway in-memory runtime state (coalescers, TTL & LRU caches).""" + +from __future__ import annotations + +from concurrent.futures import Future, ThreadPoolExecutor +from threading import Event, Lock +import unittest + +from sandboxes.gateway.state import ( + BuildOwnerCache, + GatewayRuntimeState, + MetricsResponseCache, + SingleflightCoalescer, +) + +TEST_TIER = "unit" + + +class GatewayRuntimeStateTests(unittest.TestCase): + def test_singleflight_shares_leader_result_and_clears_after_wave(self) -> None: + entered, release, joined = Event(), Event(), Event() + guard = Lock() + waiters = 0 + calls = 0 + + class ObservedFuture(Future): + def result(self, *args, **kwargs): + nonlocal waiters + with guard: + waiters += 1 + if waiters == 7: + joined.set() + return super().result(*args, **kwargs) + + coalescer: SingleflightCoalescer[str, bytes] = SingleflightCoalescer( + future_factory=ObservedFuture + ) + + def compute() -> bytes: + nonlocal calls + calls += 1 + entered.set() + if not release.wait(3): + raise TimeoutError("test did not release leader") + return b"payload" + + with ThreadPoolExecutor(max_workers=8) as pool: + first = pool.submit(coalescer.run, "k", compute) + self.assertTrue(entered.wait(3)) + others = [pool.submit(coalescer.run, "k", compute) for _ in range(7)] + try: + self.assertTrue(joined.wait(3)) + self.assertEqual(calls, 1) + self.assertTrue(coalescer.has_in_flight("k")) + finally: + release.set() + for fut in (first, *others): + self.assertEqual(fut.result(3), b"payload") + + self.assertEqual(coalescer.in_flight_count, 0) + # Subsequent call runs fresh rather than serving a cached snapshot. + self.assertEqual(coalescer.run("k", lambda: b"fresh"), b"fresh") + + def test_singleflight_failure_propagates_without_poisoning_next_call(self) -> None: + coalescer: SingleflightCoalescer[str, bytes] = SingleflightCoalescer() + + def boom() -> bytes: + raise ValueError("scan failed") + + with self.assertRaisesRegex(ValueError, "scan failed"): + coalescer.run("k", boom) + self.assertEqual(coalescer.in_flight_count, 0) + self.assertEqual(coalescer.run("k", lambda: b"ok"), b"ok") + + def test_metrics_cache_respects_ttl_and_refresh(self) -> None: + now = [100.0] + cache = MetricsResponseCache(clock=lambda: now[0]) + calls = 0 + + def compute() -> bytes: + nonlocal calls + calls += 1 + return f"v{calls}".encode() + + self.assertEqual(cache.get_or_compute(ttl_seconds=5.0, cacheable=True, compute=compute), b"v1") + now[0] = 104.0 + self.assertEqual(cache.get_or_compute(ttl_seconds=5.0, cacheable=True, compute=compute), b"v1") + # Non-cacheable (refresh/full) bypasses cache without overwriting it. + self.assertEqual(cache.get_or_compute(ttl_seconds=5.0, cacheable=False, compute=compute), b"v2") + self.assertEqual(cache.get_or_compute(ttl_seconds=5.0, cacheable=True, compute=compute), b"v1") + # TTL expiry recomputes and stores fresh value. + now[0] = 110.0 + self.assertEqual(cache.get_or_compute(ttl_seconds=5.0, cacheable=True, compute=compute), b"v3") + + def test_build_owner_cache_bounds_lru_and_retries_failed_metric_writes(self) -> None: + cache = BuildOwnerCache(max_entries=2) + cache.record_owner("b1", ("n1", "j1", "e1")) + cache.record_owner("b2", ("n2", "j2", "e2")) + cache.record_owner("b1", ("n1", "j1", "e1")) # bump b1 to MRU + cache.record_owner("b3", ("n3", "j3", "e3")) # evicts b2 + self.assertIsNone(cache.get_owner("b2")) + self.assertEqual(cache.get_owner("b1"), ("n1", "j1", "e1")) + self.assertEqual(cache.get_owner("b3"), ("n3", "j3", "e3")) + + attempts = 0 + + def flaky_write() -> None: + nonlocal attempts + attempts += 1 + if attempts == 1: + raise OSError("disk full") + + with self.assertRaises(OSError): + cache.record_metric_once(("b1", "t1"), flaky_write) + self.assertFalse(cache.has_recorded_metric(("b1", "t1"))) + self.assertTrue(cache.record_metric_once(("b1", "t1"), flaky_write)) + self.assertFalse(cache.record_metric_once(("b1", "t1"), flaky_write)) + self.assertEqual(attempts, 2) + + def test_runtime_state_creates_independent_instances(self) -> None: + left, right = GatewayRuntimeState(), GatewayRuntimeState() + left.builds.record_owner("b1", ("n1", "j1", "e1")) + self.assertIsNone(right.builds.get_owner("b1")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_guest_continuity.py b/tests/test_guest_continuity.py index d940cb35..b3f1aa1a 100644 --- a/tests/test_guest_continuity.py +++ b/tests/test_guest_continuity.py @@ -2,14 +2,16 @@ from dataclasses import replace import unittest -from unittest.mock import patch from tests.test_cli import ( owned_heartbeat, sandbox_route, temporary_root, ) -from sandboxes import cli +from sandboxes.autoscaler import ( + guest_continuity_matches, + quarantine_unverified_guests, +) from sandboxes.control_state import ( ControlStateStore, QUARANTINE_REASON, ) @@ -47,13 +49,20 @@ def continuity_pair(): class GuestContinuityTests(unittest.TestCase): def continuity_cycle(self, store, job, probe, route, routing=None): - with patch.object(cli, "_probe_unreachable_node", return_value=probe) as probed: - jobs, _ = cli._quarantine_unverified_guests( - [job], store.load_heartbeats(), control_state=store, policy=ScalePolicy(), - deployment_id="prod-a", route_reservations={"owned": (route,)}, - execution_authorized=True, bearer_token="test-token", routing_store=routing, - ) - return jobs[0].phase, probed.call_count + calls = 0 + + def probe_nodes(heartbeats, _token, _ttl): + nonlocal calls + calls += len(heartbeats) + return {job_id: probe for job_id in heartbeats} + + jobs, _ = quarantine_unverified_guests( + [job], store.load_heartbeats(), control_state=store, policy=ScalePolicy(), + deployment_id="prod-a", route_reservations={"owned": (route,)}, + execution_authorized=True, bearer_token="test-token", routing_store=routing, + probe_nodes_fn=probe_nodes, + ) + return jobs[0].phase, calls def test_quarantine_survives_push_restart_and_rejects_obsolete_recovery(self): with temporary_root() as root: @@ -93,6 +102,6 @@ def test_incomplete_or_wrong_incarnation_inventory_cannot_reopen_placement(self) for fresh in invalid: with self.subTest(fresh=fresh): self.assertFalse( - cli._guest_continuity_matches(heartbeat, fresh, (route,)) + guest_continuity_matches(heartbeat, fresh, (route,)) ) - self.assertTrue(cli._guest_continuity_matches(heartbeat, heartbeat, (route,))) + self.assertTrue(guest_continuity_matches(heartbeat, heartbeat, (route,))) diff --git a/tests/test_gvisor_distribution.py b/tests/test_gvisor_distribution.py index ee27aa23..eae752b6 100644 --- a/tests/test_gvisor_distribution.py +++ b/tests/test_gvisor_distribution.py @@ -9,39 +9,10 @@ GVISOR_SIDECARS, distribution_files, installed_sidecar_fingerprints, - require_reflink_restore_runtime, - REFLINK_RESTORE_PATCH_SHA256, ) class GvisorDistributionTests(unittest.TestCase): - def test_reflink_gate_requires_pinned_patch_and_complete_distribution(self): - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - runsc = self.fixture(root) - path = root / "build-manifest.json" - manifest = json.loads(path.read_text()) - manifest["patches"] = [ - {"name": "20260817/0004-ucloud-abort-hibernation.patch", - "sha256": "c97ae915c984f50a554c9b79ede4b73a5ab68e0ad5d89469e8f09819468519fe"}, - {"name": "20260817/0006-ucloud-ram-application-memory.patch", - "sha256": "af09c7f45e666c4e7e46c5a999cc8414034deb069c7c25c9fdcf29c9b808310e"}, - ] - path.write_text(json.dumps(manifest)) - with self.assertRaisesRegex(ValueError, "qualified reflink"): - require_reflink_restore_runtime(runsc, GVISOR_COMMIT) - entry = {"name": "20260817/0007-ucloud-reflink-application-memory.patch", "sha256": "0" * 64} - manifest["patches"].append(entry) - path.write_text(json.dumps(manifest)) - with self.assertRaisesRegex(ValueError, "qualified reflink"): - require_reflink_restore_runtime(runsc, GVISOR_COMMIT) - entry["sha256"] = REFLINK_RESTORE_PATCH_SHA256 - path.write_text(json.dumps(manifest)) - require_reflink_restore_runtime(runsc, GVISOR_COMMIT) - (root / "gvisor-bin" / "gvisor_sentry").write_bytes(b"changed") - with self.assertRaisesRegex(ValueError, "mismatch"): - require_reflink_restore_runtime(runsc, GVISOR_COMMIT) - def fixture(self, root): files = {} for name in ["runsc", *(f"gvisor-bin/{n}" for n in GVISOR_SIDECARS)]: @@ -118,7 +89,7 @@ def test_node_fences_same_runsc_with_changed_companion(self): def boot_config(): return boot_config_sha256(runsc, GVISOR_COMMIT, network="none", - reflink_memory_restore=False, ram_backing=False) + ram_backing=False) before = boot_config() (root / "gvisor-bin/gvisor_sentry").write_bytes(b"changed kernel") diff --git a/tests/test_hybrid_memory_admission.py b/tests/test_hybrid_memory_admission.py deleted file mode 100644 index 256e8b1b..00000000 --- a/tests/test_hybrid_memory_admission.py +++ /dev/null @@ -1,94 +0,0 @@ -"""Real allocation/journal placement changes precede admission cost quotes.""" -from dataclasses import replace -from types import SimpleNamespace -import unittest -from unittest.mock import patch - -from tests import test_split_memory_lifecycle as fixtures -from tests.admission_backends import AdmissionBackendCase -from sandboxes.direct_registry import DirectSandboxRegistry -from sandboxes.direct_service import DirectSandboxService -from sandboxes.hibernation import HibernationState -from sandboxes.memory_backing import MemoryBackingStore -from sandboxes.models import NodeRuntimeMetrics, ResourceQuantity, utc_now -from sandboxes.resource_evidence import MemoryBackingCapacity -from sandboxes.sandbox import SandboxSpec - -# The noded half starts ucloud-noded (tests/noded_admission.py). -TEST_TIER = "contract" - - -class HybridMemoryAdmissionTests(AdmissionBackendCase, unittest.TestCase): - def setUp(self): - f = self.fixture = fixtures.SplitLifecycleTests() - f.setUp() - self.addCleanup(f.tearDown) - registry = self.registry = DirectSandboxRegistry(f.root / "registry.sqlite") - spec = SandboxSpec(id=f.sandbox.sandbox_id, image="image", memory_mb=4096, - disk_mb=1024, parkable=True, managed_process=True) - registration = registry.plan(spec=spec, sandbox_generation=1, - operation_id="create", runtime_compatibility_sha256="a" * 64, - split_memory_backing=True) - f.sandbox = replace(f.sandbox, spec_sha256=registration.spec_sha256, - workspace_directory=registration.workspace_directory, - memory=registration.memory_reference) - active_root = f.root / "ram" - active_root.mkdir(mode=0o700) - f.warden.config = replace(f.warden.config, application_memory_root=active_root) - f.runner.memory_root = active_root - f.storage = fixtures.SplitStorage(sandbox_id=spec.id, sandbox_generation=1, - volume_id=f.sandbox.workspace_directory, - mount_path=f.config.memory_root / f.sandbox.workspace_directory) - f.storage.mount_path.mkdir() - f.warden.storage = f.storage - f.rootfs.events = f.storage.events - with patch("sandboxes.memory_backing.subprocess.run", - return_value=SimpleNamespace(stdout="tmpfs rw,noswap\n")): - f.warden.memory_backing = MemoryBackingStore(f.config.memory_root, - f.root / "allocations.sqlite", hard_capacity_bytes=64 << 30, - quota=fixtures.FakeQuota(), active_root=active_root) - f.warden.memory_backing.prepare(registration.memory_reference, - sandbox_id=spec.id, sandbox_generation=1) - f.warden.memory_capacity = registry - registration = registry.commit_quota(spec.id, expected_revision=registration.revision, - project_id=1, total_mb=spec.requested_resources().disk_mb, - quota_path=f.storage.mount_path) - registration = registry.commit_rootfs(spec.id, expected_revision=registration.revision, - image_id="sha256:" + "b" * 64, sandbox=f.sandbox) - registry.commit_owned(spec.id, expected_revision=registration.revision) - f.warden.create(f.sandbox, operation_id="create") - self.capture_initial_checkpoint() - self.assertEqual(f.warden.application_memory_mode(spec.id, 1), "ram") - f.warden.config = replace(f.warden.config, reflink_memory_restore=True) - self.service = self.admitted(DirectSandboxService(SimpleNamespace(warden=f.warden, registry=registry))) - self.service.admission_wait_seconds = .05 - self.service.configure_active_capacity(ResourceQuantity(vcpu=8, memory_mb=16 << 10), - runtime_metrics_provider=lambda: NodeRuntimeMetrics(collected_at=utc_now(), - cpu_count=8, cpu_percent=0, memory_total_mb=16 << 10, - memory_available_mb=12 << 10, - memory_backing=MemoryBackingCapacity(total_bytes=8 << 30, - available_bytes=0, identity="ram-mount"))) - - def capture_initial_checkpoint(self): - self.fixture.warden.park(self.fixture.sandbox, operation_id="park-before-upgrade") - - def test_parked_continuation_selects_file_before_growth_admission(self): - service, f = self.service, self.fixture - key = (f.sandbox.sandbox_id, 1) - self.registry.growth_intent(*key, action="wait", request_id="model-request") - service.admit_managed_continuation(*key, "model-request") - self.assertEqual(f.warden.application_memory_mode(*key), "file") - self.assertTrue(self.registry.relay_wake_fence(*key, "model-request")) - self.assertEqual(service.reclaim_demand()[1].ram_backing_bytes, 0) - self.assertEqual(service._restore_cost(*key, ResourceQuantity(memory_mb=4096)).memory_bytes, - 4 << 30) - - def test_absent_candidate_restore_rollback_selects_file_only_after_parked(self): - f = self.fixture - journal = f.warden._journal(f.sandbox) - parked = journal.load() - journal.begin_restore(operation_id="interrupted-restore", expected_revision=parked.revision) - self.assertEqual(f.warden.application_memory_mode(f.sandbox.sandbox_id, 1), "ram") - self.assertEqual(f.warden.reconcile(f.sandbox).state, HibernationState.PARKED) - self.assertEqual(f.warden.application_memory_mode(f.sandbox.sandbox_id, 1), "file") - diff --git a/tests/test_image_foundations.py b/tests/test_image_foundations.py index 5948b133..25a34663 100644 --- a/tests/test_image_foundations.py +++ b/tests/test_image_foundations.py @@ -206,7 +206,7 @@ def check_preparer_resume(self, generation): "sandboxes.managed_registry.RegistryUsageStore": Mock(), "sandboxes.environment_dependencies.EnvironmentDependencyResolver": Mock(), "sandboxes.images.ImageStore": store, - "sandboxes.gateway.registry_refs._persist_registry_image_protection": True, + "sandboxes.gateway.registry_refs.persist_registry_image_protection": True, "sandboxes.environment_artifact.load_image_environment": ("root", SimpleNamespace(components=[])), "sandboxes.registry_disk.registry_disk_usage": SimpleNamespace(used_bytes=0, available_bytes=1024**4), "sandboxes.host_locks.HOST_LOCKS.configure": None, diff --git a/tests/test_image_polling.py b/tests/test_image_polling.py index ba7db09c..c7518a03 100644 --- a/tests/test_image_polling.py +++ b/tests/test_image_polling.py @@ -1,9 +1,7 @@ -from collections import OrderedDict from concurrent.futures import ThreadPoolExecutor from dataclasses import replace from pathlib import Path from tempfile import TemporaryDirectory -from threading import RLock from types import SimpleNamespace import unittest from unittest.mock import Mock @@ -12,7 +10,8 @@ ControlPlaneHandler, ProxiedResponse, ) -from sandboxes.gateway.node_rpc import _node_transport_error_response +from sandboxes.gateway.node_rpc import node_transport_error_response +from sandboxes.gateway.state import GatewayRuntimeState from sandboxes.images import ImageRecord, ImageStore from sandboxes.models import utc_now from tests.gateway_support import gateway_services @@ -21,9 +20,7 @@ class ImagePollingTests(unittest.TestCase): def handler(self): class Handler(ControlPlaneHandler): - image_build_owners = OrderedDict() - image_build_owners_lock = RLock() - image_build_metrics_seen = OrderedDict() + runtime_state = GatewayRuntimeState() h = object.__new__(Handler) h.services = gateway_services() @@ -244,7 +241,7 @@ def fetch(url, path, **kwargs): def test_restarted_owner_does_not_use_old_hint(self): h = self.handler() - h.image_build_owners["build-id"] = ("b", "b", "old") + h.runtime_state.builds.owners["build-id"] = ("b", "b", "old") h.services.fleet.ready_heartbeats = lambda: [self.node("a"), self.node("b", "new")] calls = [] @@ -267,12 +264,12 @@ def test_owner_timeout_is_retryable_without_fanout_and_recovers(self): success = SimpleNamespace(status=200, json=lambda: {"build": running}) h._proxy_request = Mock(side_effect=[ success, - _node_transport_error_response(TimeoutError("fixture timeout")), + node_transport_error_response(TimeoutError("fixture timeout")), success, ]) h._get_image_build("build-id") - self.assertEqual(h.image_build_owners["build-id"], ("owner", "owner", "one")) + self.assertEqual(h.runtime_state.builds.owners["build-id"], ("owner", "owner", "one")) h._get_image_build("build-id") response = h._write_json.call_args self.assertEqual(response.kwargs["status"], 504) @@ -289,7 +286,7 @@ def test_failed_owner_statuses_are_not_absence(self): (502, 502), (503, 503), (400, 502), (403, 502)]: with self.subTest(upstream=upstream): h = self.handler() - h.image_build_owners["build-id"] = ("owner", "owner", "one") + h.runtime_state.builds.owners["build-id"] = ("owner", "owner", "one") h.services.fleet.ready_heartbeats = lambda: [self.node("owner"), self.node("peer")] h._proxy_request = Mock(return_value=ProxiedResponse( upstream, {}, b'{"error":"private upstream detail","retryable":false}' @@ -304,7 +301,7 @@ def test_failed_owner_statuses_are_not_absence(self): def test_missing_owner_heartbeat_is_retryable_without_peer_scan(self): h = self.handler() - h.image_build_owners["build-id"] = ("owner", "owner", "one") + h.runtime_state.builds.owners["build-id"] = ("owner", "owner", "one") h.services.fleet.ready_heartbeats = lambda: [self.node("peer")] h._proxy_request = Mock() h._write_json = Mock() @@ -315,7 +312,7 @@ def test_missing_owner_heartbeat_is_retryable_without_peer_scan(self): def test_confirmed_absence_returns_404_after_owner_and_fallback_probes(self): h = self.handler() - h.image_build_owners["build-id"] = ("owner", "owner", "one") + h.runtime_state.builds.owners["build-id"] = ("owner", "owner", "one") h.services.fleet.ready_heartbeats = lambda: [self.node("owner"), self.node("peer")] h._proxy_request = Mock(return_value=ProxiedResponse(404, {}, b"{}")) h._write_json = Mock() @@ -392,7 +389,7 @@ def fetch(url, path, **kwargs): h._get_image_build("image") self.assertEqual(calls, ["http://a", "http://b"]) self.assertEqual(h._write_json.call_args.args[0]["build"]["build_id"], "b") - self.assertNotIn("image", h.image_build_owners) + self.assertNotIn("image", h.runtime_state.builds.owners) def test_unknown_build_does_not_enrich_unrelated_results(self): h = self.handler() diff --git a/tests/test_image_roots.py b/tests/test_image_roots.py index ec20b525..8d7ae475 100644 --- a/tests/test_image_roots.py +++ b/tests/test_image_roots.py @@ -16,7 +16,7 @@ from sandboxes.environment_dependencies import EnvironmentDependencyResolver from sandboxes.environment_manifest import EnvironmentManifest from sandboxes.gateway.image_roots import ImageRootsStore, retention_view -from sandboxes.gateway.placement import _sandbox_required_capabilities +from sandboxes.gateway.placement import sandbox_required_capabilities from sandboxes.managed_registry import RegistryUsageStore, digest_protection_tag from sandboxes.sandbox import SandboxSpec @@ -83,9 +83,9 @@ def test_the_resolver_dispatches_a_switched_root_and_its_closure(self): def test_a_dispatched_root_requires_both_worker_capabilities(self): spec = SandboxSpec(id="s", image="r/a@" + D["1"], cpus=1, memory_mb=512) - self.assertEqual(_sandbox_required_capabilities(spec.to_dict()), ()) + self.assertEqual(sandbox_required_capabilities(spec.to_dict()), ()) pinned = SandboxSpec(id="s", image="r/a@" + D["1"], cpus=1, memory_mb=512, environment_root=D["2"]) - self.assertEqual(_sandbox_required_capabilities(pinned.to_dict()), + self.assertEqual(sandbox_required_capabilities(pinned.to_dict()), (ENVIRONMENT_ROOT_CAPABILITY, ENVIRONMENT_RAFS_CAPABILITY)) @@ -297,7 +297,7 @@ def test_a_create_with_its_dispatched_root_skips_the_node_pull(self): image = "10.42.0.2:5000/managed/a@" + D["1"] self.assertIsNone(ControlPlaneHandler._ensure_image_for_create(handler, heartbeat, image, D["5"])) self.assertEqual(pulls, []) - with mock.patch("sandboxes.control_plane._heartbeat_has_image", return_value=False): + with mock.patch("sandboxes.control_plane.heartbeat_has_image", return_value=False): ControlPlaneHandler._ensure_image_for_create(handler, heartbeat, image, D["6"]) # Not its dispatched root. ControlPlaneHandler._ensure_image_for_create(handler, heartbeat, image) self.assertEqual(len(pulls), 2) diff --git a/tests/test_memory_backing_mode.py b/tests/test_memory_backing_mode.py index c0ed8183..0d5b307b 100644 --- a/tests/test_memory_backing_mode.py +++ b/tests/test_memory_backing_mode.py @@ -1,7 +1,6 @@ from concurrent.futures import ThreadPoolExecutor from threading import Event from contextlib import closing -from dataclasses import replace from pathlib import Path import sqlite3 from tempfile import TemporaryDirectory @@ -53,66 +52,6 @@ def blocked_validate(*args, **kwargs): release.set() allocation.result(2) - def test_file_mode_is_published_only_after_commit(self): - self.store.prepare(self.ref, **self.owner) - entered, release = Event(), Event() - class SlowCommit(sqlite3.Connection): - def commit(self): - entered.set() - if not release.wait(3): - raise TimeoutError('test failed to release commit') - return super().commit() - def connect(): - return sqlite3.connect(self.store.journal, factory=SlowCommit, check_same_thread=False) - self.store._write_batches.close() - with patch.object(self.store._write_batches, 'connect', side_effect=connect), \ - ThreadPoolExecutor(max_workers=2) as pool: - selection = pool.submit(self.store.prepare_file_restore, self.ref, **self.owner) - try: - self.assertTrue(entered.wait(1)) - read = pool.submit(self.store.active_mode, 'guest', 1) - self.assertEqual(read.result(1), 'ram') - finally: - release.set() - self.assertEqual(selection.result(2).active_mode, 'file') - self.assertEqual(self.store.active_mode('guest', 1), 'file') - - def test_selection_survives_restart_without_reversing_reimport(self): - lease = self.store.prepare(self.ref, **self.owner) - self.assertEqual(lease.active_mode, 'ram') - self.assertEqual(self.store.active_mode('guest', 1), 'ram') - selected = self.store.prepare_file_restore(self.ref, **self.owner) - self.assertEqual(selected.active_mode, 'file') - self.assertEqual(selected.path, lease.path) - restarted = self.open_store() - self.assertEqual(restarted.active_mode('guest', 1), 'file') - self.assertEqual(restarted.require(self.ref, **self.owner).active_mode, 'file') - restarted.delete(self.ref, **self.owner) - self.assertIsNone(restarted.active_mode('guest', 1)) - self.assertEqual(restarted.prepare(self.ref, **self.owner).active_mode, 'file') - - def test_still_present_ram_mapping_cannot_be_abandoned(self): - self.store.prepare(self.ref, **self.owner) - active = self.ram / self.ref.allocation_id / 'application_memory.active' - active.write_bytes(b'live application state') - with self.assertRaisesRegex(MemoryBackingError, 'live RAM'): - self.store.prepare_file_restore(self.ref, **self.owner) - self.assertEqual(active.read_bytes(), b'live application state') - self.assertEqual(self.open_store().active_mode('guest', 1), 'ram') - - def test_missing_stale_and_changed_quota_owners_cannot_select_file(self): - with self.assertRaisesRegex(MemoryBackingError, 'retained'): - self.store.prepare_file_restore(self.ref, **self.owner) - self.store.prepare(self.ref, **self.owner) - for ref, owner in ((self.ref, dict(sandbox_id='guest', sandbox_generation=2)), - (MemoryBackingRef(self.ref.allocation_id, 8192), self.owner)): - with self.assertRaisesRegex(MemoryBackingError, 'retained'): - self.store.prepare_file_restore(ref, **owner) - self.quota.projects.clear() - with self.assertRaisesRegex(MemoryBackingError, 'project changed'): - self.store.prepare_file_restore(self.ref, **self.owner) - self.assertEqual(self.open_store().active_mode('guest', 1), 'ram') - def test_limit_starts_small_and_moves_within_ceiling_and_capacity(self): ref = MemoryBackingRef('guest.sandbox-1', 6144) lease = self.store.prepare(ref, **self.owner, limit_bytes=1024) @@ -171,59 +110,3 @@ def test_journal_from_before_version_3_is_refused_unchanged(self): with closing(sqlite3.connect(journal)) as conn: self.assertEqual(conn.execute('PRAGMA user_version').fetchone()[0], 2) self.assertEqual(len(conn.execute('PRAGMA table_info(allocations)').fetchall()), 6) - - def test_selection_failure_does_not_publish_file_mode(self): - self.store.prepare(self.ref, **self.owner) - real_connect = self.store._connect - class FailedSelection(sqlite3.Connection): - def commit(self): - raise sqlite3.OperationalError('injected durability failure') - def failed_connect(): - return sqlite3.connect(self.store.journal, factory=FailedSelection, check_same_thread=False) - self.store._write_batches.close() - with patch.object(self.store._write_batches, 'connect', side_effect=failed_connect): - with self.assertRaisesRegex(sqlite3.OperationalError, 'durability'): - self.store.prepare_file_restore(self.ref, **self.owner) - self.assertEqual(self.store.active_mode('guest', 1), 'ram') - with closing(real_connect()) as conn: - self.assertEqual(conn.execute('SELECT active_mode FROM allocations').fetchone()[0], 'ram') - - def test_reader_cannot_be_disabled_until_owned_allocations_drain(self): - self.store.configure_reflink_restore(True) - self.store.prepare(self.ref, **self.owner) - self.store.prepare_file_restore(self.ref, **self.owner) - with self.assertRaisesRegex(MemoryBackingError, 'reader is required'): - self.open_store().configure_reflink_restore(False) - self.store.delete(self.ref, **self.owner) - self.open_store().configure_reflink_restore(False) - - -class WardenFileModeTests(unittest.TestCase): - def setUp(self): - self.fixture = fixtures.SplitLifecycleTests() - self.fixture.setUp() - self.addCleanup(self.fixture.tearDown) - self.fixture.split() - self.fixture.warden.config = replace(self.fixture.warden.config, reflink_memory_restore=True) - - def test_restore_uses_owned_file_mode_and_keeps_runtime_identity_stable(self): - f = self.fixture - fingerprint = f.warden._runtime_fingerprint(f.sandbox) - parked = f.warden.park(f.sandbox, operation_id='park-file') - # The dedicated retention tests exercise the registry/project handoff. - with patch.object(f.warden, '_retain_restore_source'): - f.warden.resume(f.sandbox, operation_id='wake-file') - command = next(cmd for cmd in f.runner.commands if 'restore' in cmd) - self.assertIn('--application-memory-reflink-restore=true', command) - self.assertNotIn('--application-memory-ram-backing=true', command) - self.assertIn(f'--application-memory-file-dir={f.config.memory_root}', command) - self.assertEqual(f.warden._runtime_fingerprint(f.sandbox), fingerprint) - self.assertEqual(f.warden.application_memory_mode(f.sandbox.sandbox_id, 1), 'file') - self.assertGreater(parked.hibernation_generation, 0) - - def test_running_runtime_cannot_enter_restore_selection(self): - f = self.fixture - with patch.object(f.warden.memory_backing, 'prepare_file_restore') as select: - with self.assertRaisesRegex(RuntimeError, 'expected parked'): - f.warden.resume(f.sandbox, operation_id='invalid-wake') - select.assert_not_called() diff --git a/tests/test_memory_retention_batch.py b/tests/test_memory_retention_batch.py deleted file mode 100644 index a8cd8ab1..00000000 --- a/tests/test_memory_retention_batch.py +++ /dev/null @@ -1,130 +0,0 @@ -"""Retention batches acknowledge only durable, owner-fenced quota transitions.""" -from concurrent.futures import ThreadPoolExecutor -from pathlib import Path -import sqlite3 -from tempfile import TemporaryDirectory -from threading import Barrier, Event -import unittest - -from sandboxes.checkpoint_components import MemoryBackingRef -from sandboxes.memory_backing import MemoryBackingStore, MemoryBackingError -from tests.test_split_memory_lifecycle import FakeQuota - - -class MemoryRetentionBatchTests(unittest.TestCase): - def setUp(self): - self.tmp = TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - root = Path(self.tmp.name) - self.quota = FakeQuota() - self.store = MemoryBackingStore(root / 'memory', root / 'journal.sqlite', - hard_capacity_bytes=1 << 24, quota=self.quota) - self.refs = [MemoryBackingRef(f'sandbox-{i}.sandbox-1', 1 << 20) for i in range(2)] - for i, ref in enumerate(self.refs): - lease = self.store.prepare(ref, sandbox_id=f'sandbox-{i}', sandbox_generation=1) - path = lease.path / 'hibernate-1' - path.mkdir(mode=0o700) - source = path / 'application_memory.img' - source.write_bytes(b'memory') - source.chmod(0o600) - - def retain(self, i): - self.store.retain_checkpoint(self.refs[i], sandbox_id=f'sandbox-{i}', - sandbox_generation=1, hibernation_generation=1, - manifest_sha256='a' * 64, allocated_bytes=65536) - - def rows(self): - with sqlite3.connect(self.store.journal) as conn: - return conn.execute('SELECT project_id,state FROM retained_checkpoints ORDER BY allocation_id').fetchall() - - def test_concurrent_owners_share_commits_and_quota_sees_durable_prepare(self): - barrier = Barrier(2) - original = self.quota.retain_file - - def assign(path, project, size): - # A separate connection must see the prepared claim BEFORE the - # irreversible inode ownership change, even with a shared commit. - self.assertIn((project, 'preparing'), self.rows()) - barrier.wait(timeout=5) - original(path, project, size) - - self.quota.retain_file = assign - self.store._write_batches.delay = .05 - operations = self.store._write_batches.operations - commits = self.store._write_batches.commits - with ThreadPoolExecutor(2) as pool: - list(pool.map(self.retain, range(2))) - rows = self.rows() - self.assertEqual([state for _, state in rows], ['ready', 'ready']) - self.assertEqual(len({project for project, _ in rows}), 2) - self.assertEqual(self.store._write_batches.operations - operations, 4) - self.assertLess(self.store._write_batches.commits - commits, 4) - - def test_slow_quota_setup_does_not_stall_other_owners(self): - # xfs_quota runs while one owner prepares; other owners' wake reads - # and journal writes must not queue behind that subprocess. - entered, release = Event(), Event() - original = self.quota.provision - - def slow_provision(*args): - entered.set() - self.assertTrue(release.wait(5)) - original(*args) - - self.quota.provision = slow_provision - ref = MemoryBackingRef('sandbox-9.sandbox-1', 1 << 20) - with ThreadPoolExecutor(2) as pool: - creating = pool.submit(self.store.prepare, ref, sandbox_id='sandbox-9', - sandbox_generation=1) - try: - self.assertTrue(entered.wait(5)) - woken = pool.submit(self.store.require, self.refs[0], - sandbox_id='sandbox-0', sandbox_generation=1) - self.assertEqual(woken.result(2).sandbox_id, 'sandbox-0') - retained = pool.submit(self.retain, 1) - retained.result(2) - finally: - release.set() - self.assertEqual(creating.result(5).sandbox_id, 'sandbox-9') - - def test_commit_failures_preserve_recoverable_ownership(self): - for failed_commit in (1, 2): - with self.subTest(failed_commit=failed_commit): - # A fresh owner is used for each failure point. - i = failed_commit - 1 - self.store = MemoryBackingStore(self.store.root, self.store.journal, - hard_capacity_bytes=1 << 24, quota=self.quota) - attempts = [] - journal = self.store.journal - - class FailingConnection(sqlite3.Connection): - def commit(conn): - attempts.append(True) - if len(attempts) == failed_commit: - raise sqlite3.OperationalError('injected commit failure') - return super().commit() - - def connect(): - conn = sqlite3.connect(journal, factory=FailingConnection, check_same_thread=False) - conn.execute('PRAGMA synchronous=FULL') - return conn - - self.store._write_batches.connect = connect - with self.assertRaisesRegex(sqlite3.OperationalError, 'injected'): - self.retain(i) - rows = self.rows() - if failed_commit == 1: - self.assertEqual(rows, []) - self.assertFalse(any(p.name == 'application_memory.img' for p in self.quota.projects)) - else: - self.assertEqual(rows[-1][1], 'preparing') - self.store = MemoryBackingStore(self.store.root, journal, - hard_capacity_bytes=1 << 24, quota=self.quota) - self.retain(i) - self.assertTrue(all(state == 'ready' for _, state in self.rows())) - - def test_replaced_journal_fails_closed_before_assignment(self): - self.store.journal.rename(self.store.journal.with_suffix('.old')) - self.store.journal.touch() - with self.assertRaisesRegex(MemoryBackingError, 'replaced'): - self.store._write_batches.validate() diff --git a/tests/test_migration_runtime_eligibility.py b/tests/test_migration_runtime_eligibility.py index 8c10636e..71fa4e75 100644 --- a/tests/test_migration_runtime_eligibility.py +++ b/tests/test_migration_runtime_eligibility.py @@ -1,15 +1,13 @@ from dataclasses import replace -from types import SimpleNamespace import unittest from tests import test_control_plane as fixtures -from tests.gateway_support import gateway_services from sandboxes.capabilities import ( HIBERNATE_LOCAL_CAPABILITY, HOST_EROFS_CAPABILITY, RUNTIME_COMPATIBILITY_CAPABILITY_PREFIX, STORAGE_NATIVE_CAPABILITY, STORAGE_NATIVE_MIGRATION_CAPABILITY, ) -from sandboxes.control_plane import ControlPlaneHandler +from sandboxes.gateway.migrations import select_migration_destination from sandboxes.models import NodeHeartbeat, NodeRuntimeMetrics, ResourceQuantity, utc_now @@ -48,13 +46,14 @@ def source(self, *, detached=False, published=False): return route, RUNTIME_COMPATIBILITY_CAPABILITY_PREFIX + snapshot.manifest.runtime.node_compatibility_sha256 def select(self, route, destinations, owner=None): - handler = object.__new__(ControlPlaneHandler) - handler.services = gateway_services(heartbeat_ttl_seconds=120) - handler.services.placement.routes = lambda: [route] - handler.routing_store = SimpleNamespace(sandbox_migrations=lambda **_: []) - handler.services.fleet.ready_sandbox_heartbeats = lambda **_kwargs: destinations - handler._heartbeat_for_route = lambda **_: owner - return handler._select_migration_destination(route, requested_node_id="") + return select_migration_destination( + route, + ready_heartbeats=destinations, + routes=[route], + active_migrations=[], + source_heartbeat=owner, + requested_node_id="", + ) def test_source_less_checkpoint_requires_its_exact_advertised_runtime(self): route, capability = self.source(detached=True, published=True) diff --git a/tests/test_migration_selection.py b/tests/test_migration_selection.py new file mode 100644 index 00000000..f21c26ad --- /dev/null +++ b/tests/test_migration_selection.py @@ -0,0 +1,187 @@ +"""Pure decision tests for gateway migration destination selection.""" + +from __future__ import annotations + +from datetime import datetime, timezone +import unittest + +from sandboxes.capabilities import ( + DISK_QUOTA_CAPABILITY, + HIBERNATE_LOCAL_CAPABILITY, + RUNTIME_COMPATIBILITY_CAPABILITY_PREFIX, + RUNTIME_CPU_CAPABILITY_PREFIX, + STORAGE_NATIVE_CAPABILITY, + STORAGE_NATIVE_MIGRATION_CAPABILITY, +) +from sandboxes.gateway.migrations import ( + cold_offload_fence_matches, + migration_pending_demand_id, + parse_detach_request, + parse_migration_request, + select_migration_destination, +) +from sandboxes.models import ( + NodeHeartbeat, + NodeRuntimeMetrics, + ResourceQuantity, + SOFT_DRAIN_LABEL, +) +from sandboxes.routing import SandboxRoute + +TEST_TIER = "unit" + +_NOW = datetime(2026, 10, 18, 0, 0, tzinfo=timezone.utc) +_RUNTIME_CAP = RUNTIME_COMPATIBILITY_CAPABILITY_PREFIX + ("a" * 64) +_CPU_CAP_A = RUNTIME_CPU_CAPABILITY_PREFIX + ("1" * 64) +_CPU_CAP_B = RUNTIME_CPU_CAPABILITY_PREFIX + ("2" * 64) + + +def _heartbeat( + node_id: str, + *, + disk_free_mb: int = 20_000, + capabilities: tuple[str, ...] = ( + DISK_QUOTA_CAPABILITY, + HIBERNATE_LOCAL_CAPABILITY, + STORAGE_NATIVE_CAPABILITY, + STORAGE_NATIVE_MIGRATION_CAPABILITY, + _RUNTIME_CAP, + _CPU_CAP_A, + ), + cached_images: tuple[str, ...] = (), + soft_drained: bool = False, +) -> NodeHeartbeat: + total = ResourceQuantity(vcpu=16.0, memory_mb=32_768, disk_mb=disk_free_mb) + labels = {SOFT_DRAIN_LABEL: _NOW.isoformat()} if soft_drained else {} + return NodeHeartbeat( + node_id=node_id, + job_id=f"job-{node_id}", + updated_at=_NOW, + active_sandboxes=0, + node_url=f"http://{node_id}:8090", + capabilities=capabilities, + total_resources=total, + resources_known=True, + used_resources=ResourceQuantity(), + runtime_metrics=NodeRuntimeMetrics( + collected_at=_NOW, + cpu_count=16, + memory_total_mb=32_768, + memory_available_mb=32_768, + storage_hard_capacity_mb=disk_free_mb, + ), + cached_images=cached_images, + cached_images_known=True, + labels=labels, + inventory_complete=True, + admission_open=True, + ) + + +def _source_route(node_id: str = "node-src", *, image: str = "app:v1") -> SandboxRoute: + return SandboxRoute( + sandbox_id="sbx-1", + node_id=node_id, + job_id=f"job-{node_id}", + node_url=f"http://{node_id}:8090", + resources=ResourceQuantity(vcpu=2.0, memory_mb=2048, disk_mb=4096), + spec={"id": "sbx-1", "image": image}, + state="parked", + generation=1, + create_operation_id="op-1", + spec_hash="c" * 64, + worker_state="attached", + created_at=_NOW.isoformat(), + updated_at=_NOW.isoformat(), + ) + + +class MigrationDestinationSelectionTests(unittest.TestCase): + def test_prefers_image_resident_and_excludes_source_and_cpu_mismatch(self) -> None: + src = _heartbeat("node-src") + wrong_cpu = _heartbeat("node-bad-cpu", capabilities=( + DISK_QUOTA_CAPABILITY, + STORAGE_NATIVE_CAPABILITY, + STORAGE_NATIVE_MIGRATION_CAPABILITY, + _RUNTIME_CAP, + _CPU_CAP_B, + )) + cold_big = _heartbeat("node-cold", disk_free_mb=80_000) + warm_small = _heartbeat("node-warm", disk_free_mb=20_000, cached_images=("app:v1",)) + + chosen = select_migration_destination( + _source_route(), + ready_heartbeats=[src, wrong_cpu, cold_big, warm_small], + routes=[], + active_migrations=[], + ) + self.assertIsNotNone(chosen) + assert chosen is not None + self.assertEqual(chosen.node_id, "node-warm") + + def test_plain_move_rejects_soft_drained_but_wake_falls_back(self) -> None: + src = _heartbeat("node-src") + drained = _heartbeat("node-drained", soft_drained=True) + + self.assertIsNone( + select_migration_destination( + _source_route(), + ready_heartbeats=[src, drained], + routes=[], + active_migrations=[], + require_active_resources=False, + ) + ) + wake_choice = select_migration_destination( + _source_route(), + ready_heartbeats=[src, drained], + routes=[], + active_migrations=[], + require_active_resources=True, + ) + self.assertIsNotNone(wake_choice) + assert wake_choice is not None + self.assertEqual(wake_choice.node_id, "node-drained") + + +class MigrationRequestParsingTests(unittest.TestCase): + def test_parse_detach_request_accepts_empty_or_if_cold_dict(self) -> None: + self.assertEqual(parse_detach_request({}), (False, None)) + fence = {"generation": 2, "state": "parked"} + self.assertEqual(parse_detach_request({"if_cold": fence}), (True, fence)) + with self.assertRaises(ValueError): + parse_detach_request(["not-a-dict"]) + with self.assertRaises(ValueError): + parse_detach_request({"other": 1}) + with self.assertRaises(ValueError): + parse_detach_request({"if_cold": "invalid"}) + + def test_cold_offload_fence_matches_enforces_exact_types(self) -> None: + expected = {"generation": 1, "active": False} + self.assertTrue(cold_offload_fence_matches(expected, {"generation": 1, "active": False})) + self.assertFalse(cold_offload_fence_matches(expected, {"generation": True, "active": False})) + self.assertFalse(cold_offload_fence_matches(expected, {"generation": 2, "active": False})) + + def test_parse_migration_request_uses_default_id_and_strict_soft_drain(self) -> None: + self.assertEqual( + parse_migration_request({}, default_migration_id="mig-default"), + ("mig-default", "", False), + ) + self.assertEqual( + parse_migration_request( + {"migration_id": " mig-1 ", "destination_node_id": " n2 ", "soft_drain": True}, + default_migration_id="mig-default", + ), + ("mig-1", "n2", True), + ) + self.assertEqual( + parse_migration_request({"soft_drain": "true"}, default_migration_id="mig-default"), + ("mig-default", "", False), + ) + self.assertEqual(migration_pending_demand_id("sbx-1"), "__migration__:sbx-1") + with self.assertRaises(ValueError): + parse_migration_request("bad", default_migration_id="mig-default") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_network_policy.py b/tests/test_network_policy.py index b5d9de80..9b4027d7 100644 --- a/tests/test_network_policy.py +++ b/tests/test_network_policy.py @@ -6,7 +6,7 @@ import unittest from sandboxes.config import SandboxPoolConfig -from sandboxes.gateway.placement import _sandbox_required_capabilities +from sandboxes.gateway.placement import sandbox_required_capabilities from sandboxes.direct_network import DirectNetworkError, DirectNetworkManager from sandboxes.direct_oci import DirectOciConfigBuilder, DirectOciConfigError from sandboxes.direct_provisioner import DirectSandboxProvisioner @@ -41,7 +41,7 @@ def test_strict_contract_and_legacy_fingerprint(self): sandbox_spec_fingerprint(spec), sandbox_spec_fingerprint(restricted) ) self.assertEqual( - _sandbox_required_capabilities(restricted.to_dict()), + sandbox_required_capabilities(restricted.to_dict()), ("network-policy-relay-v1:default",), ) for invalid in ( diff --git a/tests/test_node_http_pools.py b/tests/test_node_http_pools.py index 8ce24855..52886232 100644 --- a/tests/test_node_http_pools.py +++ b/tests/test_node_http_pools.py @@ -90,12 +90,12 @@ def test_pool_admission_failure_is_safe_but_transport_timeout_remains_ambiguous( request.Request("http://node/v1/sandboxes/one/exec", data=b"{}"), timeout=1, authenticated=True, ) - response = node_rpc._node_transport_error_response(raised.exception.reason) + response = node_rpc.node_transport_error_response(raised.exception.reason) self.assertEqual(response.status, 503) self.assertTrue(json.loads(response.body)["retryable"]) self.assertEqual(json.loads(response.body)["error_code"], "http_request_capacity_exhausted") self.assertEqual(response.headers["Retry-After"], "1") self.assertEqual(response.transport_error_kind, "") - ambiguous = node_rpc._node_transport_error_response(TimeoutError("timed out")) + ambiguous = node_rpc.node_transport_error_response(TimeoutError("timed out")) self.assertEqual(ambiguous.status, 504) self.assertNotIn("error_code", json.loads(ambiguous.body)) diff --git a/tests/test_placement_choice.py b/tests/test_placement_choice.py index e7be2595..cb04632b 100644 --- a/tests/test_placement_choice.py +++ b/tests/test_placement_choice.py @@ -23,7 +23,7 @@ ) from sandboxes.placement_accounting import ( PlacementReservation, - _node_available_resources, + node_available_resources, ) from sandboxes.placement_choice import ( PENDING_RESIDENCY, @@ -115,7 +115,7 @@ def test_fit_charges_records_in_placement_accounting_terms(self): ] self.assertTrue(node_fits(node, SHAPE, charges[:1])) self.assertFalse(node_fits(node, SHAPE, charges)) - self.assertEqual(_node_available_resources(node, charges).disk_mb, 0) + self.assertEqual(node_available_resources(node, charges).disk_mb, 0) self.assertEqual(fit_count(node, PLAIN, [], 10), 2) self.assertEqual(fit_count(node, PLAIN, charges[:1], 10), 1) self.assertEqual(fit_count(heartbeat("b"), PLAIN, [], 5), 5) diff --git a/tests/test_reflink_retention.py b/tests/test_reflink_retention.py deleted file mode 100644 index ece1223e..00000000 --- a/tests/test_reflink_retention.py +++ /dev/null @@ -1,430 +0,0 @@ -"""Real ownership journals with injected XFS/native boundaries. - -Kernel FICLONE/quota behavior has a separate Linux qualification; these tests -exercise ordering, failure recovery, and exact durable capacity ownership. -""" -from dataclasses import replace -from contextlib import closing -from concurrent.futures import ThreadPoolExecutor -import os -import sqlite3 -from threading import Event, Thread -from types import SimpleNamespace -import unittest -from unittest.mock import patch - -from sandboxes.direct_registry import ( - DirectSandboxRegistry, DirectRegistryCapacityUnavailable, DirectRegistryConflictError, -) -from sandboxes.direct_runtime import build_direct_runtime_service -from sandboxes.direct_service import DirectSandboxService -from sandboxes.direct_warden import DirectRunscWarden, DirectWardenError -from sandboxes.hibernation import HibernationState -from sandboxes.memory_backing import MemoryBackingStore, MemoryBackingError -from sandboxes.sandbox import SandboxSpec -from tests import test_direct_warden as fixtures -from tests import test_split_memory_lifecycle as split_fixtures - -TEST_TIER = "contract" - - -class RetentionQuota(split_fixtures.FakeQuota): - def __init__(self): - super().__init__() - self.events = [] - self.failure = None - self.before_assignment = lambda: None - self.retained_projects = set() - self.fail_release = False - - def retain_file(self, path, project_id, quota_bytes): - self.before_assignment() - self.events.append(('before', project_id, quota_bytes)) - if self.failure == 'before': - raise OSError('injected before assignment') - self.projects[path] = (project_id, quota_bytes) - self.retained_projects.add(project_id) - self.events.append(('assigned', project_id, quota_bytes)) - if self.failure == 'after': - raise OSError('injected after assignment') - - def release(self, root, project_id): - self.events.append(('release', project_id)) - if project_id in self.retained_projects and self.fail_release: - raise OSError('injected retention trim failure') - super().release(root, project_id) - - -class ReflinkRetentionTests(unittest.TestCase): - def setUp(self): - fixtures.DirectRunscWardenTests.setUp(self) - self.addCleanup(self.temporary.cleanup) - self.spec = SandboxSpec(id=self.sandbox.sandbox_id, image='image', memory_mb=4, disk_mb=16, - parkable=True) - self.base = self.spec.requested_resources().disk_mb - self.registry = DirectSandboxRegistry(self.root / 'direct-registry.sqlite', hard_disk_capacity_mb=self.base+100) - planned = self.registry.plan(spec=self.spec, sandbox_generation=1, operation_id='create:1', - runtime_compatibility_sha256='b'*64, split_memory_backing=True) - self.sandbox = replace(self.sandbox, spec_sha256=planned.spec_sha256) - split_fixtures.SplitLifecycleTests.split(self, planned.memory_reference) - self.quota = RetentionQuota() - self.quota.projects.update(self.warden.memory_backing.quota.projects) - self.warden.memory_backing.quota = self.quota - quota = self.registry.commit_quota(self.spec.id, expected_revision=planned.revision, - project_id=1, total_mb=self.base, quota_path=self.config.memory_root / self.memory_directory) - rootfs = self.registry.commit_rootfs(self.spec.id, expected_revision=quota.revision, - image_id='sha256:'+'e'*64, sandbox=self.sandbox) - self.registry.commit_owned(self.spec.id, expected_revision=rootfs.revision) - self.config = replace(self.config, reflink_memory_restore=True) - self.warden.config = self.config - self.warden.memory_capacity = self.registry - self.warden.memory_backing.configure_reflink_restore(True) - self.runner.identity_config = self.config - self.warden.park(self.sandbox, operation_id='park:1') - self.source = self.warden.artifacts.generation_path(sandbox_id=self.spec.id, - sandbox_generation=1, hibernation_generation=1) / 'application_memory.img' - self.source_bytes = self.source.read_bytes() - self.source_identity = (self.source.stat().st_dev, self.source.stat().st_ino) - self.base_project = self.quota.projects[self.config.memory_root / self.memory_directory] - self.quota.before_assignment = self.assert_reserved - - def assert_reserved(self): - self.assertGreater(self.registry.reflink_overlap_bytes(), 0) - self.assertEqual(len(self.registry.list_reflink_overlaps(self.spec.id, 1)), 1) - self.assertEqual(self.quota.projects[self.config.memory_root / self.memory_directory], self.base_project) - - def assert_source(self): - self.assertEqual(self.source.read_bytes(), self.source_bytes) - self.assertEqual((self.source.stat().st_dev, self.source.stat().st_ino), self.source_identity) - - def reopen(self): - old = self.warden.memory_backing - store = MemoryBackingStore(old.root, old.journal, hard_capacity_bytes=old.hard_capacity_bytes, - quota=self.quota) - self.registry = DirectSandboxRegistry(self.registry.path, hard_disk_capacity_mb=self.base+100) - self.warden = DirectRunscWarden(self.config, runner=self.runner, fencer=self.fencer, - storage=self.storage, rootfs_lifecycle=self.rootfs, memory_backing=store, - memory_capacity=self.registry) - - def test_capacity_denial_precedes_project_assignment_and_candidate(self): - self.registry.hard_disk_capacity_mb = self.base - with self.assertRaises(DirectRegistryCapacityUnavailable): - self.warden.resume(self.sandbox, operation_id='wake:1') - self.assertEqual(self.quota.events, []) - self.assertEqual(self.registry.reflink_overlap_bytes(), 0) - self.assert_source() - self.assertEqual(self.warden.inspect(self.sandbox).state, HibernationState.PARKED) - self.assertFalse(any('restore' in command for command in self.runner.commands)) - - def test_assignment_failures_recover_same_source_and_claim_after_restart(self): - for failure in ('before', 'after'): - with self.subTest(failure=failure): - self.quota.failure = failure - with self.assertRaisesRegex(OSError, 'assignment'): - self.warden.resume(self.sandbox, operation_id='wake:' + failure) - self.assert_source() - self.assert_reserved() - with closing(sqlite3.connect(self.warden.memory_backing.journal)) as conn: - self.assertEqual(conn.execute('SELECT state FROM retained_checkpoints').fetchone()[0], 'preparing') - self.reopen() - self.quota.failure = None - running = self.warden.resume(self.sandbox, operation_id='wake:success') - self.assertEqual(running.state, HibernationState.RUNNING) - self.assert_reserved() - self.warden.reconcile_retired_memory_capacity() - self.assertEqual(self.registry.reflink_overlap_bytes(), 0) - self.assertFalse(self.source.exists()) - assigned = {event[1] for event in self.quota.events if event[0] == 'assigned'} - self.assertEqual(len(assigned), 1) - self.assertEqual(self.quota.projects[self.config.memory_root / self.memory_directory], self.base_project) - - def test_failed_candidate_retries_without_consuming_immutable_source(self): - self.runner.fail_readiness = True - with self.assertRaises(DirectWardenError): - self.warden.resume(self.sandbox, operation_id='wake:failed') - self.assert_source() - self.assert_reserved() - self.assertEqual(self.warden.inspect(self.sandbox).state, HibernationState.PARKED) - self.reopen() - self.runner.fail_readiness = False - self.assertEqual(self.warden.resume(self.sandbox, operation_id='wake:retry').state, HibernationState.RUNNING) - self.assert_reserved() - self.warden.reconcile_retired_memory_capacity() - self.assertEqual(self.registry.reflink_overlap_bytes(), 0) - - def test_running_recovery_releases_claim_after_artifact_was_already_removed(self): - self.quota.fail_release = True - running = self.warden.resume(self.sandbox, operation_id='wake:1') - self.assertEqual(running.state, HibernationState.RUNNING) - self.assertTrue(self.source.parent.exists()) - self.assert_reserved() - with self.assertRaisesRegex(OSError, 'trim failure'): - self.warden.reconcile_retired_memory_capacity() - self.assertFalse(self.source.parent.exists()) - self.reopen() - self.quota.fail_release = False - self.assertEqual(self.warden.reconcile(self.sandbox).state, HibernationState.RUNNING) - self.assert_reserved() - self.warden.reconcile_retired_memory_capacity() - self.assertEqual(self.registry.reflink_overlap_bytes(), 0) - self.warden.reconcile(self.sandbox) - self.assertEqual(self.registry.list_reflink_overlaps(self.spec.id, 1), ()) - - def test_slow_physical_release_holds_neither_wake_nor_lifecycle_lock(self): - running = self.warden.resume(self.sandbox, operation_id='wake:1') - self.assertEqual(running.state, HibernationState.RUNNING) - self.assertFalse(any(event[0] == 'release' for event in self.quota.events)) - self.assert_reserved() - entered, finish = Event(), Event() - def trim(*_): - entered.set() - self.assertTrue(finish.wait(3)) - with ThreadPoolExecutor(1) as threads, patch.object(self.quota, 'release_many', side_effect=trim): - cleanup = threads.submit(self.warden.reconcile_retired_memory_capacity) - try: - self.assertTrue(entered.wait(3)) - # The ordinary foreground journal fence is available while - # physical cleanup blocks; running reconciliation cannot trim. - with self.warden._locked(self.sandbox): - self.assertEqual(self.warden._journal(self.sandbox).load().state, - HibernationState.RUNNING) - self.assertEqual(self.warden.reconcile(self.sandbox).state, HibernationState.RUNNING) - self.assert_reserved() - finally: - finish.set() - self.assertEqual(cleanup.result(3), 1) - self.assertEqual(self.registry.reflink_overlap_bytes(), 0) - - def test_slow_old_generation_unlink_does_not_block_reconcile_capture_or_wake(self): - self.warden.resume(self.sandbox, operation_id='wake:1') - self.assert_source() # Wake did not unlink the immutable generation. - old_directory_inode = self.source.parent.stat().st_ino - entered, finish = Event(), Event() - unlink = os.unlink - - def slow_unlink(name, *, dir_fd=None): - if (name == 'application_memory.img' and dir_fd is not None - and os.fstat(dir_fd).st_ino == old_directory_inode): - entered.set() - self.assertTrue(finish.wait(5)) - return unlink(name, dir_fd=dir_fd) - - self.quota.before_assignment = lambda: None - with ThreadPoolExecutor(2) as threads, patch('sandboxes.hibernation.os.unlink', side_effect=slow_unlink): - cleanup = threads.submit(self.warden.reconcile_retired_memory_capacity) - try: - self.assertTrue(entered.wait(2)) - self.assertEqual(self.warden.reconcile(self.sandbox).state, HibernationState.RUNNING) - parked = threads.submit(self.warden.park, self.sandbox, operation_id='park:2').result(2) - self.assertEqual(parked.hibernation_generation, 2) - # A later restore has independent source files and remains - # runnable while old-generation fsync/unlink is stalled. - running = threads.submit(self.warden.resume, self.sandbox, operation_id='wake:2').result(2) - self.assertEqual(running.state, HibernationState.RUNNING) - newer = self.source.parent.parent / 'hibernate-2' / 'application_memory.img' - self.assertTrue(newer.exists()) - self.assertEqual(len(self.registry.list_reflink_overlaps()), 2) - finally: - finish.set() - self.assertEqual(cleanup.result(2), 1) - self.assertTrue(newer.exists()) - self.assertEqual(len(self.registry.list_reflink_overlaps()), 1) - self.warden.reconcile_retired_memory_capacity() - self.assertEqual(self.registry.reflink_overlap_bytes(), 0) - - def test_current_failed_restore_source_cannot_be_retired(self): - self.runner.fail_readiness = True - with self.assertRaises(DirectWardenError): - self.warden.resume(self.sandbox, operation_id='wake:failed') - self.assertEqual(self.warden.reconcile_retired_memory_capacity(), 0) - self.assert_source() - self.assert_reserved() - - def test_repeated_wakes_reuse_retirement_lock_and_report_preparation(self): - self.quota.before_assignment = lambda: None - for generation in range(1, 4): - timings = {} - self.warden.resume(self.sandbox, operation_id=f'wake:{generation}', timings=timings) - preparation = ('prepare_workspace', 'validate_checkpoint', 'join_network_prepare', - 'prepare_memory', 'retain_source') - for phase in preparation: - self.assertGreaterEqual(timings[phase], 0) - self.assertLessEqual(sum(timings[phase] for phase in preparation), - timings['validate_artifact']) - self.assertEqual(self.warden.reconcile_retired_memory_capacity(), 1) - self.assertEqual(len(list(self.warden.artifacts.root.glob('.retire-*.lock'))), 1) - if generation < 3: - self.warden.park(self.sandbox, operation_id=f'park:{generation + 1}') - - def test_retirement_crash_after_payload_unlink_resumes_from_authenticated_manifest(self): - self.warden.resume(self.sandbox, operation_id='wake:1') - unlink = os.unlink - - def crash(name, *, dir_fd=None): - result = unlink(name, dir_fd=dir_fd) - if name == 'application_memory.img': - raise OSError('injected retirement crash after unlink') - return result - - with patch('sandboxes.hibernation.os.unlink', side_effect=crash): - with self.assertRaisesRegex(OSError, 'retirement crash'): - self.warden.reconcile_retired_memory_capacity() - self.assertFalse(self.source.exists()) - self.assertTrue((self.source.parent / self.warden.artifacts.MANIFEST_NAME).exists()) - self.assert_reserved() - self.reopen() - self.assertEqual(self.warden.reconcile(self.sandbox).state, HibernationState.RUNNING) - self.assertEqual(self.warden.reconcile_retired_memory_capacity(), 1) - self.assertEqual(self.registry.reflink_overlap_bytes(), 0) - - def test_retirement_wrong_manifest_cannot_unlink_source(self): - self.warden.resume(self.sandbox, operation_id='wake:1') - claim = self.registry.list_reflink_overlaps()[0] - with patch.object(self.registry, 'list_reflink_overlaps', return_value=(replace(claim, manifest_sha256='0'*64),)): - with self.assertRaisesRegex(Exception, 'identity changed'): - self.warden.reconcile_retired_memory_capacity() - self.assert_source() - self.assert_reserved() - - def test_existing_service_reconciliation_loop_finishes_retirement(self): - self.warden.resume(self.sandbox, operation_id='wake:maintenance') - service = DirectSandboxService(SimpleNamespace(warden=self.warden, registry=self.registry, - image_cache_reconciliation_pending=False), deletion_reconcile_interval_seconds=.001) - reconcile = self.warden.reconcile_retired_memory_capacity - def once(): - try: - return reconcile() - finally: - service._stop_event.set() - with patch.object(self.warden, 'reconcile_retired_memory_capacity', side_effect=once) as cleanup: - thread = Thread(target=service._deletion_reconciliation_loop) - thread.start() - thread.join(3) - self.assertFalse(thread.is_alive()) - cleanup.assert_called_once() - self.assertEqual(self.registry.reflink_overlap_bytes(), 0) - - def test_delete_releases_only_after_owned_files_are_deleted(self): - with patch.object(self.warden.memory_backing, 'retain_checkpoint', side_effect=OSError('before local journal')): - with self.assertRaises(OSError): - self.warden.resume(self.sandbox, operation_id='wake:1') - self.assert_reserved() - self.warden.delete(self.sandbox) - with self.assertRaisesRegex(DirectWardenError, 'still exists'): - self.warden.release_deleted_memory_capacity(self.sandbox) - self.assert_reserved() - self.warden.memory_backing.delete(self.sandbox.memory, sandbox_id=self.spec.id, sandbox_generation=1) - self.warden.release_deleted_memory_capacity(self.sandbox) - self.assertEqual(self.registry.reflink_overlap_bytes(), 0) - - def test_open_source_reader_keeps_physical_claim_after_unlink(self): - store = self.warden.memory_backing - with store.read_lease(self.sandbox.memory, sandbox_id=self.spec.id, sandbox_generation=1): - with self.source.open('rb') as reader: - running = self.warden.resume(self.sandbox, operation_id='wake:1') - self.assertEqual(running.state, HibernationState.RUNNING) - self.assertTrue(self.source.exists()) - self.assertEqual(reader.read(), self.source_bytes) - self.assert_reserved() - self.assertEqual(self.warden.reconcile_retired_memory_capacity(), 0) - self.assertFalse(self.source.exists()) - self.warden.reconcile_retired_memory_capacity() - self.assertEqual(self.registry.reflink_overlap_bytes(), 0) - - def test_retention_retry_rejects_a_replaced_source_inode(self): - self.quota.failure = 'after' - with self.assertRaises(OSError): - self.warden.resume(self.sandbox, operation_id='wake:1') - claim = self.registry.list_reflink_overlaps(self.spec.id, 1)[0] - original = self.source.with_suffix('.original') - self.source.rename(original) - self.source.write_bytes(self.source_bytes) - self.source.chmod(0o600) - with self.assertRaisesRegex(MemoryBackingError, 'identity conflicts'): - self.warden.memory_backing.retain_checkpoint(self.sandbox.memory, - sandbox_id=self.spec.id, sandbox_generation=1, hibernation_generation=1, - manifest_sha256=claim.manifest_sha256, allocated_bytes=claim.allocated_bytes) - self.assert_reserved() - - def test_feature_disable_is_fenced_until_deleted_owner_retention_drains(self): - self.quota.failure = 'after' - with self.assertRaises(OSError): - self.warden.resume(self.sandbox, operation_id='wake:1') - self.warden.delete(self.sandbox) - self.warden.memory_backing.delete(self.sandbox.memory, sandbox_id=self.spec.id, sandbox_generation=1) - # Simulate restart after allocation deletion, before ancillary project - # and global capacity cleanup. Disabling the reader cannot strand it. - with self.assertRaisesRegex(MemoryBackingError, 'reader is required'): - self.warden.memory_backing.configure_reflink_restore(False) - self.quota.failure = None - self.warden.release_deleted_memory_capacity(self.sandbox) - self.warden.memory_backing.configure_reflink_restore(False) - - def test_factory_cannot_disable_reader_with_registry_only_orphan_claim(self): - with patch.object(self.warden.memory_backing, 'retain_checkpoint', side_effect=OSError('before local row')): - with self.assertRaises(OSError): - self.warden.resume(self.sandbox, operation_id='wake:1') - self.warden.delete(self.sandbox) - self.warden.memory_backing.delete(self.sandbox.memory, sandbox_id=self.spec.id, sandbox_generation=1) - self.assertGreater(self.registry.reflink_overlap_bytes(), 0) - with (patch('sandboxes.direct_runtime.installed_sidecar_fingerprints', return_value={}), - patch('sandboxes.direct_runtime.require_capture_barrier_runtime'), - patch('sandboxes.direct_runtime._cpu_features_sha256', return_value='a'*64), - patch('sandboxes.direct_runtime.StorageNativeNodeClient.wait_ready', return_value={'metrics': {}}), - patch('sandboxes.direct_runtime.DirectRunscWarden') as constructor): - with self.assertRaisesRegex(ValueError, 'overlap capacity drains'): - build_direct_runtime_service(state_root=self.root, volume_mount_root=self.config.memory_root, - runsc=self.config.runsc, runsc_commit='a'*40, init_binary=self.root/'init', - storage_native_socket=self.root/'storage.sock', memory_backing_hard_capacity_bytes=1 << 30, - environment_registry=object(), environment_backend_socket=self.root/'environment-io.sock') - constructor.assert_not_called() - - def test_same_parked_incarnation_reimport_gets_fresh_retention_project(self): - self.quota.failure = 'after' - with self.assertRaises(OSError): - self.warden.resume(self.sandbox, operation_id='wake:failed') - old_claim = self.registry.list_reflink_overlaps(self.spec.id, 1)[0] - old_project = next(iter(self.quota.retained_projects)) - deleting = self.registry.begin_delete(self.spec.id, expected_revision=self.registry.get(self.spec.id).revision) - self.warden.delete(self.sandbox) - store = self.warden.memory_backing - store.delete(self.sandbox.memory, sandbox_id=self.spec.id, sandbox_generation=1) - self.warden.release_deleted_memory_capacity(self.sandbox) - self.registry.commit_deleted(self.spec.id, sandbox_generation=1, expected_revision=deleting.revision) - self.assertEqual(self.registry.reflink_overlap_bytes(), 0) - - # The migration protocol permits this exact sandbox generation to - # return with a fresh migration ID; no guest execution happened away. - imported = self.registry.plan_import(spec=self.spec, sandbox_generation=1, - operation_id='import:back', runtime_compatibility_sha256='b'*64, - migration_id='migration:back', migration_sha256='c'*64, split_memory_backing=True) - quota = self.registry.commit_import_quota(self.spec.id, expected_revision=imported.revision, - project_id=2, total_mb=self.base, quota_path=self.config.memory_root/self.memory_directory) - rootfs = self.registry.commit_import_rootfs(self.spec.id, expected_revision=quota.revision, - image_id='sha256:'+'e'*64, sandbox=self.sandbox) - ready = self.registry.commit_import_ready(self.spec.id, expected_revision=rootfs.revision, - migration_id='migration:back', migration_sha256='c'*64) - self.registry.activate_import(self.spec.id, expected_revision=ready.revision, - migration_id='migration:back', migration_sha256='c'*64) - store.prepare(self.sandbox.memory, sandbox_id=self.spec.id, sandbox_generation=1) - self.base_project = self.quota.projects[self.config.memory_root/self.memory_directory] - self.source.parent.mkdir(mode=0o700) - self.source.write_bytes(b'reimported-memory') - self.source.chmod(0o600) - size = max(4096, self.source.stat().st_blocks*512) - digest = 'c'*64 - self.registry.reserve_reflink_overlap(self.spec.id, 1, 1, size, manifest_sha256=digest) - self.quota.failure = None - arguments = dict(sandbox_id=self.spec.id, sandbox_generation=1, hibernation_generation=1, - manifest_sha256=digest, allocated_bytes=size) - store.retain_checkpoint(self.sandbox.memory, **arguments) - self.reopen() - self.warden.memory_backing.retain_checkpoint(self.sandbox.memory, **arguments) - new_projects = self.quota.retained_projects - {old_project} - self.assertEqual(len(new_projects), 1) - self.assertNotEqual(next(iter(new_projects)), self.base_project[0]) - with self.assertRaises(DirectRegistryConflictError): - self.registry.release_reflink_overlap(self.spec.id, 1, 1, - manifest_sha256=old_claim.manifest_sha256) - self.assertEqual(self.registry.reflink_overlap_bytes(), size) - self.assertEqual(self.source.read_bytes(), b'reimported-memory') diff --git a/tests/test_registry_disk.py b/tests/test_registry_disk.py index 7d055982..45272a73 100644 --- a/tests/test_registry_disk.py +++ b/tests/test_registry_disk.py @@ -486,6 +486,7 @@ def test_guard_fields_default_round_trip_and_validate(self) -> None: DeploymentConfig.from_dict(custom).to_dict()) self.assertEqual(DeploymentConfig.from_dict(custom).registry_disk_refuse_percent, 95) for invalid in ( + {"registry_disk_guard_enabled": "no"}, {"registry_disk_cleanup_percent": 95}, # above refuse {"registry_disk_target_percent": 75}, # above cleanup {"registry_disk_refuse_percent": 101}, @@ -493,6 +494,11 @@ def test_guard_fields_default_round_trip_and_validate(self) -> None: ): with self.subTest(invalid=invalid), self.assertRaises(ValueError): DeploymentConfig.from_dict(config.to_dict() | invalid) + disabled = DeploymentConfig.from_dict(config.to_dict() | {"registry_disk_guard_enabled": False}) + self.assertFalse(disabled.registry_disk_guard_enabled) + self.assertFalse(disabled.to_dict()["registry_disk_guard_enabled"]) + self.assertIsNone(registry_disk_usage(disabled)) + self.assertIsNone(RegistryDiskMonitor.from_config(disabled)) self.assertTrue(config.registry_maintenance_state_file().name.endswith(".json")) self.assertTrue(os.path.isabs(config.registry_maintenance_state_file())) diff --git a/tests/test_registry_usage_hotpaths.py b/tests/test_registry_usage_hotpaths.py index de2aa241..543c607d 100644 --- a/tests/test_registry_usage_hotpaths.py +++ b/tests/test_registry_usage_hotpaths.py @@ -5,7 +5,7 @@ import unittest from unittest.mock import patch -from sandboxes.gateway.registry_refs import _persist_registry_image_protection +from sandboxes.gateway.registry_refs import persist_registry_image_protection from sandboxes.managed_registry import ( RegistryImageLeaseNotFound, RegistryUsageStateError, RegistryUsageStore, ) @@ -23,7 +23,7 @@ def test_gateway_protection_uses_scoped_reads_and_preserves_renewal_policy(self) image = 'registry.example/repo:tag@' + DIGEST def protect(owner, seconds=0, *, persistent=False, touch=False, ref=image): - return _persist_registry_image_protection( + return persist_registry_image_protection( store, ref, owner, touch=touch, persistent=persistent, now=now + timedelta(seconds=seconds), ttl_seconds=10, ) diff --git a/tests/test_relay_transitions.py b/tests/test_relay_transitions.py new file mode 100644 index 00000000..e2815d2b --- /dev/null +++ b/tests/test_relay_transitions.py @@ -0,0 +1,148 @@ +"""Pure decision and invariant tests for model-relay state transitions.""" + +from __future__ import annotations + +import unittest + +from hypothesis import given, strategies as st + +from sandboxes.shared_control.relay_transitions import ( + CompleteLifecycle, + RetryLifecycle, + canonicalize_relay_request, + classify_wait_mode, + lifecycle_retry_delay_seconds, + plan_lifecycle_dispatch_outcome, +) + +TEST_TIER = "unit" + + +class RelayTransitionsTests(unittest.TestCase): + def test_canonical_digest_ignores_trace_and_retry_headers(self) -> None: + base = canonicalize_relay_request( + rollout_id="r-1", + endpoint="/v1/chat/completions", + method="POST", + headers={"Content-Type": "application/json", "X-Custom": "1"}, + raw_body=b'{"messages":[]}', + response_reservation=4096, + ) + with_trace = canonicalize_relay_request( + rollout_id="r-1", + endpoint="/v1/chat/completions", + method="POST", + headers={ + "Content-Type": "application/json", + "X-Custom": "1", + "Traceparent": "00-abc-def-01", + "X-Request-Id": "req-999", + "X-Stainless-Retry-Count": "2", + }, + raw_body=b'{"messages":[]}', + response_reservation=4096, + ) + self.assertEqual(base.digest, with_trace.digest) + self.assertEqual(base.reserved_bytes, base.payload_bytes + 4096) + + def test_classify_wait_mode_local_wait_suppresses_gateway_park(self) -> None: + self.assertEqual( + classify_wait_mode( + sandbox_id="sbx-1", + local_wait_requested=True, + local_model_waits_enabled=True, + has_park_notifier=True, + ), + (True, False), + ) + self.assertEqual( + classify_wait_mode( + sandbox_id="sbx-1", + local_wait_requested=False, + local_model_waits_enabled=True, + has_park_notifier=True, + ), + (False, True), + ) + self.assertEqual( + classify_wait_mode( + sandbox_id=None, + local_wait_requested=True, + local_model_waits_enabled=True, + has_park_notifier=True, + ), + (False, False), + ) + + def test_park_and_wake_reattach_is_order_independent(self) -> None: + # Park finishes first (epoch A), then wake finishes on migrated epoch B. + park_first = plan_lifecycle_dispatch_outcome( + action="park", + attempts=1, + parked_transport_epoch=None, + wake_transport_epoch=None, + result_epoch="epoch-a", + unavailable=False, + failure=None, + deferred=None, + ) + self.assertIsInstance(park_first, CompleteLifecycle) + assert isinstance(park_first, CompleteLifecycle) + self.assertFalse(park_first.reattach_required) + + wake_second = plan_lifecycle_dispatch_outcome( + action="wake", + attempts=1, + parked_transport_epoch="epoch-a", + wake_transport_epoch=None, + result_epoch="epoch-b", + unavailable=False, + failure=None, + deferred=None, + ) + assert isinstance(wake_second, CompleteLifecycle) + self.assertTrue(wake_second.reattach_required) + + # Wake finishes first (epoch B), then delayed park receipt arrives (epoch A). + park_late = plan_lifecycle_dispatch_outcome( + action="park", + attempts=1, + parked_transport_epoch=None, + wake_transport_epoch="epoch-b", + result_epoch="epoch-a", + unavailable=False, + failure=None, + deferred=None, + ) + assert isinstance(park_late, CompleteLifecycle) + self.assertTrue(park_late.reattach_required) + + def test_deferred_park_still_records_epoch_and_uses_deferral_delay(self) -> None: + outcome = plan_lifecycle_dispatch_outcome( + action="park", + attempts=3, + parked_transport_epoch=None, + wake_transport_epoch=None, + result_epoch="epoch-a", + unavailable=False, + failure=None, + deferred=1.5, + ) + self.assertEqual( + outcome, + RetryLifecycle( + delay_seconds=1.5, + last_error=None, + record_park_epoch="epoch-a", + ), + ) + + @given(attempts=st.integers(min_value=0, max_value=100)) + def test_backoff_is_positive_and_capped_at_five_seconds(self, attempts: int) -> None: + delay = lifecycle_retry_delay_seconds(attempts) + self.assertGreater(delay, 0.0) + self.assertLessEqual(delay, 5.0) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_retired_memory_maintenance.py b/tests/test_retired_memory_maintenance.py deleted file mode 100644 index cf4d246f..00000000 --- a/tests/test_retired_memory_maintenance.py +++ /dev/null @@ -1,146 +0,0 @@ -"""Physical cleanup is replayable maintenance, never wake authority.""" -from concurrent.futures import ThreadPoolExecutor -from contextlib import closing -from pathlib import Path -import shutil -import sqlite3 -from tempfile import TemporaryDirectory -from threading import Event -import unittest -from unittest.mock import patch - -from tests.test_split_memory_lifecycle import FakeQuota -from sandboxes.checkpoint_components import MemoryBackingRef -from sandboxes.memory_backing import ( - MemoryBackingStore, MemoryBackingError, RetainedCheckpointRef, XfsMemoryQuota, -) - - -class RetiredMemoryMaintenanceTests(unittest.TestCase): - def setUp(self): - directory = TemporaryDirectory() - self.addCleanup(directory.cleanup) - self.root = Path(directory.name).resolve() - self.quota = FakeQuota() - self.store = MemoryBackingStore(self.root / "memory", self.root / "state.sqlite", - hard_capacity_bytes=1 << 30, quota=self.quota) - self.ref = MemoryBackingRef("s.sandbox-1", 64 << 20) - self.owner = dict(sandbox_id="s", sandbox_generation=1) - self.store.prepare(self.ref, **self.owner) - self.store.configure_reflink_restore(True) - - def checkpoint(self, generation=1): - checkpoint = RetainedCheckpointRef(self.ref, generation, "a" * 64) - directory = self.store.root / self.ref.allocation_id / f"hibernate-{generation}" - directory.mkdir(mode=0o700) - path = directory / "application_memory.img" - path.write_bytes(b"x" * 4096) - path.chmod(0o600) - size = max(4096, path.stat().st_blocks * 512) - self.store.retain_checkpoint(self.ref, **self.owner, hibernation_generation=generation, - manifest_sha256=checkpoint.manifest_sha256, allocated_bytes=size) - shutil.rmtree(directory) - return checkpoint - - def state(self, generation=1): - with closing(sqlite3.connect(self.store.journal)) as connection: - return connection.execute("SELECT project_id,state FROM retained_checkpoints " - "WHERE allocation_id=? AND hibernation_generation=?", - (self.ref.allocation_id, generation)).fetchone() - - def test_many_generations_share_one_batch_and_all_claims_outlive_physical_barrier(self): - checkpoints = [self.checkpoint(index) for index in range(1, 9)] - released = [] - def physical(_root, projects): - self.assertEqual(len(projects), 8) - self.assertEqual(released, []) - self.assertTrue(all(self.state(index)[1] == "retiring" for index in range(1, 9))) - self.store.require(self.ref, **self.owner) # no owner mutation lock spans trim - with patch.object(self.quota, "release_many", side_effect=physical) as release: - self.assertEqual(self.store.release_retained_checkpoints(checkpoints, - release_claim=released.append), 8) - release.assert_called_once() - self.assertEqual(released, checkpoints) - self.assertTrue(all(self.state(index)[1] == "deleted" for index in range(1, 9))) - - def test_physical_failure_and_post_local_commit_crash_keep_replayable_claims(self): - checkpoint = self.checkpoint() - released = [] - with patch.object(self.quota, "release_many", side_effect=OSError("trim failed")): - with self.assertRaisesRegex(OSError, "trim failed"): - self.store.release_retained_checkpoints([checkpoint], release_claim=released.append) - self.assertEqual(self.state()[1], "retiring") - self.assertEqual(released, []) - with self.assertRaisesRegex(MemoryBackingError, 'retained'): - self.store.configure_reflink_restore(False) - def crash(_): - self.assertEqual(self.state()[1], "deleted") - raise OSError("registry commit failed") - with self.assertRaisesRegex(OSError, "registry commit failed"): - self.store.release_retained_checkpoints([checkpoint], release_claim=crash) - reopened = MemoryBackingStore(self.store.root, self.store.journal, - hard_capacity_bytes=1 << 30, quota=self.quota) - self.assertEqual(reopened.release_retained_checkpoints([checkpoint], - release_claim=released.append), 1) - self.assertEqual(released, [checkpoint]) - - def test_reader_and_reappearing_source_keep_global_claim(self): - checkpoint = self.checkpoint() - released = [] - with self.store.read_lease(self.ref, **self.owner): - self.assertEqual(self.store.release_retained_checkpoints([checkpoint], - release_claim=released.append), 0) - path = self.store.root / self.ref.allocation_id / "hibernate-1" - with patch.object(self.quota, "release_many", side_effect=lambda *_: path.mkdir(mode=0o700)): - self.assertEqual(self.store.release_retained_checkpoints([checkpoint], - release_claim=released.append), 0) - self.assertEqual(released, []) - self.assertEqual(self.state()[1], "retiring") - - def test_old_batch_cannot_release_deleted_then_reimported_same_digest(self): - checkpoint = self.checkpoint() - old_project = self.state()[0] - entered, finish = Event(), Event() - released = [] - def physical(*_): - entered.set() - self.assertTrue(finish.wait(3)) - with ThreadPoolExecutor(1) as threads, patch.object(self.quota, "release_many", side_effect=physical): - batch = threads.submit(self.store.release_retained_checkpoints, [checkpoint], - release_claim=released.append) - try: - self.assertTrue(entered.wait(3)) - # Deletion's synchronous barrier may finish while the old - # batch is outside locks. Reimport gets a fresh monotonic ID. - self.assertTrue(self.store.release_retained_checkpoint(self.ref, - hibernation_generation=1, manifest_sha256=checkpoint.manifest_sha256)) - self.store.delete(self.ref, **self.owner) - self.store.prepare(self.ref, **self.owner) - self.checkpoint() - self.assertNotEqual(self.state()[0], old_project) - finally: - finish.set() - self.assertEqual(batch.result(3), 0) - self.assertEqual(released, []) - self.assertEqual(self.state()[1], "ready") - - def test_registry_only_claim_needs_absent_generation(self): - checkpoint = RetainedCheckpointRef(self.ref, 3, "b" * 64) - path = self.store.root / self.ref.allocation_id / "hibernate-3" - path.mkdir(mode=0o700) - released = [] - self.assertEqual(self.store.release_retained_checkpoints([checkpoint], - release_claim=released.append), 0) - path.rmdir() - self.assertEqual(self.store.release_retained_checkpoints([checkpoint], - release_claim=released.append), 1) - - def test_xfs_batch_performs_one_trim_before_all_project_releases(self): - quota = XfsMemoryQuota() - quota.filesystem_root = Path("/xfs") - with patch("sandboxes.memory_backing.subprocess.run") as command, \ - patch.object(quota._trim, "release") as trim: - command.return_value.stdout = "/dev/loop0\n" - quota.release_many(Path("/xfs/memory"), (101, 102, 103)) - trim.assert_called_once() - self.assertEqual(command.call_count, 4) diff --git a/tests/test_routing.py b/tests/test_routing.py index 07b75abf..a020c1ca 100644 --- a/tests/test_routing.py +++ b/tests/test_routing.py @@ -19,7 +19,7 @@ from sandboxes.shared_control.__main__ import main as shared_control_main from sandboxes.routing import open_routing_store from sandboxes.shared_control.routing_repository import init_routing_authority -from sandboxes.control_plane import _sandbox_transport_epoch +from sandboxes.gateway.sandbox_proxy import sandbox_transport_epoch from sandboxes.models import SandboxInventoryEntry, ResourceQuantity, utc_now from sandboxes.managed_process import ManagedProcessRecord from tests.support import ( @@ -217,8 +217,8 @@ def test_scoped_epoch_history_preserves_completed_handoffs(self) -> None: scoped = store.sandbox_migrations(active_only=False, sandbox_id=moved.sandbox_id) self.assertEqual(decode.call_count, 1) self.assertEqual(scoped[0].phase, "complete") - self.assertEqual(_sandbox_transport_epoch(moved, scoped), _sandbox_transport_epoch(moved, history)) - self.assertNotEqual(_sandbox_transport_epoch(moved, scoped), _sandbox_transport_epoch(moved, [])) + self.assertEqual(sandbox_transport_epoch(moved, scoped), sandbox_transport_epoch(moved, history)) + self.assertNotEqual(sandbox_transport_epoch(moved, scoped), sandbox_transport_epoch(moved, [])) def test_active_migration_lookup_is_scoped_to_sandbox(self) -> None: with routing_store(self) as store: diff --git a/tests/test_routing_pool.py b/tests/test_routing_pool.py index 4728cc84..863ede11 100644 --- a/tests/test_routing_pool.py +++ b/tests/test_routing_pool.py @@ -126,6 +126,7 @@ def test_failed_transaction_does_not_poison_next_borrower(self): def test_warm_durable_wake_records_observation_with_outcome_only(self): from unittest.mock import Mock from sandboxes.control_plane import ControlPlaneHandler + from tests.gateway_support import gateway_services with TemporaryDirectory() as tmp: store = routing_store_for(self, Path(tmp) / 'routing.sqlite') route = store.upsert_sandbox(_sandbox_route( @@ -134,6 +135,7 @@ def test_warm_durable_wake_records_observation_with_outcome_only(self): handler = object.__new__(ControlPlaneHandler) handler.routing_store = store handler.metrics_store = Mock() + handler.services = gateway_services(routing_store=store, metrics_store=handler.metrics_store) payload = dict(request_id='request', rollout_id='rollout', durable_lifecycle=True) handler._prepare_program_lifecycle(route, 'wake', payload) self.assertIsNone(store.program_request_readonly('request')) @@ -152,6 +154,7 @@ def test_warm_durable_wake_records_observation_with_outcome_only(self): def test_failed_warm_wake_retains_demand_and_original_start_observation(self): from unittest.mock import Mock from sandboxes.control_plane import ControlPlaneHandler + from tests.gateway_support import gateway_services with TemporaryDirectory() as tmp: store = routing_store_for(self, Path(tmp) / 'routing.sqlite') route = store.upsert_sandbox(_sandbox_route( @@ -160,6 +163,7 @@ def test_failed_warm_wake_retains_demand_and_original_start_observation(self): handler = object.__new__(ControlPlaneHandler) handler.routing_store = store handler.metrics_store = Mock() + handler.services = gateway_services(routing_store=store, metrics_store=handler.metrics_store) payload = dict(request_id='request', rollout_id='rollout', durable_lifecycle=True) handler._prepare_program_lifecycle(route, 'wake', payload) started = handler._warm_program_wake_observation[3] diff --git a/tests/test_routing_transitions.py b/tests/test_routing_transitions.py new file mode 100644 index 00000000..3ee83e0a --- /dev/null +++ b/tests/test_routing_transitions.py @@ -0,0 +1,407 @@ +"""Pure decision and invariant tests for routing state transitions. + +These exercise the functional core extracted from ``RoutingStore`` directly +on plain inputs (and Hypothesis strategies) without PostgreSQL or wall clocks. +""" + +from __future__ import annotations + +from dataclasses import replace +from datetime import datetime, timezone +import unittest + +from hypothesis import given, strategies as st + +from sandboxes.models import ResourceQuantity, SandboxInventoryEntry +from sandboxes.routing import ( + ProgramRequestState, + SandboxOwnerLossDisposition, + SandboxRoute, + SandboxRouteConflictError, + route_with_inventory_snapshot, + sandbox_owner_loss_disposition, +) +from sandboxes.routing_transitions import ( + PROGRAM_STATE_RANK, + classify_absent_node_routes, + plan_node_epoch_retirement, + plan_observed_route_updates, + plan_sandbox_state_transition, + project_program_request_transition, + validate_program_transition_args, + validate_sandbox_state_transition_args, +) + +TEST_TIER = "unit" + +_SPEC_HASH = "a" * 64 +_T0 = "2026-10-18T00:00:00+00:00" +_T1 = "2026-10-18T00:01:00+00:00" +_T2 = "2026-10-18T00:02:00+00:00" + + +def _route( + sandbox_id: str = "sbx-1", + *, + state: str = "running", + generation: int = 1, + node_id: str = "node-1", + job_id: str = "job-1", + node_url: str = "http://node-1:8090", + node_epoch: str = "boot-1", + activity_epoch: int = 5, + worker_state: str = "attached", + delete_operation_id: str = "", + updated_at: str = _T0, + snapshot_manifest_digest: str = "", + snapshot_repository: str = "", + snapshot_tag: str = "", + storage_schema: str = "", + storage_snapshot: dict | None = None, +) -> SandboxRoute: + return SandboxRoute( + sandbox_id=sandbox_id, + node_id=node_id, + job_id=job_id, + node_url=node_url, + resources=ResourceQuantity(vcpu=2.0, memory_mb=2048, disk_mb=4096), + spec={"id": sandbox_id, "image": "ubuntu:24.04"}, + state=state, + generation=generation, + create_operation_id="op-1", + spec_hash=_SPEC_HASH, + node_epoch=node_epoch, + activity_epoch=activity_epoch, + worker_state=worker_state, + delete_operation_id=delete_operation_id, + storage_schema=storage_schema, + snapshot_manifest_digest=snapshot_manifest_digest, + snapshot_repository=snapshot_repository, + snapshot_tag=snapshot_tag, + storage_snapshot=storage_snapshot or {}, + created_at=_T0, + updated_at=updated_at, + ) + + +def _portable_parked_route(sandbox_id: str = "sbx-parked", **kwargs) -> SandboxRoute: + return _route( + sandbox_id, + state="parked", + storage_schema="storage-native-v1", + snapshot_manifest_digest="sha256:" + "b" * 64, + snapshot_repository="ucloud/sandboxes", + snapshot_tag="snap-1", + storage_snapshot={ + "schema": "storage-native-v1", + "bucket": "snapshots", + "manifest_key": "m/key", + }, + **kwargs, + ) + + +def _same_incarnation(left: SandboxRoute, right: SandboxRoute) -> bool: + return ( + left.node_id == right.node_id + and left.job_id == right.job_id + and left.node_url.rstrip("/") == right.node_url.rstrip("/") + and left.generation == right.generation + and left.create_operation_id == right.create_operation_id + and left.spec_hash == right.spec_hash + ) + + +def _route_update_is_current( + existing: SandboxRoute, candidate: SandboxRoute, *, allow_node_epoch_adoption: bool = False +) -> bool: + if not _same_incarnation(existing, candidate): + return False + if existing.node_epoch and candidate.node_epoch: + if existing.node_epoch != candidate.node_epoch: + return allow_node_epoch_adoption + return candidate.activity_epoch >= existing.activity_epoch + return True + + +class ProgramTransitionTests(unittest.TestCase): + def test_validate_rejects_blank_ids_and_unknown_state(self) -> None: + with self.assertRaises(ValueError): + validate_program_transition_args( + request_id=" ", rollout_id="r-1", state="model_wait" + ) + with self.assertRaises(ValueError): + validate_program_transition_args( + request_id="req-1", rollout_id="r-1", state="bogus" + ) + + def test_monotonic_rank_and_idempotency(self) -> None: + route = _route() + first = project_program_request_transition( + None, + route, + request_id="req-1", + rollout_id="rollout-1", + state="model_wait", + transition_at=_T0, + state_cls=ProgramRequestState, + conflict_error_cls=SandboxRouteConflictError, + ) + self.assertTrue(first.changed) + self.assertEqual(first.state.state, "model_wait") + self.assertEqual(first.state.accepted_at, _T0) + + replay = project_program_request_transition( + first.state, + route, + request_id="req-1", + rollout_id="rollout-1", + state="model_wait", + transition_at=_T1, + state_cls=ProgramRequestState, + conflict_error_cls=SandboxRouteConflictError, + ) + self.assertFalse(replay.changed) + self.assertEqual(replay.state, first.state) + + advanced = project_program_request_transition( + first.state, + route, + request_id="req-1", + rollout_id="rollout-1", + state="waking", + transition_at=_T1, + state_cls=ProgramRequestState, + conflict_error_cls=SandboxRouteConflictError, + ) + self.assertTrue(advanced.changed) + self.assertEqual(advanced.state.state, "waking") + self.assertEqual(advanced.state.wake_started_at, _T1) + + # Older state cannot regress a newer state. + regressed = project_program_request_transition( + advanced.state, + route, + request_id="req-1", + rollout_id="rollout-1", + state="model_wait", + transition_at=_T2, + state_cls=ProgramRequestState, + conflict_error_cls=SandboxRouteConflictError, + ) + self.assertEqual(regressed.state.state, "waking") + self.assertFalse(regressed.changed) + + def test_conflict_when_request_belongs_to_other_generation(self) -> None: + route1 = _route(generation=1) + route2 = _route(generation=2) + first = project_program_request_transition( + None, + route1, + request_id="req-1", + rollout_id="rollout-1", + state="model_wait", + transition_at=_T0, + state_cls=ProgramRequestState, + conflict_error_cls=SandboxRouteConflictError, + ) + with self.assertRaises(SandboxRouteConflictError): + project_program_request_transition( + first.state, + route2, + request_id="req-1", + rollout_id="rollout-1", + state="waking", + transition_at=_T1, + state_cls=ProgramRequestState, + conflict_error_cls=SandboxRouteConflictError, + ) + + @given( + states=st.lists( + st.sampled_from(tuple(PROGRAM_STATE_RANK.keys())), + min_size=1, + max_size=10, + ) + ) + def test_program_state_rank_never_decreases(self, states: list[str]) -> None: + route = _route() + current = None + best_rank = 0 + for idx, next_state in enumerate(states): + result = project_program_request_transition( + current, + route, + request_id="req-prop", + rollout_id="rollout-prop", + state=next_state, + transition_at=f"2026-10-18T00:00:{idx:02d}+00:00", + state_cls=ProgramRequestState, + conflict_error_cls=SandboxRouteConflictError, + ) + current = result.state + rank = PROGRAM_STATE_RANK[current.state] + self.assertGreaterEqual(rank, best_rank) + best_rank = rank + + +class LifecycleStateTransitionTests(unittest.TestCase): + def test_lifecycle_proof_must_postdate_route_and_match_boot(self) -> None: + route = _route(state="running", node_epoch="boot-1", activity_epoch=5) + proof_stale = validate_sandbox_state_transition_args( + expected_states=("running",), + state="parked", + node_epoch="boot-1", + activity_epoch=5, + ) + self.assertIsNone( + plan_sandbox_state_transition( + route, + route, + proof_stale, + same_incarnation=_same_incarnation, + updated_at=_T1, + ) + ) + + proof_wrong_boot = validate_sandbox_state_transition_args( + expected_states=("running",), + state="parked", + node_epoch="boot-2", + activity_epoch=10, + ) + self.assertIsNone( + plan_sandbox_state_transition( + route, + route, + proof_wrong_boot, + same_incarnation=_same_incarnation, + updated_at=_T1, + ) + ) + + proof_ok = validate_sandbox_state_transition_args( + expected_states=("running",), + state="parked", + node_epoch="boot-1", + activity_epoch=6, + ) + updated = plan_sandbox_state_transition( + route, + route, + proof_ok, + same_incarnation=_same_incarnation, + updated_at=_T1, + ) + self.assertIsNotNone(updated) + assert updated is not None + self.assertEqual(updated.state, "parked") + self.assertEqual(updated.activity_epoch, 6) + + # Pending delete blocks lifecycle transitions. + deleting = replace(route, delete_operation_id="del-1") + self.assertIsNone( + plan_sandbox_state_transition( + deleting, + route, + proof_ok, + same_incarnation=_same_incarnation, + updated_at=_T1, + ) + ) + + +class NodeReconciliationTests(unittest.TestCase): + def test_watermark_only_observation_uses_touched_ids_not_full_write(self) -> None: + existing = _route("sbx-1", state="running", activity_epoch=5) + entry = SandboxInventoryEntry( + sandbox_id="sbx-1", + generation=1, + operation_id="op-1", + spec_hash=_SPEC_HASH, + state="running", + resources=existing.resources, + ) + plan = plan_observed_route_updates( + {"sbx-1": existing}, + (entry,), + node_id="node-1", + job_id="job-1", + node_url="http://node-1:8090", + observed_at=_T1, + node_epoch="boot-1", + activity_epoch=9, + route_with_inventory_snapshot=route_with_inventory_snapshot, + route_update_is_current=_route_update_is_current, + ) + self.assertEqual(plan.writes, ()) + self.assertEqual(plan.touched_ids, frozenset({"sbx-1"})) + self.assertEqual(plan.accepted_ids, frozenset({"sbx-1"})) + + def test_absent_routes_preserve_creating_and_other_epochs(self) -> None: + creating = _route("sbx-creating", state="creating", activity_epoch=1) + other_boot = _route("sbx-other-boot", state="running", node_epoch="boot-old") + newer_activity = _route("sbx-newer", state="running", activity_epoch=10) + gone_running = _route("sbx-gone", state="running", activity_epoch=5) + gone_portable = _portable_parked_route("sbx-portable", activity_epoch=5) + + plan = classify_absent_node_routes( + (creating, other_boot, newer_activity, gone_running, gone_portable), + reported_ids=set(), + inventory_complete=True, + node_epoch="boot-1", + activity_epoch=6, + observed_at_dt=datetime(2026, 10, 18, 0, 1, tzinfo=timezone.utc), + owner_loss_disposition=sandbox_owner_loss_disposition, + recover_detached_value=SandboxOwnerLossDisposition.RECOVER_DETACHED, + ) + self.assertEqual([r.sandbox_id for r in plan.detach], ["sbx-portable"]) + self.assertEqual([r.sandbox_id for r in plan.delete], ["sbx-gone"]) + + +class EpochRetirementTests(unittest.TestCase): + def test_reboot_readopts_parked_detaches_portable_keeps_deletes_loses_running( + self, + ) -> None: + running = _route("sbx-run", state="running", node_epoch="boot-1") + parked_local = _route("sbx-park-local", state="parked", node_epoch="boot-1") + parked_portable = _portable_parked_route("sbx-park-port", node_epoch="boot-1") + deleting = _route( + "sbx-del", + state="running", + node_epoch="boot-1", + delete_operation_id="del-op", + ) + new_boot = _route("sbx-new", state="running", node_epoch="boot-2") + + inventory = ( + SandboxInventoryEntry( + sandbox_id="sbx-park-local", + generation=1, + operation_id="op-1", + spec_hash=_SPEC_HASH, + state="parked", + resources=parked_local.resources, + ), + ) + plan = plan_node_epoch_retirement( + (running, parked_local, parked_portable, deleting, new_boot), + ("boot-1",), + node_epoch="boot-2", + activity_epoch=3, + inventory=inventory, + observed_at=_T1, + owner_loss_disposition=sandbox_owner_loss_disposition, + terminal_delete_value=SandboxOwnerLossDisposition.TERMINAL_DELETE, + recover_detached_value=SandboxOwnerLossDisposition.RECOVER_DETACHED, + ) + self.assertEqual([r.sandbox_id for r in plan.pending_deletes], ["sbx-del"]) + self.assertEqual([r.sandbox_id for r in plan.readopted_routes], ["sbx-park-local"]) + self.assertEqual(plan.readopted_routes[0].node_epoch, "boot-2") + self.assertEqual(plan.readopted_routes[0].activity_epoch, 3) + self.assertEqual([r.sandbox_id for r in plan.detach_routes], ["sbx-park-port"]) + self.assertEqual([r.sandbox_id for r in plan.lost_routes], ["sbx-run"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_rules_baseline.json b/tests/test_rules_baseline.json index 6da333e8..cf070aac 100644 --- a/tests/test_rules_baseline.json +++ b/tests/test_rules_baseline.json @@ -94,7 +94,7 @@ }, "test_control_plane.py": { "new": 9, - "private": 48, + "private": 43, "private_patch": 6 }, "test_control_state_cache.py": { @@ -265,8 +265,6 @@ "test_import": 1 }, "test_guest_continuity.py": { - "private": 3, - "private_patch": 1, "test_import": 1 }, "test_guest_environment.py": { @@ -291,10 +289,6 @@ "private": 10, "sleep": 4 }, - "test_hybrid_memory_admission.py": { - "private": 2, - "test_import": 1 - }, "test_image_build_admission.py": { "clock": 4, "private": 22, @@ -332,7 +326,6 @@ }, "test_image_roots.py": { "private": 5, - "private_patch": 1, "test_import": 1 }, "test_images.py": { @@ -396,8 +389,6 @@ "test_import": 2 }, "test_memory_backing_mode.py": { - "private": 7, - "private_patch": 1, "test_import": 1 }, "test_memory_filesystem.py": { @@ -412,10 +403,6 @@ "test_memory_reclamation.py": { "test_import": 1 }, - "test_memory_retention_batch.py": { - "private": 7, - "test_import": 1 - }, "test_metrics.py": { "clock": 3, "private": 4, @@ -423,8 +410,7 @@ "test_import": 2 }, "test_migration_runtime_eligibility.py": { - "new": 1, - "private": 4, + "private": 2, "test_import": 1 }, "test_model_relay.py": { @@ -448,7 +434,7 @@ "private": 14 }, "test_node_http_pools.py": { - "private": 5, + "private": 3, "private_patch": 3 }, "test_node_response_errors.py": { @@ -533,11 +519,6 @@ "test_reflink_overlap_capacity.py": { "test_import": 1 }, - "test_reflink_retention.py": { - "private": 4, - "private_patch": 1, - "test_import": 2 - }, "test_registry_blob_mount.py": { "private_patch": 7, "test_import": 1 @@ -584,10 +565,6 @@ "private": 3, "test_import": 1 }, - "test_retired_memory_maintenance.py": { - "private": 1, - "test_import": 1 - }, "test_routing.py": { "private": 3, "private_patch": 3, @@ -658,8 +635,8 @@ "test_import": 2 }, "test_split_memory_wiring.py": { - "private": 4, - "test_import": 4 + "private": 3, + "test_import": 3 }, "test_split_snapshot_routing.py": { "private": 2, @@ -772,18 +749,18 @@ }, "test_wake_batch.py": { "new": 1, - "private": 6, + "private": 4, "test_import": 2 }, "test_wake_capacity.py": { "new": 10, - "private": 58, - "private_patch": 3, + "private": 48, + "private_patch": 2, "test_import": 2 }, "test_wake_owner_admission.py": { "new": 3, - "private": 8, + "private": 7, "private_patch": 2, "test_import": 1 }, diff --git a/tests/test_sandbox_proxy.py b/tests/test_sandbox_proxy.py new file mode 100644 index 00000000..42ff7033 --- /dev/null +++ b/tests/test_sandbox_proxy.py @@ -0,0 +1,198 @@ +"""Pure decision and parsing unit tests for gateway sandbox proxy logic.""" + +from __future__ import annotations + +import json +from types import SimpleNamespace +import unittest + +from sandboxes.gateway.node_rpc import ProxiedResponse +from sandboxes.gateway.sandbox_proxy import ( + build_program_request_transition_args, + build_wake_unavailable_response, + classify_buffered_bulk_request, + is_warm_wake_route, + lifecycle_node_payload, + lifecycle_proxy_error, + sandbox_supports_managed_lifecycle, + sandbox_transport_epoch, + validate_lifecycle_payload, +) +from sandboxes.http_contract import SandboxHttpRoute +from sandboxes.models import ResourceQuantity +from sandboxes.routing import SandboxRoute +from sandboxes.wake_placement import WakeUnavailable + +TEST_TIER = "unit" + +_NOW = "2026-10-18T00:00:00+00:00" + + +def _route( + *, + state: str = "running", + worker_state: str = "attached", + generation: int = 2, + delete_operation_id: str = "", + parkable: bool = True, + managed_process: bool = True, +) -> SandboxRoute: + return SandboxRoute( + sandbox_id="sbx-1", + node_id="node-1", + job_id="job-1", + node_url="http://node-1:8090", + resources=ResourceQuantity(vcpu=2.0, memory_mb=2048, disk_mb=4096), + spec={ + "id": "sbx-1", + "image": "ubuntu:24.04", + "parkable": parkable, + "managed_process": managed_process, + }, + state=state, + generation=generation, + create_operation_id="op-create", + spec_hash="a" * 64, + worker_state=worker_state, + delete_operation_id=delete_operation_id, + created_at=_NOW, + updated_at=_NOW, + ) + + +class SandboxProxyCoreTests(unittest.TestCase): + def test_is_warm_wake_route_checks_resident_state_and_generation(self) -> None: + self.assertTrue(is_warm_wake_route(_route(state="running"), 2)) + self.assertTrue(is_warm_wake_route(_route(state="waking"), 2)) + self.assertFalse(is_warm_wake_route(_route(state="running"), 3)) + self.assertFalse(is_warm_wake_route(_route(state="parked"), 2)) + self.assertFalse(is_warm_wake_route(_route(delete_operation_id="del-1"), 2)) + self.assertFalse( + is_warm_wake_route( + SimpleNamespace( + delete_operation_id="", + worker_state="detached", + state="running", + generation=2, + ), + 2, + ) + ) + + def test_validate_lifecycle_payload_checks_fields_generation_and_spec(self) -> None: + route = _route(generation=2) + payload, err = validate_lifecycle_payload( + route, + "wake", + json.dumps( + { + "operation_id": "op-1", + "generation": 2, + "request_id": "req-1", + "rollout_id": "roll-1", + "durable_lifecycle": True, + } + ).encode(), + ) + self.assertIsNone(err) + assert payload is not None + self.assertEqual(payload["operation_id"], "op-1") + + # Generation mismatch -> 409 Conflict + _, mismatch = validate_lifecycle_payload( + route, "wake", json.dumps({"operation_id": "op-1", "generation": 1}).encode() + ) + assert mismatch is not None + self.assertEqual(mismatch[0], 409) + + # Missing request_id/rollout_id pair -> 400 Bad Request + _, bad = validate_lifecycle_payload( + route, "park", json.dumps({"operation_id": "op-1", "request_id": "req-1"}).encode() + ) + assert bad is not None + self.assertEqual(bad[0], 400) + + # Non-managed sandbox rejects request-bound lifecycle -> 409 Conflict + non_managed = _route(parkable=False, managed_process=False) + self.assertFalse(sandbox_supports_managed_lifecycle(non_managed.spec)) + _, conflict = validate_lifecycle_payload( + non_managed, + "park", + json.dumps( + {"operation_id": "op-1", "request_id": "req-1", "rollout_id": "roll-1"} + ).encode(), + ) + assert conflict is not None + self.assertEqual(conflict[0], 409) + + def test_lifecycle_node_payload_and_proxy_error_formatting(self) -> None: + park_body = lifecycle_node_payload( + 2, + "park", + {"operation_id": "op-1", "request_id": "req-1", "durable_lifecycle": True, "background": True}, + ) + self.assertEqual( + park_body, + {"operation_id": "op-1", "relay_request_id": "req-1", "generation": 2, "background": True}, + ) + with self.assertRaises(ValueError): + lifecycle_node_payload(2, "park", {"operation_id": "op-1", "background": "yes"}) + + resp = ProxiedResponse(503, {"Content-Type": "application/json"}, b'{"error":"busy"}') + self.assertEqual(lifecycle_proxy_error(resp), "HTTP 503: busy") + + def test_transport_epoch_hashes_only_committed_migrations_for_incarnation(self) -> None: + route = _route(generation=2) + m1 = SimpleNamespace( + migration_id="mig-1", + sandbox_id="sbx-1", + generation=2, + create_operation_id="op-create", + phase="complete", + ) + m_uncommitted = SimpleNamespace( + migration_id="mig-2", + sandbox_id="sbx-1", + generation=2, + create_operation_id="op-create", + phase="staged", + ) + self.assertEqual( + sandbox_transport_epoch(route, [m1]), + sandbox_transport_epoch(route, [m1, m_uncommitted]), + ) + self.assertNotEqual( + sandbox_transport_epoch(route, []), + sandbox_transport_epoch(route, [m1]), + ) + + def test_transition_args_bulk_classification_and_wake_unavailable(self) -> None: + route = _route(generation=2) + args = build_program_request_transition_args( + route, + {"request_id": "req-1", "rollout_id": "roll-1", "request_created_at": 1700000000.0}, + state="acting", + now_iso=_NOW, + warm_observation=("req-1", "sbx-1", 2, "2026-10-18T00:00:05+00:00"), + clear_error=True, + ) + assert args is not None + self.assertEqual(args["wake_started_at"], "2026-10-18T00:00:05+00:00") + self.assertEqual(args["response_ready_at"], "2026-10-18T00:00:05+00:00") + self.assertTrue(args["clear_error"]) + + files_action = SandboxHttpRoute(sandbox_id="sbx-1", action="files", wakes=True) + self.assertTrue(classify_buffered_bulk_request("POST", 10, files_action)) + self.assertTrue(classify_buffered_bulk_request("POST", 100_000, None)) + self.assertFalse(classify_buffered_bulk_request("PUT", 100_000, files_action)) + self.assertFalse(classify_buffered_bulk_request("GET", 10, files_action)) + + payload, headers = build_wake_unavailable_response( + WakeUnavailable("busy", error_code="wake_busy", retry_after=3) + ) + self.assertEqual(payload["error_code"], "wake_busy") + self.assertEqual(headers["Retry-After"], "3") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_split_memory_wiring.py b/tests/test_split_memory_wiring.py index 3958b5cd..15b045e5 100644 --- a/tests/test_split_memory_wiring.py +++ b/tests/test_split_memory_wiring.py @@ -1,6 +1,5 @@ """Configuration and node accounting for split memory backing and its RAM and reflink options.""" from contextlib import redirect_stdout -from dataclasses import replace from io import StringIO from pathlib import Path import subprocess @@ -23,44 +22,13 @@ class SplitMemoryWiringTests(unittest.TestCase): - def test_provider_bootstrap_uses_one_reflink_option_contract(self): - from tests.test_policy import node - base = DeploymentConfig.default(scope_id="test") - base = replace(base, sandbox=replace( - base.sandbox, direct_ram_memory_backing=True, direct_reflink_memory_restore=True, - )) - for provider in ("ucloud", "hetzner"): - config = replace(base, provider=replace(base.provider, kind=provider)) - with self.subTest(provider=provider), patch.object( - cli, "read_bearer_token_source", return_value="test-token" - ): - for role in ("sandbox", "builder"): - options = cli.vm_init_options_for_job( - config, node("worker").job, role, - package_spec="/tmp/package.tar.gz", package_sha256="a" * 64, - ) - self.assertEqual(options.direct_reflink_memory_restore, role == "sandbox") - self.assertEqual(cli.vm_init_options_to_dict(options)["directReflinkMemoryRestore"], role == "sandbox") - script = render_vm_init_script(options) - self.assertEqual(" --reflink-memory-restore" in script, role == "sandbox") - - def test_reflink_restore_is_explicit(self): + def test_reflink_restore_flag_is_retired_false_only(self): raw = DeploymentConfig.default(scope_id="test").to_dict() - raw["sandbox"].pop("direct_reflink_memory_restore") - self.assertFalse(DeploymentConfig.from_dict(raw).sandbox.direct_reflink_memory_restore) - raw["sandbox"]["direct_reflink_memory_restore"] = True - for ram in (False, True): - raw["sandbox"]["direct_ram_memory_backing"] = ram - self.assertTrue(DeploymentConfig.from_dict(raw).sandbox.direct_reflink_memory_restore) - script = render_vm_init_script(vm_fixtures.VmInitTests._options( - direct_ram_memory_backing=ram, direct_reflink_memory_restore=True, - )) - self.assertIn(" --reflink-memory-restore", script) - self.assertIn("UCLOUD_DIRECT_REFLINK_MEMORY_RESTORE=1", script) - self.assertEqual(" --application-memory-root ${UCLOUD_APPLICATION_MEMORY_ROOT}" in script, ram) - syntax = subprocess.run(["bash", "-n"], input=script, text=True, capture_output=True) - self.assertEqual(syntax.returncode, 0, syntax.stderr) - for value in (1, "true", None): + self.assertNotIn("direct_reflink_memory_restore", raw["sandbox"]) + # Legacy deployment files that still set false load cleanly. + raw["sandbox"]["direct_reflink_memory_restore"] = False + DeploymentConfig.from_dict(raw) + for value in (True, 1, "true", None): raw["sandbox"]["direct_reflink_memory_restore"] = value with self.subTest(value=value), self.assertRaises(ValueError): DeploymentConfig.from_dict(raw) @@ -70,6 +38,8 @@ def test_reflink_restore_is_explicit(self): def test_ram_backing_survives_bootstrap_restart(self): raw = DeploymentConfig.default(scope_id="test").to_dict() raw["sandbox"].pop("direct_ram_memory_backing") + self.assertTrue(DeploymentConfig.from_dict(raw).sandbox.direct_ram_memory_backing) + raw["sandbox"]["direct_ram_memory_backing"] = False self.assertFalse(DeploymentConfig.from_dict(raw).sandbox.direct_ram_memory_backing) raw["sandbox"]["direct_ram_memory_backing"] = True self.assertTrue(DeploymentConfig.from_dict(raw).sandbox.direct_ram_memory_backing) @@ -106,7 +76,6 @@ def test_cli_forwards_only_explicit_split_settings(self): "--runsc-commit", "a" * 40, "--node-control-bearer-token-file", "/tmp/token", "--memory-backing-hard-capacity-bytes", "123456", "--application-memory-root", "/run/test-memory", - "--reflink-memory-restore", "--checkpoint-registry-url", "http://registry:5000", "--checkpoint-registry-repository", "snapshots/memory-checkpoints", ]) @@ -118,7 +87,6 @@ def test_cli_forwards_only_explicit_split_settings(self): patch.object(cli, "telemetry_from_args", return_value=Mock()), \ redirect_stdout(StringIO()): self.assertEqual(cli.cmd_serve_direct_node_agent(args), 0) - self.assertTrue(build.call_args.kwargs["reflink_memory_restore"]) self.assertEqual(build.call_args.kwargs["application_memory_root"], Path("/run/test-memory")) self.assertEqual(build.call_args.kwargs["memory_backing_hard_capacity_bytes"], 123456) self.assertEqual(build.call_args.kwargs["checkpoint_registry_url"], "http://registry:5000") @@ -174,7 +142,6 @@ def test_heartbeat_adds_reserved_bytes_once_and_never_adds_capacity(self): metrics=lambda: {"memory_backing_hard_reserved_bytes": memory_reserved[0]}, hard_capacity_bytes=100 * mib, ) - warden.config.reflink_memory_restore = True server = direct_fixtures.build_direct_node_agent_server( "127.0.0.1", 0, service=service, image_file=root / "images", job_id="job", node_id="node", total_resources=ResourceQuantity(), @@ -182,7 +149,7 @@ def test_heartbeat_adds_reserved_bytes_once_and_never_adds_capacity(self): ) try: self.assertIn("sandbox-checkpoint-v3", server.RequestHandlerClass.capabilities) - self.assertIn("sandbox-memory-reflink-restore-v1", server.RequestHandlerClass.capabilities) + self.assertNotIn("sandbox-memory-reflink-restore-v1", server.RequestHandlerClass.capabilities) first = server.RequestHandlerClass.runtime_metrics_provider() memory_reserved[0] = 40 * mib overlap_reserved[0] = 0 diff --git a/tests/test_standalone_noded_config.py b/tests/test_standalone_noded_config.py new file mode 100644 index 00000000..722d55b5 --- /dev/null +++ b/tests/test_standalone_noded_config.py @@ -0,0 +1,124 @@ +from __future__ import annotations + +from dataclasses import asdict +import json +import subprocess +import unittest +from pathlib import Path +from tempfile import TemporaryDirectory + +from sandboxes.config import SandboxPoolConfig +from sandboxes.models import ResourceQuantity +from sandboxes.standalone_noded_config import ( + DEFAULT_STANDALONE_NODED_CONFIG_PATH, + build_standalone_noded_config, +) +from sandboxes.vm_init import VmInitOptions, render_vm_init_script + +TEST_TIER = "unit" + + +class StandaloneNodedConfigTest(unittest.TestCase): + def test_sandbox_pool_config_flag_defaults_false_and_roundtrips(self) -> None: + base = asdict(SandboxPoolConfig()) + base["direct_network_allow_tcp"] = list(base["direct_network_allow_tcp"]) + base.pop("direct_node_standalone_rust") + default_cfg = SandboxPoolConfig.from_dict(base) + self.assertFalse(default_cfg.direct_node_standalone_rust) + enabled = SandboxPoolConfig.from_dict({**base, "direct_node_standalone_rust": True}) + self.assertTrue(enabled.direct_node_standalone_rust) + with self.assertRaises(ValueError): + SandboxPoolConfig.from_dict({**base, "direct_node_standalone_rust": "yes"}) + + def test_vm_init_renders_standalone_rust_noded_without_python_node_service(self) -> None: + options = VmInitOptions( + job_id="job-rust-1", + node_id="node-rust-1", + heartbeat_url="http://10.0.0.1:8080/v1/heartbeats", + heartbeat_bearer_token_file="/etc/ucloud-sandboxes/hb.token", + heartbeat_bearer_token="hb-secret", + node_control_bearer_token_file="/etc/ucloud-sandboxes/ctrl.token", + node_control_bearer_token="ctrl-secret", + deployment_id="dep-1", + package_spec="/tmp/node-package.tar.gz", + package_sha256="a" * 64, + role="sandbox", + total_resources=ResourceQuantity(vcpu=16.0, memory_mb=32768, disk_mb=600_000), + direct_runsc_commit="b" * 40, + storage_native_registry_url="http://10.0.0.2:5000", + direct_ram_memory_backing=True, + direct_node_standalone_rust=True, + ) + script = render_vm_init_script(options) + self.assertIn(f"--standalone-config {DEFAULT_STANDALONE_NODED_CONFIG_PATH}", script) + self.assertIn("sandboxes.standalone_noded_config", script) + self.assertIn("systemctl disable --now ucloud-sandbox-node.service", script) + self.assertNotIn("serve-direct-node-agent", script) + self.assertNotIn("--upstream-unix", script) + self.assertNotIn("systemctl enable ucloud-sandbox-node.service", script) + + def test_standalone_config_schema_matches_rust_noded_config_loader(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + cfg = build_standalone_noded_config( + job_id="job-1", + node_id="node-1", + node_url="http://127.0.0.1:8090", + deployment_id="dep-1", + agent_version="0.9.0", + init_version="init-1", + state_root=str(root / "state"), + image_cache_root=str(root / "images"), + volume_mount_root=str(root / "volumes"), + storage_native_socket=str(root / "storage.sock"), + runsc="/usr/bin/true", + init_binary="/usr/bin/true", + managed_init_binary="/usr/bin/true", + network="none", + total_vcpu=8.0, + total_memory_mb=16384, + total_disk_mb=50000, + memory_backing_hard_capacity_bytes=0, + environment_registry_url="http://127.0.0.1:5000", + environment_registry_repository="envs", + environment_backend_socket=str(root / "env.sock"), + checkpoint_registry_url="http://127.0.0.1:5000", + checkpoint_registry_repository="snapshots", + heartbeat_url="http://127.0.0.1:8080/v1/heartbeats", + heartbeat_bearer_token="hb-secret", + node_epoch="epoch-1", + ) + self.assertEqual(cfg["heartbeat"]["node_id"], "node-1") + self.assertTrue(cfg["create"]["admission"]["rust_admission_enabled"]) + self.assertIn("sandbox", cfg["heartbeat"]["capabilities"]) + self.assertIn("direct-runsc-v1", cfg["heartbeat"]["capabilities"]) + + # Verify JSON round-trip and exact binary schema parse if ucloud-noded is built. + cfg_path = root / "noded-standalone.json" + cfg_path.write_text(json.dumps(cfg), encoding="utf-8") + noded_bin = Path("runtime/noded/target/debug/ucloud-noded") + if noded_bin.is_file(): + token_path = root / "token" + token_path.write_text("secret-token\n", encoding="utf-8") + # Passing an invalid --listen after --standalone-config exercises CLI parsing, + # and passing a missing token checks standalone validation without starting a server. + res = subprocess.run( + [ + str(noded_bin), + "--listen", + "127.0.0.1:0", + "--standalone-config", + str(cfg_path), + "--node-control-token-file", + str(root / "missing-token"), + ], + capture_output=True, + text=True, + check=False, + ) + self.assertEqual(res.returncode, 2) + self.assertIn("cannot read", res.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_wake_batch.py b/tests/test_wake_batch.py index 10260740..eaf0959e 100644 --- a/tests/test_wake_batch.py +++ b/tests/test_wake_batch.py @@ -9,7 +9,7 @@ from tests.support import wait_until from tests.test_control_plane import _gateway_server, _sandbox_route, build_heartbeat from tests import test_wake_capacity as capacity_fixtures -from sandboxes import control_plane +from sandboxes.gateway.sandbox_proxy import LocalWakeBatcher from sandboxes.models import ResourceQuantity from sandboxes.routing import RoutingUnavailable @@ -52,7 +52,7 @@ def test_batch_respects_device_capacity_and_deduplicates_wake(self): def test_waiting_callers_share_commit_and_observe_durable_results(self): with TemporaryDirectory() as temp: handler, routes = self.fixture(Path(temp), 12) - batcher = control_plane._LocalWakeBatcher() + batcher = LocalWakeBatcher() held, release = Event(), Event() def hold_worker_turn(): @@ -106,7 +106,7 @@ def test_failed_commit_rolls_back_every_reservation_and_unblocks_callers(self): store.reserve_sandbox_wakes([(r, 'wake:' + r.sandbox_id) for r in routes]) self.assertEqual([store.get_sandbox(r.sandbox_id).state for r in routes], ["parked", "parked"]) - batcher = control_plane._LocalWakeBatcher() + batcher = LocalWakeBatcher() with self.assertRaises(RoutingUnavailable): batcher.reserve(handler, routes[1]) with store._transaction() as conn: diff --git a/tests/test_wake_capacity.py b/tests/test_wake_capacity.py index 944de622..a4626fa5 100644 --- a/tests/test_wake_capacity.py +++ b/tests/test_wake_capacity.py @@ -10,7 +10,9 @@ from tests import test_direct_provisioner as direct_fixtures from tests.gateway_support import gateway_services from sandboxes import control_plane, placement_accounting +from sandboxes.gateway import migrations as gateway_migrations from sandboxes.control_state import ControlStateStore +from sandboxes.gateway.migrations import migration_runtime_capability from sandboxes.registry import heartbeat_to_dict from sandboxes.direct_service import DirectSandboxService from sandboxes.models import NodeRuntimeMetrics, ResourceQuantity, SandboxInventoryEntry, utc_now @@ -84,15 +86,15 @@ def test_wakes_reserve_devices_until_observed_live(self): state="parked", resources=route.resources, ) heartbeat = replace(self.heartbeat(), inventory=(entry,)) - self.assertFalse(placement_accounting._node_has_storage_device_capacity(heartbeat, [route])) - self.assertEqual(placement_accounting._node_reserved_storage_device_slots(heartbeat, [route, route]), 1) + self.assertFalse(placement_accounting.node_has_storage_device_capacity(heartbeat, [route])) + self.assertEqual(placement_accounting.node_reserved_storage_device_slots(heartbeat, [route, route]), 1) running = replace(route, state="running") - self.assertFalse(placement_accounting._node_has_storage_device_capacity(heartbeat, [running])) - self.assertEqual(placement_accounting._node_reserved_storage_device_slots(heartbeat, [running]), 1) - self.assertTrue(placement_accounting._node_has_storage_device_capacity(heartbeat, [replace(route, state="parked")])) + self.assertFalse(placement_accounting.node_has_storage_device_capacity(heartbeat, [running])) + self.assertEqual(placement_accounting.node_reserved_storage_device_slots(heartbeat, [running]), 1) + self.assertTrue(placement_accounting.node_has_storage_device_capacity(heartbeat, [replace(route, state="parked")])) observed = replace(heartbeat, inventory=(replace(entry, state="restoring"),)) - self.assertEqual(placement_accounting._node_reserved_storage_device_slots(observed, [route]), 0) - self.assertFalse(placement_accounting._node_has_storage_device_capacity(self.heartbeat(active=64), [])) + self.assertEqual(placement_accounting.node_reserved_storage_device_slots(observed, [route]), 0) + self.assertFalse(placement_accounting.node_has_storage_device_capacity(self.heartbeat(active=64), [])) def test_full_owner_requests_snapshot_publication(self): with TemporaryDirectory() as directory: @@ -171,8 +173,8 @@ def test_closed_source_can_offload_but_closed_destination_cannot_admit(self): ) store.upsert_heartbeat(destination) route = handler.routing_store.upsert_sandbox(self.route()) - with patch.object(control_plane, '_node_available_resources', - wraps=control_plane._node_available_resources) as available: + with patch.object(gateway_migrations, 'node_available_resources', + wraps=gateway_migrations.node_available_resources) as available: selected = handler._select_migration_destination( route, requested_node_id="", require_active_resources=True, ) @@ -290,7 +292,7 @@ def test_migration_reserves_last_destination_device_slot(self): destination = replace(source_node, node_id="destination", job_id="dest-job", node_url="http://dest:8090") handler.services.fleet.ready_sandbox_heartbeats = lambda **_kwargs: [source_node, destination] # Parked owners themselves need no new device until a wake is reserved. - self.assertTrue(placement_accounting._node_has_storage_device_capacity(source_node, [source])) + self.assertTrue(placement_accounting.node_has_storage_device_capacity(source_node, [source])) self.assertIsNotNone(handler._select_migration_destination(another, requested_node_id="")) handler.routing_store.begin_sandbox_migration( source, migration_id="capacity-migration", destination_node_id="destination", @@ -322,7 +324,7 @@ def test_detached_wake_never_targets_a_worker_still_registering_its_id(self): ) capabilities = self.heartbeat().capabilities + ( "sandbox-migrate-storage-native-v1", "hibernate-local-v2", - control_plane._migration_runtime_capability(source, None)) + migration_runtime_capability(source, None)) former = replace(self.heartbeat(), capabilities=capabilities) holder = replace(former, node_id="holder", job_id="holder-job", node_url="http://holder:8090", inventory=(stale,)) diff --git a/tests/test_wake_owner_admission.py b/tests/test_wake_owner_admission.py index 6d6320ec..ab62983c 100644 --- a/tests/test_wake_owner_admission.py +++ b/tests/test_wake_owner_admission.py @@ -106,7 +106,7 @@ def test_owner_view_preserves_incoming_migration_reservations(self): placement = gateway_services(routing_store=routing).placement full = placement.routes() scoped = placement.routes_for_node(owner) - expected = [r for r in full if control_plane._route_targets_node(r, owner)] + expected = [r for r in full if control_plane.route_targets_node(r, owner)] self.assertEqual(scoped, expected) reservation = scoped[-1] self.assertEqual(reservation.resources.memory_mb, 1024)