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
2 changes: 1 addition & 1 deletion docs/security/cvm-boundaries.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ This is the main configuration file for the application in JSON format:
| local_key_provider_enabled | 0.3.1 | boolean | Use a local key provider |
| key_provider_id | 0.5.1 | string | Optional pin for the key provider identity (hex-encoded bytes). For `kms` this is the KMS CA public key; for `local` the sealing-provider MR. For `tpm`, `sev-snp`, `tdx-seal` and `none` it must be an empty string — the TPM app-root public key is instance-specific and is not used as a provider id or measured as one. When empty, any provider is accepted; its identity is still recorded in the `key-provider` launch event. |
| public_logs | 0.3.3 | boolean | Whether logs are publicly visible |
| public_sysinfo | 0.3.3 | boolean | Whether system info is public. Covers the guest dashboard and `/metrics`, including the `dstack_gpu_*` series (since 0.6.0), which expose each GPU's UUID and PCI bus address alongside utilization, memory, temperature and power. |
| public_sysinfo | 0.3.3 | boolean | Whether system info is public. Covers the guest dashboard and `/metrics`, including the `dstack_gpu_*` series (since 0.6.0), which expose each GPU's UUID and PCI bus address alongside utilization, memory, temperature and power. On a host that sets `cvm.gpu.share_host_address`, `dstack_gpu_info` also carries each GPU's host PCI address. |
| public_tcbinfo | 0.5.1 | boolean | Whether TCB info is public |
| allowed_envs | 0.4.2 | array of string | List of allowed environment variable names. An entry may be `NAME: spec` to also constrain the value, see [Environment value specs](#environment-value-specs). |
| no_instance_id | 0.4.2 | boolean | Disable instance ID generation |
Expand Down
3 changes: 3 additions & 0 deletions dstack/dstack-util/src/gpu_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,8 @@ fn collect_device_fields(sampler: &mut Sampler, index: u32, device: &Device<'_>)
temperature_c,
power_usage_mw,
errors,
// Only the host knows it; the guest agent fills it in.
host_pci_bus_id: String::new(),
}
}

Expand Down Expand Up @@ -266,6 +268,7 @@ mod tests {
temperature_c: Some(40),
power_usage_mw: None,
errors: vec!["power: not supported".into()],
host_pci_bus_id: String::new(),
}],
error: String::new(),
cc_ready: Some(true),
Expand Down
119 changes: 117 additions & 2 deletions dstack/guest-agent/src/gpu_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,16 @@
//! ~2% of a core on every GPU guest whether or not anyone is watching, to
//! publish a number the consumer can already derive.

use std::collections::HashMap;
use std::path::Path;
use std::process::Stdio;
use std::sync::{LazyLock, OnceLock};
use std::time::Duration;
use std::time::{Duration, Instant};

use anyhow::{bail, Context, Result};
use cached_cell::TtlCell;
use dstack_types::shared_filenames::{HOST_SHARED_DIR, SYS_CONFIG};
use dstack_types::SysConfig;
use guest_api::GpuInfoResponse;
#[cfg(test)]
use or_panic::ResultOrPanic;
Expand Down Expand Up @@ -235,7 +238,8 @@ async fn refresh_if_free() {
/// Caller must hold [`REFRESH_LOCK`].
async fn sample_into_cache() {
match timeout(SAMPLE_TIMEOUT, collect()).await {
Ok(Ok(response)) => {
Ok(Ok(mut response)) => {
fill_host_pci_bus_ids(&mut response, &host_topology().await);
SNAPSHOT.set(response);
}
Ok(Err(error)) => {
Expand Down Expand Up @@ -291,6 +295,92 @@ fn collector_path() -> String {
DSTACK_UTIL.to_string()
}

/// How long to wait before asking the host again after it did not answer.
///
/// The usual reason is a VMM older than `HostApi.GpuTopology`. Asking again
/// later picks up a VMM upgraded while this guest keeps running, and one vsock
/// call every few minutes costs nothing.
const TOPOLOGY_RETRY: Duration = Duration::from_secs(300);
/// Upper bound on the host call. A sample must not wait on a slow host.
const TOPOLOGY_TIMEOUT: Duration = Duration::from_secs(3);

/// Guest PCI address to host PCI address, as the host last reported it.
#[derive(Default)]
struct HostTopology {
/// Set once the host answered. A VM's passthrough devices are fixed at
/// launch, so one answer holds for the life of this guest.
known: Option<HashMap<String, String>>,
/// When the last failed call was made.
failed_at: Option<Instant>,
}

static HOST_TOPOLOGY: LazyLock<Mutex<HostTopology>> =
LazyLock::new(|| Mutex::new(HostTopology::default()));

/// The host address of each passthrough device, by guest address. Empty when
/// the host does not report it; never fails.
async fn host_topology() -> HashMap<String, String> {
let mut topology = HOST_TOPOLOGY.lock().await;
if let Some(known) = &topology.known {
return known.clone();
}
if topology
.failed_at
.is_some_and(|at| at.elapsed() < TOPOLOGY_RETRY)
{
return HashMap::new();
}
match timeout(TOPOLOGY_TIMEOUT, query_host_topology()).await {
Ok(Ok(known)) => {
topology.known = Some(known.clone());
known
}
Ok(Err(error)) => {
debug!("no GPU host addresses from the host: {error:#}");
topology.failed_at = Some(Instant::now());
HashMap::new()
}
Err(_) => {
debug!("no GPU host addresses: the host did not answer in {TOPOLOGY_TIMEOUT:?}");
topology.failed_at = Some(Instant::now());
HashMap::new()
}
}
}

async fn query_host_topology() -> Result<HashMap<String, String>> {
let sys_config: SysConfig = serde_json::from_str(
&fs_err::read_to_string(format!("{HOST_SHARED_DIR}/{SYS_CONFIG}"))
.context("failed to read the system config")?,
)
.context("invalid system config")?;
let url = sys_config
.host_api_url
.context("host_api_url is not configured")?;
let response = host_api::client::new_client(url).gpu_topology().await?;
Ok(response
.devices
.into_iter()
.filter_map(|device| {
Some((
lspci::normalize_bdf(&device.guest_bdf)?,
lspci::normalize_bdf(&device.host_bdf)?,
))
})
.collect())
}

/// Sets each GPU's host address from the host's table, matched by the guest
/// address NVML reported.
fn fill_host_pci_bus_ids(response: &mut GpuInfoResponse, topology: &HashMap<String, String>) {
for gpu in &mut response.gpus {
let host = lspci::normalize_bdf(&gpu.pci_bus_id).and_then(|guest| topology.get(&guest));
if let Some(host) = host {
gpu.host_pci_bus_id = host.clone();
}
}
}

/// The guest has no NVIDIA hardware. Empty devices with no error is the
/// documented encoding for "the collector ran and found nothing".
fn no_gpus() -> GpuInfoResponse {
Expand Down Expand Up @@ -399,6 +489,31 @@ mod tests {
assert!(FAILURE_BACKOFF > SAMPLE_TTL);
}

/// NVML writes an eight-digit domain and the host a four-digit one; the
/// match must not depend on that. A GPU the host did not list stays empty.
#[test]
fn host_addresses_are_matched_by_guest_address() {
let mut response = GpuInfoResponse {
gpus: vec![
GpuDevice {
index: 0,
pci_bus_id: "00000000:01:00.0".into(),
..Default::default()
},
GpuDevice {
index: 1,
pci_bus_id: "00000000:02:00.0".into(),
..Default::default()
},
],
..Default::default()
};
let topology = HashMap::from([("0000:01:00.0".to_string(), "0001:1a:00.0".to_string())]);
fill_host_pci_bus_ids(&mut response, &topology);
assert_eq!(response.gpus[0].host_pci_bus_id, "0001:1a:00.0");
assert_eq!(response.gpus[1].host_pci_bus_id, "");
}

/// An empty cache is always due; that is the cold-start path.
#[test]
fn an_empty_cache_is_due() {
Expand Down
32 changes: 32 additions & 0 deletions dstack/guest-agent/src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,18 @@ mod filters {
))
}

/// [`gpu_labels`] plus the host PCI address. Kept off every other series
/// so adding it did not change their label sets; join on this one.
pub fn gpu_info_labels(gpu: &guest_api::GpuDevice) -> Result<String, rinja::Error> {
Ok(format!(
"{{index=\"{}\", uuid=\"{}\", pci_bus_id=\"{}\", host_pci_bus_id=\"{}\"}}",
gpu.index,
prometheus_label(&gpu.uuid)?,
prometheus_label(&gpu.pci_bus_id)?,
prometheus_label(&gpu.host_pci_bus_id)?,
))
}

pub fn prometheus_label(s: &str) -> Result<String, rinja::Error> {
Ok(s.replace('\\', "\\\\")
.replace('\n', "\\n")
Expand Down Expand Up @@ -240,6 +252,26 @@ mod tests {
assert!(failed.contains("dstack_gpu_nvml_up 0"));
}

/// The host address rides on `dstack_gpu_info` only. The other series
/// keep the label set they had, so upgrading does not split their history.
#[test]
fn the_host_address_is_only_on_the_info_series() {
let body = render(GpuInfoResponse {
gpus: vec![GpuDevice {
host_pci_bus_id: "0001:1a:00.0".into(),
utilization_gpu: Some(5),
..gpu(1)
}],
..Default::default()
});
assert!(body.contains(
r#"dstack_gpu_info{index="1", uuid="GPU-1", pci_bus_id="00000000:01:00.0", host_pci_bus_id="0001:1a:00.0"} 1"#
), "{body}");
assert!(body.contains(
r#"dstack_gpu_utilization_percent{index="1", uuid="GPU-1", pci_bus_id="00000000:01:00.0"} 5"#
));
}

/// Label values are escaped, so a hostile UUID cannot inject a series.
#[test]
fn label_values_are_escaped() {
Expand Down
6 changes: 6 additions & 0 deletions dstack/guest-agent/templates/metrics.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,12 @@ dstack_gpu_cc_enabled {% if enabled %}1{% else %}0{% endif %}
dstack_gpu_cc_ready {% if ready %}1{% else %}0{% endif %}
{%- when None %}{% endmatch %}

# HELP dstack_gpu_info Always 1. Carries each GPU's host PCI address, as the host reports it, for joining guest series with host ones.
# TYPE dstack_gpu_info gauge
{%- for gpu in gpu_info.gpus %}
dstack_gpu_info{{ gpu|gpu_info_labels }} 1
{%- endfor %}

# HELP dstack_gpu_utilization_percent GPU SM duty cycle, percent.
# TYPE dstack_gpu_utilization_percent gauge
{%- for gpu in gpu_info.gpus %}{% match gpu.utilization_gpu %}{% when Some with (value) %}
Expand Down
4 changes: 4 additions & 0 deletions dstack/guest-api/proto/guest_api.proto
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,10 @@ message GpuDevice {
optional uint32 power_usage_mw = 10;
// Failed queries for this card, one per entry; empty if all fields succeeded
repeated string errors = 11;
// PCI address of this card on the host, dddd:bb:dd.f. Reported by the host
// and not verifiable by the guest: use it to label telemetry, never for a
// security decision. Empty when the host did not report one.
string host_pci_bus_id = 12;
}

// GPU inventory collected through NVML.
Expand Down
1 change: 1 addition & 0 deletions dstack/guest-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ mod tests {
temperature_c: Some(0),
power_usage_mw: None,
errors: vec!["temperature: timeout".into()],
host_pci_bus_id: "0001:1a:00.0".into(),
}],
};
let bytes = original.encode_to_vec();
Expand Down
19 changes: 19 additions & 0 deletions dstack/host-api/proto/host_api.proto
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,23 @@ message SealedEnv {
bytes sealed_env = 1;
}

// A device the host passed through to the guest with VFIO.
message PassthroughDevice {
// PCI address as the guest sees it, dddd:bb:dd.f
string guest_bdf = 1;
// PCI address on the host, dddd:bb:dd.f
string host_bdf = 2;
}

// Where each passed-through device sits on the host.
//
// Reported by the host and not verifiable by the guest: use it to label
// telemetry, never for a security decision. Empty when the VM has no
// passthrough devices, or when the host cannot tell how QEMU laid them out.
message GpuTopologyResponse {
repeated PassthroughDevice devices = 1;
}

service HostApi {
rpc Info(google.protobuf.Empty) returns (HostInfo);
rpc Notify(Notification) returns (google.protobuf.Empty);
Expand All @@ -42,4 +59,6 @@ service HostApi {
// answer means the window is closed, and the guest starts application code
// only after one.
rpc UpdateSealedEnv(SealedEnv) returns (google.protobuf.Empty);
// The host PCI address of each GPU and NVSwitch passed through to this VM.
rpc GpuTopology(google.protobuf.Empty) returns (GpuTopologyResponse);
}
94 changes: 94 additions & 0 deletions dstack/lspci/src/bdf.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// SPDX-FileCopyrightText: © 2026 Phala Network <dstack@phala.network>
//
// SPDX-License-Identifier: Apache-2.0

//! One spelling for a PCI address.
//!
//! The same device reaches dstack written three ways: `1b:00.0` in a VM
//! manifest and QEMU's `host=`, `0000:1b:00.0` from `lspci -D` and sysfs, and
//! `00000000:1b:00.0` from NVML. Comparing them as strings silently fails, so
//! every comparison goes through [`normalize_bdf`].

/// Rewrites a PCI address as `dddd:bb:dd.f`, lowercase.
///
/// Accepts an address with or without the domain, and a domain of up to eight
/// hex digits as NVML writes it. A missing domain is domain 0, which is what
/// QEMU's `vfio-pci,host=` assumes too. Returns `None` for anything that is not
/// a PCI address, rather than passing it through.
pub fn normalize_bdf(address: &str) -> Option<String> {
let mut parts = address.trim().rsplitn(3, ':');
let device_function = parts.next()?;
let bus = parts.next()?;
let domain = parts.next().unwrap_or("0");
let (device, function) = device_function.split_once('.')?;

let domain = parse_hex(domain, 8)?;
let bus = parse_hex(bus, 2)?;
let device = parse_hex(device, 2)?;
let function = parse_hex(function, 1)?;
if domain > 0xffff || device > 0x1f || function > 7 {
return None;
}
Some(format!("{domain:04x}:{bus:02x}:{device:02x}.{function:x}"))
}

fn parse_hex(digits: &str, max_len: usize) -> Option<u32> {
if digits.is_empty() || digits.len() > max_len {
return None;
}
if !digits.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return None;
}
u32::from_str_radix(digits, 16).ok()
}

#[cfg(test)]
mod tests {
use super::normalize_bdf;

#[test]
fn every_spelling_of_one_device_normalizes_to_the_same_address() {
for spelling in [
"1b:00.0",
"0000:1b:00.0",
"00000000:1b:00.0",
"0000:1B:00.0",
] {
assert_eq!(
normalize_bdf(spelling).as_deref(),
Some("0000:1b:00.0"),
"{spelling}"
);
}
}

#[test]
fn a_non_zero_domain_is_kept() {
assert_eq!(
normalize_bdf("0001:4a:00.0").as_deref(),
Some("0001:4a:00.0")
);
assert_eq!(
normalize_bdf("00000001:4a:00.0").as_deref(),
Some("0001:4a:00.0")
);
}

#[test]
fn anything_that_is_not_a_pci_address_is_rejected() {
for input in [
"",
"1b:00",
"0f.00.0",
"zz:00.0",
"0f:20.0",
"1b:00.8",
"100:00.0",
"1b:00.0,bus=pci.1",
"1:0000:1b:00.0",
"000100000:1b:00.0",
] {
assert_eq!(normalize_bdf(input), None, "{input:?}");
}
}
}
3 changes: 3 additions & 0 deletions dstack/lspci/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,11 @@ use std::process::Command;

use anyhow::{Context, Result};

mod bdf;
pub mod sysfs;

pub use bdf::normalize_bdf;

/// Represents a PCI device with the specified fields.
#[derive(Debug)]
pub struct Device {
Expand Down
Loading
Loading