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. `dstack_gpu_info` also carries each GPU's PCIe Device Serial Number. |
| 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
22 changes: 19 additions & 3 deletions dstack/dstack-util/src/gpu_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ use nvml_wrapper::error::NvmlError;
use nvml_wrapper::{Device, Nvml};
use tracing::{debug, warn};

mod dsn;

/// Per-run state for error log deduplication.
///
/// A single run touches each (device, field) pair once, so this only collapses
Expand Down Expand Up @@ -153,11 +155,23 @@ fn collect_device_fields(sampler: &mut Sampler, index: u32, device: &Device<'_>)
String::new()
}
};
let pci_bus_id = match device.pci_info() {
Ok(pci) => pci.bus_id,
let (pci_bus_id, pci_dsn) = match device.pci_info() {
Ok(pci) => {
let pci_dsn = match dsn::read(pci.domain, &pci.bus_id) {
Ok(pci_dsn) => pci_dsn.unwrap_or_default(),
Err(e) => {
errors.push(format!("pci_dsn: {e:#}"));
if sampler.warned.insert((index, "pci_dsn")) {
warn!("failed to read GPU {index} pci_dsn: {e:#}");
}
String::new()
}
};
(pci.bus_id, pci_dsn)
}
Err(e) => {
push_error(sampler, index, "pci_bus_id", e, &mut errors);
String::new()
(String::new(), String::new())
}
};

Expand Down Expand Up @@ -205,6 +219,7 @@ fn collect_device_fields(sampler: &mut Sampler, index: u32, device: &Device<'_>)
temperature_c,
power_usage_mw,
errors,
pci_dsn,
}
}

Expand Down Expand Up @@ -266,6 +281,7 @@ mod tests {
temperature_c: Some(40),
power_usage_mw: None,
errors: vec!["power: not supported".into()],
pci_dsn: "01-23-45-67-89-ab-cd-ef".into(),
}],
error: String::new(),
cc_ready: Some(true),
Expand Down
147 changes: 147 additions & 0 deletions dstack/dstack-util/src/gpu_info/dsn.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
// SPDX-FileCopyrightText: © 2026 Phala Network <dstack@phala.network>
//
// SPDX-License-Identifier: Apache-2.0

//! PCIe Device Serial Number of a GPU, read from its config space.
//!
//! The DSN is burned into the card and passes through VFIO unchanged, so the
//! guest and the host read the same value for the same card. That makes it
//! the key for joining guest GPU telemetry with host telemetry, where the PCI
//! addresses on the two sides have nothing in common.

use std::os::unix::fs::FileExt;

use anyhow::{Context, Result};

/// Extended capabilities start right after the 256-byte legacy config space.
const EXT_CAP_START: u64 = 0x100;
const EXT_CAP_END: u64 = 0x1000;
const EXT_CAP_ID_DSN: u32 = 0x0003;

/// Reads the DSN of the device NVML reports as `nvml_bus_id`.
///
/// Returns `None` when the device has no DSN capability, and also when the
/// extended config space is not reachable: a kernel booted with
/// `pci=nommconf`, or a caller without root, sees only the first 256 or 64
/// bytes.
pub(super) fn read(domain: u32, nvml_bus_id: &str) -> Result<Option<String>> {
// NVML writes `00000000:1B:00.0`; sysfs names the device `0000:1b:00.0`.
let (_, bus_device_function) = nvml_bus_id
.split_once(':')
.with_context(|| format!("unexpected NVML bus id {nvml_bus_id:?}"))?;
let path = format!(
"/sys/bus/pci/devices/{domain:04x}:{}/config",
bus_device_function.to_ascii_lowercase()
);
let config = fs_err::File::open(&path)?;
// Read only the dwords the walk visits. Every config access from a CVM is
// a trap to the host, so reading the whole 4 KiB per sample is wasteful.
Ok(find(|offset| {
let mut dword = [0u8; 4];
config
.file()
.read_exact_at(&mut dword, offset)
.ok()
.map(|()| u32::from_le_bytes(dword))
}))
}

/// Walks the extended capability list for the DSN and formats it as `lspci`
/// does: eight bytes, most significant first, joined by `-`.
///
/// `read_dword` returns `None` past the end of what is readable. A header of
/// ID 0 is followed, not treated as the end: VFIO rewrites the first header
/// to ID 0 to hide the capability it describes, but keeps its next pointer.
fn find(read_dword: impl Fn(u64) -> Option<u32>) -> Option<String> {
let mut offset = EXT_CAP_START;
// Every capability takes at least one dword, so a longer chain is a loop.
for _ in 0..(EXT_CAP_END - EXT_CAP_START) / 4 {
let header = read_dword(offset)?;
if header == 0 || header == u32::MAX {
return None;
}
if header & 0xffff == EXT_CAP_ID_DSN {
let low = read_dword(offset + 4)?;
let high = read_dword(offset + 8)?;
let serial = (u64::from(high) << 32 | u64::from(low)).to_be_bytes();
let bytes: Vec<String> = serial.iter().map(|byte| format!("{byte:02x}")).collect();
return Some(bytes.join("-"));
}
let next = u64::from(header >> 20) & 0xffc;
if next < EXT_CAP_START {
return None;
}
offset = next;
}
None
}

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

fn header(id: u32, next: u32) -> u32 {
(next << 20) | (1 << 16) | id
}

fn config_space(len: usize, dwords: &[(u64, u32)]) -> Vec<u8> {
let mut config = vec![0u8; len];
for &(offset, value) in dwords {
let offset = offset as usize;
config[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
}
config
}

fn find_in(config: &[u8]) -> Option<String> {
find(|offset| {
let offset = usize::try_from(offset).ok()?;
let bytes = config.get(offset..offset + 4)?;
Some(u32::from_le_bytes(bytes.try_into().ok()?))
})
}

/// The layout a GPU behind VFIO shows the guest: the first header hidden
/// as ID 0 but still pointing on, another capability, then the DSN.
#[test]
fn the_dsn_is_found_past_a_header_vfio_hid() {
let config = config_space(
0x1000,
&[
(0x100, header(0, 0x150)),
(0x150, header(0x0001, 0x200)),
(0x200, header(EXT_CAP_ID_DSN, 0)),
(0x204, 0x89ab_cdef),
(0x208, 0x0123_4567),
],
);
assert_eq!(find_in(&config).as_deref(), Some("01-23-45-67-89-ab-cd-ef"));
}

#[test]
fn no_extended_config_space_means_no_dsn() {
// `pci=nommconf` exposes 256 bytes; a non-root reader gets 64.
assert_eq!(find_in(&config_space(0x100, &[])), None);
assert_eq!(find_in(&config_space(0x40, &[])), None);
}

#[test]
fn a_list_without_a_dsn_ends_with_none() {
let empty = config_space(0x1000, &[]);
assert_eq!(find_in(&empty), None);
let no_dsn = config_space(0x1000, &[(0x100, header(0x0001, 0))]);
assert_eq!(find_in(&no_dsn), None);
}

#[test]
fn a_looping_list_ends() {
let config = config_space(0x1000, &[(0x100, header(0x0001, 0x100))]);
assert_eq!(find_in(&config), None);
}

#[test]
fn a_truncated_dsn_is_not_reported() {
let config = config_space(0x108, &[(0x100, header(EXT_CAP_ID_DSN, 0)), (0x104, 1)]);
assert_eq!(find_in(&config), None);
}
}
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 PCIe DSN. 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=\"{}\", pci_dsn=\"{}\"}}",
gpu.index,
prometheus_label(&gpu.uuid)?,
prometheus_label(&gpu.pci_bus_id)?,
prometheus_label(&gpu.pci_dsn)?,
))
}

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 DSN 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_dsn_is_only_on_the_info_series() {
let body = render(GpuInfoResponse {
gpus: vec![GpuDevice {
pci_dsn: "01-23-45-67-89-ab-cd-ef".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", pci_dsn="01-23-45-67-89-ab-cd-ef"} 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 PCIe Device Serial Number, which the host reads the same, 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
6 changes: 6 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,12 @@ 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;
// PCIe Device Serial Number, formatted as lspci prints it
// (`xx-xx-xx-xx-xx-xx-xx-xx`). The same card reports the same value on the
// host, so this is the key for joining guest and host GPU telemetry. Empty
// when the card has no DSN capability or the guest cannot read extended
// config space.
string pci_dsn = 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()],
pci_dsn: "01-23-45-67-89-ab-cd-ef".into(),
}],
};
let bytes = original.encode_to_vec();
Expand Down
Loading