Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions dstack/crates/dstack-cli-core/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -482,6 +482,23 @@ mod tests {
toml::from_str::<toml::Value>(&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());
Expand Down
33 changes: 29 additions & 4 deletions dstack/crates/dstack-cli-core/src/ports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u16> = 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<u16> {
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
Expand Down Expand Up @@ -94,6 +111,14 @@ fn parse_port_number(value: &str, label: &str, spec: &str) -> Result<u16> {
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();
Expand Down
130 changes: 86 additions & 44 deletions dstack/crates/dstackup/src/image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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-<ver>` image;
//! legacy releases may also contain `dstack-nvidia-<ver>` variants.
//! `install` validates the selected image against `digest.txt`, the OS image
Expand All @@ -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<version>`; `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);

Expand Down Expand Up @@ -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<Release> {
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('/');
Expand All @@ -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);
}

Expand All @@ -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<String>, &'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)> {
Expand Down Expand Up @@ -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).
Expand All @@ -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-");
Expand Down Expand Up @@ -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);
}
}
}

Expand All @@ -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"
);
}

Expand Down
45 changes: 42 additions & 3 deletions dstack/crates/dstackup/src/systemd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,25 +68,35 @@ 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()),
)
}

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,
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('"');
Expand All @@ -109,6 +119,35 @@ 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 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!(
Expand Down
Loading