From e9d7b9fae5b8c299460b7b30869d69cbbd3f3276 Mon Sep 17 00:00:00 2001 From: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:42:53 +0000 Subject: [PATCH 1/4] fix(dstackup): write WorkingDirectory as a bare path in unit files systemd does not unquote `WorkingDirectory=`, so the quoted value dstackup wrote is read as a relative path. systemd 259 rejects it ("path is not absolute"), and `dstackup install` then fails to start dstack-auth. Write the path bare, escaping only `%`. Signed-off-by: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> --- dstack/crates/dstackup/src/systemd.rs | 30 +++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/dstack/crates/dstackup/src/systemd.rs b/dstack/crates/dstackup/src/systemd.rs index 974521e43d..9c2142d76c 100644 --- a/dstack/crates/dstackup/src/systemd.rs +++ b/dstack/crates/dstackup/src/systemd.rs @@ -68,7 +68,7 @@ pub(crate) fn auth_unit_file(bin: &str, allowlist: &Path, port: u16, prefix: &Pa [Install]\nWantedBy=multi-user.target\n", bin = systemd_arg(bin), cfg = systemd_arg(&allowlist.display().to_string()), - wd = systemd_arg(&prefix.display().to_string()), + wd = systemd_path(&prefix.display().to_string()), ) } @@ -83,10 +83,16 @@ pub(crate) fn vmm_unit_file(bin: &str, config: &Path, prefix: &Path, auth_unit: auth = auth_unit, bin = systemd_arg(bin), cfg = systemd_arg(&config.display().to_string()), - wd = systemd_arg(&prefix.display().to_string()), + wd = systemd_path(&prefix.display().to_string()), ) } +/// `WorkingDirectory=` takes a bare absolute path; systemd does not unquote it +/// (systemd 259 rejects a quoted value as "path is not absolute"). +fn systemd_path(value: &str) -> String { + value.replace('%', "%%") +} + fn systemd_arg(value: &str) -> String { let mut out = String::with_capacity(value.len() + 2); out.push('"'); @@ -109,6 +115,26 @@ fn systemd_arg(value: &str) -> String { mod tests { use super::*; + #[test] + fn working_directory_is_a_bare_path() { + let prefix = Path::new("/var/lib/dstack"); + for unit in [ + auth_unit_file("/bin/auth", Path::new("/etc/a.json"), 8001, prefix), + vmm_unit_file( + "/bin/vmm", + Path::new("/etc/vmm.toml"), + prefix, + "dstack-auth", + ), + ] { + assert!( + unit.contains("\nWorkingDirectory=/var/lib/dstack\n"), + "{unit}" + ); + } + assert_eq!(systemd_path("/srv/100%"), "/srv/100%%"); + } + #[test] fn systemd_arg_quotes_paths_and_escapes_specifiers() { assert_eq!( From 9ee2d6b27ea1d5852f30a8ed92b4860223299fa3 Mon Sep 17 00:00:00 2001 From: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:43:10 +0000 Subject: [PATCH 2/4] fix(dstackup): load vhost_vsock before starting the VMM The VMM host API binds vsock CID 2, which needs the vhost_vsock transport. /dev/vhost-vsock is a static device node that loads the module only on first open, so on a fresh host the bind fails with EADDRNOTAVAIL and the VMM exits ("Failed to bind host API"). Load the module in ExecStartPre. Signed-off-by: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> --- dstack/crates/dstackup/src/systemd.rs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/dstack/crates/dstackup/src/systemd.rs b/dstack/crates/dstackup/src/systemd.rs index 9c2142d76c..f350062229 100644 --- a/dstack/crates/dstackup/src/systemd.rs +++ b/dstack/crates/dstackup/src/systemd.rs @@ -75,9 +75,13 @@ pub(crate) fn auth_unit_file(bin: &str, allowlist: &Path, port: u16, prefix: &Pa pub(crate) fn vmm_unit_file(bin: &str, config: &Path, prefix: &Path, auth_unit: &str) -> String { // KillMode defaults to control-group, so `systemctl stop` tears down the // VMM + supervisor + CVM qemus together (deterministic teardown). + // + // The host API listens on vsock CID 2, which only exists once the + // vhost_vsock transport is loaded. /dev/vhost-vsock is a static device node + // that loads the module on first open, so it can exist without the module. format!( "[Unit]\nDescription=dstack VMM\nAfter=network.target docker.service {auth}.service\nWants={auth}.service\n\n\ - [Service]\nExecStart={bin} -c {cfg}\nRestart=always\nRestartSec=2\n\ + [Service]\nExecStartPre=/sbin/modprobe vhost_vsock\nExecStart={bin} -c {cfg}\nRestart=always\nRestartSec=2\n\ TimeoutStopSec=120\nWorkingDirectory={wd}\n\n\ [Install]\nWantedBy=multi-user.target\n", auth = auth_unit, @@ -135,6 +139,15 @@ mod tests { assert_eq!(systemd_path("/srv/100%"), "/srv/100%%"); } + #[test] + fn vmm_unit_loads_vhost_vsock_first() { + let unit = vmm_unit_file("/bin/vmm", Path::new("/etc/vmm.toml"), Path::new("/d"), "a"); + let pre = unit + .find("ExecStartPre=/sbin/modprobe vhost_vsock\n") + .unwrap(); + assert!(pre < unit.find("ExecStart=").unwrap()); + } + #[test] fn systemd_arg_quotes_paths_and_escapes_specifiers() { assert_eq!( From 80444be37fc3ecab463a4857a1a35b22734ae3c3 Mon Sep 17 00:00:00 2001 From: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:41:22 +0000 Subject: [PATCH 3/4] fix(dstackup): find mkosi-os-v guest-OS releases Guest-OS releases are tagged `mkosi-os-v` by the mkosi release workflow, but `dstackup image pull` only looked for `guest-os-v`, so both a pinned `--version` and the latest-release lookup found nothing for 0.6.x. Look up `mkosi-os-v` first and keep `guest-os-v` as a fallback. These releases also publish `dstack--kernel-devel.tar.gz`, which the asset picker accepted as a host image; skip it like the `-uki` archive. Signed-off-by: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> --- dstack/crates/dstackup/src/image.rs | 130 ++++++++++++++++++---------- 1 file changed, 86 insertions(+), 44 deletions(-) diff --git a/dstack/crates/dstackup/src/image.rs b/dstack/crates/dstackup/src/image.rs index 91293b6458..b1148bdf52 100644 --- a/dstack/crates/dstackup/src/image.rs +++ b/dstack/crates/dstackup/src/image.rs @@ -4,7 +4,7 @@ //! `dstackup image` — fetch, list, and remove guest OS images. //! -//! Images are published as `guest-os-v*` release tarballs in the dstack +//! Images are published as `mkosi-os-v*` release tarballs in the dstack //! monorepo. Current releases use one hardware-adaptive `dstack-` image; //! legacy releases may also contain `dstack-nvidia-` variants. //! `install` validates the selected image against `digest.txt`, the OS image @@ -25,8 +25,10 @@ use std::time::SystemTime; const REPO: &str = "Dstack-TEE/dstack"; const LEGACY_REPO: &str = "Dstack-TEE/meta-dstack"; -const RELEASE_TAG_PREFIX: &str = "guest-os-v"; -pub(crate) const RELEASES_URL: &str = "https://github.com/Dstack-TEE/dstack/releases?q=guest-os-v"; +/// Tag prefixes of monorepo guest-OS releases. The mkosi release workflow tags +/// them `mkosi-os-v`; `guest-os-v` is still accepted. +const RELEASE_TAG_PREFIXES: [&str; 2] = ["mkosi-os-v", "guest-os-v"]; +pub(crate) const RELEASES_URL: &str = "https://github.com/Dstack-TEE/dstack/releases?q=mkosi-os-v"; const LEGACY_RELEASES_URL: &str = "https://github.com/Dstack-TEE/meta-dstack/releases"; const MONOREPO_GUEST_OS_MIN_VERSION: (u64, u64, u64) = (0, 6, 0); @@ -620,12 +622,13 @@ fn missing_named_image_message(image_dir: &str, name: &str) -> String { async fn fetch_release(version: Option<&str>, release_api_base_url: &str) -> Result { let client = reqwest::Client::new(); if let Some(version) = version { - let (version, url, releases_url) = tagged_release_location(version, release_api_base_url)?; - return fetch_tagged_release(&client, &url, releases_url) - .await? - .with_context(|| { - format!("guest-OS version {version} was not found; check {releases_url}") - }); + let (version, urls, releases_url) = tagged_release_location(version, release_api_base_url)?; + for url in &urls { + if let Some(release) = fetch_tagged_release(&client, url, releases_url).await? { + return Ok(release); + } + } + bail!("guest-OS version {version} was not found; check {releases_url}"); } let api_base = release_api_base_url.trim().trim_end_matches('/'); @@ -642,10 +645,11 @@ async fn fetch_release(version: Option<&str>, release_api_base_url: &str) -> Res .json() .await .context("parsing dstack release list")?; - if let Some(release) = releases - .into_iter() - .find(|release| release.tag_name.starts_with(RELEASE_TAG_PREFIX)) - { + if let Some(release) = releases.into_iter().find(|release| { + RELEASE_TAG_PREFIXES + .iter() + .any(|prefix| release.tag_name.starts_with(prefix)) + }) { return Ok(release); } @@ -655,27 +659,33 @@ async fn fetch_release(version: Option<&str>, release_api_base_url: &str) -> Res .with_context(|| format!("no guest-OS release found; check {RELEASES_URL}")) } +/// The release lookup URLs for a pinned version, in the order to try them. fn tagged_release_location( version: &str, release_api_base_url: &str, -) -> Result<(String, String, &'static str)> { - let version = version - .trim_start_matches(RELEASE_TAG_PREFIX) +) -> Result<(String, Vec, &'static str)> { + let version = RELEASE_TAG_PREFIXES + .iter() + .find_map(|prefix| version.strip_prefix(prefix)) + .unwrap_or(version) .trim_start_matches('v'); let core = numeric_version_core(version)?; - let (repo, tag_prefix, releases_url) = if core < MONOREPO_GUEST_OS_MIN_VERSION { - (LEGACY_REPO, "v", LEGACY_RELEASES_URL) + let api_base = release_api_base_url.trim().trim_end_matches('/'); + let (urls, releases_url) = if core < MONOREPO_GUEST_OS_MIN_VERSION { + ( + vec![format!("{api_base}/{LEGACY_REPO}/releases/tags/v{version}")], + LEGACY_RELEASES_URL, + ) } else { - (REPO, RELEASE_TAG_PREFIX, RELEASES_URL) + ( + RELEASE_TAG_PREFIXES + .iter() + .map(|prefix| format!("{api_base}/{REPO}/releases/tags/{prefix}{version}")) + .collect(), + RELEASES_URL, + ) }; - Ok(( - version.to_string(), - format!( - "{}/{repo}/releases/tags/{tag_prefix}{version}", - release_api_base_url.trim().trim_end_matches('/') - ), - releases_url, - )) + Ok((version.to_string(), urls, releases_url)) } fn numeric_version_core(version: &str) -> Result<(u64, u64, u64)> { @@ -721,7 +731,8 @@ async fn fetch_tagged_release( )) } -/// Pick a full bare-metal image tarball, never the `-uki` archive. For a GPU +/// Pick a full bare-metal image tarball, never the `-uki` or `-kernel-devel` +/// archive. For a GPU /// request, prefer a legacy `dstack-nvidia-*` asset when present and otherwise /// use the current unified image (which already contains conditional NVIDIA /// support). @@ -734,7 +745,11 @@ fn pick_asset(assets: &[Asset], gpu: bool) -> Option<&Asset> { |n: &str| n.starts_with("dstack-dev-") || n.starts_with("dstack-nvidia-dev-"); let matches = |a: &&Asset, want_legacy_gpu: bool| { let n = a.name.as_str(); - if !n.ends_with(".tar.gz") || n.ends_with("-uki.tar.gz") || is_dev_flavour(n) { + if !n.ends_with(".tar.gz") + || n.ends_with("-uki.tar.gz") + || n.ends_with("-kernel-devel.tar.gz") + || is_dev_flavour(n) + { return false; } let is_gpu = n.starts_with("dstack-nvidia-"); @@ -893,28 +908,55 @@ mod tests { assert!(pick_asset(&assets, true).is_none()); } + #[test] + fn kernel_devel_archive_is_never_selected_as_a_host_image() { + let assets = vec![ + asset("dstack-0.6.5-kernel-devel.tar.gz"), + asset("dstack-0.6.5-uki.tar.gz"), + asset("dstack-0.6.5.tar.gz"), + ]; + assert_eq!( + pick_asset(&assets, false).map(|a| a.name.as_str()), + Some("dstack-0.6.5.tar.gz") + ); + assert_eq!( + pick_asset(&assets, true).map(|a| a.name.as_str()), + Some("dstack-0.6.5.tar.gz") + ); + } + #[test] fn routes_pinned_releases_at_the_monorepo_boundary() { - for version in ["0.5.11", "v0.5.11", "guest-os-v0.5.11"] { - let (normalized, url, releases_url) = + for version in ["0.5.11", "v0.5.11", "guest-os-v0.5.11", "mkosi-os-v0.5.11"] { + let (normalized, urls, releases_url) = tagged_release_location(version, crate::cli::DEFAULT_RELEASE_API_BASE_URL).unwrap(); assert_eq!(normalized, "0.5.11"); assert_eq!( - url, - "https://api.github.com/repos/Dstack-TEE/meta-dstack/releases/tags/v0.5.11" + urls, + ["https://api.github.com/repos/Dstack-TEE/meta-dstack/releases/tags/v0.5.11"] ); assert_eq!(releases_url, LEGACY_RELEASES_URL); } for version in ["0.6.0", "0.6.0.a2", "1.0.0"] { - let (normalized, url, releases_url) = - tagged_release_location(version, crate::cli::DEFAULT_RELEASE_API_BASE_URL).unwrap(); - assert_eq!(normalized, version); - assert_eq!( - url, - format!("https://api.github.com/repos/Dstack-TEE/dstack/releases/tags/guest-os-v{version}") - ); - assert_eq!(releases_url, RELEASES_URL); + for input in [ + version.to_string(), + format!("mkosi-os-v{version}"), + format!("guest-os-v{version}"), + ] { + let (normalized, urls, releases_url) = + tagged_release_location(&input, crate::cli::DEFAULT_RELEASE_API_BASE_URL) + .unwrap(); + assert_eq!(normalized, version); + assert_eq!( + urls, + [ + format!("https://api.github.com/repos/Dstack-TEE/dstack/releases/tags/mkosi-os-v{version}"), + format!("https://api.github.com/repos/Dstack-TEE/dstack/releases/tags/guest-os-v{version}"), + ] + ); + assert_eq!(releases_url, RELEASES_URL); + } } } @@ -930,11 +972,11 @@ mod tests { #[test] fn release_api_base_url_is_configurable_and_trailing_slash_safe() { - let (_, url, _) = + let (_, urls, _) = tagged_release_location("0.6.0", " http://127.0.0.1:1234/api/ ").unwrap(); assert_eq!( - url, - "http://127.0.0.1:1234/api/Dstack-TEE/dstack/releases/tags/guest-os-v0.6.0" + urls[0], + "http://127.0.0.1:1234/api/Dstack-TEE/dstack/releases/tags/mkosi-os-v0.6.0" ); } From 5ba2610b1ea38b3c6689930695c952b4c31e0693 Mon Sep 17 00:00:00 2001 From: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:42:35 +0000 Subject: [PATCH 4/4] fix(dstack-cli): pick auto host ports inside the VMM port-mapping range `free_local_port()` bound port 0, which returns a kernel ephemeral port (32768 and up). The vmm.toml that `dstackup install` writes only allows tcp 1-20000, so the VMM refused every auto-picked port: the KMS CVM deploy in `dstackup install` failed with "Port mapping is not allowed", and so did `dstack deploy --port ` without a host port. Pick a free loopback port from 10000-19999 instead, and test that the rendered port-mapping range covers it. Signed-off-by: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> --- dstack/crates/dstack-cli-core/src/config.rs | 17 +++++++++++ dstack/crates/dstack-cli-core/src/ports.rs | 33 ++++++++++++++++++--- 2 files changed, 46 insertions(+), 4 deletions(-) diff --git a/dstack/crates/dstack-cli-core/src/config.rs b/dstack/crates/dstack-cli-core/src/config.rs index d2f832bce6..7ceecaf3d3 100644 --- a/dstack/crates/dstack-cli-core/src/config.rs +++ b/dstack/crates/dstack-cli-core/src/config.rs @@ -482,6 +482,23 @@ mod tests { toml::from_str::(&rendered).expect("vmm.toml must be valid TOML"); } + #[test] + fn vmm_toml_port_mapping_allows_auto_picked_host_ports() { + let rendered: toml::Value = toml::from_str(&vmm_toml(&VmmRender::default())).unwrap(); + let ranges = rendered["cvm"]["port_mapping"]["range"].as_array().unwrap(); + let covered = ranges.iter().any(|r| { + r["protocol"].as_str() == Some("tcp") + && r["from"].as_integer().unwrap() + <= i64::from(*crate::ports::AUTO_HOST_PORT_RANGE.start()) + && r["to"].as_integer().unwrap() + >= i64::from(*crate::ports::AUTO_HOST_PORT_RANGE.end()) + }); + assert!( + covered, + "port_mapping must cover ports::AUTO_HOST_PORT_RANGE" + ); + } + #[test] fn vmm_toml_auth_disabled_renders_empty_tokens() { let rendered = vmm_toml(&VmmRender::default()); diff --git a/dstack/crates/dstack-cli-core/src/ports.rs b/dstack/crates/dstack-cli-core/src/ports.rs index 142be1b16d..16241918ab 100644 --- a/dstack/crates/dstack-cli-core/src/ports.rs +++ b/dstack/crates/dstack-cli-core/src/ports.rs @@ -8,15 +8,32 @@ use anyhow::{bail, Context, Result}; use dstack_vmm_rpc::PortMapping; use std::net::TcpListener; +use std::ops::RangeInclusive; +use std::time::{SystemTime, UNIX_EPOCH}; -/// pick a currently-free TCP port on loopback by binding to port 0. +/// host ports handed out when the caller does not choose one. The range sits +/// below the Linux ephemeral range and inside the port-mapping allowlist that +/// `dstackup install` writes to vmm.toml (tcp 1-20000). A port from binding +/// port 0 is ephemeral, so the VMM would refuse to map it. +pub const AUTO_HOST_PORT_RANGE: RangeInclusive = 10000..=19999; + +/// pick a currently-free TCP port on loopback from [`AUTO_HOST_PORT_RANGE`]. /// /// inherently racy (the port could be taken before the VMM binds it), but fine /// for a single interactive deploy; the VMM will surface a bind conflict. pub fn free_local_port() -> Result { - let listener = TcpListener::bind("127.0.0.1:0").context("failed to find a free host port")?; - let port = listener.local_addr()?.port(); - Ok(port) + let (first, last) = (*AUTO_HOST_PORT_RANGE.start(), *AUTO_HOST_PORT_RANGE.end()); + let len = u32::from(last - first) + 1; + // start the scan at a varying offset so back-to-back picks spread out + let seed = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.subsec_nanos()) + .unwrap_or(0) + ^ std::process::id(); + (0..len) + .map(|i| first + (seed.wrapping_add(i) % len) as u16) + .find(|&port| tcp_port_free("127.0.0.1", port)) + .with_context(|| format!("failed to find a free host port in {first}-{last}")) } /// whether `addr:port` can be bound right now. Best-effort and racy, but it @@ -94,6 +111,14 @@ fn parse_port_number(value: &str, label: &str, spec: &str) -> Result { mod tests { use super::*; + #[test] + fn auto_host_ports_come_from_the_auto_range() { + let port = free_local_port().unwrap(); + assert!(AUTO_HOST_PORT_RANGE.contains(&port), "{port}"); + let mapping = parse_port("80").unwrap(); + assert!(AUTO_HOST_PORT_RANGE.contains(&(mapping.host_port as u16))); + } + #[test] fn parses_fixed_direct_host_mapping() { let p = parse_port("8080:80").unwrap();