From d5fda6c59b32ceebf8f3112dba956fb885220393 Mon Sep 17 00:00:00 2001 From: Miles Date: Tue, 17 Nov 2026 22:10:13 +0000 Subject: [PATCH 1/2] feat(driver): honor --cpu and --memory as the VM's vCPUs and memory The gateway forwards a sandbox's standard resource limits as the template's cpu_limit and memory_limit. The driver ignored them and reported both limits unsupported, so every VM got the driver-wide OPENSHELL_VM_DRIVER_VCPUS and OPENSHELL_VM_DRIVER_MEM_MIB whatever was asked for. Now cpu_limit sets the VM's vCPU count and memory_limit its memory, and the driver reports both limits supported. A CPU limit must be a whole number of CPUs (2, 2000m), because a Firecracker VM has whole vCPUs; 1.5 is refused, not rounded. Memory takes a Kubernetes quantity (8Gi, 8192Mi, 8G), rounded down to whole MiB. Requests are bounded by the new OPENSHELL_VM_MAX_VCPUS (at most Firecracker's 32) and the existing OPENSHELL_VM_MAX_MEM_MIB; each defaults to the default size. They are checked at create and again at every launch, as the memory request was before. driver_config.mem_mib is removed in favour of --memory. A driver_config that still sets it is refused with a pointer to --memory. Co-Authored-By: Claude Opus 5.5 --- README.md | 60 ++- examples/firecracker-driver.env | 22 +- install.sh | 9 +- .../crates/openshell-driver-vm/README.md | 12 +- .../crates/openshell-driver-vm/src/driver.rs | 390 ++++++++++++++---- .../crates/openshell-driver-vm/src/main.rs | 10 +- .../src/sandbox_storage.rs | 9 - 7 files changed, 391 insertions(+), 121 deletions(-) diff --git a/README.md b/README.md index ad703cc..50e558b 100644 --- a/README.md +++ b/README.md @@ -12,8 +12,8 @@ driver: libkrun, QEMU, GPU passthrough and virtiofs bind mounts are not part of It also differs from OpenShell's driver in three behaviors: a sandbox starts the way a container does, with the image's `ENV` and in the image's `WORKDIR` -([Image ENV and WORKDIR](#image-env-and-workdir)); a sandbox can set its memory and disk size -and have files copied in from the host ([Per-sandbox memory, disk size and files](#per-sandbox-memory-disk-size-and-files)); +([Image ENV and WORKDIR](#image-env-and-workdir)); a sandbox can set its vCPUs, memory and disk size +and have files copied in from the host ([Per-sandbox CPU, memory, disk size and files](#per-sandbox-cpu-memory-disk-size-and-files)); and, if enabled, the driver issues SPIFFE JWT-SVIDs to its host supervisors itself, without a SPIRE agent ([Supervisor identity](#supervisor-identity)). @@ -435,9 +435,10 @@ The driver's `OPENSHELL_VM_DEFAULT_WORKDIR` (default `/sandbox`) sets the workin sandboxes whose image has none ([Image ENV and WORKDIR](#image-env-and-workdir)). The driver's `OPENSHELL_VM_SUPERVISOR_IDENTITY*` options (optional, off by default) are in [Supervisor identity](#supervisor-identity). -The driver's `OPENSHELL_VM_MAX_MEM_MIB`, `OPENSHELL_VM_MAX_OVERLAY_DISK_MIB`, -`OPENSHELL_VM_FILES_ROOT` and `OPENSHELL_VM_FILES_MAX_BYTES` limit what a sandbox can request in its `driver_config`; see -[Per-sandbox memory, disk size and files](#per-sandbox-memory-disk-size-and-files). +The driver's `OPENSHELL_VM_MAX_VCPUS` and `OPENSHELL_VM_MAX_MEM_MIB` limit what a sandbox can request +with `--cpu` and `--memory`, and `OPENSHELL_VM_MAX_OVERLAY_DISK_MIB`, `OPENSHELL_VM_FILES_ROOT` and +`OPENSHELL_VM_FILES_MAX_BYTES` what it can request in its `driver_config`; see +[Per-sandbox CPU, memory, disk size and files](#per-sandbox-cpu-memory-disk-size-and-files). The driver's `OPENSHELL_VM_IMAGE_CACHE_MAX_IDLE_HOURS` (default 48, 0 to keep everything) sets when unused image disks are removed; see [Image cache cleanup](#image-cache-cleanup). The driver's `OPENSHELL_VM_LOCAL_IMAGE_SOURCE` (default `auto`) and @@ -463,16 +464,40 @@ guest gets compressed swap in its own memory (zram), half its memory by default zram stretches memory; it does not add any. To give VMs more, raise the driver's default, `OPENSHELL_VM_DRIVER_MEM_MIB` (`2048`), or let a sandbox ask for more with -`driver_config.mem_mib` ([Per-sandbox memory, disk size and files](#per-sandbox-memory-disk-size-and-files)). +`--memory` ([Per-sandbox CPU, memory, disk size and files](#per-sandbox-cpu-memory-disk-size-and-files)). It needs the guest kernel from this release or later, and `mkswap` and `swapon` in the bootstrap image. Without either, the guest boots without swap. `rootfs-console.log` says which happened: `openshell-firecracker: zram swap on (1024 MiB)`, or why it is off. -## Per-sandbox memory, disk size and files +## Per-sandbox CPU, memory, disk size and files -A sandbox can set its memory and the size of its writable disk, and have files copied in -from the host, through its `driver_config`. None of these is in upstream OpenShell. +A sandbox sets its vCPUs and memory with the standard `--cpu` and `--memory` options of +`openshell sandbox create`. It can also set the size of its writable disk, and have files +copied in from the host, through its `driver_config`. Upstream's VM driver ignores +`--cpu` and `--memory`, and has none of the `driver_config` settings. + +### CPU and memory + +```shell +openshell sandbox create --cpu 4 --memory 8Gi ... +``` + +**`--cpu`** is the VM's vCPU count. A Firecracker VM has whole vCPUs, so the value must be +a whole number of CPUs (`4`, or `4000m`); `1.5` is refused rather than rounded. Without +it, a VM gets `OPENSHELL_VM_DRIVER_VCPUS` (2). A request must be between 1 and +`OPENSHELL_VM_MAX_VCPUS`, which defaults to the default vCPUs: set it, up to Firecracker's +32, to let sandboxes ask for more. + +**`--memory`** is the VM's memory, as a Kubernetes quantity (`8Gi`, `8192Mi`, `8G`), +rounded down to whole MiB. Without it, a VM gets `OPENSHELL_VM_DRIVER_MEM_MIB` (2048). A +request must be between 256 MiB and `OPENSHELL_VM_MAX_MEM_MIB`, which defaults to the +default memory: set it to let sandboxes ask for more. Unlike the disk, the memory is real +host RAM once the guest touches it. + +Neither needs `allow_driver_config`: anyone who can create a sandbox can ask for up to +the two maximums. Stop and start keep the requests, and a start fails if one is outside +the limits in force, for instance after a maximum was lowered. ### Enable driver_config @@ -511,7 +536,6 @@ drops the rest: ```shell openshell sandbox create --driver-config-json '{"firecracker": { - "mem_mib": 4096, "overlay_disk_mib": 16384, "files": [ {"source": "app/app.toml", "target": "/etc/app/app.toml", "mode": "0640"}, @@ -520,11 +544,8 @@ openshell sandbox create --driver-config-json '{"firecracker": { ]}}' ... ``` -**`mem_mib`** is the VM's memory. The default is `OPENSHELL_VM_DRIVER_MEM_MIB` (2048). A -request must be between 256 and `OPENSHELL_VM_MAX_MEM_MIB`, which defaults to the default -memory: set it to let sandboxes ask for more. Unlike the disk, the memory is real host RAM -once the guest touches it. Stop and start keep the request; a start fails if it is outside -the limits in force, for instance after the maximum was lowered. +The memory is not a `driver_config` setting: a `mem_mib` there is refused, with a pointer +to `--memory` ([CPU and memory](#cpu-and-memory)). **`overlay_disk_mib`** is the size of the sandbox's writable overlay disk, which holds everything the workload writes. The default is `OPENSHELL_VM_OVERLAY_DISK_MIB` (4096). A @@ -715,7 +736,7 @@ Limits: - No virtiofs bind mounts and no GPU passthrough on Firecracker. A sandbox that asks for either is rejected at validation, not ignored. To get host files into a guest, use - [`driver_config.files`](#per-sandbox-memory-disk-size-and-files), which copies them in. + [`driver_config.files`](#per-sandbox-cpu-memory-disk-size-and-files), which copies them in. - `[openshell.supervisor.network].additional_ca_bundle` and the shared supervisor pool are rejected by the gateway for any external driver. - Rootfs tar uploads need the driver and gateway on the same filesystem and UID. @@ -737,9 +758,12 @@ Limits: - The guest environment file sits in the sandbox's own overlay (mode `0600`, root-owned). It holds what the driver passes to the guest init. - Firecracker's `jailer` is not used. +- Anyone who can create a sandbox can ask for vCPUs up to `OPENSHELL_VM_MAX_VCPUS` and + memory up to `OPENSHELL_VM_MAX_MEM_MIB`, with or without `allow_driver_config`; keep + the memory maximum within what the host can give every sandbox at once. - With `allow_driver_config` on, anyone who can create a sandbox can read every file under - `OPENSHELL_VM_FILES_ROOT` by copying it into their sandbox, can ask for memory up to - `OPENSHELL_VM_MAX_MEM_MIB` and a disk up to `OPENSHELL_VM_MAX_OVERLAY_DISK_MIB`. Put only what all sandbox users may see in the files + `OPENSHELL_VM_FILES_ROOT` by copying it into their sandbox, and can ask for a disk up to + `OPENSHELL_VM_MAX_OVERLAY_DISK_MIB`. Put only what all sandbox users may see in the files root, and keep the maximum within the host's free space: overlays are sparse, so the host disk fills only as guests write, but it can fill. diff --git a/examples/firecracker-driver.env b/examples/firecracker-driver.env index 190123c..41a682d 100644 --- a/examples/firecracker-driver.env +++ b/examples/firecracker-driver.env @@ -46,7 +46,7 @@ OPENSHELL_VM_LAUNCHER_BIN=/usr/local/libexec/openshell-firecracker/openshell-fir # Compressed swap (zram) in each guest, as a percentage of its memory: 0 to 200, # 0 for none. For more memory, raise OPENSHELL_VM_DRIVER_MEM_MIB (default 2048), or set -# OPENSHELL_VM_MAX_MEM_MIB below and request driver_config.mem_mib per sandbox. +# OPENSHELL_VM_MAX_MEM_MIB below and create sandboxes with --memory. # OPENSHELL_VM_FIRECRACKER_ZRAM_PERCENT=50 # --- Supervisor identity (optional) ------------------------------------------ @@ -61,17 +61,23 @@ OPENSHELL_VM_LAUNCHER_BIN=/usr/local/libexec/openshell-firecracker/openshell-fir # OPENSHELL_VM_SUPERVISOR_IDENTITY_ISSUER=https://openshell-identity.example.com # OPENSHELL_VM_SUPERVISOR_IDENTITY_SVID_TTL_SECS=300 -# --- Per-sandbox memory, disk size and files (optional) ----------------------- +# --- Per-sandbox CPU, memory, disk size and files (optional) ------------------ -# Limits for what a sandbox may request in its driver_config. See "Per-sandbox memory, -# disk size and files" in the README. Sandboxes can request these only when allow_driver_config is -# on (OPENSHELL_DRIVER_ADMISSION_CONFIG_JSON above, and the gateway table). +# Limits for what a sandbox may request. See "Per-sandbox CPU, memory, disk size and +# files" in the README. Any sandbox can request vCPUs and memory (sandbox create --cpu and +# --memory). +# Largest --cpu a sandbox may ask for, at most 32. Unset: no more than the default vCPUs, +# OPENSHELL_VM_DRIVER_VCPUS (2). +# OPENSHELL_VM_MAX_VCPUS=8 +# Largest --memory a sandbox may ask for, in MiB. Unset: no more than the default memory, +# OPENSHELL_VM_DRIVER_MEM_MIB (2048). +# OPENSHELL_VM_MAX_MEM_MIB=8192 +# The rest are driver_config settings, which sandboxes can request only when +# allow_driver_config is on (OPENSHELL_DRIVER_ADMISSION_CONFIG_JSON above, and the gateway +# table). # Largest overlay_disk_mib a sandbox may ask for (the default size is # OPENSHELL_VM_OVERLAY_DISK_MIB, 4096). # OPENSHELL_VM_MAX_OVERLAY_DISK_MIB=65536 -# Largest mem_mib a sandbox may ask for. Unset: no more than the default memory, -# OPENSHELL_VM_DRIVER_MEM_MIB (2048). -# OPENSHELL_VM_MAX_MEM_MIB=8192 # Host directory that driver_config.files sources are read from. Unset: no files. # OPENSHELL_VM_FILES_ROOT=/home/USER/.local/share/openshell/sandbox-files # Total bytes of files one sandbox may provision. diff --git a/install.sh b/install.sh index fe34782..44b330c 100755 --- a/install.sh +++ b/install.sh @@ -420,11 +420,18 @@ install_config() { fi if [ -f "$envfile" ] && ! grep -q 'OPENSHELL_VM_MAX_MEM_MIB' "$envfile"; then printf '\n%s\n%s\n%s\n' \ - "# Added by install.sh. Largest driver_config.mem_mib a sandbox may ask for." \ + "# Added by install.sh. Largest --memory a sandbox may ask for, in MiB." \ "# Unset: no more than the default memory, OPENSHELL_VM_DRIVER_MEM_MIB (2048)." \ "# OPENSHELL_VM_MAX_MEM_MIB=8192" >> "$envfile" say "added a commented-out OPENSHELL_VM_MAX_MEM_MIB to $envfile" fi + if [ -f "$envfile" ] && ! grep -q 'OPENSHELL_VM_MAX_VCPUS' "$envfile"; then + printf '\n%s\n%s\n%s\n' \ + "# Added by install.sh. Largest --cpu a sandbox may ask for, at most 32." \ + "# Unset: no more than the default vCPUs, OPENSHELL_VM_DRIVER_VCPUS (2)." \ + "# OPENSHELL_VM_MAX_VCPUS=8" >> "$envfile" + say "added a commented-out OPENSHELL_VM_MAX_VCPUS to $envfile" + fi } [ "$DO_BINARIES" -eq 0 ] || install_binaries diff --git a/vendor/openshell/crates/openshell-driver-vm/README.md b/vendor/openshell/crates/openshell-driver-vm/README.md index 49ca851..7e11538 100644 --- a/vendor/openshell/crates/openshell-driver-vm/README.md +++ b/vendor/openshell/crates/openshell-driver-vm/README.md @@ -26,14 +26,18 @@ Changes from upstream: that attested process. It serves OIDC discovery and JWKS endpoints over HTTP. The server stub is generated in `build.rs` without `protoc`. See `src/supervisor_identity/` and "Supervisor identity" in the repository README. -- **Per-sandbox memory, disk size and files.** `driver_config.mem_mib` sets a sandbox's - memory, from 256 MiB up to `OPENSHELL_VM_MAX_MEM_MIB` (default: `OPENSHELL_VM_DRIVER_MEM_MIB`, - which stays the default size). `driver_config.overlay_disk_mib` sets the size of a +- **CPU and memory limits.** Upstream ignores a template's `cpu_limit` and `memory_limit` + (`sandbox create --cpu / --memory`) and reports both limits unsupported. Here they set the + VM's vCPUs (whole CPUs only, up to `OPENSHELL_VM_MAX_VCPUS`, at most 32) and memory (256 MiB + up to `OPENSHELL_VM_MAX_MEM_MIB`); each maximum defaults to the default size, + `OPENSHELL_VM_DRIVER_VCPUS` and `OPENSHELL_VM_DRIVER_MEM_MIB`. Both are checked at create + and again at every launch. See `VmDriverConfig::sandbox_machine` in `src/driver.rs`. +- **Per-sandbox disk size and files.** `driver_config.overlay_disk_mib` sets the size of a sandbox's writable overlay disk, up to `OPENSHELL_VM_MAX_OVERLAY_DISK_MIB`. `driver_config.files` copies files and directories from `OPENSHELL_VM_FILES_ROOT` into the guest: the driver stages them in the overlay's upper layer and a guest init drop-in copies them into place with the requested owner and mode. See `src/sandbox_storage.rs` and - "Per-sandbox memory, disk size and files" in the repository README. + "Per-sandbox CPU, memory, disk size and files" in the repository README. - **Image cache cleanup.** Upstream never deletes a prepared disk. When the driver starts and after each sandbox start, stop or delete, it removes cache entries no sandbox references: those from other driver builds at once, and its own build's once unused for diff --git a/vendor/openshell/crates/openshell-driver-vm/src/driver.rs b/vendor/openshell/crates/openshell-driver-vm/src/driver.rs index 7a934fd..0051647 100644 --- a/vendor/openshell/crates/openshell-driver-vm/src/driver.rs +++ b/vendor/openshell/crates/openshell-driver-vm/src/driver.rs @@ -111,9 +111,11 @@ const DRIVER_NAME: &str = "openshell-driver-vm"; const WATCH_BUFFER: usize = 256; const DEFAULT_VCPUS: u8 = 2; const DEFAULT_MEM_MIB: u32 = 2048; -/// Smallest memory a sandbox may request with `driver_config.mem_mib` (not in +/// Smallest memory a sandbox may request with `memory_limit` (not in /// upstream). pub const MIN_MEM_MIB: u32 = 256; +/// Most vCPUs Firecracker gives one microVM. +pub const MAX_VCPUS: u8 = 32; const DEFAULT_OVERLAY_DISK_MIB: u64 = 4096; const DEFAULT_REGISTRY_LAYER_DOWNLOAD_CONCURRENCY: usize = 4; const MAX_REGISTRY_LAYER_DOWNLOAD_CONCURRENCY: usize = 16; @@ -143,12 +145,10 @@ struct VmSandboxDriverConfig { deserialize_with = "crate::sandbox_storage::deserialize_optional_mib" )] overlay_disk_mib: Option, - /// Memory of this sandbox's VM, in MiB (not in upstream). - #[serde( - default, - deserialize_with = "crate::sandbox_storage::deserialize_optional_mem_mib" - )] - mem_mib: Option, + /// Replaced by the template's `memory_limit` (`sandbox create --memory`); + /// accepted only so a request for it is rejected by name. + #[serde(default)] + mem_mib: Option, /// Files copied from the operator's files root into the guest (not in /// upstream). #[serde(default)] @@ -173,9 +173,62 @@ impl VmSandboxDriverConfig { return Ok(Self::default()); }; - serde_json::from_value(struct_to_json_value(config)) - .map_err(|err| format!("invalid vm driver_config: {err}")) + let config: Self = serde_json::from_value(struct_to_json_value(config)) + .map_err(|err| format!("invalid vm driver_config: {err}"))?; + if config.mem_mib.is_some() { + return Err("driver_config.mem_mib is no longer supported: \ + set the memory with sandbox create --memory" + .to_string()); + } + Ok(config) + } +} + +/// A non-negative decimal such as `2`, `0.5` or `.5`, exactly, as +/// `numerator / denominator` with the denominator a power of ten. +fn parse_decimal(value: &str) -> Option<(u128, u128)> { + let (whole, fraction) = value.split_once('.').unwrap_or((value, "")); + let digits = format!("{whole}{fraction}"); + if digits.is_empty() || digits.len() > 30 || !digits.bytes().all(|b| b.is_ascii_digit()) { + return None; } + let denominator = 10_u128.checked_pow(u32::try_from(fraction.len()).ok()?)?; + Some((digits.parse().ok()?, denominator)) +} + +/// A positive Kubernetes CPU quantity (`2`, `1.5`, `1500m`) as a number of +/// CPUs, `numerator / denominator`. +fn parse_cpu_quantity(value: &str) -> Option<(u128, u128)> { + let (numerator, denominator) = match value.strip_suffix('m') { + Some(millicores) => (millicores.parse().ok()?, 1000), + None => parse_decimal(value)?, + }; + (numerator > 0).then_some((numerator, denominator)) +} + +/// A Kubernetes memory quantity (`4Gi`, `4096Mi`, `4G`, bytes) in whole MiB, +/// rounded down. +fn parse_memory_mib(value: &str) -> Option { + let split = value + .find(|c: char| !(c.is_ascii_digit() || c == '.')) + .unwrap_or(value.len()); + let (number, suffix) = value.split_at(split); + let multiplier: u128 = match suffix { + "" => 1, + "k" | "K" => 1000, + "M" => 1000_u128.pow(2), + "G" => 1000_u128.pow(3), + "T" => 1000_u128.pow(4), + "P" => 1000_u128.pow(5), + "Ki" => 1 << 10, + "Mi" => 1 << 20, + "Gi" => 1 << 30, + "Ti" => 1 << 40, + "Pi" => 1 << 50, + _ => return None, + }; + let (numerator, denominator) = parse_decimal(number)?; + Some(numerator.checked_mul(multiplier)? / denominator / (1 << 20)) } const OPENSHELL_HOST_GATEWAY_ALIAS: &str = "host.openshell.internal"; @@ -350,9 +403,15 @@ pub struct VmDriverConfig { pub default_image: String, pub bootstrap_image: String, pub log_level: String, + /// vCPUs of a sandbox that sets no `cpu_limit`. pub vcpus: u8, + /// Most vCPUs a sandbox may request with `cpu_limit` (not in upstream). + /// Unset, a sandbox may not ask for more than `vcpus`. + #[serde(default)] + pub max_vcpus: Option, + /// Memory, in MiB, of a sandbox that sets no `memory_limit`. pub mem_mib: u32, - /// Most memory a sandbox may request with `driver_config.mem_mib` (not in + /// Most memory a sandbox may request with `memory_limit` (not in /// upstream). Unset, a sandbox may not ask for more than `mem_mib`. #[serde(default)] pub max_mem_mib: Option, @@ -449,6 +508,7 @@ impl std::fmt::Debug for VmDriverConfig { .field("bootstrap_image", &self.bootstrap_image) .field("log_level", &self.log_level) .field("vcpus", &self.vcpus) + .field("max_vcpus", &self.max_vcpus) .field("mem_mib", &self.mem_mib) .field("max_mem_mib", &self.max_mem_mib) .field("overlay_disk_mib", &self.overlay_disk_mib) @@ -530,6 +590,7 @@ impl Default for VmDriverConfig { bootstrap_image: String::new(), log_level: "info".to_string(), vcpus: DEFAULT_VCPUS, + max_vcpus: None, mem_mib: DEFAULT_MEM_MIB, max_mem_mib: None, overlay_disk_mib: DEFAULT_OVERLAY_DISK_MIB, @@ -595,7 +656,31 @@ impl VmDriverConfig { self.max_mem_mib.unwrap_or(self.mem_mib) } - pub fn validate_memory_config(&self) -> Result<(), String> { + /// Most vCPUs a sandbox may request: `max_vcpus`, or `vcpus` when unset. + pub fn effective_max_vcpus(&self) -> u8 { + self.max_vcpus.unwrap_or(self.vcpus) + } + + pub fn validate_machine_config(&self) -> Result<(), String> { + if !(1..=MAX_VCPUS).contains(&self.vcpus) { + return Err(format!( + "vcpus {} is outside Firecracker's range 1 to {MAX_VCPUS}", + self.vcpus + )); + } + if let Some(max) = self.max_vcpus { + if max < self.vcpus { + return Err(format!( + "max_vcpus {max} is smaller than the default vcpus {}", + self.vcpus + )); + } + if max > MAX_VCPUS { + return Err(format!( + "max_vcpus {max} is more than Firecracker's {MAX_VCPUS}" + )); + } + } if let Some(max) = self.max_mem_mib && max < self.mem_mib { @@ -607,22 +692,73 @@ impl VmDriverConfig { Ok(()) } - /// The memory, in MiB, of a sandbox whose `driver_config` asked for - /// `requested`: the default without a request, otherwise the request if it - /// is within [`MIN_MEM_MIB`] and [`Self::effective_max_mem_mib`]. - pub(crate) fn sandbox_mem_mib(&self, requested: Option) -> Result { - let Some(mib) = requested else { + /// The vCPUs of a sandbox with this `cpu_limit` (`sandbox create --cpu`): + /// the default when it is empty, otherwise the limit if it is a whole + /// number of CPUs from 1 to [`Self::effective_max_vcpus`]. + pub(crate) fn sandbox_vcpus(&self, cpu_limit: &str) -> Result { + let limit = cpu_limit.trim(); + if limit.is_empty() { + return Ok(self.vcpus); + } + let max = self.effective_max_vcpus(); + let (num, den) = parse_cpu_quantity(limit).ok_or_else(|| { + format!("invalid cpu_limit '{limit}': expected a number of CPUs, such as 2 or 2000m") + })?; + if !num.is_multiple_of(den) { + return Err(format!( + "cpu_limit {limit} is not a whole number of CPUs: a Firecracker VM has whole vCPUs" + )); + } + u8::try_from(num / den) + .ok() + .filter(|vcpus| (1..=max).contains(vcpus)) + .ok_or_else(|| { + format!("cpu_limit {limit} is outside the allowed range 1 to {max} vCPUs") + }) + } + + /// The memory, in MiB, of a sandbox with this `memory_limit` (`sandbox + /// create --memory`): the default when it is empty, otherwise the limit, + /// rounded down to whole MiB, if it is from [`MIN_MEM_MIB`] to + /// [`Self::effective_max_mem_mib`]. + pub(crate) fn sandbox_mem_mib(&self, memory_limit: &str) -> Result { + let limit = memory_limit.trim(); + if limit.is_empty() { return Ok(self.mem_mib); - }; + } let max = self.effective_max_mem_mib(); + let mib = parse_memory_mib(limit).ok_or_else(|| { + format!("invalid memory_limit '{limit}': expected a quantity such as 4Gi or 4096Mi") + })?; u32::try_from(mib) .ok() .filter(|mib| (MIN_MEM_MIB..=max).contains(mib)) .ok_or_else(|| { - format!("mem_mib {mib} is outside the allowed range {MIN_MEM_MIB} to {max} MiB") + format!( + "memory_limit {limit} ({mib} MiB) is outside the allowed range {MIN_MEM_MIB} to {max} MiB" + ) }) } + /// The vCPUs and memory of a sandbox, from its template's resource limits. + pub(crate) fn sandbox_machine(&self, sandbox: &Sandbox) -> Result<(u8, u32), String> { + let resources = sandbox + .spec + .as_ref() + .and_then(|spec| spec.template.as_ref()) + .and_then(|template| template.resources.as_ref()); + let (cpu_limit, memory_limit) = resources.map_or(("", ""), |resources| { + ( + resources.cpu_limit.as_str(), + resources.memory_limit.as_str(), + ) + }); + Ok(( + self.sandbox_vcpus(cpu_limit)?, + self.sandbox_mem_mib(memory_limit)?, + )) + } + pub fn validate_bootstrap_image_config(&self) -> Result<(), String> { if self.bootstrap_image.trim().is_empty() && self.default_image.trim().is_empty() { return Err( @@ -1293,8 +1429,8 @@ impl VmDriver { .validate(config.overlay_disk_mib) .map_err(|err| format!("invalid sandbox storage configuration: {err}"))?; config - .validate_memory_config() - .map_err(|err| format!("invalid VM memory configuration: {err}"))?; + .validate_machine_config() + .map_err(|err| format!("invalid VM vCPU or memory configuration: {err}"))?; if let Some(raw) = config.default_workdir.as_deref() { config.default_workdir = Some( validate_default_working_dir(raw) @@ -1750,10 +1886,10 @@ impl VmDriver { driver_reports_runtime_readiness: false, resource_capabilities: Some(ResourceCapabilities { cpu: Some(CpuResourceCapabilities { - limit_supported: false, + limit_supported: true, }), memory: Some(MemoryResourceCapabilities { - limit_supported: false, + limit_supported: true, }), gpu: None, }), @@ -1790,7 +1926,7 @@ impl VmDriver { ) .map_err(Status::invalid_argument)?; self.config - .sandbox_mem_mib(driver_config.mem_mib) + .sandbox_machine(sandbox) .map_err(Status::invalid_argument)?; // Resolve sources now, so a request naming a missing file or one // outside the files root fails at create, not during provisioning. @@ -2023,10 +2159,10 @@ impl VmDriver { let driver_config = VmSandboxDriverConfig::from_sandbox(&sandbox).map_err(Status::invalid_argument)?; // Checked again at every launch: the operator may have lowered the - // limit since the sandbox was created. - let mem_mib = self + // limits since the sandbox was created. + let (vcpus, mem_mib) = self .config - .sandbox_mem_mib(driver_config.mem_mib) + .sandbox_machine(&sandbox) .map_err(Status::failed_precondition)?; let driver_config_had_rootfs_tar = driver_config.rootfs_tar_path.is_some(); let rootfs_tar_path = match driver_config.rootfs_tar_path { @@ -2161,7 +2297,7 @@ impl VmDriver { } let mut plan = LaunchPlan { - vcpus: self.config.vcpus, + vcpus, mem_mib, kernel_profile: None, guest_init_dropins: Vec::new(), @@ -9854,88 +9990,182 @@ mod tests { } } + fn sandbox_with_limits(cpu_limit: &str, memory_limit: &str) -> Sandbox { + use openshell_core::proto::compute::v1::DriverResourceRequirements; + + Sandbox { + id: "sandbox-123".to_string(), + spec: Some(SandboxSpec { + template: Some(SandboxTemplate { + image: "example/image:latest".to_string(), + resources: Some(DriverResourceRequirements { + cpu_limit: cpu_limit.to_string(), + memory_limit: memory_limit.to_string(), + ..Default::default() + }), + ..Default::default() + }), + ..Default::default() + }), + ..Default::default() + } + } + #[test] - fn driver_config_carries_the_requested_memory() { + fn driver_config_mem_mib_points_at_memory_limit() { let sandbox = sandbox_with_driver_config(serde_json::json!({"mem_mib": 4096})); - let config = VmSandboxDriverConfig::from_sandbox(&sandbox).unwrap(); - assert_eq!(config.mem_mib, Some(4096)); + let err = VmSandboxDriverConfig::from_sandbox(&sandbox).unwrap_err(); + assert!(err.contains("--memory"), "{err}"); + } - let none = sandbox_with_driver_config(serde_json::json!({})); - assert_eq!( - VmSandboxDriverConfig::from_sandbox(&none).unwrap().mem_mib, - None - ); + #[test] + fn cpu_limit_quantities_become_whole_vcpus() { + let config = VmDriverConfig { + vcpus: 2, + max_vcpus: Some(8), + ..Default::default() + }; + assert_eq!(config.sandbox_vcpus(""), Ok(2), "the default"); + for (limit, vcpus) in [("1", 1), ("4", 4), (" 8 ", 8), ("4000m", 4), ("3.0", 3)] { + assert_eq!(config.sandbox_vcpus(limit), Ok(vcpus), "{limit}"); + } + for limit in ["1.5", "1500m", "0.5"] { + let err = config.sandbox_vcpus(limit).unwrap_err(); + assert!(err.contains("whole number"), "{limit}: {err}"); + } + for limit in ["0", "0m", "-1", "two", "2x", "m", "."] { + assert!(config.sandbox_vcpus(limit).is_err(), "{limit}"); + } + let err = config.sandbox_vcpus("9").unwrap_err(); + assert!(err.contains("1 to 8"), "{err}"); + } - for bad in [ - serde_json::json!(1.5), - serde_json::json!(-1), - serde_json::json!("4096"), + #[test] + fn cpu_limit_is_capped_by_the_default_without_max_vcpus() { + let config = VmDriverConfig { + vcpus: 2, + ..Default::default() + }; + assert_eq!(config.sandbox_vcpus("2"), Ok(2)); + assert_eq!(config.sandbox_vcpus("1"), Ok(1), "less is allowed"); + let err = config.sandbox_vcpus("3").unwrap_err(); + assert!(err.contains("1 to 2"), "{err}"); + } + + #[test] + fn memory_limit_quantities_become_mib() { + let config = VmDriverConfig { + mem_mib: 2048, + max_mem_mib: Some(16384), + ..Default::default() + }; + assert_eq!(config.sandbox_mem_mib(""), Ok(2048), "the default"); + for (limit, mib) in [ + ("4Gi", 4096), + ("4096Mi", 4096), + ("0.5Gi", 512), + ("1048576Ki", 1024), + ("4G", 3814), + ("1073741824", 1024), + ("16Gi", 16384), + (" 256Mi ", MIN_MEM_MIB), + ] { + assert_eq!(config.sandbox_mem_mib(limit), Ok(mib), "{limit}"); + } + for limit in [ + "16385Mi", "255Mi", "0", "1Ei", "4gi", "4 Gi", "Gi", "-1Gi", "1e9", ] { - let sandbox = sandbox_with_driver_config(serde_json::json!({"mem_mib": bad})); - let err = VmSandboxDriverConfig::from_sandbox(&sandbox).unwrap_err(); - assert!(err.contains("mem_mib"), "{err}"); + assert!(config.sandbox_mem_mib(limit).is_err(), "{limit}"); } + let err = config.sandbox_mem_mib("32Gi").unwrap_err(); + assert!(err.contains("256 to 16384"), "{err}"); } #[test] - fn sandbox_memory_defaults_and_is_capped_by_max_mem_mib() { - let mut config = VmDriverConfig { + fn memory_limit_is_capped_by_the_default_without_max_mem_mib() { + let config = VmDriverConfig { + mem_mib: 2048, + ..Default::default() + }; + assert_eq!(config.sandbox_mem_mib("1Gi"), Ok(1024), "less is allowed"); + let err = config.sandbox_mem_mib("2049Mi").unwrap_err(); + assert!(err.contains("256 to 2048"), "{err}"); + } + + #[test] + fn sandbox_machine_reads_the_template_limits() { + let config = VmDriverConfig { + vcpus: 2, + max_vcpus: Some(8), mem_mib: 2048, + max_mem_mib: Some(8192), ..Default::default() }; - assert_eq!(config.sandbox_mem_mib(None), Ok(2048), "the default"); assert_eq!( - config.sandbox_mem_mib(Some(1024)), - Ok(1024), - "less is allowed" + config.sandbox_machine(&sandbox_with_limits("4", "8Gi")), + Ok((4, 8192)) ); assert_eq!( - config.sandbox_mem_mib(Some(u64::from(MIN_MEM_MIB))), - Ok(MIN_MEM_MIB) + config.sandbox_machine(&sandbox_with_limits("", "")), + Ok((2, 2048)), + "empty limits are the defaults" + ); + let unset = sandbox_with_driver_config(serde_json::json!({})); + assert_eq!( + config.sandbox_machine(&unset), + Ok((2, 2048)), + "no resources" ); - // Without max_mem_mib, a sandbox cannot ask for more than the default. - let err = config.sandbox_mem_mib(Some(2049)).unwrap_err(); - assert!(err.contains("256 to 2048"), "{err}"); - - config.max_mem_mib = Some(8192); - assert_eq!(config.sandbox_mem_mib(Some(8192)), Ok(8192)); - assert_eq!(config.sandbox_mem_mib(None), Ok(2048), "still the default"); - for mib in [8193, u64::from(MIN_MEM_MIB) - 1, 0, u64::from(u32::MAX) + 1] { - assert!(config.sandbox_mem_mib(Some(mib)).is_err(), "{mib}"); - } } #[test] - fn max_mem_mib_may_not_be_below_the_default() { + fn machine_config_bounds_the_defaults_and_maximums() { let mut config = VmDriverConfig { + vcpus: 2, mem_mib: 2048, ..Default::default() }; - config.validate_memory_config().expect("unset"); + config.validate_machine_config().expect("defaults"); + config.max_vcpus = Some(2); config.max_mem_mib = Some(2048); - config.validate_memory_config().expect("equal"); + config.validate_machine_config().expect("equal"); + + config.max_vcpus = Some(1); + let err = config.validate_machine_config().unwrap_err(); + assert!(err.contains("max_vcpus 1"), "{err}"); + config.max_vcpus = Some(MAX_VCPUS + 1); + let err = config.validate_machine_config().unwrap_err(); + assert!(err.contains("Firecracker"), "{err}"); + config.max_vcpus = None; + + for vcpus in [0, MAX_VCPUS + 1] { + config.vcpus = vcpus; + assert!(config.validate_machine_config().is_err(), "{vcpus} vCPUs"); + } + config.vcpus = 2; + config.max_mem_mib = Some(2047); - let err = config.validate_memory_config().unwrap_err(); + let err = config.validate_machine_config().unwrap_err(); assert!(err.contains("max_mem_mib 2047"), "{err}"); } #[test] - fn validate_sandbox_bounds_the_requested_memory() { + fn validate_sandbox_bounds_the_requested_limits() { let mut driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - driver.config.allow_driver_config = true; + driver.config.max_vcpus = Some(4); driver.config.max_mem_mib = Some(8192); - let within = sandbox_with_driver_config(serde_json::json!({"mem_mib": 8192})); driver - .validate_sandbox(&within) - .expect("memory within the limit"); + .validate_sandbox(&sandbox_with_limits("4", "8Gi")) + .expect("limits within the maximums"); - let over = sandbox_with_driver_config(serde_json::json!({"mem_mib": 8193})); - let err = driver - .validate_sandbox(&over) - .expect_err("memory over the limit"); - assert_eq!(err.code(), Code::InvalidArgument); - assert!(err.message().contains("mem_mib"), "{}", err.message()); + for (cpu, memory, field) in [("5", "8Gi", "cpu_limit"), ("4", "8193Mi", "memory_limit")] { + let err = driver + .validate_sandbox(&sandbox_with_limits(cpu, memory)) + .expect_err("over a maximum"); + assert_eq!(err.code(), Code::InvalidArgument); + assert!(err.message().contains(field), "{}", err.message()); + } } #[test] @@ -10092,7 +10322,7 @@ mod tests { } #[test] - fn validate_vm_sandbox_accepts_template_resources_as_noop() { + fn validate_vm_sandbox_accepts_template_resources() { use openshell_core::proto::compute::v1::DriverResourceRequirements; let sandbox = Sandbox { @@ -10110,7 +10340,7 @@ mod tests { }), ..Default::default() }; - validate_vm_sandbox(&sandbox).expect("template.resources should be accepted and ignored"); + validate_vm_sandbox(&sandbox).expect("template.resources should be accepted"); } #[test] @@ -14371,11 +14601,11 @@ while :; do sleep 0.05; done"#, } #[test] - fn capabilities_report_static_resource_support() { + fn capabilities_report_cpu_and_memory_limits() { let driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); let resources = driver.capabilities().resource_capabilities.unwrap(); - assert!(!resources.cpu.unwrap().limit_supported); - assert!(!resources.memory.unwrap().limit_supported); + assert!(resources.cpu.unwrap().limit_supported); + assert!(resources.memory.unwrap().limit_supported); assert!(resources.gpu.is_none()); } diff --git a/vendor/openshell/crates/openshell-driver-vm/src/main.rs b/vendor/openshell/crates/openshell-driver-vm/src/main.rs index 89ecc92..37e606f 100644 --- a/vendor/openshell/crates/openshell-driver-vm/src/main.rs +++ b/vendor/openshell/crates/openshell-driver-vm/src/main.rs @@ -158,13 +158,20 @@ struct Args { )] provider_spiffe_allow_guest_tcp: bool, + /// vCPUs of a sandbox created without `--cpu`. #[arg(long, env = "OPENSHELL_VM_DRIVER_VCPUS", default_value_t = 2)] vcpus: u8, + /// Most vCPUs a sandbox may request with `--cpu` (at most 32). Unset, a + /// sandbox may not ask for more than `OPENSHELL_VM_DRIVER_VCPUS`. + #[arg(long, env = "OPENSHELL_VM_MAX_VCPUS")] + max_vcpus: Option, + + /// Memory, in MiB, of a sandbox created without `--memory`. #[arg(long, env = "OPENSHELL_VM_DRIVER_MEM_MIB", default_value_t = 2048)] mem_mib: u32, - /// Most memory a sandbox may request with `driver_config.mem_mib`. Unset, a + /// Most memory a sandbox may request with `--memory`. Unset, a /// sandbox may not ask for more than `OPENSHELL_VM_DRIVER_MEM_MIB`. #[arg(long, env = "OPENSHELL_VM_MAX_MEM_MIB")] max_mem_mib: Option, @@ -347,6 +354,7 @@ async fn main() -> Result<()> { bootstrap_image: args.bootstrap_image.clone(), log_level: args.log_level.clone(), vcpus: args.vcpus, + max_vcpus: args.max_vcpus, mem_mib: args.mem_mib, max_mem_mib: args.max_mem_mib, overlay_disk_mib: args.overlay_disk_mib, diff --git a/vendor/openshell/crates/openshell-driver-vm/src/sandbox_storage.rs b/vendor/openshell/crates/openshell-driver-vm/src/sandbox_storage.rs index d2f4831..844613f 100644 --- a/vendor/openshell/crates/openshell-driver-vm/src/sandbox_storage.rs +++ b/vendor/openshell/crates/openshell-driver-vm/src/sandbox_storage.rs @@ -156,15 +156,6 @@ where optional_whole_mib(deserializer, "overlay_disk_mib") } -/// Accept `mem_mib` as a whole number of MiB (not in upstream). The VM driver -/// checks it against its memory limits. -pub(crate) fn deserialize_optional_mem_mib<'de, D>(deserializer: D) -> Result, D::Error> -where - D: serde::Deserializer<'de>, -{ - optional_whole_mib(deserializer, "mem_mib") -} - /// A whole, non-negative number of MiB in `field`. `driver_config` arrives as /// a protobuf `Struct`, whose numbers are all `f64`. // The f64 is checked to be a whole number in the exactly representable range From ab7af68f08051841b28f03027fc08d553d0e0138 Mon Sep 17 00:00:00 2001 From: Miles Date: Tue, 17 Nov 2026 22:15:06 +0000 Subject: [PATCH 2/2] docs(driver): spell out virtual CPUs in doc comments clippy's doc_markdown (pedantic, denied in CI) reads mixed-case words such as vCPUs and microVM in doc comments as unquoted code. Co-Authored-By: Claude Opus 5.5 --- .../crates/openshell-driver-vm/src/driver.rs | 12 ++++++------ .../openshell/crates/openshell-driver-vm/src/main.rs | 4 ++-- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/vendor/openshell/crates/openshell-driver-vm/src/driver.rs b/vendor/openshell/crates/openshell-driver-vm/src/driver.rs index 0051647..4aecf96 100644 --- a/vendor/openshell/crates/openshell-driver-vm/src/driver.rs +++ b/vendor/openshell/crates/openshell-driver-vm/src/driver.rs @@ -114,7 +114,7 @@ const DEFAULT_MEM_MIB: u32 = 2048; /// Smallest memory a sandbox may request with `memory_limit` (not in /// upstream). pub const MIN_MEM_MIB: u32 = 256; -/// Most vCPUs Firecracker gives one microVM. +/// Most virtual CPUs Firecracker gives one VM. pub const MAX_VCPUS: u8 = 32; const DEFAULT_OVERLAY_DISK_MIB: u64 = 4096; const DEFAULT_REGISTRY_LAYER_DOWNLOAD_CONCURRENCY: usize = 4; @@ -403,9 +403,9 @@ pub struct VmDriverConfig { pub default_image: String, pub bootstrap_image: String, pub log_level: String, - /// vCPUs of a sandbox that sets no `cpu_limit`. + /// Virtual CPUs of a sandbox that sets no `cpu_limit`. pub vcpus: u8, - /// Most vCPUs a sandbox may request with `cpu_limit` (not in upstream). + /// Most virtual CPUs a sandbox may request with `cpu_limit` (not in upstream). /// Unset, a sandbox may not ask for more than `vcpus`. #[serde(default)] pub max_vcpus: Option, @@ -656,7 +656,7 @@ impl VmDriverConfig { self.max_mem_mib.unwrap_or(self.mem_mib) } - /// Most vCPUs a sandbox may request: `max_vcpus`, or `vcpus` when unset. + /// Most virtual CPUs a sandbox may request: `max_vcpus`, or `vcpus` when unset. pub fn effective_max_vcpus(&self) -> u8 { self.max_vcpus.unwrap_or(self.vcpus) } @@ -692,7 +692,7 @@ impl VmDriverConfig { Ok(()) } - /// The vCPUs of a sandbox with this `cpu_limit` (`sandbox create --cpu`): + /// The virtual CPUs of a sandbox with this `cpu_limit` (`sandbox create --cpu`): /// the default when it is empty, otherwise the limit if it is a whole /// number of CPUs from 1 to [`Self::effective_max_vcpus`]. pub(crate) fn sandbox_vcpus(&self, cpu_limit: &str) -> Result { @@ -740,7 +740,7 @@ impl VmDriverConfig { }) } - /// The vCPUs and memory of a sandbox, from its template's resource limits. + /// The virtual CPUs and memory of a sandbox, from its template's resource limits. pub(crate) fn sandbox_machine(&self, sandbox: &Sandbox) -> Result<(u8, u32), String> { let resources = sandbox .spec diff --git a/vendor/openshell/crates/openshell-driver-vm/src/main.rs b/vendor/openshell/crates/openshell-driver-vm/src/main.rs index 37e606f..0cf3ace 100644 --- a/vendor/openshell/crates/openshell-driver-vm/src/main.rs +++ b/vendor/openshell/crates/openshell-driver-vm/src/main.rs @@ -158,11 +158,11 @@ struct Args { )] provider_spiffe_allow_guest_tcp: bool, - /// vCPUs of a sandbox created without `--cpu`. + /// Virtual CPUs of a sandbox created without `--cpu`. #[arg(long, env = "OPENSHELL_VM_DRIVER_VCPUS", default_value_t = 2)] vcpus: u8, - /// Most vCPUs a sandbox may request with `--cpu` (at most 32). Unset, a + /// Most virtual CPUs a sandbox may request with `--cpu` (at most 32). Unset, a /// sandbox may not ask for more than `OPENSHELL_VM_DRIVER_VCPUS`. #[arg(long, env = "OPENSHELL_VM_MAX_VCPUS")] max_vcpus: Option,