The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
feat(runtime): grow native disks through the Rust API (#2744)
ltstrikeree447570dc5b
diff --git a/docs/contributing/architecture/README.md b/docs/contributing/architecture/README.mdindex e30be2c1d..f7e4c441c 100644--- a/docs/contributing/architecture/README.md+++ b/docs/contributing/architecture/README.md@@ -122,8 +122,8 @@ and [Darwin blocking semantics](https://github.com/apple-oss-distributions/xnu/b### Per-box lifecycle ownership`BoxImpl::with_operation` acquires the box's lifecycle write lock and refreshes-persisted state before start/stop, implicit boot/adoption, outbound updates, and-watcher reports. Internal boot and attach helpers reuse that admission; they never+persisted state before start/stop, implicit boot/adoption, outbound updates, resize,+and watcher reports. Internal boot and attach helpers reuse that admission; they neveracquire a second lifecycle lock. An initialized handle cannot attach its old liveresources to a different PID or `started_at`.@@ -193,8 +193,16 @@ Disk APIs use the runtime's shared lock manager with persisted box lock IDs inan independent `<home>/locks/disk/` namespace, serializing operations across handles.Blocking acquisition follows disk → lifecycle → short state guard order, withbox existence rechecked after disk admission and before disk side effects.-Clone, export, and snapshot mutations share `with_disk_admission` for acquisition-and existence rechecks, keeping new entry points on the same admission path.++Export, snapshot mutations, and online resize use `with_disk_admission` to acquire+the lock and recheck box existence. Clone acquires the same lock with an owned guard+and rechecks box existence. The provisioning worker holds a reference to that guard+while it records the clone's base disk dependency.++Resize holds disk and lifecycle admission through device confirmation, guest+filesystem growth, and the final update to the disk target in box state. Its owned+task keeps both guards when the caller stops waiting.+If a batch clone fails after staging begins, every unprovisioned stagingdirectory is cleaned up, while successfully provisioned clones are retained.Snapshot restore queues for disk → lifecycle admission, rechecks that the box is@@ -202,13 +210,15 @@ inactive after the lifecycle state refresh, and holds both admissions through direplacement.The quiesce bracket holds lifecycle write admission through freeze, pause, diskwork, resume, and thaw.+Explicit stop/removal already holding lifecycle admission only tries disk admissionand returns `InvalidState` when busy, allowing retry without a deadlock. Natural-exitcleanup instead waits in disk → lifecycle order, then uses the shared removal corewith both admissions held.Final archive writing releases lifecycle admission but retains disk exclusionwhile its caller awaits it.-Disk operations execute in the caller's future, so cancellation does not guarantee++Snapshot, clone, and export execute in the caller's future, so cancellation does not guaranteecompletion of disk work or resume/thaw cleanup: a blocking worker may continueafter the caller drops its guards.Lifecycle-read/disk-write composition is not provided.diff --git a/docs/contributing/architecture/vmm/README.md b/docs/contributing/architecture/vmm/README.mdindex 45f01f570..6ba1b78f5 100644--- a/docs/contributing/architecture/vmm/README.md+++ b/docs/contributing/architecture/vmm/README.md@@ -576,11 +576,17 @@ setup. Its empty disk registry makes `resize_disk()` return `InvalidInput`.attach order (`vda` container, `vdb` guest root), and defaults to `console=hvc0`.The single filesystem device exports logical shares below its aggregate root;matching mount instructions are sent only for the native engine.-- **Runtime control.** The host-only `vmm.sock` handles disk resize and- [directory delivery](../../../../src/vmm/README.md#host-directory-delivery)- through a serial control thread. The shim routes resize requests by `block_id`+- **Runtime control.** The host-only `vmm.sock` serves HTTP/1.1 over a serial+ control thread. `POST /v1/resize-disk` routes a target size by `block_id`through [`VmControl::resize_disk`](../../../../src/vmm/README.md#virtio-block-device).+ `POST /v1/mount-control` accepts [directory delivery](../../../../src/vmm/README.md#host-directory-delivery)+ operations, with a directory descriptor attached when registering a mount.+The `box.sock` listener forwards guest RPCs, including Mount and Detach.+- **Runtime resize.** `LiteBox::resize` confirms the requested device size,+ runs `resize2fs` in the guest, and saves the completed target in box state.+ Queries read the image capacity, and callers can retry the same target+ after an uncertain or partial result.- **File size limits.** The VMM bounds guest I/O by virtual disk capacity.The host kernel enforces the shim's configured or inherited[`RLIMIT_FSIZE` soft limit](../../../../src/boxlite/src/jailer/README.md#layer-3-resource-limits).diff --git a/docs/guides/resource-limits.md b/docs/guides/resource-limits.mdindex c2c141765..538d283e3 100644--- a/docs/guides/resource-limits.md+++ b/docs/guides/resource-limits.md@@ -251,6 +251,15 @@ boxlite.BoxOptions(The disk lives as long as the box. By default the box is removed when it stops; set`auto_delete=0` to keep the box, and its disk, after stop.+The Rust API can [grow a running native Linux box's root disk](../reference/rust/README.md#online-disk-growth) to at most 1024 GiB.+The shim's configured or inherited `RLIMIT_FSIZE` soft limit can restrict growth.++Restarts reuse the existing QCOW2 image, and clones and exports preserve its virtual capacity in their copies.+Clone options and export manifests carry the last saved resize target, falling back to the creation option if none was saved.++If ext4 growth fails after the disk grows, retry the same target with `resize` once the box is running, including after a restart.+The retry saves the target after filesystem growth succeeds.+**I/O Monitoring:**- Currently not exposed in metrics- Future featurediff --git a/docs/reference/rust/README.md b/docs/reference/rust/README.mdindex bf2797c9f..ba42c5467 100644--- a/docs/reference/rust/README.md+++ b/docs/reference/rust/README.md@@ -444,12 +444,60 @@ HTTP contract, reconfiguration, disable, and generation semantics.| `ssh` | `fn ssh(&self) -> SshHandle` | Control SSH (local or REST-backed); only configure may implicitly start or resume the box || `network` | `fn network(&self) -> NetworkHandle` | Get box-scoped policy and tunnel operations || `start` | `async fn start(&self) -> BoxliteResult<()>` | Start the box |+| `resize` | `async fn resize(&self, options: ResizeOptions) -> BoxliteResult<BoxResources>` | Query or grow a running native Linux box's root disk || `run` | `async fn run(&self, command: BoxCommand) -> BoxliteResult<Execution>` | Run command || `metrics` | `async fn metrics(&self) -> BoxliteResult<BoxMetrics>` | Get box metrics || `stop` | `async fn stop(&self) -> BoxliteResult<()>` | Stop the box || `executions` | `fn executions(&self) -> ExecutionsHandle` | Live session inventory and control recovery; never boots a box || `attach` | `async fn attach(&self, options: AttachOptions) -> BoxliteResult<Execution>` | Attach to init or a named live session; only one output reader is allowed |+#### Online disk growth++`ResizeOptions::disk_size_gb` is an absolute capacity in binary GiB, from 1 through 1024.+On Linux x86_64, the default Rust build supports this operation for boxes running on the native VMM.+Shrinking is rejected.++Its kernel needs `CONFIG_BLK_DEV_WRITE_MOUNTED=y` for the guest's `resize2fs`; the [native kernel build](../../../src/vmm/boot/README.md#how-it-works) includes it.++```rust,no_run+use boxlite::ResizeOptions;++# async fn example(bx: &boxlite::LiteBox) -> boxlite::BoxliteResult<()> {+let current = bx.resize(ResizeOptions::default()).await?;+let grown = bx.resize(ResizeOptions { disk_size_gb: Some(20) }).await?;+assert_eq!(grown.disk_size_gb, 20);+# Ok(())+# }+```++An empty request reads the current virtual capacity from the image.+For an explicit request, the shim confirms the requested capacity and the guest runs `resize2fs`.+The guest reaps the resize command alongside other executions, so their exit results remain available during filesystem growth.++The runtime saves the target in box state after both steps succeed. The creation option keeps its original value.++The operation continues in the runtime if the caller drops its waiting future.+Resize serializes with stop and disk-copy operations; a handle from an earlier VM run is rejected.++If the device reply is lost or times out, the result is unknown and the previously saved target is retained. Retry the same absolute target or query the current image capacity.++After shim confirmation, a filesystem or state write failure reports partial completion and retains the prior saved target.+Retrying the same target repeats device confirmation and filesystem growth before saving the target.+An older guest without the RPC returns `Unsupported` with the partial-completion context.++Restarting with an existing root disk preserves its filesystem and saved target.+Retry an interrupted grow with the same target after the box is running.++A fresh overlay uses the larger of the effective target and the base image capacity.+The effective target is the saved resize target when present, or the creation option otherwise.++Clone options and export manifests carry the latest saved disk target.+Their copied images retain the virtual capacity captured by each operation.++The shim's configured or inherited `RLIMIT_FSIZE` soft limit can restrict growth.++Other engines and remote backends return `Unsupported`; this API is not exposed through REST, CLI or other SDKs.+#### ExecutionsHandle`LiteBox::executions()` returns an owned, cloneable `ExecutionsHandle` without@@ -868,7 +916,8 @@ pub struct BoxOptions {/// Memory in MiB (default: 512)pub memory_mib: Option<u32>,- /// Disk size in GB for rootfs (sparse, grows as needed)+ /// Requested virtual root disk capacity in GiB at creation.+ /// The copy-on-write disk is sparsely allocated.pub disk_size_gb: Option<u64>,/// Working directory inside boxdiff --git a/make/test.mk b/make/test.mkindex a4d223a8b..1ea5da2bd 100644--- a/make/test.mk+++ b/make/test.mk@@ -375,7 +375,7 @@ _guest-boot-probe: $(if $(SETUP_DONE),,runtime\:debug)test\:integration\:vmm\:native: _ensure-kvm _ensure-vmm-kernel $(if $(SETUP_DONE),,runtime\:debug) _guest-boot-probe $(VMM_DISK_GROW_INIT)@cargo test -p boxlite --features native --lib --no-run@timeout 300s cargo test -p boxlite --features native --lib vmm::native::tests:: -- --ignored --test-threads=1- @timeout 600s cargo test -p boxlite --features krun,gvproxy,native --test native_vmm -- --ignored --test-threads=1+ @timeout 600s cargo test -p boxlite --test native_vmm -- --ignored --test-threads=1# PR2 primitives: descriptor registration, guest RPC attach/detach, and reference lifetime.PHONY_TARGETS += test\:integration\:vmm\:mount-deliverydiff --git a/src/boxlite/Cargo.toml b/src/boxlite/Cargo.tomlindex 7f49f713a..86425fe92 100644--- a/src/boxlite/Cargo.toml+++ b/src/boxlite/Cargo.toml@@ -51,8 +51,8 @@ async-stream = "0.3"tonic = "0.12"tower = "0.5"hyper-util = { version = "0.1", features = ["tokio"] }-# gvproxy ServicesMux control client (HTTP/1.1 over the per-box unix socket).-hyper = { version = "1", features = ["client", "http1"] }+# gvproxy and native shim control over per-box Unix sockets.+hyper = { version = "1", features = ["client", "http1", "server"] }http = "1"hyper-rustls = { version = "0.27", features = ["http1", "rustls-native-certs"], optional = true }rustls = { version = "0.23", default-features = false, features = ["aws_lc_rs"], optional = true }diff --git a/src/boxlite/src/db/boxes.rs b/src/boxlite/src/db/boxes.rsindex 64ca1c3b2..d2a509984 100644--- a/src/boxlite/src/db/boxes.rs+++ b/src/boxlite/src/db/boxes.rs@@ -140,7 +140,7 @@ impl BoxStore {/// Update box state.///- /// Updates both queryable columns and JSON blob.+ /// Updates queryable columns and JSON while preserving runtime overrides from the row./// Returns error if box doesn't exist (Podman pattern: verify RowsAffected).pub fn update_state(&self, box_id: &str, state: &BoxState) -> BoxliteResult<()> {let conn = self.db.conn();@@ -150,7 +150,9 @@ impl BoxStore {let rows_affected = db_err!(conn.execute("UPDATE box_state SET status = ?1, pid = ?2, \- json = json_set(?3, '$.outbound_policy', json_extract(json, '$.outbound_policy')) \+ json = json_set(?3, \+ '$.outbound_policy', json_extract(json, '$.outbound_policy'), \+ '$.disk_size_gb', json_extract(json, '$.disk_size_gb')) \WHERE id = ?4",params![state.status.as_str(), state.pid, json, box_id],))?;@@ -181,6 +183,21 @@ impl BoxStore {Ok(())}+ /// Save a completed resize target in box state.+ #[cfg(all(target_os = "linux", target_arch = "x86_64"))]+ pub fn update_disk_size(&self, box_id: &str, disk_size_gb: u64) -> BoxliteResult<()> {+ let disk_size_gb = i64::try_from(disk_size_gb)+ .map_err(|_| BoxliteError::InvalidArgument("disk size exceeds SQLite range".into()))?;+ let changed = db_err!(self.db.conn().execute(+ "UPDATE box_state SET json = json_set(json, '$.disk_size_gb', ?1) WHERE id = ?2",+ params![disk_size_gb, box_id],+ ))?;+ if changed == 0 {+ return Err(BoxliteError::NotFound(box_id.to_string()));+ }+ Ok(())+ }+// ========================================================================// Combined operations// ========================================================================@@ -483,7 +500,7 @@ mod tests {const TEST_ID_3: &str = "01HJK4TNRPQSXYZ8WM6NCVT9R3";#[test]- fn network_policy_survives_stale_lifecycle_writes_and_reopen() {+ fn runtime_overrides_survive_stale_lifecycle_writes_and_reopen() {use crate::runtime::options::{NetworkMode, OutboundNetworkConfig};let (store, dir) = create_test_db();let config = create_test_config(TEST_ID_1);@@ -494,12 +511,30 @@ mod tests {allow_net: vec!["example.com".into()],};store.update_outbound(TEST_ID_1, &policy).unwrap();+ store+ .db+ .conn()+ .execute(+ "UPDATE box_state SET json = json_set(json, '$.disk_size_gb', 20) WHERE id = ?1",+ [TEST_ID_1],+ )+ .unwrap();stale.status = BoxStatus::Stopped;store.update_state(TEST_ID_1, &stale).unwrap();let reopened = BoxStore::new(Database::open(&dir.path().join("test.db")).unwrap());let (config, state) = reopened.load(TEST_ID_1).unwrap().unwrap();assert_eq!(state.status, BoxStatus::Stopped);assert_eq!(state.outbound_policy, Some(policy));+ let saved_target: Option<i64> = reopened+ .db+ .conn()+ .query_row(+ "SELECT json_extract(json, '$.disk_size_gb') FROM box_state WHERE id = ?1",+ [TEST_ID_1],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(saved_target, Some(20));let info = crate::BoxInfo::new(&config, &state);assert_eq!(info.network.unwrap().outbound.allow_net, ["example.com"]);assert!(diff --git a/src/boxlite/src/lib.rs b/src/boxlite/src/lib.rsindex 6871287e4..3846ebbd6 100644--- a/src/boxlite/src/lib.rs+++ b/src/boxlite/src/lib.rs@@ -39,8 +39,8 @@ mod default_runtime_dir;pub use agents::{Agent, AgentTurn, Agents};pub use litebox::{- BoxConnection, BoxReader, BoxTunnel, BoxWriter, LiteBox, SocketAddress, TunnelForwarder,- TunnelOptions,+ BoxConnection, BoxReader, BoxResources, BoxTunnel, BoxWriter, LiteBox, ResizeOptions,+ SocketAddress, TunnelForwarder, TunnelOptions,};pub use portal::GuestSession;pub use runtime::{diff --git a/src/boxlite/src/litebox/box_impl.rs b/src/boxlite/src/litebox/box_impl.rsindex b146af949..987a3f8ac 100644--- a/src/boxlite/src/litebox/box_impl.rs+++ b/src/boxlite/src/litebox/box_impl.rs@@ -47,6 +47,10 @@ use operations::{StopCommit, StopReason};/// Shared reference to BoxImpl.pub type SharedBoxImpl = Arc<BoxImpl>;+#[cfg(all(test, target_os = "linux", target_arch = "x86_64"))]+#[path = "box_impl/tests/resize.rs"]+mod resize_tests;+// ============================================================================// LIVE STATE// ============================================================================@@ -58,7 +62,7 @@ pub type SharedBoxImpl = Arc<BoxImpl>;pub(crate) struct LiveState {// VM process controlhandler: std::sync::Mutex<Box<dyn VmmHandler>>,- guest_session: GuestSession,+ pub(super) guest_session: GuestSession,/// Host-side network control backend (gvproxy ServicesMux client), owned/// beside `guest_session`. `None` when the box was created network-disabled.@@ -786,19 +790,20 @@ impl BoxImpl {self.config.id)));}- self.with_operation(async {- if self.shutdown_token.is_cancelled() || self.state.read().status != BoxStatus::Running- {- return Err(BoxliteError::InvalidState(format!(- "Box {} is not running",- self.id()- )));- }- self.live- .get_or_try_init(|| self.init_live_state(false))- .await- })- .await+ self.with_operation(self.existing_live_state_locked()).await+ }++ /// Caller holds lifecycle admission; attaching here must never boot a new VM.+ pub(super) async fn existing_live_state_locked(&self) -> BoxliteResult<&LiveState> {+ if self.shutdown_token.is_cancelled() || self.state.read().status != BoxStatus::Running {+ return Err(BoxliteError::InvalidState(format!(+ "Box {} is not running",+ self.id()+ )));+ }+ self.live+ .get_or_try_init(|| self.init_live_state(false))+ .await}pub(crate) async fn metrics(&self) -> BoxliteResult<BoxMetrics> {@@ -1448,12 +1453,11 @@ impl BoxImpl {// New and restarted VMs remain guarded until DB persistence succeeds.// Running adoption disarms cleanup before reconnecting to the live VM.let mut state = state;- state.outbound_policy = self- .runtime- .box_manager- .update_box(&self.config.id)?- .outbound_policy;- let builder = BoxBuilder::new(Arc::clone(&self.runtime), self.config.clone(), state)?;+ let persisted = self.runtime.box_manager.update_box(self.id())?;+ state.outbound_policy = persisted.outbound_policy;+ let mut config = self.config.clone();+ config.options.disk_size_gb = persisted.disk_size_gb.or(config.options.disk_size_gb);+ let builder = BoxBuilder::new(Arc::clone(&self.runtime), config, state)?;let crate::litebox::init::BuiltBox {live: live_state,guard: mut cleanup_guard,@@ -1782,6 +1786,10 @@ impl crate::runtime::backend::BoxBackend for BoxImpl {self.start().await}+ async fn resize(&self, options: crate::ResizeOptions) -> BoxliteResult<crate::BoxResources> {+ self.resize(options).await+ }+async fn exec(&self, command: BoxCommand) -> BoxliteResult<Execution> {self.exec(command).await}diff --git a/src/boxlite/src/litebox/box_impl/tests/operation_lock.rs b/src/boxlite/src/litebox/box_impl/tests/operation_lock.rsindex 9ffbef95e..30205e794 100644--- a/src/boxlite/src/litebox/box_impl/tests/operation_lock.rs+++ b/src/boxlite/src/litebox/box_impl/tests/operation_lock.rs@@ -1148,6 +1148,7 @@ async fn batch_clone_shares_base_and_records_refs_until_last_removal() {Qcow2Helper::qcow2_virtual_size(&child).unwrap(),virtual_size);+ assert_eq!(copy.config.options.disk_size_gb, None);assert_eq!(copy.state.read().status, BoxStatus::Stopped);let policy = OutboundNetworkConfig::from(©.config.options.network);assert_eq!(Some(policy), state.outbound_policy);diff --git a/src/boxlite/src/litebox/box_impl/tests/resize.rs b/src/boxlite/src/litebox/box_impl/tests/resize.rsnew file mode 100644index 000000000..1ac347a56--- /dev/null+++ b/src/boxlite/src/litebox/box_impl/tests/resize.rs@@ -0,0 +1,851 @@+use super::*;+use crate::disk::constants::filenames::CONTAINER_DISK;+use crate::disk::{BackingFormat, Qcow2Helper};+use crate::litebox::archive::{ArchiveManifest, MANIFEST_FILENAME, extract_archive};+use crate::litebox::config::ContainerRuntimeConfig;+use crate::runtime::id::BoxIDMint;+use crate::runtime::options::{BoxOptions, BoxliteOptions, NetworkMode, OutboundNetworkConfig};+use crate::runtime::rt_impl::RuntimeImpl;+use crate::runtime::types::ContainerID;+use crate::vmm::VmmKind;+use crate::vmm::vmm_socket::{self, ControlError, ControlOp, ControlReply};+use boxlite_shared::*;+use chrono::Utc;+use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};+use std::sync::{OnceLock, Weak};+use tokio::sync::Semaphore;+use tonic::{Request, Response, Status};++struct GuestGate {+ fail: AtomicBool,+ control_refuses: AtomicBool,+ control_reports_wrong_size: AtomicBool,+ control_calls: AtomicUsize,+ calls: AtomicUsize,+ entered: Semaphore,+ release: Semaphore,+ completed: Semaphore,+ disk_replacement_on_thaw: OnceLock<(PathBuf, Weak<BoxImpl>)>,+}++impl GuestGate {+ fn new() -> Arc<Self> {+ Arc::new(Self {+ fail: AtomicBool::new(true),+ control_refuses: AtomicBool::new(false),+ control_reports_wrong_size: AtomicBool::new(false),+ control_calls: AtomicUsize::new(0),+ calls: AtomicUsize::new(0),+ entered: Semaphore::new(0),+ release: Semaphore::new(0),+ completed: Semaphore::new(0),+ disk_replacement_on_thaw: OnceLock::new(),+ })+ }++ async fn entered(&self) {+ tokio::time::timeout(Duration::from_secs(5), self.entered.acquire())+ .await+ .expect("filesystem request reached the guest")+ .unwrap()+ .forget();+ }+}++struct ResizeGuest(Arc<GuestGate>);++#[tonic::async_trait]+impl Guest for ResizeGuest {+ async fn init(+ &self,+ _: Request<GuestInitRequest>,+ ) -> Result<Response<GuestInitResponse>, Status> {+ Err(Status::unimplemented("fixture is already initialized"))+ }+ async fn ping(&self, _: Request<PingRequest>) -> Result<Response<PingResponse>, Status> {+ Ok(Response::new(PingResponse {+ version: "0.13.1".into(),+ ..Default::default()+ }))+ }+ async fn shutdown(+ &self,+ _: Request<ShutdownRequest>,+ ) -> Result<Response<ShutdownResponse>, Status> {+ Ok(Response::new(ShutdownResponse {}))+ }+ async fn quiesce(+ &self,+ _: Request<QuiesceRequest>,+ ) -> Result<Response<QuiesceResponse>, Status> {+ Ok(Response::new(QuiesceResponse { frozen_count: 0 }))+ }+ async fn thaw(&self, _: Request<ThawRequest>) -> Result<Response<ThawResponse>, Status> {+ if let Some((replacement, source)) = self.0.disk_replacement_on_thaw.get() {+ let source = source+ .upgrade()+ .ok_or_else(|| Status::internal("copy source fixture was dropped"))?;+ tokio::fs::rename(replacement, source.layout.disk_path())+ .await+ .map_err(|error| Status::internal(error.to_string()))?;+ let policy = OutboundNetworkConfig {+ mode: NetworkMode::Disabled,+ ..Default::default()+ };+ source+ .runtime+ .box_manager+ .save_outbound(source.id(), &policy)+ .map_err(|error| Status::internal(error.to_string()))?;+ }+ Ok(Response::new(ThawResponse { thawed_count: 0 }))+ }+ async fn sync_clock(+ &self,+ _: Request<SyncClockRequest>,+ ) -> Result<Response<SyncClockResponse>, Status> {+ Err(Status::unimplemented("unused"))+ }+ async fn resize_filesystem(+ &self,+ request: Request<ResizeFilesystemRequest>,+ ) -> Result<Response<ResizeFilesystemResponse>, Status> {+ let request = request.into_inner();+ assert_eq!(request.device, "/dev/vda");+ assert_eq!(request.minimum_bytes, 20_u64 << 30);+ let gate = Arc::clone(&self.0);+ // The guest keeps resizing after the RPC caller stops waiting.+ tokio::spawn(async move {+ gate.calls.fetch_add(1, Ordering::SeqCst);+ gate.entered.add_permits(1);+ gate.release.acquire().await.unwrap().forget();+ if gate.fail.load(Ordering::SeqCst) {+ return Err(Status::unimplemented("injected old guest"));+ }+ gate.completed.add_permits(1);+ Ok(Response::new(ResizeFilesystemResponse {}))+ })+ .await+ .unwrap()+ }+}++struct Handler;+impl VmmHandler for Handler {+ fn stop(&mut self) -> BoxliteResult<()> {+ Ok(())+ }+ fn metrics(&self) -> BoxliteResult<crate::vmm::controller::VmmMetrics> {+ Ok(Default::default())+ }+ fn is_running(&self) -> bool {+ true+ }+ fn pid(&self) -> u32 {+ 0+ }+}++struct Fixture {+ bx: Arc<crate::LiteBox>,+ inner: Arc<BoxImpl>,+ home: tempfile::TempDir,+ server: JoinHandle<()>,+}++impl Fixture {+ fn completed_disk_size_gb(&self) -> Option<i64> {+ self.inner+ .runtime+ .box_manager+ .db()+ .conn()+ .query_row(+ "SELECT json_extract(json, '$.disk_size_gb') FROM box_state WHERE id = ?1",+ [self.inner.id().as_str()],+ |row| row.get(0),+ )+ .unwrap()+ }+}++impl Drop for Fixture {+ fn drop(&mut self) {+ self.server.abort();+ }+}++async fn fixture(gate: Arc<GuestGate>, kind: VmmKind) -> Fixture {+ let home = tempfile::tempdir_in("/tmp").unwrap();+ let runtime = RuntimeImpl::new_for_test(BoxliteOptions {+ home_dir: home.path().to_path_buf(),+ image_registries: vec![],+ ..Default::default()+ })+ .unwrap();+ let id = BoxIDMint::mint();+ let config = BoxConfig {+ id: id.clone(),+ name: None,+ created_at: Utc::now(),+ container: ContainerRuntimeConfig {+ id: ContainerID::new(),+ },+ options: BoxOptions {+ disk_size_gb: Some(10),+ auto_delete: Some(0),+ detach: true,+ ..Default::default()+ },+ engine_kind: kind,+ box_home: runtime.layout.boxes_dir().join(id.as_str()),+ };+ let mut state = BoxState::new();+ state.status = BoxStatus::Running;+ let lock_id = runtime.lock_manager.allocate().unwrap();+ runtime+ .disk_lock_manager+ .allocate_and_retrieve(lock_id)+ .unwrap();+ state.set_lock_id(lock_id);+ runtime.box_manager.add_box(&config, &state).unwrap();+ let inner = BoxImpl::new(+ config,+ state,+ runtime.clone(),+ runtime.shutdown_token.child_token(),+ );+ let disk = Qcow2Helper::create_disk(&inner.layout.disk_path(), true).unwrap();+ let base = Qcow2Helper::create_disk(&home.path().join("base.qcow2"), true).unwrap();+ std::fs::create_dir_all(inner.layout.sockets_dir()).unwrap();+ inner.layout.sockets().ensure().unwrap();+ let path = inner.layout.disk_path();+ let control_gate = gate.clone();+ vmm_socket::serve(&inner.layout.sockets().vmm_sock(), move |op, directory| {+ assert!(directory.is_none());+ let (block_id, bytes) = match op {+ ControlOp::ResizeDisk { block_id, bytes } => (block_id, bytes),+ #[cfg(feature = "native")]+ _ => panic!("expected a disk resize request"),+ };+ assert_eq!(block_id, "vda");+ control_gate.control_calls.fetch_add(1, Ordering::SeqCst);+ if control_gate.control_refuses.load(Ordering::SeqCst) {+ return Err(ControlError::InvalidInput("injected resize refusal".into()));+ }+ if Qcow2Helper::qcow2_virtual_size(&path).unwrap() < bytes {+ // Fake the device boundary with a real image made by production code.+ // The native acceptance test covers imago's in-place grow separately.+ let replacement = path.with_extension("replacement");+ let image = Qcow2Helper::create_cow_child_disk(+ base.path(),+ BackingFormat::Qcow2,+ &replacement,+ bytes,+ )+ .unwrap();+ std::fs::rename(image.path(), &path).unwrap();+ }+ let actual = Qcow2Helper::qcow2_virtual_size(&path).unwrap();+ if control_gate+ .control_reports_wrong_size+ .load(Ordering::SeqCst)+ {+ return Ok(ControlReply::DiskSize(actual - 512));+ }+ Ok(ControlReply::DiskSize(actual))+ })+ .unwrap();++ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let incoming =+ tonic::transport::server::TcpIncoming::from_listener(listener, true, None).unwrap();+ let server = tokio::spawn(async move {+ tonic::transport::Server::builder()+ .add_service(GuestServer::new(ResizeGuest(gate)))+ .serve_with_incoming(incoming)+ .await+ .unwrap();+ });+ let live = LiveState::new(+ Box::new(Handler),+ GuestSession::new(BoxTransport::tcp(address.port())),+ None,+ None,+ BoxMetricsStorage::new(),+ disk,+ None,+ None,+ );+ assert!(inner.live.set(live).is_ok());+ let inner = Arc::new(inner);+ let bx = Arc::new(crate::LiteBox::new(+ inner.clone(),+ inner.clone(),+ Arc::new(crate::litebox::LocalSnapshotBackend::new(inner.clone())),+ ));+ Fixture {+ bx,+ inner,+ home,+ server,+ }+}++const SAVED_DISK_GIB: u64 = 20;+const COPIED_DISK_BYTES: u64 = 22 << 30;+const GROWN_DISK_BYTES: u64 = 24 << 30;++async fn copy_fixture() -> (Fixture, tokio::process::Child) {+ let gate = GuestGate::new();+ gate.fail.store(false, Ordering::SeqCst);+ gate.release.add_permits(1);+ let fixture = fixture(Arc::clone(&gate), VmmKind::Native).await;+ fixture+ .bx+ .resize(crate::ResizeOptions {+ disk_size_gb: Some(SAVED_DISK_GIB),+ })+ .await+ .unwrap();+ assert_eq!(+ OutboundNetworkConfig::from(&fixture.inner.config.options.network).mode,+ NetworkMode::Enabled+ );++ vmm_socket::grow_disk(+ &fixture.inner.layout.sockets().vmm_sock(),+ "vda",+ COPIED_DISK_BYTES,+ )+ .await+ .unwrap();+ let replacement = Qcow2Helper::create_cow_child_disk(+ &fixture.home.path().join("base.qcow2"),+ BackingFormat::Qcow2,+ &fixture.home.path().join("grown.qcow2"),+ GROWN_DISK_BYTES,+ )+ .unwrap()+ .leak();+ // Thaw runs after the image capture and before recording the copy options.+ gate.disk_replacement_on_thaw+ .set((replacement, Arc::downgrade(&fixture.inner)))+ .unwrap();++ let shim = tokio::process::Command::new("sleep")+ .arg("300")+ .kill_on_drop(true)+ .spawn()+ .unwrap();+ let mut state = fixture.inner.state.write();+ state.pid = Some(shim.id().unwrap());+ fixture+ .inner+ .runtime+ .box_manager+ .save_box(fixture.inner.id(), &state)+ .unwrap();+ drop(state);+ (fixture, shim)+}++fn restore_source_network(fixture: &Fixture) {+ fixture+ .inner+ .runtime+ .box_manager+ .save_outbound(fixture.inner.id(), &OutboundNetworkConfig::default())+ .unwrap();+}++fn assert_copied_disk_and_options(fixture: &Fixture, copied_disk: &Path, options: &BoxOptions) {+ assert_eq!(+ Qcow2Helper::qcow2_virtual_size(&fixture.inner.layout.disk_path()).unwrap(),+ GROWN_DISK_BYTES,+ "the source must grow when the guest thaws"+ );+ let copied_bytes = Qcow2Helper::qcow2_virtual_size(copied_disk).unwrap();+ assert_eq!(copied_bytes, COPIED_DISK_BYTES);+ assert_eq!(+ OutboundNetworkConfig::from(&options.network).mode,+ NetworkMode::Disabled,+ "the copy must carry the outbound policy committed during thaw"+ );+ assert_eq!(+ options.disk_size_gb,+ Some(SAVED_DISK_GIB),+ "the copy options must carry the last saved disk size"+ );+}++#[tokio::test]+async fn export_copy_uses_latest_saved_disk_size() {+ let (fixture, _shim) = copy_fixture().await;+ let archive = fixture+ .bx+ .export(+ Default::default(),+ &fixture.home.path().join("copy.boxlite"),+ )+ .await+ .unwrap();+ restore_source_network(&fixture);+ let extracted = tempfile::tempdir_in(fixture.home.path()).unwrap();+ extract_archive(archive.path(), extracted.path()).unwrap();+ let manifest: ArchiveManifest =+ serde_json::from_slice(&std::fs::read(extracted.path().join(MANIFEST_FILENAME)).unwrap())+ .unwrap();+ assert_copied_disk_and_options(+ &fixture,+ &extracted.path().join(CONTAINER_DISK),+ &manifest.box_options.unwrap(),+ );+}++#[tokio::test]+async fn clone_copy_uses_latest_saved_disk_size() {+ let (fixture, _shim) = copy_fixture().await;+ let clone = fixture+ .bx+ .clone_box(Default::default(), None)+ .await+ .unwrap();+ restore_source_network(&fixture);+ let (config, _) = fixture+ .inner+ .runtime+ .box_manager+ .box_by_id(clone.id())+ .unwrap()+ .unwrap();+ assert_copied_disk_and_options(+ &fixture,+ &config.box_home.join("disks").join(CONTAINER_DISK),+ &config.options,+ );+}++#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn resize_persists_after_guest_success_when_caller_cancels() {+ let gate = GuestGate::new();+ let fixture = fixture(gate.clone(), VmmKind::Native).await;+ let target = crate::ResizeOptions {+ disk_size_gb: Some(20),+ };+ let bx = fixture.bx.clone();+ let first = tokio::spawn(async move { bx.resize(target).await });+ gate.entered().await;+ assert_eq!(fixture.completed_disk_size_gb(), None);+ gate.release.add_permits(1);+ let error = first.await.unwrap().unwrap_err();+ assert!(matches!(error, BoxliteError::Unsupported(_)));+ assert!(error.to_string().contains("partially completed"));+ assert_eq!(fixture.completed_disk_size_gb(), None);+ assert_eq!(+ fixture+ .bx+ .resize(Default::default())+ .await+ .unwrap()+ .disk_size_gb,+ 20+ );+ assert_eq!(fixture.completed_disk_size_gb(), None);++ gate.fail.store(false, Ordering::SeqCst);+ let bx = fixture.bx.clone();+ let retry = tokio::spawn(async move { bx.resize(target).await });+ gate.entered().await;+ assert_eq!(fixture.completed_disk_size_gb(), None);+ retry.abort();+ assert!(retry.await.unwrap_err().is_cancelled());+ let locker = fixture+ .inner+ .runtime+ .lock_manager+ .retrieve(fixture.inner.state.read().lock_id.unwrap())+ .unwrap();+ assert!(+ LockGuard::try_new(locker.as_ref()).is_none(),+ "the detached resize still owns lifecycle admission"+ );+ let inner = fixture.inner.clone();+ let mut stop = tokio::spawn(async move { inner.stop().await });+ assert!(+ tokio::time::timeout(Duration::from_millis(30), &mut stop)+ .await+ .is_err(),+ "stop waits for the admitted grow"+ );+ gate.release.add_permits(1);+ tokio::time::timeout(Duration::from_secs(5), stop)+ .await+ .unwrap()+ .unwrap()+ .unwrap();+ let (config, state) = fixture+ .inner+ .runtime+ .box_manager+ .box_by_id(fixture.inner.id())+ .unwrap()+ .unwrap();+ assert_eq!(fixture.completed_disk_size_gb(), Some(20));+ assert_eq!(config.options.disk_size_gb, Some(10));+ assert_eq!(state.status, BoxStatus::Stopped);+ assert_eq!(gate.control_calls.load(Ordering::SeqCst), 2);+ assert_eq!(+ gate.calls.load(Ordering::SeqCst),+ 2,+ "equal target retries the filesystem step"+ );+}++#[tokio::test]+async fn resize_retries_after_guest_timeout_and_late_completion() {+ let gate = GuestGate::new();+ gate.fail.store(false, Ordering::SeqCst);+ let fixture = fixture(gate.clone(), VmmKind::Native).await;+ let target = crate::ResizeOptions {+ disk_size_gb: Some(20),+ };+ let bx = fixture.bx.clone();+ let first = tokio::spawn(async move { bx.resize(target).await });+ gate.entered().await;++ // Advance the host deadline once the device request has finished.+ tokio::time::pause();+ tokio::time::advance(Duration::from_secs(61)).await;+ tokio::time::resume();+ let error = tokio::time::timeout(Duration::from_secs(5), first)+ .await+ .expect("the host filesystem deadline must bound the resize")+ .unwrap()+ .unwrap_err();+ let BoxliteError::Engine(message) = error else {+ panic!("expected a guest timeout error, got {error}");+ };+ assert!(+ message.contains("guest filesystem resize timed out"),+ "{message}"+ );+ assert!(message.contains("partially completed"), "{message}");+ assert!(message.contains("retry the target"), "{message}");+ assert_eq!(fixture.completed_disk_size_gb(), None);++ gate.release.add_permits(1);+ tokio::time::timeout(Duration::from_secs(5), gate.completed.acquire())+ .await+ .expect("the guest finishes even after the host times out")+ .unwrap()+ .forget();+ assert_eq!(fixture.completed_disk_size_gb(), None);++ let bx = fixture.bx.clone();+ let retry = tokio::spawn(async move { bx.resize(target).await });+ gate.entered().await;+ assert_eq!(fixture.completed_disk_size_gb(), None);+ gate.release.add_permits(1);+ let grown = retry.await.unwrap().unwrap();+ assert_eq!(grown.disk_size_gb, 20);+ assert_eq!(fixture.completed_disk_size_gb(), Some(20));+ assert_eq!(gate.control_calls.load(Ordering::SeqCst), 2);+ assert_eq!(gate.calls.load(Ordering::SeqCst), 2);+}++#[tokio::test]+async fn resize_rejects_other_engines_and_stopped_boxes() {+ let fixture = fixture(GuestGate::new(), VmmKind::Libkrun).await;+ assert!(matches!(+ fixture.bx.resize(Default::default()).await,+ Err(BoxliteError::Unsupported(_))+ ));+ let fixture = self::fixture(GuestGate::new(), VmmKind::Native).await;+ fixture.inner.stop().await.unwrap();+ assert!(matches!(+ fixture.bx.resize(Default::default()).await,+ Err(BoxliteError::InvalidState(_))+ ));+}++#[tokio::test]+async fn device_refusal_preserves_disk_capacity_and_saved_target() {+ let gate = GuestGate::new();+ gate.control_refuses.store(true, Ordering::SeqCst);+ let fixture = fixture(gate.clone(), VmmKind::Native).await;+ let error = fixture+ .bx+ .resize(crate::ResizeOptions {+ disk_size_gb: Some(20),+ })+ .await+ .unwrap_err();+ assert!(matches!(+ error,+ BoxliteError::InvalidArgument(message) if message == "injected resize refusal"+ ));+ assert_eq!(fixture.completed_disk_size_gb(), None);+ assert_eq!(+ fixture+ .bx+ .resize(Default::default())+ .await+ .unwrap()+ .disk_size_gb,+ 10+ );+ assert_eq!(fixture.completed_disk_size_gb(), None);+ assert_eq!(gate.control_calls.load(Ordering::SeqCst), 1);+ assert_eq!(gate.calls.load(Ordering::SeqCst), 0);+}++#[tokio::test]+async fn resize_retries_after_mismatched_device_reply() {+ let gate = GuestGate::new();+ gate.control_reports_wrong_size+ .store(true, Ordering::SeqCst);+ let fixture = fixture(gate.clone(), VmmKind::Native).await;+ let target = crate::ResizeOptions {+ disk_size_gb: Some(20),+ };+ let error = fixture.bx.resize(target).await.unwrap_err();+ let BoxliteError::Engine(message) = error else {+ panic!("expected a device reply error, got {error}");+ };+ assert!(message.contains("shim reported"), "{message}");+ assert!(!message.contains("partially completed"), "{message}");+ assert_eq!(gate.calls.load(Ordering::SeqCst), 0);+ assert_eq!(fixture.completed_disk_size_gb(), None);+ assert!(message.contains("completion is unknown"), "{message}");+ assert!(message.contains("retry the target"), "{message}");+ assert_eq!(+ fixture+ .bx+ .resize(Default::default())+ .await+ .unwrap()+ .disk_size_gb,+ 20+ );+ assert_eq!(fixture.completed_disk_size_gb(), None);+ assert_eq!(gate.control_calls.load(Ordering::SeqCst), 1);+ gate.control_reports_wrong_size+ .store(false, Ordering::SeqCst);+ gate.fail.store(false, Ordering::SeqCst);+ gate.release.add_permits(1);+ let grown = fixture.bx.resize(target).await.unwrap();+ assert_eq!(grown, crate::BoxResources { disk_size_gb: 20 });+ assert_eq!(fixture.completed_disk_size_gb(), Some(20));+ assert_eq!(gate.control_calls.load(Ordering::SeqCst), 2);+ assert_eq!(gate.calls.load(Ordering::SeqCst), 1);+}++#[tokio::test]+async fn resize_reports_partial_completion_after_database_failure_and_retries() {+ let gate = GuestGate::new();+ gate.fail.store(false, Ordering::SeqCst);+ gate.release.add_permits(1);+ let fixture = fixture(gate.clone(), VmmKind::Native).await;+ let db = fixture.inner.runtime.box_manager.db();+ db.conn()+ .execute_batch(+ "CREATE TRIGGER fail_disk_capacity_save BEFORE UPDATE ON box_state+ WHEN json_extract(NEW.json, '$.disk_size_gb') = 20+ BEGIN SELECT RAISE(ABORT, 'injected persistence failure'); END;",+ )+ .unwrap();+ let target = crate::ResizeOptions {+ disk_size_gb: Some(20),+ };+ let error = fixture.bx.resize(target).await.unwrap_err();+ let BoxliteError::Database(message) = error else {+ panic!("expected a database error, got {error}");+ };+ assert_eq!(gate.control_calls.load(Ordering::SeqCst), 1);+ assert_eq!(gate.calls.load(Ordering::SeqCst), 1);+ assert!(message.contains("partially completed"), "{message}");+ assert!(message.contains("20 GiB"), "{message}");+ assert!(+ message.contains("injected persistence failure"),+ "{message}"+ );+ assert!(message.contains("retry the target"), "{message}");+ assert_eq!(fixture.completed_disk_size_gb(), None);+ assert_eq!(+ fixture+ .bx+ .resize(Default::default())+ .await+ .unwrap()+ .disk_size_gb,+ 20+ );+ assert_eq!(fixture.completed_disk_size_gb(), None);+ assert_eq!(gate.control_calls.load(Ordering::SeqCst), 1);++ db.conn()+ .execute_batch("DROP TRIGGER fail_disk_capacity_save;")+ .unwrap();+ gate.release.add_permits(1);+ let grown = fixture.bx.resize(target).await.unwrap();+ assert_eq!(grown, crate::BoxResources { disk_size_gb: 20 });+ assert_eq!(fixture.completed_disk_size_gb(), Some(20));+ assert_eq!(gate.control_calls.load(Ordering::SeqCst), 2);+ assert_eq!(gate.calls.load(Ordering::SeqCst), 2);+}++#[tokio::test]+async fn resize_rejects_a_handle_from_an_earlier_vm_run() {+ let gate = GuestGate::new();+ gate.fail.store(false, Ordering::SeqCst);+ gate.release.add_permits(1);+ let fixture = fixture(gate.clone(), VmmKind::Native).await;+ let mut replacement = fixture+ .inner+ .runtime+ .box_manager+ .update_box(fixture.inner.id())+ .unwrap();+ replacement.started_at = Some(Utc::now());+ fixture+ .inner+ .runtime+ .box_manager+ .save_box(fixture.inner.id(), &replacement)+ .unwrap();++ let result = fixture+ .bx+ .resize(crate::ResizeOptions {+ disk_size_gb: Some(20),+ })+ .await;+ assert!(+ matches!(result, Err(BoxliteError::Stopped(_))),+ "a cached guest connection must not resize a replacement VM: {result:?}"+ );+ assert_eq!(gate.calls.load(Ordering::SeqCst), 0);+ assert_eq!(+ Qcow2Helper::qcow2_virtual_size(&fixture.inner.layout.disk_path()).unwrap(),+ 10_u64 << 30+ );+}++#[tokio::test]+async fn resize_serializes_with_disk_operations_and_stop_uses_the_lifecycle_lock() {+ let gate = GuestGate::new();+ gate.fail.store(false, Ordering::SeqCst);+ let fixture = fixture(gate.clone(), VmmKind::Native).await;+ let disk_locker = fixture.inner.disk_locker().unwrap();+ let disk_guard = LockGuard::new_async(disk_locker.as_ref()).await;+ let bx = fixture.bx.clone();+ let mut grow = tokio::spawn(async move {+ bx.resize(crate::ResizeOptions {+ disk_size_gb: Some(20),+ })+ .await+ });+ assert!(+ tokio::time::timeout(Duration::from_millis(30), &mut grow)+ .await+ .is_err()+ );+ assert_eq!(+ Qcow2Helper::qcow2_virtual_size(&fixture.inner.layout.disk_path()).unwrap(),+ 10_u64 << 30+ );+ drop(disk_guard);+ gate.entered().await;+ let lock_id = fixture.inner.state.read().lock_id.unwrap();+ let independent = fixture+ .inner+ .runtime+ .lock_manager+ .retrieve(lock_id)+ .unwrap();+ assert!(+ LockGuard::try_new(&*independent).is_none(),+ "grow owns the lifecycle lock"+ );+ let mut stop = Box::pin(fixture.inner.stop());+ assert!(futures::poll!(&mut stop).is_pending());+ assert!(+ !fixture.inner.shutdown_token.is_cancelled(),+ "stop must wait until the admitted filesystem grow finishes"+ );+ gate.release.add_permits(1);+ grow.await.unwrap().unwrap();+ tokio::time::timeout(Duration::from_secs(5), stop)+ .await+ .unwrap()+ .unwrap();+}++#[tokio::test]+async fn resize_capacity_is_carried_into_clones_and_exported_options() {+ let gate = GuestGate::new();+ gate.fail.store(false, Ordering::SeqCst);+ gate.release.add_permits(1);+ let fixture = fixture(gate, VmmKind::Native).await;+ fixture+ .bx+ .resize(crate::ResizeOptions {+ disk_size_gb: Some(20),+ })+ .await+ .unwrap();+ fixture.bx.stop().await.unwrap();++ let cloned = fixture+ .bx+ .clone_box(Default::default(), None)+ .await+ .unwrap();+ let (config, _) = fixture+ .inner+ .runtime+ .box_manager+ .box_by_id(cloned.id())+ .unwrap()+ .unwrap();+ assert_eq!(config.options.disk_size_gb, Some(20));+ assert_eq!(+ config+ .options+ .advanced+ .security+ .resource_limits+ .max_file_size,+ None+ );++ let destination = tempfile::tempdir().unwrap();+ let exported = fixture+ .bx+ .export(Default::default(), destination.path())+ .await+ .unwrap();+ let file = std::fs::File::open(exported.path()).unwrap();+ let mut archive = ::tar::Archive::new(zstd::Decoder::new(file).unwrap());+ let mut found = false;+ for entry in archive.entries().unwrap() {+ let entry = entry.unwrap();+ if entry.path().unwrap() == std::path::Path::new(crate::litebox::archive::MANIFEST_FILENAME)+ {+ let manifest: crate::litebox::archive::ArchiveManifest =+ serde_json::from_reader(entry).unwrap();+ let options = manifest.box_options.unwrap();+ assert_eq!(options.disk_size_gb, Some(20));+ assert_eq!(+ options.advanced.security.resource_limits.max_file_size,+ None+ );+ found = true;+ break;+ }+ }+ assert!(found, "export contains the effective options");+}diff --git a/src/boxlite/src/litebox/clone_export.rs b/src/boxlite/src/litebox/clone_export.rsindex 266d7cb1e..1db71c24c 100644--- a/src/boxlite/src/litebox/clone_export.rs+++ b/src/boxlite/src/litebox/clone_export.rs@@ -18,12 +18,9 @@ use crate::runtime::types::BoxStatus;impl BoxImpl {fn options_for_copy(&self) -> BoxliteResult<crate::runtime::options::BoxOptions> {let mut options = self.config.options.clone();- if let Some(policy) = self- .runtime- .box_manager- .update_box(self.id())?- .outbound_policy- {+ let state = self.runtime.box_manager.update_box(self.id())?;+ options.disk_size_gb = state.disk_size_gb.or(options.disk_size_gb);+ if let Some(policy) = state.outbound_policy {options.network = policy.try_into()?;}Ok(options)diff --git a/src/boxlite/src/litebox/init/mod.rs b/src/boxlite/src/litebox/init/mod.rsindex a4f71136a..9cb5aa1d2 100644--- a/src/boxlite/src/litebox/init/mod.rs+++ b/src/boxlite/src/litebox/init/mod.rs@@ -194,7 +194,7 @@ impl BoxBuilder {/// # Arguments////// * `runtime` - Runtime providing resources (layout, guest_rootfs, etc.)- /// * `config` - Box configuration (immutable after creation)+ /// * `config` - Box configuration with any saved disk target applied/// * `state` - Current box state (determines init mode)pub(crate) fn new(runtime: SharedRuntimeImpl,diff --git a/src/boxlite/src/litebox/init/tasks/guest_init.rs b/src/boxlite/src/litebox/init/tasks/guest_init.rsindex 44e3b25bd..8d7fec3fc 100644--- a/src/boxlite/src/litebox/init/tasks/guest_init.rs+++ b/src/boxlite/src/litebox/init/tasks/guest_init.rs@@ -363,6 +363,14 @@ mod tests {thawed_count: 0,}))}++ async fn resize_filesystem(+ &self,+ _: tonic::Request<boxlite_shared::ResizeFilesystemRequest>,+ ) -> Result<tonic::Response<boxlite_shared::ResizeFilesystemResponse>, tonic::Status>+ {+ Err(tonic::Status::unimplemented("not used by these tests"))+ }}#[tonic::async_trait]diff --git a/src/boxlite/src/litebox/manager.rs b/src/boxlite/src/litebox/manager.rsindex 7e14eba51..47fc2a24e 100644--- a/src/boxlite/src/litebox/manager.rs+++ b/src/boxlite/src/litebox/manager.rs@@ -198,6 +198,11 @@ impl BoxManager {Ok(())}+ #[cfg(all(target_os = "linux", target_arch = "x86_64"))]+ pub fn save_disk_size(&self, id: &BoxID, disk_size_gb: u64) -> BoxliteResult<()> {+ self.store.update_disk_size(id.as_str(), disk_size_gb)+ }+pub fn save_outbound(&self,id: &BoxID,diff --git a/src/boxlite/src/litebox/mod.rs b/src/boxlite/src/litebox/mod.rsindex 28a53bae0..2fd87f44a 100644--- a/src/boxlite/src/litebox/mod.rs+++ b/src/boxlite/src/litebox/mod.rs@@ -16,6 +16,7 @@ pub(crate) mod local_snapshot;mod manager;mod network;pub(crate) mod ports;+mod resize;mod snapshot;pub(crate) mod snapshot_mgr;mod ssh;@@ -35,9 +36,10 @@ pub use network::{BoxConnection, BoxReader, BoxTunnel, BoxWriter, NetworkHandle, SocketAddress, TunnelForwarder,TunnelOptions,};+pub use resize::ResizeOptions;pub use snapshot::SnapshotHandle;pub use ssh::{SshAccount, SshCaConfig, SshConfig, SshHandle, SshStatus};-pub use state::{BoxState, BoxStatus, HealthState, HealthStatus};+pub use state::{BoxResources, BoxState, BoxStatus, HealthState, HealthStatus};pub(crate) use box_impl::SharedBoxImpl;pub(crate) use init::BoxBuilder;@@ -50,7 +52,7 @@ use crate::metrics::BoxMetrics;use crate::runtime::backend::{BoxBackend, BoxNetworkBackend, SnapshotBackend};use crate::runtime::options::{BoxArchive, CloneOptions, ExportOptions};use crate::{BoxID, BoxInfo};-use boxlite_shared::errors::BoxliteResult;+use boxlite_shared::errors::{BoxliteError, BoxliteResult};pub use config::BoxConfig;/// LiteBox - Handle to a box.@@ -114,6 +116,21 @@ impl LiteBox {self.box_backend.start().await}+ /// Grow a running native Linux box's root disk, or query its allocation.+ ///+ /// Explicit targets are 1–1024 GiB and cannot shrink the disk. The runtime+ /// saves the target in box state after device and guest filesystem growth succeed.+ ///+ /// Retry the same target after a partial or uncertain result. The operation+ /// continues if the caller cancels its wait.+ pub async fn resize(&self, options: ResizeOptions) -> BoxliteResult<BoxResources> {+ options.validate()?;+ let backend = Arc::clone(&self.box_backend);+ tokio::spawn(async move { backend.resize(options).await })+ .await+ .map_err(|error| BoxliteError::Internal(format!("resize task failed: {error}")))?+ }+pub async fn exec(&self, command: BoxCommand) -> BoxliteResult<Execution> {self.box_backend.exec(command).await}diff --git a/src/boxlite/src/litebox/resize.rs b/src/boxlite/src/litebox/resize.rsnew file mode 100644index 000000000..83b617f90--- /dev/null+++ b/src/boxlite/src/litebox/resize.rs@@ -0,0 +1,169 @@+//! Online root-disk allocation and recovery.++use boxlite_shared::{BoxliteError, BoxliteResult};+use serde::{Deserialize, Serialize};++use super::BoxResources;+const ONLINE_GROW_MAX_GB: u64 = 1024;++/// Absolute targets. An omitted disk size queries the current allocation.+#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct ResizeOptions {+ /// Root disk capacity in binary GiB, from 1 through 1024; growth only.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub disk_size_gb: Option<u64>,+}++impl ResizeOptions {+ pub(crate) fn validate(&self) -> BoxliteResult<()> {+ if let Some(size) = self.disk_size_gb+ && !(1..=ONLINE_GROW_MAX_GB).contains(&size)+ {+ return Err(BoxliteError::InvalidArgument(format!(+ "disk_size_gb must be between 1 and {ONLINE_GROW_MAX_GB}, got {size}"+ )));+ }+ Ok(())+ }++ #[cfg(any(test, all(target_os = "linux", target_arch = "x86_64")))]+ fn target(self, current: BoxResources) -> BoxliteResult<BoxResources> {+ self.validate()?;+ let disk_size_gb = self.disk_size_gb.unwrap_or(current.disk_size_gb);+ if disk_size_gb < current.disk_size_gb {+ return Err(BoxliteError::InvalidArgument(format!(+ "cannot shrink disk from {} GiB to {disk_size_gb} GiB",+ current.disk_size_gb+ )));+ }+ Ok(BoxResources { disk_size_gb })+ }+}++impl super::box_impl::BoxImpl {+ pub(crate) async fn resize(&self, options: ResizeOptions) -> BoxliteResult<BoxResources> {+ #[cfg(all(target_os = "linux", target_arch = "x86_64"))]+ {+ self.resize_native(options).await+ }+ #[cfg(not(all(target_os = "linux", target_arch = "x86_64")))]+ {+ let _ = options;+ Err(BoxliteError::Unsupported(+ "online disk resize requires the native Linux VMM".into(),+ ))+ }+ }++ #[cfg(all(target_os = "linux", target_arch = "x86_64"))]+ async fn resize_native(&self, options: ResizeOptions) -> BoxliteResult<BoxResources> {+ if self.config.engine_kind != crate::vmm::VmmKind::Native {+ return Err(BoxliteError::Unsupported(+ "online disk resize requires the native VMM".into(),+ ));+ }+ self.with_disk_admission(self.with_operation(self.resize_admitted(options)))+ .await+ }++ #[cfg(all(target_os = "linux", target_arch = "x86_64"))]+ async fn resize_admitted(&self, options: ResizeOptions) -> BoxliteResult<BoxResources> {+ use std::time::Duration;++ let live = self.existing_live_state_locked().await?;+ let current = BoxResources::from_disk(&self.layout.disk_path())?;+ if options.disk_size_gb.is_none() {+ return Ok(current);+ }+ let target = options.target(current)?;+ let bytes = target.disk_size_gb * (1 << 30);++ // An equal target repeats device confirmation and completes pending steps.+ crate::vmm::vmm_socket::grow_disk(&self.layout.sockets().vmm_sock(), "vda", bytes).await?;++ let filesystem = tokio::time::timeout(Duration::from_secs(60), async {+ live.guest_session+ .guest()+ .await?+ .resize_filesystem(bytes)+ .await+ })+ .await+ .unwrap_or_else(|_| {+ Err(BoxliteError::Engine(+ "guest filesystem resize timed out".into(),+ ))+ });+ filesystem.map_err(|error| partial_resize_error(target, error))?;++ self.runtime+ .box_manager+ .save_disk_size(&self.config.id, target.disk_size_gb)+ .map_err(|error| {+ BoxliteError::Database(format!(+ "disk resize partially completed: {} GiB allocated and filesystem expanded, state persistence failed: {error}; retry the target",+ target.disk_size_gb+ ))+ })?;+ Ok(target)+ }+}++#[cfg(all(target_os = "linux", target_arch = "x86_64"))]+fn partial_resize_error(resources: BoxResources, error: BoxliteError) -> BoxliteError {+ let message = format!(+ "disk resize partially completed: {} GiB allocated, filesystem grow failed: {error}; retry the target",+ resources.disk_size_gb+ );+ match error {+ BoxliteError::Unsupported(_) => BoxliteError::Unsupported(message),+ BoxliteError::InvalidArgument(_) => BoxliteError::InvalidArgument(message),+ _ => BoxliteError::Engine(message),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn resize_disk_targets_and_wire_contract() {+ let current = BoxResources { disk_size_gb: 10 };+ assert_eq!(ResizeOptions::default().target(current).unwrap(), current);+ assert_eq!(+ serde_json::to_value(ResizeOptions::default()).unwrap(),+ serde_json::json!({})+ );+ for size in [10, 20, 1024] {+ let options: ResizeOptions =+ serde_json::from_value(serde_json::json!({"disk_size_gb": size})).unwrap();+ assert_eq!(options.target(current).unwrap().disk_size_gb, size);+ }+ for size in [0, 1, 9, 1025, u64::MAX] {+ assert!(+ ResizeOptions {+ disk_size_gb: Some(size)+ }+ .target(current)+ .is_err()+ );+ }+ assert_eq!(+ ResizeOptions {+ disk_size_gb: Some(1)+ }+ .target(BoxResources { disk_size_gb: 1 })+ .unwrap()+ .disk_size_gb,+ 1+ );+ for body in [+ r#"{"disk_size_gb":-1}"#,+ r#"{"disk_size_gb":1.5}"#,+ r#"{"cpus":2}"#,+ ] {+ assert!(serde_json::from_str::<ResizeOptions>(body).is_err());+ }+ }+}diff --git a/src/boxlite/src/litebox/state.rs b/src/boxlite/src/litebox/state.rsindex 355b6dead..05e6903f6 100644--- a/src/boxlite/src/litebox/state.rs+++ b/src/boxlite/src/litebox/state.rs@@ -202,6 +202,22 @@ impl std::fmt::Display for BoxStatus {}}+/// Virtual disk capacity in binary GiB.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+pub struct BoxResources {+ pub disk_size_gb: u64,+}++#[cfg(all(target_os = "linux", target_arch = "x86_64"))]+impl BoxResources {+ pub(crate) fn from_disk(path: &std::path::Path) -> boxlite_shared::BoxliteResult<Self> {+ let bytes = crate::disk::Qcow2Helper::qcow2_virtual_size(path)?;+ Ok(Self {+ disk_size_gb: bytes.div_ceil(1 << 30),+ })+ }+}+/// Dynamic box state (changes during lifecycle).////// This is updated frequently and persisted to database.@@ -212,6 +228,9 @@ pub struct BoxState {/// whether the VM has a NIC; an override never adds or removes the device.#[serde(default)]pub outbound_policy: Option<crate::runtime::options::OutboundNetworkConfig>,+ /// Last completed online resize target in GiB.+ #[serde(default)]+ pub disk_size_gb: Option<u64>,/// Current lifecycle status.pub status: BoxStatus,pub pid: Option<u32>,@@ -364,6 +383,7 @@ impl BoxState {Self {status: BoxStatus::Configured,outbound_policy: None,+ disk_size_gb: None,pid: None,container_id: None,last_updated: Utc::now(),diff --git a/src/boxlite/src/portal/interfaces/guest.rs b/src/boxlite/src/portal/interfaces/guest.rsindex 3263ea6cc..c3cd6d8d0 100644--- a/src/boxlite/src/portal/interfaces/guest.rs+++ b/src/boxlite/src/portal/interfaces/guest.rs@@ -132,6 +132,28 @@ impl GuestInterface {.await?;Ok(())}++ /// Fill the container root disk after the kernel observes its new capacity.+ #[cfg(all(target_os = "linux", target_arch = "x86_64"))]+ pub(crate) async fn resize_filesystem(&mut self, minimum_bytes: u64) -> BoxliteResult<()> {+ self.client+ .resize_filesystem(boxlite_shared::ResizeFilesystemRequest {+ device: "/dev/vda".into(),+ minimum_bytes,+ })+ .await+ .map_err(|error| {+ if error.code() == tonic::Code::Unimplemented {+ BoxliteError::Unsupported(+ "guest has no filesystem resize RPC; restart with the current runtime"+ .into(),+ )+ } else {+ BoxliteError::Engine(format!("guest filesystem resize failed: {error}"))+ }+ })?;+ Ok(())+ }}/// A guest agent version as `(major, minor, patch)`.diff --git a/src/boxlite/src/runtime/backend.rs b/src/boxlite/src/runtime/backend.rsindex d89b97f17..d358ab6a0 100644--- a/src/boxlite/src/runtime/backend.rs+++ b/src/boxlite/src/runtime/backend.rs@@ -96,6 +96,12 @@ pub(crate) trait BoxBackend: Send + Sync + Any {async fn start(&self) -> BoxliteResult<()>;+ async fn resize(&self, _options: crate::ResizeOptions) -> BoxliteResult<crate::BoxResources> {+ Err(BoxliteError::Unsupported(+ "this backend does not support online disk resize".into(),+ ))+ }+async fn exec(&self, command: BoxCommand) -> BoxliteResult<Execution>;async fn list_executions(&self) -> BoxliteResult<Vec<crate::ExecutionInfo>>;diff --git a/src/boxlite/src/runtime/options.rs b/src/boxlite/src/runtime/options.rsindex 9da2046b0..5e018b6cf 100644--- a/src/boxlite/src/runtime/options.rs+++ b/src/boxlite/src/runtime/options.rs@@ -385,11 +385,9 @@ pub struct BoxOptions {#[serde(serialize_with = "super::cpu_count::serialize_optional")]pub cpus: Option<f64>,pub memory_mib: Option<u32>,- /// Disk size in GB for the container rootfs (sparse, grows as needed).+ /// Requested virtual capacity of the container rootfs at creation, in GiB.///- /// The actual disk will be at least as large as the base image.- /// If set, the COW overlay will have this virtual size, allowing- /// the container to write more data than the base image size.+ /// A new sparse COW disk is at least as large as the base image.pub disk_size_gb: Option<u64>,pub working_dir: Option<String>,diff --git a/src/boxlite/src/vmm/controller/mount_control/registry.rs b/src/boxlite/src/vmm/controller/mount_control/registry.rsindex 5b18f9c75..97f19c377 100644--- a/src/boxlite/src/vmm/controller/mount_control/registry.rs+++ b/src/boxlite/src/vmm/controller/mount_control/registry.rs@@ -1,5 +1,5 @@use super::{ControlMount, MountState};-use crate::vmm::vmm_socket::{ControlOp, ControlReply, MAX_FRAME};+use crate::vmm::vmm_socket::{ControlOp, ControlReply, MAX_MOUNT_BODY};use boxlite_vmm::lookup_aggregate;use std::fs::File;use std::io;@@ -94,7 +94,7 @@ impl Registry {// counter includes JSON escaping without copying existing records.let cost = record_cost(&mount)?;let envelope = br#"{"Ok":{"mounts":[]}}"#.len();- if self.list_bytes + cost + envelope > MAX_FRAME as usize {+ if self.list_bytes + cost + envelope > MAX_MOUNT_BODY {return Err(errno(libc::ENOSPC));}// Reserve memory before publication so the remaining record insertiondiff --git a/src/boxlite/src/vmm/mod.rs b/src/boxlite/src/vmm/mod.rsindex baf8b6eeb..5404abd6c 100644--- a/src/boxlite/src/vmm/mod.rs+++ b/src/boxlite/src/vmm/mod.rs@@ -26,10 +26,7 @@ pub mod krun;#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]pub mod native;pub mod registry;-#[cfg(any(- test,- all(feature = "native", target_os = "linux", target_arch = "x86_64")-))]+#[cfg(any(test, all(target_os = "linux", target_arch = "x86_64")))]pub(crate) mod vmm_socket;use crate::experimental::custom_kernel::{KernelFormat, KernelOptions};diff --git a/src/boxlite/src/vmm/native/tests/mod.rs b/src/boxlite/src/vmm/native/tests/mod.rsindex 021d971a7..efb0d2193 100644--- a/src/boxlite/src/vmm/native/tests/mod.rs+++ b/src/boxlite/src/vmm/native/tests/mod.rs@@ -489,7 +489,7 @@ async fn reports_a_missing_kernel_through_the_exit_file() {#[tokio::test]#[ignore = "requires Linux x86_64 with /dev/kvm, VMM_KERNEL, VMM_DISK_GROW_INIT and a boxlite-shim built with native"]async fn grows_a_disk_through_the_shim_control_socket() {- use crate::vmm::vmm_socket::{ControlOp, ControlReply, ControlRequest, VERSION, request};+ use crate::vmm::vmm_socket::{ControlError, ControlOp, ControlReply, exchange};let test_box = TestBox::new();let kernel = fs::read(std::env::var_os("VMM_KERNEL").expect("set VMM_KERNEL")).unwrap();@@ -510,11 +510,13 @@ async fn grows_a_disk_through_the_shim_control_socket() {format: DiskFormat::Raw,});+ let mut options = BoxOptions::default();+ options.advanced.security.resource_limits.max_file_size = Some(32 << 20);let mut controller = ShimController::new(find_binary("boxlite-shim").unwrap(),VmmKind::Native,test_box.box_id.clone(),- BoxOptions::default(),+ options,test_box.layout.clone(),).unwrap();@@ -530,17 +532,28 @@ async fn grows_a_disk_through_the_shim_control_socket() {tokio::time::sleep(Duration::from_millis(20)).await;}let path = test_box.layout.sockets().vmm_sock();- let grow = ControlRequest {- version: VERSION,- op: ControlOp::ResizeDisk {- block_id: "vda".into(),- bytes: 2 << 20,- },+ let request_growth = |bytes| {+ let path = path.clone();+ tokio::task::spawn_blocking(move || {+ exchange(+ &path,+ ControlOp::ResizeDisk {+ block_id: "vda".into(),+ bytes,+ },+ None,+ Duration::from_secs(15),+ )+ .unwrap()+ })};- let reply = tokio::task::spawn_blocking(move || request(&path, &grow, Duration::from_secs(15)))- .await- .unwrap()- .unwrap();+ let oversized = request_growth(64 << 20).await.unwrap();+ assert!(+ matches!(&oversized, Err(ControlError::Failed(message)) if message.contains("RLIMIT_FSIZE")),+ "over-limit growth: {oversized:?}"+ );+ assert_eq!(fs::metadata(&disk).unwrap().len(), 1 << 20);+ let reply = request_growth(2 << 20).await.unwrap();let exit = tokio::time::timeout(SHIM_TIMEOUT,ProcessMonitor::new(handler.pid()).wait_for_exit(),diff --git a/src/boxlite/src/vmm/tests/vmm_socket.rs b/src/boxlite/src/vmm/tests/vmm_socket.rsindex 399c24d4a..a85245406 100644--- a/src/boxlite/src/vmm/tests/vmm_socket.rs+++ b/src/boxlite/src/vmm/tests/vmm_socket.rs@@ -1,18 +1,89 @@use super::*;+use std::io::{Read, Write};use std::os::unix::fs::PermissionsExt;-fn grow_to(block_id: &str, bytes: u64) -> ControlRequest {- ControlRequest {- version: VERSION,- op: ControlOp::ResizeDisk {- block_id: block_id.into(),- bytes,- },+const GROW: &[u8] = br#"{"block_id":"container","bytes":4096}"#;+const TEST_TIMEOUT: Duration = Duration::from_secs(5);++fn runtime() -> Runtime {+ tokio::runtime::Builder::new_current_thread()+ .enable_io()+ .enable_time()+ .build()+ .unwrap()+}++fn echo_resize(op: ControlOp, directory: Option<File>) -> ControlResponse {+ assert!(directory.is_none());+ match op {+ ControlOp::ResizeDisk { bytes, .. } => Ok(ControlReply::DiskSize(bytes)),+ #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+ _ => panic!("expected a resize request"),+ }+}++fn http_request(method: &str, path: &str, body: &[u8]) -> Vec<u8> {+ let headers = format!(+ "{method} {path} HTTP/1.1\r\nHost: vmm\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",+ body.len(),+ );+ [headers.as_bytes(), body].concat()+}++fn write_http(mut stream: &UnixStream, method: &str, path: &str, body: &[u8]) {+ stream.write_all(&http_request(method, path, body)).unwrap();+}++fn owner_uid() -> libc::uid_t {+ // SAFETY: geteuid has no preconditions.+ unsafe { libc::geteuid() }+}++fn set_response_timeout(stream: &UnixStream) {+ // Darwin can reject timeout changes after the peer disconnects.+ stream.set_read_timeout(Some(TEST_TIMEOUT)).unwrap();+}++fn read_http(mut stream: &UnixStream) -> String {+ let mut response = String::new();+ if let Err(error) = stream.read_to_string(&mut response) {+ // Rejecting a request can close the socket with unread input.+ assert!(+ error.kind() == io::ErrorKind::ConnectionReset && !response.is_empty(),+ "{error}"+ );}+ response+}++fn raw_http(path: &Path, method: &str, route: &str, body: &[u8]) -> String {+ let client = UnixStream::connect(path).unwrap();+ set_response_timeout(&client);+ write_http(&client, method, route, body);+ read_http(&client)}#[test]-fn a_request_reaches_the_handler_and_its_answer_returns() {+fn http_resize_reaches_the_handler() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("vmm.sock");+ serve(&path, |op, _| match op {+ ControlOp::ResizeDisk { block_id, bytes } => {+ assert_eq!(block_id, "container");+ assert_eq!(bytes, 4096);+ Ok(ControlReply::DiskSize(bytes))+ }+ #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+ _ => panic!("expected a resize request"),+ })+ .unwrap();+ let reply = raw_http(&path, "POST", RESIZE_PATH, GROW);+ assert!(reply.starts_with("HTTP/1.1 200 "), "{reply}");+ assert!(reply.ends_with(r#"{"Ok":{"disk_size":4096}}"#), "{reply}");+}++#[tokio::test]+async fn a_request_reaches_the_handler_and_its_answer_returns() {let dir = tempfile::tempdir().unwrap();let path = dir.path().join("vmm.sock");serve(&path, |op, _| match op {@@ -29,28 +100,84 @@ fn a_request_reaches_the_handler_and_its_answer_returns() {let mode = std::fs::metadata(&path).unwrap().permissions().mode();assert_eq!(mode & 0o777, 0o600, "the socket is owner-only");- let timeout = Duration::from_secs(5);assert_eq!(- request(&path, &grow_to("container", 4096), timeout).unwrap(),+ timeout(TEST_TIMEOUT, request(&path, "container", 4096))+ .await+ .unwrap()+ .unwrap(),Ok(ControlReply::DiskSize(4096)));assert_eq!(- request(&path, &grow_to("missing", 4096), timeout).unwrap(),+ timeout(TEST_TIMEOUT, request(&path, "missing", 4096))+ .await+ .unwrap()+ .unwrap(),Err(ControlError::InvalidInput("no disk missing".into())));}-#[test]-fn accept_recovers_from_temporary_errors_with_bounded_backoff() {- let (mut client, stream) = UnixStream::pair().unwrap();- client- .set_read_timeout(Some(Duration::from_secs(1)))- .unwrap();- write_frame(- &mut client,- &serde_json::to_vec(&grow_to("container", 4096)).unwrap(),+#[tokio::test]+async fn client_returns_reply_when_socket_shutdown_would_fail() {+ use std::pin::Pin;+ use std::task::{Context, Poll};+ use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};++ struct ShutdownFails(tokio::net::UnixStream);++ impl AsyncRead for ShutdownFails {+ fn poll_read(+ mut self: Pin<&mut Self>,+ cx: &mut Context<'_>,+ buf: &mut ReadBuf<'_>,+ ) -> Poll<io::Result<()>> {+ Pin::new(&mut self.0).poll_read(cx, buf)+ }+ }++ impl AsyncWrite for ShutdownFails {+ fn poll_write(+ mut self: Pin<&mut Self>,+ cx: &mut Context<'_>,+ bytes: &[u8],+ ) -> Poll<io::Result<usize>> {+ Pin::new(&mut self.0).poll_write(cx, bytes)+ }++ fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {+ Pin::new(&mut self.0).poll_flush(cx)+ }++ fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {+ // Darwin can report ENOTCONN when the peer already closed.+ Poll::Ready(Err(io::ErrorKind::NotConnected.into()))+ }+ }++ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("vmm.sock");+ serve(&path, echo_resize).unwrap();+ let stream = tokio::net::UnixStream::connect(&path).await.unwrap();++ let reply = timeout(+ TEST_TIMEOUT,+ exchange_http(+ TokioIo::new(ShutdownFails(stream)),+ RESIZE_PATH,+ GROW.to_vec(),+ MAX_BODY,+ ),)+ .await+ .unwrap().unwrap();+ assert_eq!(reply, Ok(ControlReply::DiskSize(4096)));+}++#[test]+fn accept_recovers_from_temporary_errors_with_bounded_backoff() {+ let (client, stream) = UnixStream::pair().unwrap();+ set_response_timeout(&client);+ write_http(&client, "POST", RESIZE_PATH, GROW);let accept_error = |errno| Err(io::Error::from_raw_os_error(errno));let incoming = [@@ -70,69 +197,138 @@ fn accept_recovers_from_temporary_errors_with_bounded_backoff() {panic!("the listener must stop accepting after EBADF")}));let mut waits = Vec::new();- serve_connections(- incoming,- // SAFETY: `geteuid` has no preconditions.- unsafe { libc::geteuid() },- |op, _| match op {- ControlOp::ResizeDisk { bytes, .. } => Ok(ControlReply::DiskSize(bytes)),- #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]- _ => panic!("expected a resize request"),- },- |delay| waits.push(delay),- );+ serve_connections(&runtime(), incoming, owner_uid(), echo_resize, |delay| {+ waits.push(delay)+ });- let reply = read_frame(&mut client).expect("request after EMFILE must receive a reply");- let reply: ControlResponse = serde_json::from_slice(&reply).unwrap();- assert_eq!(reply, Ok(ControlReply::DiskSize(4096)));+ let reply = read_http(&client);+ assert!(reply.starts_with("HTTP/1.1 200 "), "{reply}");assert_eq!(waits, [5, 10, 20, 40, 50, 50, 5].map(Duration::from_millis));}#[test]-fn another_version_is_unsupported_and_the_shim_keeps_serving() {+fn only_the_versioned_post_route_can_dispatch() {let dir = tempfile::tempdir().unwrap();let path = dir.path().join("vmm.sock");- serve(&path, |_, _| Ok(ControlReply::DiskSize(1))).unwrap();- let timeout = Duration::from_secs(5);- let mut future = grow_to("container", 512);- future.version = VERSION + 1;- assert!(matches!(- request(&path, &future, timeout).unwrap(),- Err(ControlError::Unsupported(_))- ));- assert_eq!(- request(&path, &grow_to("container", 512), timeout).unwrap(),- Ok(ControlReply::DiskSize(1))- );+ serve(&path, |_, _| panic!("invalid requests must not dispatch")).unwrap();++ let reply = raw_http(&path, "POST", "/v2/resize-disk", GROW);+ assert!(reply.starts_with("HTTP/1.1 404 "), "{reply}");+ let reply = raw_http(&path, "GET", RESIZE_PATH, &[]);+ assert!(reply.starts_with("HTTP/1.1 405 "), "{reply}");+ assert!(reply.contains("\r\nallow: POST\r\n"), "{reply}");+}++#[test]+fn request_size_and_read_deadlines_are_bounded() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("vmm.sock");+ serve(&path, |op, directory| {+ assert!(matches!(&op, ControlOp::ResizeDisk { block_id, .. } if block_id == "container"));+ echo_resize(op, directory)+ })+ .unwrap();++ let mut headers = UnixStream::connect(&path).unwrap();+ set_response_timeout(&headers);+ let mut request = format!("POST {RESIZE_PATH} HTTP/1.1\r\nHost: vmm\r\nX-Pad: ").into_bytes();+ request.resize(HTTP_BUFFER, b'x');+ headers.write_all(&request).unwrap();+ let reply = read_http(&headers);+ assert!(reply.starts_with("HTTP/1.1 431 "), "{reply}");++ let padded_json = [GROW, &vec![b' '; MAX_BODY + 1 - GROW.len()]].concat();+ let reply = raw_http(&path, "POST", RESIZE_PATH, &padded_json);+ assert!(reply.starts_with("HTTP/1.1 413 "), "{reply}");++ let reply = raw_http(&path, "POST", RESIZE_PATH, &padded_json[..MAX_BODY]);+ assert!(reply.starts_with("HTTP/1.1 200 "), "{reply}");++ let mut blocked = UnixStream::connect(&path).unwrap();+ set_response_timeout(&blocked);+ blocked+ .write_all(b"POST /v1/resize-disk HTTP/1.1\r\nHost: vmm\r\nContent-Length: 50\r\n\r\n{")+ .unwrap();+ let reply = read_http(&blocked);+ assert!(reply.starts_with("HTTP/1.1 408 "), "{reply}");++ let _silent = UnixStream::connect(&path).unwrap();+ let reply = raw_http(&path, "POST", RESIZE_PATH, GROW);+ assert!(reply.starts_with("HTTP/1.1 200 "), "{reply}");}#[test]-fn an_oversized_or_unknown_request_is_bounded() {+fn only_complete_first_requests_dispatch_when_clients_disconnect_before_accept() {let dir = tempfile::tempdir().unwrap();let path = dir.path().join("vmm.sock");- serve(&path, |_, _| Ok(ControlReply::DiskSize(1))).unwrap();-- // An oversized frame ends the connection without a reply.- let mut stream = UnixStream::connect(&path).unwrap();- stream.write_all(&(MAX_FRAME + 1).to_le_bytes()).unwrap();- let mut reply = Vec::new();- stream.read_to_end(&mut reply).unwrap();- assert!(reply.is_empty());-- // An operation this protocol does not name is refused as invalid.- let mut stream = UnixStream::connect(&path).unwrap();- write_frame(&mut stream, br#"{"version":1,"op":"reboot"}"#).unwrap();- let response: ControlResponse =- serde_json::from_slice(&read_frame(&mut stream).unwrap()).unwrap();- assert!(matches!(response, Err(ControlError::InvalidInput(_))));-- // A partial header times out, and the next connection is accepted.+ let listener = UnixListener::bind(&path).unwrap();++ let client = UnixStream::connect(&path).unwrap();+ write_http(&client, "POST", RESIZE_PATH, GROW);+ write_http(+ &client,+ "POST",+ RESIZE_PATH,+ br#"{"block_id":"container","bytes":8192}"#,+ );+ drop(client);+let mut partial = UnixStream::connect(&path).unwrap();- partial.write_all(&[1, 0]).unwrap();- assert_eq!(- request(&path, &grow_to("container", 512), Duration::from_secs(5)).unwrap(),- Ok(ControlReply::DiskSize(1))+ partial+ .write_all(b"POST /v1/resize-disk HTTP/1.1\r\nHost: vmm\r\nContent-Length: 50\r\n\r\n{")+ .unwrap();+ drop(partial);+ let client = UnixStream::connect(&path).unwrap();+ set_response_timeout(&client);+ write_http(&client, "POST", RESIZE_PATH, GROW);++ let mut submitted = Vec::new();+ serve_connections(+ &runtime(),+ listener.incoming().take(3),+ owner_uid(),+ |op, directory| {+ let reply = echo_resize(op, directory);+ match &reply {+ Ok(ControlReply::DiskSize(bytes)) => submitted.push(*bytes),+ _ => panic!("expected a resize reply"),+ }+ reply+ },+ std::thread::sleep,);+ assert_eq!(submitted, [4096, 4096]);+ let reply = read_http(&client);+ assert!(reply.starts_with("HTTP/1.1 200 "), "{reply}");+}++#[test]+fn a_stalled_reply_releases_the_connection_at_the_deadline() {+ let (client, mut stream) = UnixStream::pair().unwrap();+ stream.set_nonblocking(true).unwrap();+ loop {+ match stream.write(&[0; 4096]) {+ Ok(size) => assert!(size > 0),+ Err(error) if error.kind() == io::ErrorKind::WouldBlock => break,+ Err(error) => panic!("fill socket buffer: {error}"),+ }+ }+ write_http(&client, "POST", RESIZE_PATH, GROW);++ let runtime = tokio::runtime::Builder::new_current_thread()+ .enable_io()+ .enable_time()+ .start_paused(true)+ .build()+ .unwrap();+ let mut dispatched = false;+ let error = answer(&runtime, stream, owner_uid(), &mut |op, directory| {+ dispatched = true;+ echo_resize(op, directory)+ })+ .unwrap_err();+ assert!(dispatched, "only the reply should stall");+ assert_eq!(error.kind(), io::ErrorKind::TimedOut);}#[test]@@ -140,11 +336,9 @@ fn serving_replaces_a_stale_socket() {let dir = tempfile::tempdir().unwrap();let path = dir.path().join("vmm.sock");drop(UnixListener::bind(&path).unwrap());- serve(&path, |_, _| Ok(ControlReply::DiskSize(7))).unwrap();- assert_eq!(- request(&path, &grow_to("container", 7), Duration::from_secs(5)).unwrap(),- Ok(ControlReply::DiskSize(7))- );+ serve(&path, echo_resize).unwrap();+ let reply = raw_http(&path, "POST", RESIZE_PATH, GROW);+ assert!(reply.starts_with("HTTP/1.1 200 "), "{reply}");}#[test]@@ -156,18 +350,107 @@ fn resize_requires_a_block_id_and_rejects_index_only_requests() {}).unwrap();for body in [- br#"{"version":1,"op":"resize_disk","bytes":4096}"#.as_slice(),- br#"{"version":1,"op":"resize_disk","index":0,"bytes":4096}"#.as_slice(),+ br#"{"bytes":4096}"#.as_slice(),+ br#"{"index":0,"bytes":4096}"#.as_slice(),] {- let mut stream = UnixStream::connect(&path).unwrap();- stream- .set_read_timeout(Some(Duration::from_secs(5)))+ let reply = raw_http(&path, "POST", RESIZE_PATH, body);+ assert!(reply.starts_with("HTTP/1.1 400 "), "{reply}");+ }+}++#[test]+fn a_framed_client_cannot_dispatch_to_an_http_shim() {+ let body = br#"{"version":1,"op":"resize_disk","block_id":"container","bytes":4096}"#;+ let (mut client, stream) = UnixStream::pair().unwrap();+ set_response_timeout(&client);+ client+ .write_all(&[&(body.len() as u32).to_le_bytes(), body.as_slice()].concat())+ .unwrap();+ client.shutdown(std::net::Shutdown::Write).unwrap();++ let _ = answer(&runtime(), stream, owner_uid(), &mut |_, _| {+ panic!("framed requests must not dispatch")+ });+ let reply = read_http(&client);+ assert!(+ reply.is_empty() || reply.starts_with("HTTP/1.1 400 "),+ "{reply}"+ );+}++#[tokio::test]+async fn the_client_rejects_an_oversized_reply() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("vmm.sock");+ let listener = tokio::net::UnixListener::bind(&path).unwrap();+ let peer = async {+ let (stream, _) = listener.accept().await.unwrap();+ let _ = hyper::server::conn::http1::Builder::new()+ .keep_alive(false)+ .header_read_timeout(None)+ .serve_connection(+ TokioIo::new(stream),+ hyper::service::service_fn(|request: Request<Incoming>| async {+ let _ = request.into_body().collect().await.unwrap();+ Ok::<_, Infallible>(Response::new(Full::new(Bytes::from(vec![+ b' ';+ MAX_BODY + 1+ ]))))+ }),+ )+ .await;+ };+ let (reply, ()) = timeout(TEST_TIMEOUT, async {+ tokio::join!(request(&path, "container", 4096), peer)+ })+ .await+ .unwrap();+ assert!(+ reply+ .unwrap_err()+ .into_inner()+ .unwrap()+ .is::<LengthLimitError>()+ );+}++#[cfg(all(+ feature = "native",+ target_os = "linux",+ target_arch = "x86_64",+ target_env = "gnu"+))]+#[test]+fn http_runs_under_the_production_vmm_filter() {+ const CHILD: &str = "BOXLITE_TEST_HTTP_SECCOMP_CHILD";+ const DONE: &str = "HTTP resize served under VMM seccomp";+ if std::env::var_os(CHILD).is_none() {+ let output = std::process::Command::new(std::env::current_exe().unwrap())+ .args([+ "--exact",+ "vmm::vmm_socket::tests::http_runs_under_the_production_vmm_filter",+ "--nocapture",+ ])+ .env(CHILD, "1")+ .output().unwrap();- write_frame(&mut stream, body).unwrap();- let response: ControlResponse =- serde_json::from_slice(&read_frame(&mut stream).unwrap()).unwrap();- assert!(matches!(response, Err(ControlError::InvalidInput(_))));+ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(+ output.status.success() && stdout.contains(DONE),+ "{:?}\n{stdout}\n{}",+ output.status,+ String::from_utf8_lossy(&output.stderr),+ );+ return;}++ let dir = tempfile::tempdir().unwrap();+ crate::jailer::seccomp::apply_vmm_filter("vmm-http-test").unwrap();+ let path = dir.path().join("vmm.sock");+ serve(&path, echo_resize).unwrap();+ let reply = raw_http(&path, "POST", RESIZE_PATH, GROW);+ assert!(reply.starts_with("HTTP/1.1 200 "), "{reply}");+ println!("{DONE}");}#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]@@ -205,28 +488,37 @@ mod mounts {}}+ #[test]+ fn mount_route_rejects_unknown_and_resize_operations() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("vmm.sock");+ serve(&path, |_, _| {+ panic!("invalid mount requests must not dispatch")+ })+ .unwrap();+ for body in [+ br#"{"op":"reboot"}"#.as_slice(),+ br#"{"op":"resize_disk","block_id":"vda","bytes":4096}"#.as_slice(),+ ] {+ let reply = raw_http(&path, "POST", MOUNT_PATH, body);+ assert!(reply.starts_with("HTTP/1.1 400 "), "{reply}");+ }+ }+#[test]fn fragmented_directory_delivery_survives_an_unread_reply() {let (dir, _fs, path) = fixture();let directory = File::open(dir.path()).unwrap();let mut stream = UnixStream::connect(&path).unwrap();stream.set_read_timeout(Some(TIMEOUT)).unwrap();- let frame = serde_json::to_vec(&ControlRequest {- version: VERSION,- op: registration("/data"),- })- .unwrap();- let header = (frame.len() as u32).to_le_bytes();- stream.write_all(&header[..2]).unwrap();- transport::send_parts(- &stream,- &header[2..],- &frame[..1],- Some(directory.as_raw_fd()),- Instant::now() + TIMEOUT,- )- .unwrap();- stream.write_all(&frame[1..]).unwrap();+ let body = serde_json::to_vec(®istration("/data")).unwrap();+ let request = http_request("POST", MOUNT_PATH, &body);+ assert_eq!(+ transport::send_with_file(stream.as_raw_fd(), &request[..1], directory.as_raw_fd())+ .unwrap(),+ 1+ );+ stream.write_all(&request[1..]).unwrap();stream.read_exact(&mut [0]).unwrap();drop(stream);@@ -265,28 +557,28 @@ mod mounts {exchange(&path, registration("/data"), Some(&file), TIMEOUT).unwrap(),Err(ControlError::Mount(libc::ENOTDIR)));- let frame = serde_json::to_vec(&ControlRequest {- version: VERSION,- op: registration("/data"),- })- .unwrap();- let stream = UnixStream::connect(&path).unwrap();- let end = Instant::now() + TIMEOUT;- let descriptor = Some(directory.as_raw_fd());- transport::send_parts(- &stream,- &(frame.len() as u32).to_le_bytes(),- &[],- descriptor,- end,- )- .unwrap();- transport::send_parts(&stream, &frame, &[], descriptor, end).unwrap();- // Closing the malformed exchange must still leave the listener usable.- assert_eq!(- transport::receive_frame(&stream, end).unwrap_err().kind(),- io::ErrorKind::UnexpectedEof- );+ let body = serde_json::to_vec(®istration("/data")).unwrap();+ let request = http_request("POST", MOUNT_PATH, &body);+ let mut stream = UnixStream::connect(&path).unwrap();+ stream.set_read_timeout(Some(TIMEOUT)).unwrap();+ // Put the second descriptor on the final byte of the body.+ let last = request.len() - 1;+ let send_descriptor = |stream: &UnixStream, bytes: &[u8]| {+ assert_eq!(+ transport::send_with_file(stream.as_raw_fd(), bytes, directory.as_raw_fd())+ .unwrap(),+ 1+ );+ };+ send_descriptor(&stream, &request[..1]);+ stream.write_all(&request[1..last]).unwrap();+ send_descriptor(&stream, &request[last..]);+ let mut reply = [0; 1];+ match stream.read(&mut reply) {+ Ok(0) => {}+ Err(error) if error.kind() == io::ErrorKind::ConnectionReset => {}+ result => panic!("malformed descriptor exchange stayed open: {result:?}"),+ }let client = MountControlClient::new(path);assert!(client.list().unwrap().is_empty());client@@ -294,6 +586,42 @@ mod mounts {.unwrap();}+ #[test]+ fn a_trailing_descriptor_does_not_publish_a_mount() {+ let dir = tempfile::tempdir().unwrap();+ let tag = dir.path().to_str().unwrap();+ let filesystem = Arc::new(AggregateFs::new(vec![]).unwrap());+ boxlite_vmm::insert_aggregate(tag, filesystem);+ let directory = File::open(dir.path()).unwrap();+ let body = serde_json::to_vec(®istration("/data")).unwrap();+ let (mut client, stream) = UnixStream::pair().unwrap();++ // Queue the complete HTTP request before the byte carrying the descriptor.+ client+ .write_all(&http_request("POST", MOUNT_PATH, &body))+ .unwrap();+ assert_eq!(+ transport::send_with_file(client.as_raw_fd(), b"x", directory.as_raw_fd()).unwrap(),+ 1+ );+ client.shutdown(std::net::Shutdown::Write).unwrap();++ let mut registry = Registry::default();+ let mut dispatches = 0;+ let _ = answer(&runtime(), stream, owner_uid(), &mut |op, directory| {+ dispatches += 1;+ registry+ .request(tag, op, directory)+ .map_err(|error| ControlError::Mount(error.raw_os_error().unwrap()))+ });+ assert_eq!(+ registry.request(tag, ControlOp::ListMounts, None).unwrap(),+ ControlReply::Mounts(vec![]),+ "a descriptor beyond the request body must not publish a mount"+ );+ assert_eq!(dispatches, 0);+ }+#[test]fn mount_list_fits_after_registration_reaches_capacity() {let (dir, _fs, path) = fixture();@@ -340,8 +668,13 @@ mod mounts {let queued = UnixStream::connect(&path).unwrap();let (tx, rx) = std::sync::mpsc::channel();std::thread::spawn(move || {- let deadline = Instant::now() + Duration::from_millis(100);- tx.send(transport::connect(&path, deadline)).unwrap();+ tx.send(exchange(+ &path,+ ControlOp::ListMounts,+ None,+ Duration::from_millis(100),+ ))+ .unwrap();});let result = rx.recv_timeout(TIMEOUT);drop(queued);@@ -360,14 +693,13 @@ mod mounts {boxlite_vmm::insert_aggregate(&tag, fs.clone());let mut registry = Registry::default();let listener = UnixListener::bind(&path).unwrap();- // This shim belongs to another uid, so the test process is a foreign peer.- // SAFETY: `geteuid` has no preconditions.- let owner = unsafe { libc::geteuid() } + 1;+ let owner = owner_uid() + 1;let handled = Arc::new(AtomicUsize::new(0));let seen = Arc::clone(&handled);std::thread::spawn(move || {serve_connections(- listener.incoming(),+ &runtime(),+ listener.incoming().take(2),owner,move |op, directory| {seen.fetch_add(1, Ordering::SeqCst);@@ -395,12 +727,74 @@ mod mounts {}#[test]- fn a_kernel_socket_timeout_reports_the_deadline() {- let (stream, _silent_peer) = UnixStream::pair().unwrap();- let end = Instant::now() + Duration::from_millis(100);- assert_eq!(- transport::receive_frame(&stream, end).unwrap_err().kind(),- io::ErrorKind::TimedOut+ fn client_deadline_includes_a_silent_peer() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("vmm.sock");+ let _silent_peer = UnixListener::bind(&path).unwrap();+ let result = exchange(+ &path,+ ControlOp::ListMounts,+ None,+ Duration::from_millis(100),);+ assert_eq!(result.unwrap_err().kind(), io::ErrorKind::TimedOut);}}++#[cfg(all(target_os = "linux", target_arch = "x86_64"))]+#[tokio::test]+async fn resize_client_validates_replies_and_reports_unsupported_shims() {+ use boxlite_shared::BoxliteError;++ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("vmm.sock");+ assert!(matches!(+ grow_disk(&path, "vda", 4096).await,+ Err(BoxliteError::Unsupported(_))+ ));+ serve(&path, |op, _| match op {+ ControlOp::ResizeDisk {+ block_id,+ bytes: 4096 | 8192,+ } if block_id == "vda" => Ok(ControlReply::DiskSize(4096)),+ _ => Err(ControlError::Unsupported("old engine".into())),+ })+ .unwrap();+ grow_disk(&path, "vda", 4096).await.unwrap();+ assert!(matches!(+ grow_disk(&path, "vda", 8192).await,+ Err(BoxliteError::Engine(_))+ ));+ assert!(matches!(+ grow_disk(&path, "vda", 16384).await,+ Err(BoxliteError::Unsupported(_))+ ));+}++#[cfg(all(target_os = "linux", target_arch = "x86_64"))]+#[tokio::test]+async fn an_http_client_reports_uncertainty_with_a_framed_shim() {+ use boxlite_shared::BoxliteError;++ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("vmm.sock");+ let listener = tokio::net::UnixListener::bind(&path).unwrap();+ let old_peer = async {+ use tokio::io::AsyncReadExt;+ let (mut stream, _) = listener.accept().await.unwrap();+ let length = stream.read_u32_le().await.unwrap();+ assert_eq!(length, u32::from_le_bytes(*b"POST"));+ assert!(length > 4096);+ };+ let (reply, ()) = timeout(CLIENT_TIMEOUT, async {+ tokio::join!(grow_disk(&path, "vda", 4096), old_peer)+ })+ .await+ .unwrap();+ assert!(matches!(+ reply,+ Err(BoxliteError::Engine(message)) if message.contains("completion is unknown")+ && message.contains("retry the target")+ && message.contains("matching versions")+ ));+}diff --git a/src/boxlite/src/vmm/vmm_socket.rs b/src/boxlite/src/vmm/vmm_socket.rsindex 451759224..b53a871ea 100644--- a/src/boxlite/src/vmm/vmm_socket.rs+++ b/src/boxlite/src/vmm/vmm_socket.rs@@ -3,51 +3,76 @@//! The shim serves one Unix socket, `vmm.sock` in the box's socket//! directory, for runtime operations on the VMM it hosts. The socket is//! host-only (mode 0600, never bridged into guest vsock) and at a fixed path,-//! so a runtime that restarts can still reach a running box. Each connection-//! carries one request and one response: a 4-byte little-endian length, then-//! a JSON object of at most [`MAX_FRAME`] bytes. Native directory registration-//! carries one open directory via `SCM_RIGHTS`. Requests name [`VERSION`].+//! so a runtime that restarts can still reach a running box with a matching+//! shim. Each connection carries one HTTP/1.1 JSON request and response.+//! Directory registration attaches one open directory via `SCM_RIGHTS`.-use std::fs::File;use std::io;-#[cfg(test)]-use std::io::{Read, Write};-use std::os::unix::net::{UnixListener, UnixStream};use std::path::Path;use std::time::Duration;+use bytes::Bytes;+use http_body_util::{BodyExt, Full, Limited};+use hyper::header::{CONNECTION, CONTENT_TYPE, HOST};+use hyper::{Request, StatusCode};+use hyper_util::rt::TokioIo;use serde::{Deserialize, Serialize};+use tokio::time::timeout;++#[cfg(any(test, feature = "native"))]+use {+ http_body_util::LengthLimitError,+ hyper::{+ Method, Response,+ body::Incoming,+ header::{ALLOW, HeaderValue},+ },+ hyper_util::rt::TokioTimer,+ std::{+ cell::RefCell,+ convert::Infallible,+ fs::File,+ os::unix::net::{UnixListener, UnixStream},+ },+ tokio::{+ runtime::Runtime,+ time::{Instant, timeout_at},+ },+};#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]use super::controller::mount_control::{ControlMount, MountState};-#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]-use std::time::Instant;-#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]mod transport;-/// The protocol version a request names.-pub(crate) const VERSION: u32 = 1;-/// The largest frame either side accepts.+const RESIZE_PATH: &str = "/v1/resize-disk";+const MAX_BODY: usize = 4096;+#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+const MOUNT_PATH: &str = "/v1/mount-control";#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]-pub(crate) const MAX_FRAME: u32 = 64 * 1024;-#[cfg(not(all(feature = "native", target_os = "linux", target_arch = "x86_64")))]-const MAX_FRAME: u32 = 4096;-/// How long the shim waits for a request or a reply write.-const IO_TIMEOUT: Duration = Duration::from_secs(2);+pub(super) const MAX_MOUNT_BODY: usize = 64 * 1024;+const HTTP_BUFFER: usize = 8192;+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]+const CLIENT_TIMEOUT: Duration = Duration::from_secs(15);+#[cfg(any(test, feature = "native"))]+const READ_TIMEOUT: Duration = Duration::from_secs(2);+// Allow the request read, ten-second device reply wait, and reply write.+#[cfg(any(test, feature = "native"))]+const SERVER_TIMEOUT: Duration = Duration::from_secs(14);+#[cfg(any(test, feature = "native"))]const ACCEPT_RETRY_INITIAL: Duration = Duration::from_millis(5);+#[cfg(any(test, feature = "native"))]const ACCEPT_RETRY_MAX: Duration = Duration::from_millis(50);-/// One versioned request. Its operation sits beside `version`, tagged by-/// `op`; an unknown operation fails to parse.-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]-pub(crate) struct ControlRequest {- pub(crate) version: u32,- #[serde(flatten)]- pub(crate) op: ControlOp,+#[derive(Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+struct ResizeDiskRequest {+ block_id: String,+ bytes: u64,}/// The operations a shim may serve.+#[cfg(any(test, feature = "native"))]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(tag = "op", rename_all = "snake_case")]pub(crate) enum ControlOp {@@ -101,6 +126,7 @@ pub(crate) enum ControlError {/// Binds `path` (replacing a stale socket), makes it owner-only, and serves/// each connection on a `vmm-control` thread with `handle`.+#[cfg(any(test, feature = "native"))]pub(crate) fn serve(path: &Path,handle: impl FnMut(ControlOp, Option<File>) -> ControlResponse + Send + 'static,@@ -112,14 +138,36 @@ pub(crate) fn serve(restrict_to_owner(path)?;// SAFETY: `geteuid` has no preconditions.let owner = unsafe { libc::geteuid() };+ let (ready, started) = std::sync::mpsc::channel();std::thread::Builder::new().name("vmm-control".into())- .spawn(move || serve_connections(listener.incoming(), owner, handle, std::thread::sleep))?;- Ok(())+ .spawn(move || {+ let runtime = tokio::runtime::Builder::new_current_thread()+ .enable_io()+ .enable_time()+ .build();+ match runtime {+ Ok(runtime) => {+ let _ = ready.send(Ok(()));+ serve_connections(+ &runtime,+ listener.incoming(),+ owner,+ handle,+ std::thread::sleep,+ );+ }+ Err(error) => {+ let _ = ready.send(Err(error));+ }+ }+ })?;+ started.recv().map_err(io::Error::other)?}-/// `owner` is the uid whose mount control requests this shim accepts.+#[cfg(any(test, feature = "native"))]fn serve_connections(+ runtime: &Runtime,incoming: impl Iterator<Item = io::Result<UnixStream>>,owner: libc::uid_t,mut handle: impl FnMut(ControlOp, Option<File>) -> ControlResponse,@@ -153,140 +201,351 @@ fn serve_connections(continue;}};- if let Err(error) = answer(stream, owner, &mut handle) {+ if let Err(error) = answer(runtime, stream, owner, &mut handle) {tracing::debug!(%error, "control connection ended");}}}+#[cfg(any(test, feature = "native"))]fn answer(+ runtime: &Runtime,stream: UnixStream,owner: libc::uid_t,handle: &mut impl FnMut(ControlOp, Option<File>) -> ControlResponse,) -> io::Result<()> {- // The resize path of other platforms has no peer check.- #[cfg(not(all(feature = "native", target_os = "linux", target_arch = "x86_64")))]- let _ = owner;#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]- let (frame, file) = transport::receive_frame(&stream, Instant::now() + IO_TIMEOUT)?;+ let same_user = transport::same_user(&stream, owner)+ .map_err(|error| error.raw_os_error().unwrap_or(libc::EIO));#[cfg(not(all(feature = "native", target_os = "linux", target_arch = "x86_64")))]- let (mut stream, frame, file) = {- let mut stream = stream;- stream.set_read_timeout(Some(IO_TIMEOUT))?;- stream.set_write_timeout(Some(IO_TIMEOUT))?;- let frame = read_frame(&mut stream)?;- (stream, frame, None)- };- let response = match serde_json::from_slice::<ControlRequest>(&frame) {- Ok(request) if request.version == VERSION => {- #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]- let checked = check_request(&stream, owner, &request.op, file.is_some());- #[cfg(not(all(feature = "native", target_os = "linux", target_arch = "x86_64")))]- let checked = Ok(());- checked.and_then(|()| handle(request.op, file))- }- Ok(request) => Err(ControlError::Unsupported(format!(- "protocol version {}",- request.version- ))),- Err(error) => Err(ControlError::InvalidInput(error.to_string())),- };- let reply = serde_json::to_vec(&response)?;- #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]- return transport::send_frame(&stream, &reply, None, Instant::now() + IO_TIMEOUT);- #[cfg(not(all(feature = "native", target_os = "linux", target_arch = "x86_64")))]- write_frame(&mut stream, &reply)+ let _ = owner;++ runtime.block_on(async {+ stream.set_nonblocking(true)?;+ let stream = tokio::net::UnixStream::from_std(stream)?;+ #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+ let (stream, received) = transport::AncillaryIo::new(stream, None);++ // One request per connection. The listener owns the mutable handler+ // and lends it to Hyper only for synchronous dispatch.+ let handle = RefCell::new(handle);+ let read_deadline = Instant::now() + READ_TIMEOUT;+ let connection = hyper::server::conn::http1::Builder::new()+ .keep_alive(false)+ .half_close(true)+ .max_buf_size(HTTP_BUFFER)+ .timer(TokioTimer::new())+ .header_read_timeout(READ_TIMEOUT)+ .serve_connection(+ TokioIo::new(stream),+ hyper::service::service_fn(|request| async {+ let reply = handle_http(request, read_deadline, |op| {+ #[cfg(all(+ feature = "native",+ target_os = "linux",+ target_arch = "x86_64"+ ))]+ let file = {+ let file = received.take();+ check_request(&op, file.is_some(), same_user)?;+ file+ };+ #[cfg(not(all(+ feature = "native",+ target_os = "linux",+ target_arch = "x86_64"+ )))]+ let file = None;+ handle.borrow_mut()(op, file)+ })+ .await;+ Ok::<_, Infallible>(reply)+ }),+ );+ timeout(SERVER_TIMEOUT, connection)+ .await+ .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "control connection timed out"))?+ .map_err(io::Error::other)+ })}#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]fn check_request(- stream: &UnixStream,- owner: libc::uid_t,op: &ControlOp,has_fd: bool,+ same_user: Result<bool, i32>,) -> Result<(), ControlError> {let register = matches!(op, ControlOp::RegisterMount { .. });if has_fd != register {return Err(ControlError::Mount(libc::EINVAL));}- if !matches!(op, ControlOp::ResizeDisk { .. })- && !transport::same_user(stream, owner)- .map_err(|error| ControlError::Mount(error.raw_os_error().unwrap_or(libc::EIO)))?- {+ if !matches!(op, ControlOp::ResizeDisk { .. }) && !same_user.map_err(ControlError::Mount)? {return Err(ControlError::Mount(libc::EPERM));}Ok(())}+#[cfg(any(test, feature = "native"))]+async fn handle_http(+ request: Request<Incoming>,+ read_deadline: Instant,+ handle: impl FnOnce(ControlOp) -> ControlResponse,+) -> Response<Full<Bytes>> {+ type ParseControlOp = fn(&[u8]) -> Result<ControlOp, ControlError>;+ let (parse, max_body): (ParseControlOp, _) = match request.uri().path() {+ RESIZE_PATH => (parse_resize, MAX_BODY),+ #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+ MOUNT_PATH => (parse_mount, MAX_MOUNT_BODY),+ _ => return invalid_request(StatusCode::NOT_FOUND, "unknown control path"),+ };+ if request.method() != Method::POST {+ let mut response = invalid_request(StatusCode::METHOD_NOT_ALLOWED, "control requires POST");+ response+ .headers_mut()+ .insert(ALLOW, HeaderValue::from_static("POST"));+ return response;+ }++ let body = Limited::new(request.into_body(), max_body);+ let body = match timeout_at(read_deadline, body.collect()).await {+ Ok(Ok(body)) => body.to_bytes(),+ Ok(Err(error)) if error.is::<LengthLimitError>() => {+ return invalid_request(StatusCode::PAYLOAD_TOO_LARGE, "control request too large");+ }+ Ok(Err(_)) => {+ return invalid_request(StatusCode::BAD_REQUEST, "incomplete control request");+ }+ Err(_) => return invalid_request(StatusCode::REQUEST_TIMEOUT, "control request timed out"),+ };+ let reply = parse(&body).and_then(handle);+ json_reply(reply_status(&reply), &reply, max_body)+}++#[cfg(any(test, feature = "native"))]+fn parse_resize(body: &[u8]) -> Result<ControlOp, ControlError> {+ let request: ResizeDiskRequest = serde_json::from_slice(body)+ .map_err(|error| ControlError::InvalidInput(error.to_string()))?;+ Ok(ControlOp::ResizeDisk {+ block_id: request.block_id,+ bytes: request.bytes,+ })+}+#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]-pub(crate) fn exchange(- path: &Path,- op: ControlOp,- directory: Option<&File>,- timeout: Duration,-) -> io::Result<ControlResponse> {- use std::os::fd::AsRawFd;+fn parse_mount(body: &[u8]) -> Result<ControlOp, ControlError> {+ let op = serde_json::from_slice(body)+ .map_err(|error| ControlError::InvalidInput(error.to_string()))?;+ if matches!(op, ControlOp::ResizeDisk { .. }) {+ return Err(ControlError::InvalidInput(+ "expected a mount operation".into(),+ ));+ }+ Ok(op)+}- let deadline = Instant::now() + timeout;- let stream = transport::connect(path, deadline)?;- let request = ControlRequest {- version: VERSION,- op,+#[cfg(any(test, feature = "native"))]+fn invalid_request(status: StatusCode, message: impl Into<String>) -> Response<Full<Bytes>> {+ json_reply(+ status,+ &Err(ControlError::InvalidInput(message.into())),+ MAX_BODY,+ )+}++fn reply_status(reply: &ControlResponse) -> StatusCode {+ match reply {+ Ok(_) => StatusCode::OK,+ Err(ControlError::InvalidInput(_)) => StatusCode::BAD_REQUEST,+ Err(ControlError::Unsupported(_)) => StatusCode::NOT_IMPLEMENTED,+ Err(ControlError::Failed(_)) => StatusCode::INTERNAL_SERVER_ERROR,+ #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+ Err(ControlError::Mount(errno)) => match *errno {+ libc::EINVAL | libc::ENOTDIR => StatusCode::BAD_REQUEST,+ libc::EPERM | libc::EACCES => StatusCode::FORBIDDEN,+ libc::ENOENT => StatusCode::NOT_FOUND,+ libc::EBUSY => StatusCode::CONFLICT,+ libc::ENOSPC => StatusCode::INSUFFICIENT_STORAGE,+ _ => StatusCode::INTERNAL_SERVER_ERROR,+ },+ }+}++#[cfg(any(test, feature = "native"))]+fn json_reply(+ status: StatusCode,+ reply: &ControlResponse,+ max_body: usize,+) -> Response<Full<Bytes>> {+ let (status, body) = match serde_json::to_vec(reply) {+ Ok(body) if body.len() <= max_body => (status, Bytes::from(body)),+ _ => (+ StatusCode::INTERNAL_SERVER_ERROR,+ Bytes::from_static(br#"{"Err":{"failed":"control reply exceeds the size limit"}}"#),+ ),};- let frame = serde_json::to_vec(&request)?;- transport::send_frame(&stream, &frame, directory.map(AsRawFd::as_raw_fd), deadline)?;- let (reply, attached) = transport::receive_frame(&stream, deadline)?;- if attached.is_some() {+ let mut response = Response::new(Full::new(body));+ *response.status_mut() = status;+ response+ .headers_mut()+ .insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));+ response+}++async fn request(path: &Path, block_id: &str, bytes: u64) -> io::Result<ControlResponse> {+ let body = serde_json::to_vec(&ResizeDiskRequest {+ block_id: block_id.into(),+ bytes,+ })?;+ let stream = tokio::net::UnixStream::connect(path).await?;+ exchange_http(TokioIo::new(stream), RESIZE_PATH, body, MAX_BODY).await+}++async fn exchange_http(+ stream: impl hyper::rt::Read + hyper::rt::Write + Unpin,+ route: &'static str,+ body: Vec<u8>,+ max_body: usize,+) -> io::Result<ControlResponse> {+ if body.len() > max_body {return Err(io::Error::new(- io::ErrorKind::InvalidData,- "descriptor in control reply",+ io::ErrorKind::InvalidInput,+ "control request too large",));}- Ok(serde_json::from_slice(&reply)?)+ let (mut sender, connection) = hyper::client::conn::http1::Builder::new()+ .max_buf_size(HTTP_BUFFER)+ .handshake(stream)+ .await+ .map_err(io::Error::other)?;+ let request = Request::post(route)+ .header(HOST, "vmm")+ .header(CONTENT_TYPE, "application/json")+ .header(CONNECTION, "close")+ .body(Full::new(Bytes::from(body)))+ .map_err(io::Error::other)?;+ let exchange = async {+ let response = sender+ .send_request(request)+ .await+ .map_err(io::Error::other)?;+ let status = response.status();+ let body = Limited::new(response.into_body(), max_body)+ .collect()+ .await+ .map_err(io::Error::other)?;+ let reply: ControlResponse = serde_json::from_slice(&body.to_bytes())?;+ if status != reply_status(&reply) {+ return Err(io::Error::new(+ io::ErrorKind::InvalidData,+ format!("unexpected HTTP control status {status}"),+ ));+ }+ Ok(reply)+ };+ tokio::pin!(exchange);+ // Drive the connection within this exchange so canceling it closes the socket.+ // Drop the socket at completion because the peer may already have closed.+ tokio::select! {+ biased;+ reply = &mut exchange => reply,+ result = connection.without_shutdown() => {+ result.map_err(io::Error::other)?;+ exchange.await+ }+ }}-/// Sends `request` to the shim at `path` and waits up to `timeout` for the-/// answer, as the host side of one exchange.-#[cfg(test)]-pub(crate) fn request(+/// A blocking exchange for the native mount client and shim tests.+#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+pub(crate) fn exchange(path: &Path,- request: &ControlRequest,+ op: ControlOp,+ directory: Option<&File>,timeout: Duration,) -> io::Result<ControlResponse> {- let mut stream = UnixStream::connect(path)?;- stream.set_read_timeout(Some(timeout))?;- stream.set_write_timeout(Some(timeout))?;- write_frame(&mut stream, &serde_json::to_vec(request)?)?;- Ok(serde_json::from_slice(&read_frame(&mut stream)?)?)+ let deadline = std::time::Instant::now() + timeout;+ let (route, body, max_body) = match op {+ ControlOp::ResizeDisk { block_id, bytes } => (+ RESIZE_PATH,+ serde_json::to_vec(&ResizeDiskRequest { block_id, bytes })?,+ MAX_BODY,+ ),+ op => (MOUNT_PATH, serde_json::to_vec(&op)?, MAX_MOUNT_BODY),+ };+ // A blocking Unix connect waits on a full listen backlog until the deadline.+ let stream = transport::connect(path, deadline)?;+ stream.set_nonblocking(true)?;+ let directory = directory.map(File::try_clone).transpose()?;+ let runtime = tokio::runtime::Builder::new_current_thread()+ .enable_io()+ .enable_time()+ .build()?;+ runtime.block_on(async {+ let stream = tokio::net::UnixStream::from_std(stream)?;+ let (stream, received) = transport::AncillaryIo::new(stream, directory);+ let reply = timeout_at(+ Instant::from_std(deadline),+ exchange_http(TokioIo::new(stream), route, body, max_body),+ )+ .await+ .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "VMM control deadline"))??;+ if received.take().is_some() {+ return Err(io::Error::new(+ io::ErrorKind::InvalidData,+ "descriptor in control reply",+ ));+ }+ Ok(reply)+ })}-#[cfg(test)]-fn read_frame(stream: &mut UnixStream) -> io::Result<Vec<u8>> {- let mut length = [0u8; 4];- stream.read_exact(&mut length)?;- let length = u32::from_le_bytes(length);- if length > MAX_FRAME {- return Err(io::Error::new(- io::ErrorKind::InvalidData,- format!("control frame of {length} bytes exceeds {MAX_FRAME}"),- ));- }- let mut frame = vec![0u8; length as usize];- stream.read_exact(&mut frame)?;- Ok(frame)-}+/// Request an absolute disk capacity through the native shim's host-only channel.+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]+pub(crate) async fn grow_disk(+ path: &Path,+ block_id: &str,+ bytes: u64,+) -> boxlite_shared::BoxliteResult<()> {+ use boxlite_shared::BoxliteError;-#[cfg(test)]-fn write_frame(stream: &mut UnixStream, frame: &[u8]) -> io::Result<()> {- let length = u32::try_from(frame.len())- .ok()- .filter(|length| *length <= MAX_FRAME)- .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "control frame too large"))?;- stream.write_all(&length.to_le_bytes())?;- stream.write_all(frame)+ // The worker waits up to ten seconds; allow the bounded exchange to outlast it.+ let response = timeout(CLIENT_TIMEOUT, request(path, block_id, bytes))+ .await+ .map_err(|_| {+ BoxliteError::Engine(+ "disk resize completion is unknown: reply timed out; retry the target".into(),+ )+ })?+ .map_err(|error| match error.kind() {+ io::ErrorKind::NotFound | io::ErrorKind::ConnectionRefused => {+ BoxliteError::Unsupported(+ "shim has no disk control channel; restart with the current runtime".into(),+ )+ }+ _ => BoxliteError::Engine(format!(+ "disk resize completion is unknown: {error}; retry the target. \+ If the shim is older than the runtime, restart the box with matching versions."+ )),+ })?;+ match response {+ Ok(ControlReply::DiskSize(actual)) if actual == bytes => Ok(()),+ Ok(ControlReply::DiskSize(actual)) => Err(BoxliteError::Engine(format!(+ "disk resize completion is unknown: shim reported {actual} disk bytes, requested {bytes}; retry the target"+ ))),+ Err(ControlError::Unsupported(message)) => Err(BoxliteError::Unsupported(message)),+ Err(ControlError::InvalidInput(message)) => Err(BoxliteError::InvalidArgument(message)),+ Err(ControlError::Failed(message)) => Err(BoxliteError::Engine(format!(+ "disk resize completion is unknown: {message}; query allocation or retry the target"+ ))),+ #[cfg(feature = "native")]+ _ => Err(BoxliteError::Engine(+ "disk resize completion is unknown: unexpected shim reply; retry the target".into(),+ )),+ }}/// `fchmodat`, which the shim's seccomp profile allows, rather than `chmod`.+#[cfg(any(test, feature = "native"))]fn restrict_to_owner(path: &Path) -> io::Result<()> {use std::os::unix::ffi::OsStrExt;let path = std::ffi::CString::new(path.as_os_str().as_bytes())?;diff --git a/src/boxlite/src/vmm/vmm_socket/transport.rs b/src/boxlite/src/vmm/vmm_socket/transport.rsindex 6a30653d7..dfcbc12c4 100644--- a/src/boxlite/src/vmm/vmm_socket/transport.rs+++ b/src/boxlite/src/vmm/vmm_socket/transport.rs@@ -1,4 +1,3 @@-use super::MAX_FRAME;use std::fs::File;use std::io;use std::mem::{size_of, zeroed};@@ -6,8 +5,13 @@ use std::os::fd::{AsRawFd, FromRawFd, RawFd};use std::os::unix::ffi::OsStrExt;use std::os::unix::net::UnixStream;use std::path::Path;+use std::pin::Pin;+use std::sync::{Arc, Mutex};+use std::task::{Context, Poll, ready};use std::time::{Duration, Instant};+use tokio::io::{AsyncRead, AsyncWrite, Interest, ReadBuf};+fn remaining(end: Instant) -> io::Result<Duration> {end.checked_duration_since(Instant::now()).filter(|d| !d.is_zero())@@ -63,182 +67,230 @@ struct Ancillary {bytes: [u8; 64],}-pub(super) fn send_frame(- stream: &UnixStream,- payload: &[u8],- fd: Option<RawFd>,- end: Instant,-) -> io::Result<()> {- if payload.len() > MAX_FRAME as usize {- return Err(io::Error::from_raw_os_error(libc::EMSGSIZE));+/// A connection can deliver one descriptor with its HTTP request.+#[derive(Clone, Default)]+pub(super) struct ReceivedFile(Arc<Mutex<Option<File>>>);++impl ReceivedFile {+ pub(super) fn take(&self) -> Option<File> {+ self.0.lock().expect("received file lock poisoned").take()+ }++ fn store(&self, file: File) {+ *self.0.lock().expect("received file lock poisoned") = Some(file);}- send_parts(- stream,- &(payload.len() as u32).to_le_bytes(),- payload,- fd,- end,- )}-pub(super) fn send_parts(- stream: &UnixStream,- head: &[u8],- body: &[u8],- mut fd: Option<RawFd>,- end: Instant,-) -> io::Result<()> {- let mut offset = 0;- while offset < head.len() + body.len() {- stream.set_write_timeout(Some(remaining(end)?))?;- let mut control = Ancillary {- alignment: [],- bytes: [0; 64],- };- let (first, second) = if offset < head.len() {- (&head[offset..], body)- } else {- (&body[offset - head.len()..], &[][..])- };- let mut iov = [- libc::iovec {- iov_base: first.as_ptr().cast_mut().cast(),- iov_len: first.len(),- },- libc::iovec {- iov_base: second.as_ptr().cast_mut().cast(),- iov_len: second.len(),+/// Preserves Unix ancillary data while Hyper reads and writes HTTP bytes.+pub(super) struct AncillaryIo {+ stream: tokio::net::UnixStream,+ outgoing: Option<File>,+ received: ReceivedFile,+ first_read: bool,+}++impl AncillaryIo {+ pub(super) fn new(+ stream: tokio::net::UnixStream,+ outgoing: Option<File>,+ ) -> (Self, ReceivedFile) {+ let received = ReceivedFile::default();+ (+ Self {+ stream,+ outgoing,+ received: received.clone(),+ first_read: true,},- ];- // SAFETY: a zeroed msghdr has no optional address or ancillary pointers.- let mut msg: libc::msghdr = unsafe { zeroed() };- msg.msg_iov = iov.as_mut_ptr();- msg.msg_iovlen = if second.is_empty() { 1 } else { 2 };- if let Some(fd) = fd {- msg.msg_control = control.bytes.as_mut_ptr().cast();- msg.msg_controllen = unsafe { libc::CMSG_SPACE(size_of::<RawFd>() as _) } as _;- unsafe {- let header = libc::CMSG_FIRSTHDR(&msg);- (*header).cmsg_level = libc::SOL_SOCKET;- (*header).cmsg_type = libc::SCM_RIGHTS;- (*header).cmsg_len = libc::CMSG_LEN(size_of::<RawFd>() as _) as _;- std::ptr::write_unaligned(libc::CMSG_DATA(header).cast::<RawFd>(), fd);- }+ received,+ )+ }+}++impl AsyncRead for AncillaryIo {+ fn poll_read(+ self: Pin<&mut Self>,+ cx: &mut Context<'_>,+ buffer: &mut ReadBuf<'_>,+ ) -> Poll<io::Result<()>> {+ let this = self.get_mut();+ if buffer.remaining() == 0 {+ return Poll::Ready(Ok(()));}- let sent = unsafe { libc::sendmsg(stream.as_raw_fd(), &msg, libc::MSG_NOSIGNAL) };- if sent < 0 {- let error = io::Error::last_os_error();- if error.kind() == io::ErrorKind::Interrupted {- continue;+ // recvmsg can return preceding bytes together with a later descriptor.+ // Isolating the first byte binds the descriptor to this HTTP exchange.+ let limit = if this.first_read {+ 1+ } else {+ buffer.remaining()+ };+ loop {+ ready!(this.stream.poll_read_ready(cx))?;+ let result = this.stream.try_io(Interest::READABLE, || {+ receive_with_file(+ this.stream.as_raw_fd(),+ buffer.initialize_unfilled_to(limit),+ )+ });+ match result {+ Ok((count, file)) => {+ if let Some(file) = file {+ if !this.first_read {+ return Poll::Ready(Err(invalid_ancillary()));+ }+ this.received.store(file);+ }+ this.first_read = false;+ buffer.advance(count);+ return Poll::Ready(Ok(()));+ }+ Err(error) if retry_io(&error) => continue,+ Err(error) => return Poll::Ready(Err(error)),}- return Err(timed_out(error));- }- if sent == 0 {- return Err(io::Error::new(io::ErrorKind::WriteZero, "VMM control send"));}- offset += sent as usize;- // A positive send transferred ancillary ownership even on a short write.- fd = None;}- Ok(())}-pub(super) fn receive_exact(- stream: &UnixStream,- bytes: &mut [u8],- file: &mut Option<File>,- end: Instant,-) -> io::Result<()> {- let mut offset = 0;- while offset < bytes.len() {- stream.set_read_timeout(Some(remaining(end)?))?;- let mut control = Ancillary {- alignment: [],- bytes: [0; 64],+impl AsyncWrite for AncillaryIo {+ fn poll_write(+ self: Pin<&mut Self>,+ cx: &mut Context<'_>,+ bytes: &[u8],+ ) -> Poll<io::Result<usize>> {+ let this = self.get_mut();+ let Some(file) = &this.outgoing else {+ return Pin::new(&mut this.stream).poll_write(cx, bytes);};- let mut iov = libc::iovec {- iov_base: bytes[offset..].as_mut_ptr().cast(),- iov_len: bytes.len() - offset,- };- let mut msg: libc::msghdr = unsafe { zeroed() };- msg.msg_iov = &mut iov;- msg.msg_iovlen = 1;- msg.msg_control = control.bytes.as_mut_ptr().cast();- msg.msg_controllen = control.bytes.len() as _;- let received =- unsafe { libc::recvmsg(stream.as_raw_fd(), &mut msg, libc::MSG_CMSG_CLOEXEC) };- if received < 0 {- let error = io::Error::last_os_error();- if error.kind() == io::ErrorKind::Interrupted {- continue;- }- return Err(timed_out(error));+ if bytes.is_empty() {+ return Poll::Ready(Ok(0));}- let mut invalid = false;- // SAFETY: recvmsg populated msg and its aligned control buffer.- let (mut header, base) = unsafe { (libc::CMSG_FIRSTHDR(&msg), libc::CMSG_LEN(0) as usize) };- while !header.is_null() {- // SAFETY: this header was returned by the walk over the live buffer.- let cmsg = unsafe { &*header };- let length = cmsg.cmsg_len;- #[cfg(target_env = "musl")]- let length = length as usize;- if length < base {- invalid = true;- break;- }- if cmsg.cmsg_level == libc::SOL_SOCKET && cmsg.cmsg_type == libc::SCM_RIGHTS {- let count = (length - base) / size_of::<RawFd>();- // SAFETY: the kernel initialized this header and its payload.- let data = unsafe { libc::CMSG_DATA(header) }.cast::<RawFd>();- for index in 0..count {- // SAFETY: each full FD fits in the payload. recvmsg transferred- // ownership, including descriptors from a rejected frame.- let received = unsafe { File::from_raw_fd(data.add(index).read_unaligned()) };- if file.is_some() {- invalid = true;- } else {- *file = Some(received);- }+ loop {+ ready!(this.stream.poll_write_ready(cx))?;+ let result = this.stream.try_io(Interest::WRITABLE, || {+ send_with_file(this.stream.as_raw_fd(), bytes, file.as_raw_fd())+ });+ match result {+ Ok(0) => return Poll::Ready(Err(io::ErrorKind::WriteZero.into())),+ Ok(count) => {+ // The kernel transfers the descriptor on the first positive write.+ this.outgoing = None;+ return Poll::Ready(Ok(count));}- invalid |= !(length - base).is_multiple_of(size_of::<RawFd>());- } else {- invalid = true;+ Err(error) if retry_io(&error) => continue,+ Err(error) => return Poll::Ready(Err(error)),}- // SAFETY: header belongs to msg's live, kernel-populated buffer.- header = unsafe { libc::CMSG_NXTHDR(&msg, header) };- }- if invalid || msg.msg_flags & (libc::MSG_CTRUNC | libc::MSG_TRUNC) != 0 {- return Err(io::Error::new(- io::ErrorKind::InvalidData,- "VMM control ancillary data",- ));- }- if received == 0 {- return Err(io::Error::new(- io::ErrorKind::UnexpectedEof,- "VMM control frame",- ));}- offset += received as usize;}- Ok(())++ fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {+ Pin::new(&mut self.get_mut().stream).poll_flush(cx)+ }++ fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {+ Pin::new(&mut self.get_mut().stream).poll_shutdown(cx)+ }+}++fn retry_io(error: &io::Error) -> bool {+ matches!(+ error.kind(),+ io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted+ )+}++pub(super) fn send_with_file(socket: RawFd, bytes: &[u8], file: RawFd) -> io::Result<usize> {+ let mut control = Ancillary {+ alignment: [],+ bytes: [0; 64],+ };+ let mut iov = libc::iovec {+ iov_base: bytes.as_ptr().cast_mut().cast(),+ iov_len: bytes.len(),+ };+ // SAFETY: a zeroed msghdr has no optional address pointers.+ let mut msg: libc::msghdr = unsafe { zeroed() };+ msg.msg_iov = &mut iov;+ msg.msg_iovlen = 1;+ msg.msg_control = control.bytes.as_mut_ptr().cast();+ // SAFETY: the aligned control buffer fits a header and a single descriptor.+ let sent = unsafe {+ msg.msg_controllen = libc::CMSG_SPACE(size_of::<RawFd>() as _) as _;+ let header = libc::CMSG_FIRSTHDR(&msg);+ (*header).cmsg_level = libc::SOL_SOCKET;+ (*header).cmsg_type = libc::SCM_RIGHTS;+ (*header).cmsg_len = libc::CMSG_LEN(size_of::<RawFd>() as _) as _;+ std::ptr::write_unaligned(libc::CMSG_DATA(header).cast::<RawFd>(), file);+ libc::sendmsg(socket, &msg, libc::MSG_NOSIGNAL)+ };+ if sent < 0 {+ return Err(io::Error::last_os_error());+ }+ Ok(sent as usize)}-pub(super) fn receive_frame(- stream: &UnixStream,- end: Instant,-) -> io::Result<(Vec<u8>, Option<File>)> {+fn receive_with_file(socket: RawFd, bytes: &mut [u8]) -> io::Result<(usize, Option<File>)> {+ let mut control = Ancillary {+ alignment: [],+ bytes: [0; 64],+ };+ let mut iov = libc::iovec {+ iov_base: bytes.as_mut_ptr().cast(),+ iov_len: bytes.len(),+ };+ // SAFETY: a zeroed msghdr has no optional address pointers.+ let mut msg: libc::msghdr = unsafe { zeroed() };+ msg.msg_iov = &mut iov;+ msg.msg_iovlen = 1;+ msg.msg_control = control.bytes.as_mut_ptr().cast();+ msg.msg_controllen = control.bytes.len() as _;+ // SAFETY: the iovec and control buffer are live and writable for their declared lengths.+ let received = unsafe { libc::recvmsg(socket, &mut msg, libc::MSG_CMSG_CLOEXEC) };+ if received < 0 {+ return Err(io::Error::last_os_error());+ }let mut file = None;- let mut header = [0; 4];- receive_exact(stream, &mut header, &mut file, end)?;- let length = u32::from_le_bytes(header);- if length > MAX_FRAME {- return Err(io::Error::from_raw_os_error(libc::EMSGSIZE));+ let mut invalid = msg.msg_flags & (libc::MSG_CTRUNC | libc::MSG_TRUNC) != 0;+ // SAFETY: recvmsg populated msg and its aligned control buffer.+ let (mut header, base) = unsafe { (libc::CMSG_FIRSTHDR(&msg), libc::CMSG_LEN(0) as usize) };+ while !header.is_null() {+ // SAFETY: this header was returned by the walk over the live buffer.+ let cmsg = unsafe { &*header };+ let length = cmsg.cmsg_len;+ #[cfg(target_env = "musl")]+ let length = length as usize;+ if length < base {+ invalid = true;+ break;+ }+ if cmsg.cmsg_level == libc::SOL_SOCKET && cmsg.cmsg_type == libc::SCM_RIGHTS {+ let count = (length - base) / size_of::<RawFd>();+ // SAFETY: the kernel initialized this header and its payload.+ let data = unsafe { libc::CMSG_DATA(header) }.cast::<RawFd>();+ for index in 0..count {+ // SAFETY: each full FD fits in the payload. Take ownership so+ // even descriptors from invalid messages are closed.+ let descriptor = unsafe { File::from_raw_fd(data.add(index).read_unaligned()) };+ if file.is_some() {+ invalid = true;+ } else {+ file = Some(descriptor);+ }+ }+ invalid |= !(length - base).is_multiple_of(size_of::<RawFd>());+ } else {+ invalid = true;+ }+ // SAFETY: header belongs to msg's live, kernel-populated buffer.+ header = unsafe { libc::CMSG_NXTHDR(&msg, header) };}- let mut payload = vec![0; length as usize];- receive_exact(stream, &mut payload, &mut file, end)?;- Ok((payload, file))+ if invalid {+ return Err(invalid_ancillary());+ }+ Ok((received as usize, file))+}++fn invalid_ancillary() -> io::Error {+ io::Error::new(io::ErrorKind::InvalidData, "VMM control ancillary data")}/// Whether the peer connected as `owner`, the uid this shim serves.diff --git a/src/boxlite/tests/native_vmm.rs b/src/boxlite/tests/native_vmm.rsindex 7ee85eec4..b4e99e9d5 100644--- a/src/boxlite/tests/native_vmm.rs+++ b/src/boxlite/tests/native_vmm.rs@@ -3,11 +3,18 @@mod common;-use boxlite::BoxliteRuntime;+use anyhow::{Context, ensure};use boxlite::experimental::custom_kernel::{self, KernelFormat, KernelOptions};use boxlite::experimental::{ExperimentalFeature, RuntimeBuilder, native_vmm};+use boxlite::runtime::layout::{BoxFilesystemLayout, FilesystemLayout};use boxlite::runtime::options::BoxliteOptions;+use boxlite::{BoxliteError, BoxliteRuntime, LiteBox, ResizeOptions};use boxlite_test_utils::home::PerTestBoxHome;+use futures::StreamExt;+use std::path::Path;+use std::time::Duration;+use tokio::io::{AsyncReadExt, AsyncWriteExt};+use tokio::net::{UnixListener, UnixStream};/// Console lines the boot must reach, in order.const PROGRESS: &[&str] = &[@@ -96,6 +103,10 @@ async fn first_box_runs_boxlite_guest_as_pid_1_on_the_ext4_root() {assert!(console.contains("server bound (vsock:2695)"));assert!(!console.contains("Failed to connect to notify vsock"));assert!(!console.contains("Kernel panic"), "console:\n{console}");+ assert!(+ !console.contains("Resizing ext4 filesystem on"),+ "default disk sizing must not resize the mounted root filesystem"+ );bx.stop().await.expect("stop the native box");runtime@@ -103,3 +114,641 @@ async fn first_box_runs_boxlite_guest_as_pid_1_on_the_ext4_root() {.await.expect("remove the native box");}++async fn shell_output(bx: &LiteBox, script: &str) -> String {+ let mut execution = bx+ .exec(boxlite::BoxCommand::new("sh").args(["-c", script]))+ .await+ .unwrap();+ let mut output = String::new();+ if let Some(mut stdout) = execution.stdout() {+ while let Some(chunk) = stdout.next().await {+ output.push_str(&chunk);+ }+ }+ assert_eq!(+ execution.wait().await.unwrap().exit_code,+ 0,+ "script: {script}"+ );+ output+}++async fn root_capacity_kib(bx: &LiteBox) -> u64 {+ shell_output(bx, "df -Pk / | awk 'NR==2 {print $2}'")+ .await+ .trim()+ .parse()+ .unwrap()+}++fn open_box_db(home: &PerTestBoxHome, flags: rusqlite::OpenFlags) -> rusqlite::Connection {+ let layout = FilesystemLayout::new(home.path.clone(), Default::default());+ rusqlite::Connection::open_with_flags(layout.db_dir().join("boxlite.db"), flags).unwrap()+}++fn configured_disk_size_gb(+ db: &rusqlite::Connection,+ bx: &LiteBox,+) -> rusqlite::Result<Option<i64>> {+ db.query_row(+ "SELECT json_extract(json, '$.options.disk_size_gb') FROM box_config WHERE id = ?1",+ [bx.id().as_str()],+ |row| row.get(0),+ )+}++fn completed_disk_size_gb(+ db: &rusqlite::Connection,+ bx: &LiteBox,+) -> rusqlite::Result<Option<i64>> {+ db.query_row(+ "SELECT json_extract(json, '$.disk_size_gb') FROM box_state WHERE id = ?1",+ [bx.id().as_str()],+ |row| row.get(0),+ )+}++async fn resize_with_lost_shim_reply(+ bx: &LiteBox,+ target: ResizeOptions,+ socket_path: &Path,+ db: &rusqlite::Connection,+) -> anyhow::Result<()> {+ let target_gib = target.disk_size_gb.context("expected an explicit target")?;+ let previous_target = completed_disk_size_gb(db, bx)?;+ let shim_path = socket_path.with_file_name("resize-shim.sock");+ std::fs::rename(socket_path, &shim_path).context("move the live shim socket")?;++ let exchange = async {+ let listener = UnixListener::bind(socket_path)?;+ let proxy = async {+ let (mut client, _) = listener.accept().await?;+ // Sample the database before the shim can receive the request.+ let target_at_dispatch = completed_disk_size_gb(db, bx);+ let mut shim = UnixStream::connect(&shim_path).await?;+ let (mut shim_read, mut shim_write) = shim.split();+ let mut reply = String::new();+ // The shim closes after its HTTP response. Dropping the client here+ // leaves the response unread by the runtime.+ tokio::select! {+ result = shim_read.read_to_string(&mut reply) => { result?; }+ result = tokio::io::copy(&mut client, &mut shim_write) => {+ result?;+ anyhow::bail!("resize client closed before the shim replied");+ }+ }+ Ok::<_, anyhow::Error>((target_at_dispatch?, reply))+ };+ let (resize, intercepted) = tokio::join!(bx.resize(target), proxy);+ Ok::<_, anyhow::Error>((resize, intercepted?))+ };+ let exchange = tokio::time::timeout(Duration::from_secs(20), exchange).await;+ std::fs::rename(&shim_path, socket_path).context("restore the live shim socket")?;+ let (resize, (target_at_dispatch, reply)) =+ exchange.context("intercept the resize reply")??;++ let (headers, body) = reply+ .split_once("\r\n\r\n")+ .context("read the shim response")?;+ ensure!(+ headers.starts_with("HTTP/1.1 200 "),+ "shim response: {reply}"+ );+ let body: serde_json::Value = serde_json::from_str(body)?;+ ensure!(+ body == serde_json::json!({"Ok":{"disk_size":target_gib << 30}}),+ "shim resize result: {body}"+ );+ ensure!(+ matches!(&resize, Err(BoxliteError::Engine(message))+ if message.contains("completion is unknown") && message.contains("retry the target")),+ "unexpected resize result after dropping the successful shim reply: {resize:?}"+ );+ ensure!(+ target_at_dispatch == previous_target,+ "dispatch changed the completed disk target from {previous_target:?} to {target_at_dispatch:?}"+ );+ ensure!(+ completed_disk_size_gb(db, bx)? == previous_target,+ "a lost reply changed the completed disk target"+ );+ Ok(())+}++#[tokio::test]+#[ignore = "requires Linux x86_64 with /dev/kvm, VMM_KERNEL and a native runtime"]+async fn online_resize_allows_other_execs_to_exit() {+ const ORIGINAL_TOOL: &str = "BOXLITE_TEST_ORIGINAL_RESIZE2FS";+ let Some(original) = std::env::var_os(ORIGINAL_TOOL) else {+ // GuestArtifacts caches its resolution per process. Override only this VM's tool.+ let tool = boxlite::util::find_binary("guest-resize2fs").unwrap();+ let shim = boxlite::util::find_binary("boxlite-shim").unwrap();+ let probe = std::env::var_os("VMM_GUEST_PROBE").expect("set VMM_GUEST_PROBE");+ let fixture = tempfile::tempdir().unwrap();+ std::os::unix::fs::symlink(probe, fixture.path().join("guest-resize2fs")).unwrap();+ let paths = std::env::var_os("BOXLITE_RUNTIME_DIR")+ .map(|value| std::env::split_paths(&value).collect())+ .unwrap_or_else(|| vec![shim.parent().unwrap().to_owned()]);+ let runtime_dirs =+ std::env::join_paths(std::iter::once(fixture.path().to_owned()).chain(paths)).unwrap();+ let status = std::process::Command::new(std::env::current_exe().unwrap())+ .args([+ "--ignored",+ "--exact",+ "online_resize_allows_other_execs_to_exit",+ ])+ .env(ORIGINAL_TOOL, tool)+ .env("BOXLITE_RUNTIME_DIR", runtime_dirs)+ .status()+ .unwrap();+ assert!(status.success(), "isolated resize regression: {status}");+ return;+ };++ let kernel = std::env::var_os("VMM_KERNEL").expect("set VMM_KERNEL");+ let home = PerTestBoxHome::new();+ let runtime = native_runtime(&home);+ let mut options = common::alpine_opts();+ options.cpus = Some(1.0);+ options.disk_size_gb = Some(10);+ custom_kernel::configure(+ &mut options,+ KernelOptions::new(kernel).with_format(KernelFormat::Elf),+ );+ native_vmm::configure(&mut options);+ let bx = runtime.create(options, None).await.unwrap();+ let layout = BoxFilesystemLayout::new(+ home.path.join("boxes").join(bx.id().as_str()),+ Default::default(),+ false,+ );+ let gate = layout.shared_dir().join("resize-reaper-probe");+ std::fs::create_dir_all(&gate).unwrap();+ std::fs::copy(original, gate.join("resize2fs")).unwrap();+ bx.start().await.unwrap();++ let mut exec = bx+ .exec(boxlite::BoxCommand::new("sh").args(["-c", "read -r input; exit 23"]))+ .await+ .unwrap();+ let mut stdin = exec.stdin().unwrap();+ std::fs::write(gate.join("armed"), b"").unwrap();+ let resize = bx.resize(ResizeOptions {+ disk_size_gb: Some(20),+ });+ tokio::pin!(resize);+ let (exec_wait, ssh_disable) = tokio::select! {+ result = &mut resize => panic!("resize returned before reaching the gate: {result:?}"),+ concurrent = async {+ tokio::time::timeout(Duration::from_secs(10), async {+ while !gate.join("started").exists() {+ tokio::time::sleep(Duration::from_millis(20)).await;+ }+ })+ .await+ .expect("resize2fs never reached the gate");+ stdin.write_all(b"exit\n").await.unwrap();+ let ssh = bx.ssh();+ let deadline = Duration::from_secs(3);+ tokio::join!(+ tokio::time::timeout(deadline, exec.wait()),+ tokio::time::timeout(deadline, ssh.disable()),+ )+ } => concurrent,+ };+ // Release the fixture, finish the real ext4 resize, and stop even on regression.+ std::fs::write(gate.join("release"), b"").unwrap();+ let grown = resize.await;+ let stopped = bx.stop().await;+ let removed = runtime.remove(bx.id().as_str(), true).await;+ assert_eq!(grown.unwrap().disk_size_gb, 20);+ stopped.unwrap();+ removed.unwrap();+ assert_eq!(+ exec_wait+ .expect("exec exit was blocked while resize2fs was running")+ .unwrap()+ .exit_code,+ 23+ );+ let status = ssh_disable+ .expect("SSH disable was blocked while resize2fs was running")+ .expect("disable SSH while resize2fs is running");+ assert!(!status.enabled);+}++#[tokio::test]+#[ignore = "requires Linux x86_64 with /dev/kvm, VMM_KERNEL and a native runtime"]+async fn resize_after_snapshot_restore_uses_the_restored_disk_size() {+ let kernel = std::env::var_os("VMM_KERNEL").expect("set VMM_KERNEL");+ let home = PerTestBoxHome::new();+ let runtime = native_runtime(&home);+ let mut options = common::alpine_opts();+ options.disk_size_gb = Some(10);+ custom_kernel::configure(+ &mut options,+ KernelOptions::new(kernel).with_format(KernelFormat::Elf),+ );+ native_vmm::configure(&mut options);+ let bx = runtime.create(options, None).await.unwrap();+ let id = bx.id().to_string();+ bx.start().await.unwrap();+ bx.stop().await.unwrap();+ drop(bx);++ let bx = runtime.get(&id).await.unwrap().unwrap();+ let snapshot = bx+ .snapshots()+ .create(Default::default(), "before-growth")+ .await+ .unwrap();+ assert_eq!(snapshot.disk_info.container_disk_bytes, 10_u64 << 30);+ bx.start().await.unwrap();+ let grown = bx+ .resize(ResizeOptions {+ disk_size_gb: Some(20),+ })+ .await+ .unwrap();+ assert_eq!(grown.disk_size_gb, 20);+ let db = open_box_db(&home, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY);+ assert_eq!(completed_disk_size_gb(&db, &bx).unwrap(), Some(20));+ assert_eq!(configured_disk_size_gb(&db, &bx).unwrap(), Some(10));+ bx.stop().await.unwrap();+ drop(bx);++ let bx = runtime.get(&id).await.unwrap().unwrap();+ bx.snapshots().restore(&snapshot.name).await.unwrap();+ assert_eq!(completed_disk_size_gb(&db, &bx).unwrap(), Some(20));++ let archive = bx+ .export(Default::default(), &home.path.join("restored.boxlite"))+ .await+ .unwrap();+ let imported = runtime.import_box(archive, None).await.unwrap();+ let imported_configured_gib = configured_disk_size_gb(&db, &imported).unwrap();+ let imported_completed_gib = completed_disk_size_gb(&db, &imported).unwrap();+ imported.start().await.unwrap();+ let imported_disk = imported.resize(ResizeOptions::default()).await.unwrap();+ let imported_filesystem_kib = root_capacity_kib(&imported).await;+ imported.stop().await.unwrap();+ runtime.remove(imported.id().as_str(), true).await.unwrap();++ bx.start().await.unwrap();+ let restored = bx.resize(ResizeOptions::default()).await.unwrap();+ assert_eq!(restored.disk_size_gb, 10);+ assert_eq!(completed_disk_size_gb(&db, &bx).unwrap(), Some(20));++ let grown = bx+ .resize(ResizeOptions {+ disk_size_gb: Some(15),+ })+ .await+ .unwrap();+ assert_eq!(grown.disk_size_gb, 15);+ assert_eq!(completed_disk_size_gb(&db, &bx).unwrap(), Some(15));+ assert_eq!(configured_disk_size_gb(&db, &bx).unwrap(), Some(10));+ bx.stop().await.unwrap();+ runtime.remove(&id, true).await.unwrap();++ assert_eq!(imported_disk.disk_size_gb, 10);+ assert!(+ (9 * 1024 * 1024..=10 * 1024 * 1024).contains(&imported_filesystem_kib),+ "the imported root filesystem must use the restored 10 GiB disk: {imported_filesystem_kib} KiB"+ );+ assert_eq!(imported_configured_gib, Some(20));+ assert_eq!(imported_completed_gib, None);+}++#[tokio::test]+#[ignore = "requires Linux x86_64 with /dev/kvm, VMM_KERNEL and a native runtime"]+async fn online_disk_growth_keeps_workloads_and_recovers_an_interrupted_filesystem_step() {+ let kernel = std::env::var_os("VMM_KERNEL").expect("set VMM_KERNEL");+ let temp_dir = std::env::temp_dir();+ let home = PerTestBoxHome::new_in(+ temp_dir+ .to_str()+ .expect("test temp directory must be UTF-8"),+ );+ let runtime = native_runtime(&home);+ let mut options = common::alpine_opts();+ options.disk_size_gb = Some(10);+ options.detach = true;+ custom_kernel::configure(+ &mut options,+ KernelOptions::new(kernel).with_format(KernelFormat::Elf),+ );+ native_vmm::configure(&mut options);+ let bx = runtime.create(options, None).await.unwrap();+ bx.start().await.unwrap();+ assert_eq!(+ bx.resize(ResizeOptions::default())+ .await+ .unwrap()+ .disk_size_gb,+ 10+ );+ assert!(matches!(+ bx.resize(ResizeOptions {+ disk_size_gb: Some(9)+ })+ .await,+ Err(BoxliteError::InvalidArgument(_))+ ));+ let workload = bx.exec(boxlite::BoxCommand::new("sh").args([+ "-c", "touch /tmp/resize-running; while [ ! -e /tmp/resize-finished ]; do sleep 0.01; done; exit 23",+ ])).await.unwrap();+ shell_output(+ &bx,+ "while [ ! -e /tmp/resize-running ]; do sleep 0.01; done",+ )+ .await;+ let layout = BoxFilesystemLayout::new(+ home.path.join("boxes").join(bx.id().as_str()),+ Default::default(),+ false,+ );+ let vmm_socket = layout.sockets().vmm_sock();+ let db = open_box_db(&home, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY);+ assert_eq!(completed_disk_size_gb(&db, &bx).unwrap(), None);+ let target = ResizeOptions {+ disk_size_gb: Some(20),+ };+ let initial_capacity = root_capacity_kib(&bx).await;+ if let Err(error) = resize_with_lost_shim_reply(&bx, target, &vmm_socket, &db).await {+ let stop = bx.stop().await;+ let remove = runtime.remove(bx.id().as_str(), true).await;+ panic!("resize with lost shim reply: {error:#}\nstop: {stop:?}\nremove: {remove:?}");+ }+ assert_eq!(+ root_capacity_kib(&bx).await,+ initial_capacity,+ "the filesystem step remains pending after losing the shim reply"+ );+ assert_eq!(+ bx.resize(ResizeOptions::default())+ .await+ .unwrap()+ .disk_size_gb,+ 20+ );+ assert_eq!(completed_disk_size_gb(&db, &bx).unwrap(), None);+ assert_eq!(bx.resize(target).await.unwrap().disk_size_gb, 20);+ let capacity = root_capacity_kib(&bx).await;+ assert!(+ capacity > 19 * 1024 * 1024,+ "filesystem capacity: {capacity} KiB"+ );+ let completed_gib = completed_disk_size_gb(&db, &bx).unwrap();+ let configured_gib = configured_disk_size_gb(&db, &bx).unwrap();+ shell_output(&bx, "touch /tmp/resize-finished; dd if=/dev/zero of=/past-old-end bs=1M seek=11264 count=1 2>/dev/null; sync").await;+ assert_eq!(+ workload.wait().await.unwrap().exit_code,+ 23,+ "the in-flight workload survived growth"+ );+ drop(workload);+ if completed_gib != Some(20) || configured_gib != Some(10) {+ bx.stop().await.unwrap();+ runtime.remove(bx.id().as_str(), true).await.unwrap();+ }+ assert_eq!(completed_gib, Some(20));+ assert_eq!(configured_gib, Some(10));+ bx.resize(target).await.unwrap();++ // Lose the host after sending device growth: no reply is read, no guest RPC runs.+ let mut control = UnixStream::connect(&vmm_socket).await.unwrap();+ let body = serde_json::json!({"block_id":"vda","bytes":24_u64 << 30}).to_string();+ let request = format!(+ "POST /v1/resize-disk HTTP/1.1\r\n\+ Host: vmm\r\n\+ Content-Type: application/json\r\n\+ Content-Length: {}\r\n\+ Connection: close\r\n\r\n{body}",+ body.len()+ );+ control.write_all(request.as_bytes()).await.unwrap();+ drop(control);+ tokio::time::timeout(Duration::from_secs(15), async {+ while bx+ .resize(ResizeOptions::default())+ .await+ .unwrap()+ .disk_size_gb+ != 24+ {+ tokio::time::sleep(Duration::from_millis(10)).await;+ }+ })+ .await+ .expect("query recovers the device growth without its reply");+ assert_eq!(+ root_capacity_kib(&bx).await,+ capacity,+ "query must leave the filesystem step pending"+ );+ assert_eq!(completed_disk_size_gb(&db, &bx).unwrap(), Some(20));++ // An unavailable shim leaves the completed disk target intact.+ let hidden_socket = vmm_socket.with_file_name("resize-shim.sock");+ std::fs::rename(&vmm_socket, &hidden_socket).unwrap();+ let undispatched = bx+ .resize(ResizeOptions {+ disk_size_gb: Some(30),+ })+ .await;+ std::fs::rename(&hidden_socket, &vmm_socket).unwrap();+ assert!(matches!(undispatched, Err(BoxliteError::Unsupported(_))));+ assert_eq!(completed_disk_size_gb(&db, &bx).unwrap(), Some(20));++ let id = bx.id().to_string();+ drop(bx);+ drop(runtime);+ let runtime = native_runtime(&home);+ let adopted = runtime.get(&id).await.unwrap().unwrap();+ assert_eq!(+ adopted+ .resize(ResizeOptions::default())+ .await+ .unwrap()+ .disk_size_gb,+ 24+ );+ assert_eq!(completed_disk_size_gb(&db, &adopted).unwrap(), Some(20));++ adopted.stop().await.unwrap();+ let restarted = runtime.get(&id).await.unwrap().unwrap();+ restarted.start().await.unwrap();+ assert_eq!(+ restarted+ .resize(ResizeOptions::default())+ .await+ .unwrap()+ .disk_size_gb,+ 24+ );+ let restarted_capacity = root_capacity_kib(&restarted).await;+ let restarted_target = completed_disk_size_gb(&db, &restarted).unwrap();+ if restarted_capacity != capacity || restarted_target != Some(20) {+ restarted.stop().await.unwrap();+ runtime.remove(&id, true).await.unwrap();+ }+ assert_eq!(+ restarted_capacity, capacity,+ "starting with the existing disk leaves ext4 growth pending"+ );+ assert_eq!(restarted_target, Some(20));+ let grown = restarted+ .resize(ResizeOptions {+ disk_size_gb: Some(24),+ })+ .await+ .unwrap();+ assert_eq!(grown.disk_size_gb, 24);+ let capacity = root_capacity_kib(&restarted).await;+ assert!(+ capacity > 23 * 1024 * 1024,+ "retry completed ext4 growth: {capacity} KiB"+ );+ assert_eq!(completed_disk_size_gb(&db, &restarted).unwrap(), Some(24));+ // Write 21 GiB to verify the recovered filesystem can use the grown disk.+ let fill = tokio::time::timeout(Duration::from_secs(180), async {+ restarted+ .exec(boxlite::BoxCommand::new("sh").args([+ "-c",+ "dd if=/dev/zero of=/grow-fill bs=1M count=21504 2>/dev/null && sync && rm /grow-fill /past-old-end",+ ]))+ .await?+ .wait()+ .await+ })+ .await;+ restarted.stop().await.unwrap();+ runtime.remove(&id, true).await.unwrap();+ assert_eq!(+ fill.expect("write 21 GiB to the recovered filesystem")+ .unwrap()+ .exit_code,+ 0+ );+}++#[tokio::test]+#[ignore = "requires Linux x86_64 with /dev/kvm, VMM_KERNEL and a native runtime"]+async fn first_native_boot_uses_creation_size_with_legacy_state() {+ assert_native_boot_disk(BootDisk::LegacyState).await;+}++#[tokio::test]+#[ignore = "requires Linux x86_64 with /dev/kvm, VMM_KERNEL and a native runtime"]+async fn first_native_boot_uses_latest_completed_disk_target() {+ assert_native_boot_disk(BootDisk::NewWithCompletedTarget).await;+}++#[tokio::test]+#[ignore = "requires Linux x86_64 with /dev/kvm, VMM_KERNEL and a native runtime"]+async fn failed_native_boot_recreates_missing_disk_at_latest_completed_target() {+ assert_native_boot_disk(BootDisk::MissingAfterFailure).await;+}++#[tokio::test]+#[ignore = "requires Linux x86_64 with /dev/kvm, VMM_KERNEL and a native runtime"]+async fn failed_native_boot_reuses_intact_disk_and_preserves_data() {+ assert_native_boot_disk(BootDisk::RestoredAfterFailure).await;+}++enum BootDisk {+ LegacyState,+ NewWithCompletedTarget,+ MissingAfterFailure,+ RestoredAfterFailure,+}++async fn assert_native_boot_disk(scenario: BootDisk) {+ let kernel = std::env::var_os("VMM_KERNEL").expect("set VMM_KERNEL");+ let home = PerTestBoxHome::new();+ let runtime = native_runtime(&home);+ let mut options = common::alpine_opts();+ options.disk_size_gb = Some(10);+ custom_kernel::configure(+ &mut options,+ KernelOptions::new(kernel).with_format(KernelFormat::Elf),+ );+ native_vmm::configure(&mut options);+ let mut bx = runtime.create(options, None).await.unwrap();+ let db = open_box_db(&home, rusqlite::OpenFlags::SQLITE_OPEN_READ_WRITE);+ if matches!(+ scenario,+ BootDisk::MissingAfterFailure | BootDisk::RestoredAfterFailure+ ) {+ bx.start().await.unwrap();+ if matches!(scenario, BootDisk::RestoredAfterFailure) {+ shell_output(&bx, "printf preserved > /boot-retry-marker; sync").await;+ }+ bx.stop().await.unwrap();+ let id = bx.id().to_string();+ drop(bx);+ bx = runtime.get(&id).await.unwrap().unwrap();++ let layout =+ BoxFilesystemLayout::new(home.path.join("boxes").join(&id), Default::default(), false);+ let disk = layout.disk_path();+ let saved_disk = disk.with_file_name("before-failed-start.qcow2");+ std::fs::rename(&disk, &saved_disk).unwrap();+ let error = bx.start().await.unwrap_err();+ assert!(+ matches!(&error, BoxliteError::Storage(message)+ if message.contains("Cannot restart: container rootfs disk not found")),+ "{error}"+ );+ let status: String = db+ .query_row("SELECT status FROM box_state WHERE id = ?1", [&id], |row| {+ row.get(0)+ })+ .unwrap();+ assert_eq!(status, "failed");+ if matches!(scenario, BootDisk::RestoredAfterFailure) {+ std::fs::rename(saved_disk, disk).unwrap();+ }+ }+ assert_eq!(configured_disk_size_gb(&db, &bx).unwrap(), Some(10));+ assert_eq!(completed_disk_size_gb(&db, &bx).unwrap(), None);+ let update_state = match scenario {+ BootDisk::LegacyState => {+ "UPDATE box_state SET json = json_remove(json, '$.disk_size_gb') WHERE id = ?1"+ }+ _ => "UPDATE box_state SET json = json_set(json, '$.disk_size_gb', 20) WHERE id = ?1",+ };+ assert_eq!(db.execute(update_state, [bx.id().as_str()]).unwrap(), 1);++ bx.start()+ .await+ .expect("native box starts with its root disk");+ let actual_gib = bx+ .resize(ResizeOptions::default())+ .await+ .unwrap()+ .disk_size_gb;+ let capacity = root_capacity_kib(&bx).await;+ let marker = if matches!(scenario, BootDisk::RestoredAfterFailure) {+ Some(shell_output(&bx, "cat /boot-retry-marker 2>/dev/null || true").await)+ } else {+ None+ };+ bx.stop().await.unwrap();+ runtime.remove(bx.id().as_str(), true).await.unwrap();++ let expected_gib = match scenario {+ BootDisk::LegacyState | BootDisk::RestoredAfterFailure => 10,+ BootDisk::NewWithCompletedTarget | BootDisk::MissingAfterFailure => 20,+ };+ assert_eq!(actual_gib, expected_gib);+ assert!(+ (((expected_gib - 1) << 20)..=(expected_gib << 20)).contains(&capacity),+ "filesystem must use the {expected_gib} GiB disk: {capacity} KiB"+ );+ if let Some(marker) = marker {+ assert_eq!(marker, "preserved");+ }+}diff --git a/src/guest/src/service/exec/executor.rs b/src/guest/src/service/exec/executor.rsindex 351d6f0b4..21b7c4d7b 100644--- a/src/guest/src/service/exec/executor.rs+++ b/src/guest/src/service/exec/executor.rs@@ -4,10 +4,12 @@//! - GuestExecutor: runs commands directly on guestuse crate::container::{CommandRejection, Container, SpawnFailure};-use crate::service::exec::exec_handle::{ExecHandle, PtyConfig};+use crate::service::exec::exec_handle::{ExecHandle, ExitStatus, PtyConfig};use boxlite_shared::errors::{BoxliteError, BoxliteResult};use boxlite_shared::ExecRequest;+use futures::TryStreamExt as _;use std::sync::Arc;+use std::time::Instant;use tokio::sync::Mutex;/// Executes commands inside OCI container.@@ -109,6 +111,12 @@ impl ContainerExecutor {/// Executes commands directly on guest (no container).pub struct GuestExecutor;+pub(in crate::service) struct GuestCommandOutput {+ pub status: ExitStatus,+ pub stdout: Vec<u8>,+ pub stderr: Vec<u8>,+}+impl GuestExecutor {/// Spawn directly in the guest.///@@ -125,6 +133,40 @@ impl GuestExecutor {spawn_with_pipes(req)}}++ /// Run an internal tool while the guest reaper owns its exit status.+ pub(in crate::service) async fn run_command(+ &self,+ program: String,+ args: Vec<String>,+ ) -> BoxliteResult<GuestCommandOutput> {+ let reaper = crate::reaper::REAPER+ .get()+ .expect("reaper installed at startup");+ let spawned_at = Instant::now();+ let mut child = self+ .spawn_attempt(&ExecRequest {+ program,+ args,+ ..Default::default()+ })+ .await+ .map_err(SpawnFailure::into_error)?;+ let exit = reaper.register(child.pid(), spawned_at).await;+ child.close_stdin();+ let stdout = child.stdout().expect("guest tool has a stdout pipe");+ let stderr = child.stderr().expect("guest tool has a stderr pipe");++ // Join all three even on a read error so the caller keeps ownership until exit.+ let (status, stdout, stderr) =+ tokio::join!(exit.get(), stdout.try_concat(), stderr.try_concat());+ reaper.release_slot(&exit);+ Ok(GuestCommandOutput {+ status,+ stdout: stdout?,+ stderr: stderr?,+ })+ }}/// Turn `execve`'s error into a POSIX result about the program (missing: 127,@@ -193,7 +235,8 @@ fn working_directory_is_searchable(path: &str) -> bool {/// Spawn process with pipes (standard mode).fn spawn_with_pipes(req: &ExecRequest) -> Result<ExecHandle, SpawnFailure> {- use nix::unistd::Pid;+ use nix::fcntl::OFlag;+ use nix::unistd::{pipe2, Pid};use std::os::unix::io::{FromRawFd, IntoRawFd};use std::process::Command;@@ -209,11 +252,11 @@ fn spawn_with_pipes(req: &ExecRequest) -> Result<ExecHandle, SpawnFailure> {}// Create pipes for stdin/stdout/stderr- let (stdin_read, stdin_write) = nix::unistd::pipe()+ let (stdin_read, stdin_write) = pipe2(OFlag::O_CLOEXEC).map_err(|e| BoxliteError::Internal(format!("Failed to create stdin pipe: {}", e)))?;- let (stdout_read, stdout_write) = nix::unistd::pipe()+ let (stdout_read, stdout_write) = pipe2(OFlag::O_CLOEXEC).map_err(|e| BoxliteError::Internal(format!("Failed to create stdout pipe: {}", e)))?;- let (stderr_read, stderr_write) = nix::unistd::pipe()+ let (stderr_read, stderr_write) = pipe2(OFlag::O_CLOEXEC).map_err(|e| BoxliteError::Internal(format!("Failed to create stderr pipe: {}", e)))?;// Configure command to use our pipes.diff --git a/src/guest/src/service/guest.rs b/src/guest/src/service/guest.rsindex 6c8cfd760..80c479b50 100644--- a/src/guest/src/service/guest.rs+++ b/src/guest/src/service/guest.rs@@ -1,14 +1,14 @@//! Guest service implementation.//!//! Handles guest initialization and management (Init, Ping, Shutdown,-//! Quiesce, Thaw RPCs).+//! Quiesce, Thaw, SyncClock and ResizeFilesystem RPCs).use crate::service::server::GuestServer;use boxlite_shared::{guest_init_response, Guest as GuestService, GuestInitError, GuestInitRequest,GuestInitResponse, GuestInitSuccess, PingRequest, PingResponse, QuiesceRequest,- QuiesceResponse, ShutdownRequest, ShutdownResponse, SyncClockRequest, SyncClockResponse,- ThawRequest, ThawResponse,+ QuiesceResponse, ResizeFilesystemRequest, ResizeFilesystemResponse, ShutdownRequest,+ ShutdownResponse, SyncClockRequest, SyncClockResponse, ThawRequest, ThawResponse,};use tonic::{Request, Response, Status};use tracing::{debug, error, info, warn};@@ -259,6 +259,73 @@ impl GuestService for GuestServer {);Ok(Response::new(SyncClockResponse {}))}++ async fn resize_filesystem(+ &self,+ request: Request<ResizeFilesystemRequest>,+ ) -> Result<Response<ResizeFilesystemResponse>, Status> {+ use std::os::unix::fs::FileTypeExt;+ use std::path::Path;+ use std::time::Duration;++ let request = request.into_inner();+ if request.device != "/dev/vda"+ || request.minimum_bytes == 0+ || !request.minimum_bytes.is_multiple_of(512)+ {+ return Err(Status::invalid_argument(+ "resize requires /dev/vda and a positive sector-aligned capacity",+ ));+ }+ let initialized = self.init_state.lock().await.initialized;+ if !initialized || self.shutting_down.load(std::sync::atomic::Ordering::SeqCst) {+ return Err(Status::failed_precondition(+ "guest must be initialized and running",+ ));+ }+ // Let resize2fs finish and be reaped even if the RPC is cancelled.+ tokio::spawn(async move {+ let device = Path::new("/dev/vda");+ let metadata = tokio::fs::symlink_metadata(device).await.map_err(|error| {+ Status::failed_precondition(format!("root disk unavailable: {error}"))+ })?;+ if !metadata.file_type().is_block_device() {+ return Err(Status::failed_precondition(+ "root disk must be a block device",+ ));+ }+ wait_for_disk_capacity(+ Path::new("/sys/class/block/vda/size"),+ request.minimum_bytes,+ Duration::from_secs(10),+ )+ .await+ .map_err(|error| *error)?;+ info!(device = %device.display(), "Resizing ext4 to fill disk");+ let output = crate::service::exec::executor::GuestExecutor+ .run_command(+ format!("{}/resize2fs", boxlite_shared::layout::BIN_DIR),+ vec![request.device],+ )+ .await+ .map_err(|error| Status::internal(error.to_string()))?;+ if !output.status.success() {+ return Err(Status::internal(format!(+ "resize2fs failed on {} (exit {}): {}",+ device.display(),+ output.status.shell_code(),+ String::from_utf8_lossy(&output.stderr).trim()+ )));+ }+ info!(+ "Filesystem resize completed: {}",+ String::from_utf8_lossy(&output.stdout).trim()+ );+ Ok(Response::new(ResizeFilesystemResponse {}))+ })+ .await+ .map_err(|error| Status::internal(format!("resize task failed: {error}")))?+ }}/// Why a host-supplied timestamp was rejected.@@ -337,6 +404,32 @@ fn clock_settime_status(error: &std::io::Error) -> Status {}}+async fn wait_for_disk_capacity(+ size_path: &std::path::Path,+ minimum_bytes: u64,+ timeout: std::time::Duration,+) -> Result<(), Box<Status>> {+ tokio::time::timeout(timeout, async {+ loop {+ let text = tokio::fs::read_to_string(size_path)+ .await+ .map_err(|error| Status::internal(format!("read root disk capacity: {error}")))?;+ let bytes = text+ .trim()+ .parse::<u64>()+ .ok()+ .and_then(|sectors| sectors.checked_mul(512))+ .ok_or_else(|| Status::internal("invalid root disk capacity"))?;+ if bytes >= minimum_bytes {+ return Ok::<(), Box<Status>>(());+ }+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;+ }+ })+ .await+ .map_err(|_| Status::deadline_exceeded("kernel has not observed the grown root disk"))?+}+#[cfg(test)]mod tests {use std::time::{SystemTime, UNIX_EPOCH};@@ -346,6 +439,68 @@ mod tests {use crate::reaper::ExitSlot;use crate::service::exec::exec_handle::ExitStatus;+ #[tokio::test]+ async fn resize_filesystem_rejects_other_devices_and_uninitialized_guests() {+ let root = tempfile::tempdir().unwrap();+ let server = GuestServer::new(GuestLayout::with_base(root.path()));+ for (device, minimum_bytes) in [+ ("/dev/vdb", 1024),+ ("/dev/../dev/vda", 1024),+ ("/tmp/disk", 1024),+ ("/dev/vda", 0),+ ("/dev/vda", 513),+ ] {+ let error = server+ .resize_filesystem(Request::new(ResizeFilesystemRequest {+ device: device.into(),+ minimum_bytes,+ }))+ .await+ .unwrap_err();+ assert_eq!(error.code(), tonic::Code::InvalidArgument);+ }+ let error = server+ .resize_filesystem(Request::new(ResizeFilesystemRequest {+ device: "/dev/vda".into(),+ minimum_bytes: 1024,+ }))+ .await+ .unwrap_err();+ assert_eq!(error.code(), tonic::Code::FailedPrecondition);+ }++ #[tokio::test]+ async fn resize_filesystem_waits_for_kernel_capacity_and_bounds_the_wait() {+ use std::time::Duration;+ let root = tempfile::tempdir().unwrap();+ let path = root.path().join("size");+ tokio::fs::write(&path, "2\n").await.unwrap();+ let wait = wait_for_disk_capacity(&path, 2048, Duration::from_secs(1));+ tokio::pin!(wait);+ assert!(tokio::time::timeout(Duration::from_millis(30), &mut wait)+ .await+ .is_err());+ tokio::fs::write(&path, "4\n").await.unwrap();+ wait.await.unwrap();+ assert_eq!(+ wait_for_disk_capacity(&path, 4096, Duration::from_millis(20))+ .await+ .unwrap_err()+ .code(),+ tonic::Code::DeadlineExceeded+ );+ for invalid in ["garbage", "18446744073709551615"] {+ tokio::fs::write(&path, invalid).await.unwrap();+ assert_eq!(+ wait_for_disk_capacity(&path, 2048, Duration::from_secs(1))+ .await+ .unwrap_err()+ .code(),+ tonic::Code::Internal+ );+ }+ }+/// A quiesce that fails must not strand the rest of the teardown: the exit/// record still reaches disk, and the failure is reported afterwards.#[tokio::test]diff --git a/src/guest/tests/boot/probe.rs b/src/guest/tests/boot/probe.rsindex 730da7948..91ed50e10 100644--- a/src/guest/tests/boot/probe.rs+++ b/src/guest/tests/boot/probe.rs@@ -21,6 +21,11 @@ use std::{const MOUNTPOINT_VIEW: &str = "/dev/boot-mountpoints";fn main() {+ let scenario = std::env::args().nth(1).unwrap_or_else(|| "fresh".into());+ if scenario == "/dev/vda" {+ resize_probe();+ return;+ }assert_eq!(std::process::id(),1,@@ -30,7 +35,6 @@ fn main() {eprintln!("BOOT_PROBE_FAILED: {info}");reset();}));- let scenario = std::env::args().nth(1).unwrap_or_else(|| "fresh".into());let mut agent = Command::new("/boxlite-guest");agent.env_remove("HOSTNAME");match scenario.as_str() {@@ -156,6 +160,25 @@ fn main() {panic!("exec agent: {}", agent.exec());}+fn resize_probe() {+ let gate = std::path::Path::new("/run/boxlite/shared/resize-reaper-probe");+ if gate.join("armed").exists() {+ fs::write(gate.join("started"), b"").expect("signal that resize2fs has started");+ let deadline = std::time::Instant::now() + Duration::from_secs(20);+ while !gate.join("release").exists() {+ assert!(+ std::time::Instant::now() < deadline,+ "host did not release resize2fs"+ );+ std::thread::sleep(Duration::from_millis(20));+ }+ }+ panic!(+ "exec real resize2fs: {}",+ Command::new(gate.join("resize2fs")).arg("/dev/vda").exec()+ );+}+fn premount() {// The kernel already mounts /dev when booting from the ext4 root.for (path, kind) in [diff --git a/src/shared/proto/boxlite/v1/service.proto b/src/shared/proto/boxlite/v1/service.protoindex 895e8a7d9..a2e749dcd 100644--- a/src/shared/proto/boxlite/v1/service.proto+++ b/src/shared/proto/boxlite/v1/service.proto@@ -66,6 +66,9 @@ service Guest {// 100ms is an adjustment threshold, not an end-to-end precision guarantee.// Invalid timestamps and clock-read/set failures are returned as errors.rpc SyncClock(SyncClockRequest) returns (SyncClockResponse);++ // Grow the container root filesystem after its block device has grown.+ rpc ResizeFilesystem(ResizeFilesystemRequest) returns (ResizeFilesystemResponse);}// Persistent SSH desired state and live listener control.@@ -264,6 +267,15 @@ message SyncClockRequest {message SyncClockResponse {}+message ResizeFilesystemRequest {+ // Container root disk only (/dev/vda); user volumes and guest root are excluded.+ string device = 1;+ // Wait for the kernel to observe this capacity before invoking resize2fs.+ uint64 minimum_bytes = 2;+}++message ResizeFilesystemResponse {}+// ============================================================================// SSH runtime configuration// ============================================================================diff --git a/src/shim/src/timesync.rs b/src/shim/src/timesync.rsindex 97db6ad15..4c1c22533 100644--- a/src/shim/src/timesync.rs+++ b/src/shim/src/timesync.rs@@ -244,6 +244,14 @@ mod tests {None => Ok(tonic::Response::new(boxlite_shared::SyncClockResponse {})),}}++ async fn resize_filesystem(+ &self,+ _: tonic::Request<boxlite_shared::ResizeFilesystemRequest>,+ ) -> Result<tonic::Response<boxlite_shared::ResizeFilesystemResponse>, tonic::Status>+ {+ Err(tonic::Status::unimplemented("test fake"))+ }}async fn serve_fake(diff --git a/src/vmm/README.md b/src/vmm/README.mdindex a0c0321b7..a0b531ca6 100644--- a/src/vmm/README.md+++ b/src/vmm/README.md@@ -91,9 +91,11 @@ adapter depends on `boxlite-vmm`.On Linux x86_64 native Boxes, the host delivers directory descriptors to theshim on `vmm.sock`. The host-only socket uses mode `0600`. Mount requests also-check the peer UID. Each connection carries one version 1 request and reply,-with a four-byte little-endian length and up to 64 KiB of JSON. Registration-accepts one directory FD via `SCM_RIGHTS`. Guest RPCs use `box.sock`.+check the peer UID. Each connection carries one `POST /v1/mount-control`+request and reply over HTTP/1.1, with JSON bodies capped at 64 KiB.++Registration attaches one directory FD to the first request byte via `SCM_RIGHTS`.+Guest RPCs use `box.sock`.```mermaidsequenceDiagram@@ -116,7 +118,7 @@ including escaping and later state changes.The kernel queues connections for the serial control thread. The client hasone deadline for connect, queue wait, and I/O, including time behind a disk-resize. The frame reader owns received descriptors before validating the+resize. The shim owns received descriptors before validating therequest, so rejection releases them.Aggregate Mount and Detach reject containers whose capability bounding set@@ -130,7 +132,7 @@ directory references survive detach; repeating an old detach does not remove areplacement. Descendant mounts must be detached first. A detach received beforeits corresponding mount retains a tombstone that rejects that delayed mount.-Run `make test:unit:rust FILTER=vmm_socket` for frame and record checks.+Run `make test:unit:rust FILTER=vmm_socket` for HTTP and record checks.Run `make test:integration:vmm:mount-delivery` with a compatible `VMM_KERNEL`to register, attach, and retire a directory through the native shim and guest.diff --git a/src/vmm/boot/README.md b/src/vmm/boot/README.mdindex ad6131aa0..19574235b 100644--- a/src/vmm/boot/README.md+++ b/src/vmm/boot/README.md@@ -69,6 +69,13 @@ The native adapter attaches the requested devices and uses hvc0 for its defaultconsole; raw kernel boot tests can still select ttyS0.`make test:integration:vmm:native` verifies the actual agent with this kernel.+The fragment enables `CONFIG_BLK_DEV_WRITE_MOUNTED` because `resize2fs` opens+the mounted container root device read-write for initial sizing and online growth.+Custom native kernels need this setting when initial disk sizing or online growth calls `resize2fs`.+Without it, `resize2fs` reports `Resource busy while opening /dev/vda`.++Rebuild the kernel after changing the fragment.+## Default: building inside a BoxLite box`boxlite.lock` pins a BoxLite CLI release, its SHA-256 for each host and adiff --git a/src/vmm/boot/kernel.config b/src/vmm/boot/kernel.configindex 1ec0a4b2a..e2544ae87 100644--- a/src/vmm/boot/kernel.config+++ b/src/vmm/boot/kernel.config@@ -42,6 +42,8 @@ CONFIG_LOCALVERSION="-boxlite-m1"# virtio-mmio block devices named on the kernel command line.CONFIG_BLOCK=yCONFIG_BLK_DEV=y+# resize2fs opens the mounted container root device read-write for online growth.+CONFIG_BLK_DEV_WRITE_MOUNTED=yCONFIG_MSDOS_PARTITION=y# Aggregate host sharing over the common virtio-mmio transport.