5 Commits
Author SHA1 Message Date
kevin_janssenandClaude Opus 5.5 9fa6c05af7 Document the Proxmox host, its read-only access and the local Proxmox test VM
Rust development slice / linux (push) Failing after 15s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:17:23 +01:00
kevin_janssenandClaude Opus 5.5 63447f1b87 Provision a read-only Proxmox VE token during HTTPS installation
Rust development slice / linux (push) Failing after 15s
On hosts with pveversion and pveum the installer creates rmm-discovery@pve with
a privilege-separated PVEAuditor token, copies the cluster CA and passes both to
the agent through a systemd credential drop-in. Existing tokens are kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:14:05 +01:00
kevin_janssenandClaude Opus 5.5 ce356f0de7 Show Proxmox guests and scheduled backup status in device details
Rust development slice / linux (push) Failing after 14s
The host detail lists VMs and containers with linked inventory devices and
last successful backup, each vzdump job with its due time and result, an
overall 'all scheduled backups ran' answer and guests without a job. VM hosts
detected from a Proxmox guest list are labelled and the assignment form can
hand the decision back to automatic detection.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:12:54 +01:00
kevin_janssenandClaude Opus 5.5 70977df577 Validate Proxmox observations, evaluate scheduled backups and link VMs to their Proxmox host
Rust development slice / linux (push) Failing after 15s
linux.proxmox gets a strict validator and a 128 KiB scope budget. Device
details expose guests, backup jobs with ok/failed/missed/running status and
linked devices. Base snapshots reconcile unique guest MACs into
assets.hypervisor_asset_id with hypervisor_source='proxmox'; manual choices
are kept and can be handed back to automatic detection.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:10:35 +01:00
kevin_janssenandClaude Opus 5.5 1d2d52847c Collect Proxmox VE guests, backup jobs and vzdump runs as a read-only linux.proxmox scope
Rust development slice / linux (push) Failing after 12s
The Linux agent queries the local PVE API with a PVEAuditor token from the
systemd credential rmm-proxmox-token and the pinned cluster CA. Guests carry
MAC addresses and SMBIOS UUIDs for hypervisor mapping; jobs carry covered
guests and the scheduler's last expected run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:04:13 +01:00
30 changed files with 1568 additions and 25 deletions
Generated
+1
View File
@@ -2210,6 +2210,7 @@ dependencies = [
"rmm-domain",
"serde",
"serde_json",
"tokio",
"uuid",
]
@@ -12,6 +12,8 @@ Der Agent meldet den Gerätetyp mit dem passiven Hardwareinventar. `physical` be
Für aktuelle virtuelle Geräte kann die WebUI einen registrierten Hypervisor aus demselben Kundenbestand zuordnen. Die Geräteübersicht zeigt diese Verbindung unter dem Hostnamen der VM und verlinkt auf die Gerätedetails des Hypervisors. Die Zuordnung gilt, solange der verknüpfte Host im Bestand ist und sich als Hypervisor meldet. Eine VM mit gemeldetem Hersteller Hetzner erhält bei fehlendem konkreten Host den Anzeigeplatzhalter „Hetzner Cloud“. Der Platzhalter hat keine Kopplung und zählt nicht als registriertes Gerät.
Ein aufgenommener Proxmox-VE-Host meldet über einen vom Installer eingerichteten, nur lesenden API-Token (`PVEAuditor`) die Gäste seines Nodes, die geplanten vzdump-Backupjobs und die Läufe der letzten acht Tage. Die Gerätedetails des Hosts listen VMs und Container mit Status, Ressourcen, zugeordnetem Gerät und letzter erfolgreicher Sicherung. Darunter folgen die Backupjobs mit Zeitplan, Storage, gesicherten Gästen, letztem fälligen Zeitpunkt, Ergebnis und nächstem Lauf sowie die Gäste ohne Backupjob. Der Server bewertet jeden aktiven Job als gelaufen, fehlgeschlagen, verpasst, laufend oder noch nicht fällig. Er beantwortet damit, ob alle geplanten Backups gelaufen sind. Ein virtuelles Gerät, dessen MAC-Adresse eindeutig in der Gastliste eines Proxmox-Hosts desselben Kunden steht, wird diesem Host automatisch als Hypervisor zugeordnet und so gekennzeichnet. Eine manuelle Zuordnung hat Vorrang und lässt sich wieder an die automatische Erkennung zurückgeben. [Proxmox-Host](deploy/proxmox/README.md)
Ab Windows-Client `0.1.27` zeigt die Spalte **Speicher belegt / gesamt** jedes lokale Festplattenvolume mit Laufwerksbuchstaben separat an, das Systemlaufwerk zuerst. Ein Laufwerk mit unbekannter Kapazität behält seinen Buchstaben ohne Belegungsbalken. Die Zuordnung erfolgt pro logischem Volume, nicht pro physischem Datenträger. Netzlaufwerke, optische Medien und Volumes ohne Laufwerksbuchstaben gehören nicht zu dieser Liste. Bei älteren Inventarmeldungen bleibt die vorhandene Systemlaufwerkskapazität sichtbar.
Unter Linux zeigt die Übersicht die vom Kernel erkannten ganzen Festplatten bzw. virtuellen Gastplatten mit Gerätename, Modell (falls verfügbar) und Rohkapazität. Für direkt zuordenbare lokale Dateisysteme zählt sie belegte und für Anwendungen verfügbare Bytes über alle Partitionen, dasselbe Dateisystem nur einmal. Rot bezeichnet nachgewiesene Belegung, Grün verfügbaren Dateisystemplatz und Grau den Rest, einschließlich Reserven, unpartitioniertem Platz und nicht messbarer Belegung. Ein vollständig unbekannter Wert ist kein Nullwert. Bei gestapelten Blockgeräten und plattenübergreifenden Dateisystemen erscheint die logische Belegung separat mit den ermittelbaren Mitgliedern; sie wird nicht auf physische Platten verteilt. ZFS meldet die gemeinsame Belegung des Pools bei lesbaren ZFS-Eigenschaften, nicht die Summe der freien Bytes seiner Datasets. Alte Clients weisen den Wert für `/` als Root-Dateisystem aus.
+2
View File
@@ -11,3 +11,5 @@ uuid.workspace = true
serde.workspace = true
serde_json.workspace = true
chrono.workspace = true
[dev-dependencies]
tokio = { workspace = true }
+6 -2
View File
@@ -5,6 +5,7 @@ use crate::{
process,
};
mod disks;
pub mod proxmox;
use rmm_domain::inventory_document::{CpuTimes, DeviceType, firmware_identifier};
use std::{
collections::BTreeMap,
@@ -1281,6 +1282,10 @@ fn machine_type(proxmox_ve: bool) -> Option<DeviceType> {
virtualization_type(&output)
}
pub fn proxmox_ve() -> bool {
Path::new("/usr/bin/pveversion").is_file() && Path::new("/usr/bin/pvedaemon").is_file()
}
pub fn hardware() -> Observation<Hardware> {
const SOURCE: &str = "linux.dmi:/sys/class/dmi/id;systemd-detect-virt;pve-manager";
let mut readable_dmi = BTreeMap::new();
@@ -1298,8 +1303,7 @@ pub fn hardware() -> Observation<Hardware> {
readable_dmi.insert(field.into(), value);
}
}
let proxmox_ve =
Path::new("/usr/bin/pveversion").is_file() && Path::new("/usr/bin/pvedaemon").is_file();
let proxmox_ve = proxmox_ve();
let device_type = machine_type(proxmox_ve);
let manufacturer = readable_dmi
.get("sys_vendor")
+574
View File
@@ -0,0 +1,574 @@
//! Read-only Proxmox VE observation: hosted guests, scheduled vzdump jobs and recent
//! backup runs. Uses a dedicated PVEAuditor API token supplied by the installer as a
//! systemd credential. No writes, no root, no shell; the transport is injected so the
//! orchestration and parsing stay testable without a Proxmox host.
use super::{Observation, Quality};
use serde::Serialize;
use serde_json::Value;
use std::collections::{BTreeMap, BTreeSet};
pub const SOURCE: &str = "proxmox.api:/api2/json";
pub const OBSERVATION_MAX_BYTES: usize = rmm_domain::inventory_document::PROXMOX_OBSERVATION_MAX_BYTES;
pub const MAX_GUESTS: usize = 512;
pub const MAX_JOBS: usize = 64;
pub const MAX_RUNS: usize = 64;
const MAX_LOG_LINES: usize = 4000;
/// Weekly schedules must still show their previous due time.
const SCHEDULE_LOOKBACK_SECONDS: i64 = 8 * 24 * 3600;
const SCHEDULE_ITERATIONS: usize = 100;
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Proxmox {
pub node: String,
pub cluster: Option<String>,
pub version: Option<String>,
pub guests: Vec<Guest>,
pub backup_jobs: Vec<BackupJob>,
pub backup_runs: Vec<BackupRun>,
/// Local guests that no backup job selects (Proxmox's own analysis).
pub not_backed_up: Vec<u32>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Guest {
pub vmid: u32,
pub name: String,
pub kind: &'static str,
pub status: String,
pub template: bool,
pub cpus: Option<u32>,
pub memory_bytes: Option<u64>,
pub disk_bytes: Option<u64>,
pub uptime_seconds: Option<u64>,
pub pool: Option<String>,
pub macs: Vec<String>,
pub smbios_uuid: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct BackupJob {
pub id: String,
pub enabled: bool,
pub schedule: Option<String>,
pub storage: Option<String>,
pub mode: Option<String>,
pub selection: &'static str,
/// Local guests this job backs up, resolved from all/vmid/pool minus exclude.
pub covered_vmids: Vec<u32>,
pub next_run: Option<i64>,
/// Most recent scheduled time at or before the observation time.
pub last_expected_run: Option<i64>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct BackupRun {
pub upid: String,
pub started_at: i64,
pub ended_at: Option<i64>,
/// ok | warning | error | running
pub status: &'static str,
pub message: Option<String>,
pub guests: Vec<GuestResult>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct GuestResult {
pub vmid: u32,
/// ok | error
pub result: &'static str,
}
/// Bounded GET of one `/api2/json` path, returning the `data` member.
pub trait Api {
fn get(&self, path: &str) -> impl std::future::Future<Output = anyhow::Result<Value>> + Send;
}
pub fn not_configured() -> Observation<Proxmox> {
Observation::unavailable(SOURCE, Quality::Unsupported, "PROXMOX_NOT_CONFIGURED")
}
pub fn failed(code: &str) -> Observation<Proxmox> {
Observation::unavailable(SOURCE, Quality::Error, code)
}
/// The token secret never appears in errors, logs or observations.
pub fn token_header(credential: &str) -> Option<String> {
let token = credential.trim();
let (id, secret) = token.split_once('=')?;
let (user, name) = id.split_once('!')?;
let ok = |s: &str| !s.is_empty() && s.len() <= 128
&& s.bytes().all(|b| b.is_ascii_alphanumeric() || b"-_.@".contains(&b));
(ok(user) && user.contains('@') && ok(name) && ok(secret))
.then(|| format!("PVEAPIToken={token}"))
}
pub async fn collect(api: &impl Api, now: i64) -> Observation<Proxmox> {
match collect_data(api, now).await {
Ok((data, truncated)) => {
let mut observation = Observation::valid(SOURCE, data);
if truncated {
observation = observation.partial("PROXMOX_LIMIT");
observation.truncated = true;
}
fit(observation)
}
Err(error) => {
let code = error.to_string();
failed(if code.starts_with("PROXMOX_") && code.len() <= 64 { &code } else { "PROXMOX_API_ERROR" })
}
}
}
async fn collect_data(api: &impl Api, now: i64) -> anyhow::Result<(Proxmox, bool)> {
let status = api.get("/cluster/status").await?;
let rows = status.as_array().ok_or_else(|| anyhow::anyhow!("PROXMOX_API_SHAPE"))?;
let node = rows.iter()
.find(|r| r["type"] == "node" && flag(&r["local"]) == Some(true))
.and_then(|r| r["name"].as_str())
.filter(|n| clean(n, 64))
.ok_or_else(|| anyhow::anyhow!("PROXMOX_LOCAL_NODE_UNKNOWN"))?
.to_owned();
let cluster = rows.iter().find(|r| r["type"] == "cluster")
.and_then(|r| r["name"].as_str()).filter(|n| clean(n, 64)).map(str::to_owned);
let version = api.get("/version").await.ok()
.and_then(|v| v["version"].as_str().filter(|s| clean(s, 32)).map(str::to_owned));
let mut truncated = false;
let resources = api.get("/cluster/resources?type=vm").await?;
let mut guests = Vec::new();
for row in resources.as_array().into_iter().flatten() {
if row["node"].as_str() != Some(node.as_str()) {
continue;
}
let Some(mut guest) = guest(row) else { continue };
if guests.len() == MAX_GUESTS {
truncated = true;
break;
}
let path = format!("/nodes/{node}/{}/{}/config", guest.kind, guest.vmid);
if let Ok(config) = api.get(&path).await {
guest.macs = macs(&config);
guest.smbios_uuid = config["smbios1"].as_str().and_then(smbios_uuid);
} else {
truncated = true;
}
guests.push(guest);
}
guests.sort_by_key(|g| g.vmid);
let jobs = api.get("/cluster/backup").await?;
let mut backup_jobs = Vec::new();
for row in jobs.as_array().into_iter().flatten() {
if row["type"].as_str().is_some_and(|t| t != "vzdump") {
continue;
}
if backup_jobs.len() == MAX_JOBS {
truncated = true;
break;
}
let Some(mut job) = backup_job(row, &node, &guests) else { continue };
if job.enabled && let Some(schedule) = &job.schedule {
job.last_expected_run = last_expected_run(api, schedule, now).await;
}
backup_jobs.push(job);
}
let local: BTreeSet<u32> = guests.iter().map(|g| g.vmid).collect();
let not_backed_up = api.get("/cluster/backup-info/not-backed-up").await.ok()
.and_then(|v| v.as_array().cloned()).unwrap_or_default().iter()
.filter_map(|r| vmid(&r["vmid"])).filter(|id| local.contains(id))
.collect::<BTreeSet<_>>().into_iter().collect();
let since = now - SCHEDULE_LOOKBACK_SECONDS;
let tasks = api.get(&format!(
"/nodes/{node}/tasks?typefilter=vzdump&source=all&since={since}&limit={MAX_RUNS}"
)).await?;
let mut backup_runs = Vec::new();
for row in tasks.as_array().into_iter().flatten() {
let Some(mut run) = backup_run(row) else { continue };
if backup_runs.len() == MAX_RUNS {
truncated = true;
break;
}
let encoded = percent_encode(&run.upid);
match api.get(&format!("/nodes/{node}/tasks/{encoded}/log?start=0&limit={MAX_LOG_LINES}")).await {
Ok(log) => {
let lines: Vec<&str> = log.as_array().into_iter().flatten()
.filter_map(|l| l["t"].as_str()).collect();
run.guests = guest_results(&lines);
if run.guests.is_empty() {
// A single-guest task names its guest in the UPID.
if let (Some(id), "ok" | "warning") = (upid_vmid(&run.upid), run.status) {
run.guests.push(GuestResult { vmid: id, result: "ok" });
}
}
if lines.len() >= MAX_LOG_LINES {
truncated = true;
}
}
Err(_) => truncated = true,
}
backup_runs.push(run);
}
backup_runs.sort_by(|a, b| b.started_at.cmp(&a.started_at).then_with(|| a.upid.cmp(&b.upid)));
Ok((Proxmox { node, cluster, version, guests, backup_jobs, backup_runs, not_backed_up }, truncated))
}
/// The scheduler's own calendar evaluation, so no local schedule parser can disagree.
/// The API returns at most 100 occurrences, so frequent schedules use shorter windows.
async fn last_expected_run(api: &impl Api, schedule: &str, now: i64) -> Option<i64> {
for lookback in [SCHEDULE_LOOKBACK_SECONDS, 86_400, 7_200, 600] {
let path = format!(
"/cluster/jobs/schedule-analyze?schedule={}&starttime={}&iterations={SCHEDULE_ITERATIONS}",
percent_encode(schedule), now - lookback
);
let runs: Vec<i64> = api.get(&path).await.ok()?.as_array()?.iter()
.filter_map(|r| r["timestamp"].as_i64()).collect();
if runs.len() < SCHEDULE_ITERATIONS || runs.iter().any(|t| *t > now) {
return runs.into_iter().filter(|t| *t <= now).max();
}
}
None
}
/// Keep the newest information when the scope exceeds its wire budget.
fn fit(mut observation: Observation<Proxmox>) -> Observation<Proxmox> {
let size = |o: &Observation<Proxmox>| serde_json::to_vec(o).map(|b| b.len()).unwrap_or(usize::MAX);
while size(&observation) > OBSERVATION_MAX_BYTES - 1024 {
let Some(data) = observation.data.as_mut() else { break };
if data.backup_runs.len() > 8 {
data.backup_runs.pop();
} else if !data.guests.is_empty() {
data.guests.pop();
} else {
return failed("WIRE_SCOPE_LIMIT");
}
observation.truncated = true;
observation = observation.partial("PROXMOX_LIMIT");
}
observation
}
fn guest(row: &Value) -> Option<Guest> {
let kind = match row["type"].as_str()? {
"qemu" => "qemu",
"lxc" => "lxc",
_ => return None,
};
let vmid = vmid(&row["vmid"])?;
let name = row["name"].as_str().filter(|n| clean(n, 128)).unwrap_or("").to_owned();
Some(Guest {
vmid,
name: if name.is_empty() { format!("{kind}-{vmid}") } else { name },
kind,
status: row["status"].as_str().filter(|s| clean(s, 32)).unwrap_or("unknown").to_owned(),
template: flag(&row["template"]) == Some(true),
cpus: row["maxcpu"].as_f64().filter(|c| *c >= 0.0 && *c < 65536.0).map(|c| c.ceil() as u32),
memory_bytes: row["maxmem"].as_u64(),
disk_bytes: row["maxdisk"].as_u64(),
uptime_seconds: row["uptime"].as_u64(),
pool: row["pool"].as_str().filter(|p| clean(p, 64)).map(str::to_owned),
macs: Vec::new(),
smbios_uuid: None,
})
}
fn backup_job(row: &Value, node: &str, guests: &[Guest]) -> Option<BackupJob> {
let id = row["id"].as_str().filter(|s| clean(s, 64))?.to_owned();
let text = |key: &str, limit| row[key].as_str().filter(|s| clean(s, limit)).map(str::to_owned);
let list = |key: &str| -> BTreeSet<u32> {
row[key].as_str().unwrap_or("").split([',', ' ', ';'])
.filter_map(|s| s.trim().parse().ok()).collect()
};
let exclude = list("exclude");
let pool = text("pool", 64);
let vmids = list("vmid");
let all = flag(&row["all"]) == Some(true);
let selection = if all { "all" } else if pool.is_some() { "pool" } else { "vmid" };
let node_matches = row["node"].as_str().is_none_or(|n| n == node);
let covered_vmids = guests.iter()
.filter(|g| node_matches && !g.template)
.filter(|g| match selection {
"all" => !exclude.contains(&g.vmid),
"pool" => g.pool == pool,
_ => vmids.contains(&g.vmid),
})
.map(|g| g.vmid).collect();
Some(BackupJob {
id,
enabled: flag(&row["enabled"]).unwrap_or(true),
schedule: text("schedule", 128).or_else(|| {
// Pre-7.1 format: days of week plus start time.
let time = text("starttime", 16)?;
Some(text("dow", 64).map_or(time.clone(), |dow| format!("{dow} {time}")))
}),
storage: text("storage", 64),
mode: text("mode", 16),
selection,
covered_vmids,
next_run: row["next-run"].as_i64(),
last_expected_run: None,
})
}
fn backup_run(row: &Value) -> Option<BackupRun> {
let upid = row["upid"].as_str().filter(|s| clean(s, 160))?.to_owned();
let started_at = row["starttime"].as_i64()?;
let ended_at = row["endtime"].as_i64();
let raw = row["status"].as_str();
let (status, message) = match (ended_at, raw) {
(None, _) | (_, None) => ("running", None),
(Some(_), Some("OK")) => ("ok", None),
(Some(_), Some(s)) if s.starts_with("WARNINGS") => ("warning", Some(s)),
(Some(_), Some(s)) => ("error", Some(s)),
};
Some(BackupRun {
upid,
started_at,
ended_at,
status,
message: message.map(|m| truncate(m, 256)),
guests: Vec::new(),
})
}
/// vzdump task log lines; the last statement per guest wins.
pub fn guest_results(lines: &[&str]) -> Vec<GuestResult> {
let mut results = BTreeMap::new();
for line in lines {
let line = line.trim();
if let Some(rest) = line.strip_prefix("INFO: Finished Backup of VM ")
&& let Some(id) = leading_number(rest)
{
results.insert(id, "ok");
} else if let Some(rest) = line.strip_prefix("ERROR: Backup of VM ")
&& let Some(id) = leading_number(rest)
{
results.insert(id, "error");
}
}
results.into_iter().map(|(vmid, result)| GuestResult { vmid, result }).collect()
}
/// `netN` values: qemu `virtio=AA:..,bridge=..`; lxc `name=eth0,hwaddr=AA:..`.
pub fn macs(config: &Value) -> Vec<String> {
let mut found = BTreeSet::new();
if let Some(map) = config.as_object() {
for (key, value) in map {
let is_net = key.strip_prefix("net").is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()));
let Some(value) = value.as_str().filter(|_| is_net) else { continue };
for part in value.split(',') {
if let Some((_, candidate)) = part.split_once('=')
&& let Some(mac) = normalize_mac(candidate)
{
found.insert(mac);
}
}
}
}
found.into_iter().take(32).collect()
}
pub fn smbios_uuid(value: &str) -> Option<String> {
value.split(',').find_map(|part| part.strip_prefix("uuid="))
.and_then(|u| uuid::Uuid::parse_str(u.trim()).ok())
.filter(|u| !u.is_nil())
.map(|u| u.hyphenated().to_string())
}
pub fn normalize_mac(value: &str) -> Option<String> {
let parts: Vec<&str> = value.trim().split([':', '-']).collect();
(parts.len() == 6 && parts.iter().all(|p| p.len() == 2 && p.bytes().all(|b| b.is_ascii_hexdigit())))
.then(|| parts.join(":").to_ascii_lowercase())
.filter(|m| m != "00:00:00:00:00:00")
}
/// UPID:node:pid:pstart:starttime:type:id:user: — `id` is the vmid for single-guest runs.
fn upid_vmid(upid: &str) -> Option<u32> {
upid.split(':').nth(6).and_then(|id| id.parse().ok())
}
fn vmid(value: &Value) -> Option<u32> {
value.as_u64().or_else(|| value.as_str()?.parse().ok())
.filter(|id| (100..1_000_000_000).contains(id)).map(|id| id as u32)
}
fn flag(value: &Value) -> Option<bool> {
match value {
Value::Bool(b) => Some(*b),
Value::Number(n) => n.as_u64().map(|n| n != 0),
Value::String(s) => match s.as_str() { "1" | "true" => Some(true), "0" | "false" => Some(false), _ => None },
_ => None,
}
}
fn leading_number(text: &str) -> Option<u32> {
let digits: String = text.chars().take_while(char::is_ascii_digit).collect();
digits.parse().ok()
}
fn clean(s: &str, limit: usize) -> bool {
!s.trim().is_empty() && s.len() <= limit && !s.chars().any(char::is_control)
}
fn truncate(s: &str, limit: usize) -> String {
let s: String = s.chars().filter(|c| !c.is_control()).collect();
if s.len() <= limit {
return s;
}
let mut end = limit;
while !s.is_char_boundary(end) {
end -= 1;
}
s[..end].to_owned()
}
pub fn percent_encode(value: &str) -> String {
value.bytes().map(|b| if b.is_ascii_alphanumeric() || b"-_.~".contains(&b) {
(b as char).to_string()
} else {
format!("%{b:02X}")
}).collect()
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use std::collections::HashMap;
struct Fixture(HashMap<String, Value>);
impl Api for Fixture {
async fn get(&self, path: &str) -> anyhow::Result<Value> {
let key = path.split('?').next().unwrap();
self.0.get(path).or_else(|| self.0.get(key)).cloned()
.ok_or_else(|| anyhow::anyhow!("PROXMOX_HTTP_404"))
}
}
fn block<F: std::future::Future>(future: F) -> F::Output {
tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(future)
}
const NOW: i64 = 1_763_640_000;
const UPID_JOB: &str = "UPID:pve:00001234:00ABCDEF:691EE8A0:vzdump::root@pam:";
const UPID_ONE: &str = "UPID:pve:00001235:00ABCDF0:691EE000:vzdump:101:root@pam:";
fn fixture() -> Fixture {
let mut m = HashMap::new();
m.insert("/cluster/status".into(), json!([
{"type":"cluster","name":"lab"},
{"type":"node","name":"pve","local":1},
{"type":"node","name":"pve2","local":0}]));
m.insert("/version".into(), json!({"version":"9.2.4"}));
m.insert("/cluster/resources".into(), json!([
{"type":"qemu","vmid":100,"name":"debian","node":"pve","status":"running","maxcpu":2,"maxmem":1073741824u64,"maxdisk":10737418240u64,"uptime":42,"template":0},
{"type":"lxc","vmid":101,"name":"alpine","node":"pve","status":"stopped","maxcpu":1,"maxmem":134217728,"pool":"lab"},
{"type":"qemu","vmid":9000,"name":"tpl","node":"pve","status":"stopped","template":1},
{"type":"qemu","vmid":200,"name":"elsewhere","node":"pve2","status":"running"}]));
m.insert("/nodes/pve/qemu/100/config".into(), json!({
"net0":"virtio=BC:24:11:AA:BB:01,bridge=vmbr0,firewall=1",
"net1":"e1000=bc-24-11-aa-bb-02,bridge=vmbr1",
"smbios1":"uuid=6E1A2B3C-0000-4000-8000-0000000000AA",
"netmask":"virtio=BC:24:11:FF:FF:FF"}));
m.insert("/nodes/pve/lxc/101/config".into(), json!({
"net0":"name=eth0,bridge=vmbr0,hwaddr=BC:24:11:AA:BB:03,ip=dhcp,type=veth"}));
m.insert("/nodes/pve/qemu/9000/config".into(), json!({}));
m.insert("/cluster/backup".into(), json!([
{"id":"backup-a","type":"vzdump","schedule":"*/2:00","storage":"local","mode":"snapshot","vmid":"100,200","enabled":1,"next-run":NOW+3600},
{"id":"backup-all","type":"vzdump","schedule":"sat 03:00","all":1,"exclude":"100","enabled":0},
{"id":"backup-pool","type":"vzdump","dow":"mon,tue","starttime":"02:30","pool":"lab"},
{"id":"backup-other-node","type":"vzdump","schedule":"daily","all":1,"node":"pve2"}]));
m.insert("/cluster/jobs/schedule-analyze".into(), json!([
{"timestamp":NOW-7200},{"timestamp":NOW-1},{"timestamp":NOW+7199}]));
m.insert("/cluster/backup-info/not-backed-up".into(), json!([{"vmid":101},{"vmid":200}]));
m.insert("/nodes/pve/tasks".into(), json!([
{"upid":UPID_JOB,"starttime":NOW-600,"endtime":NOW-500,"status":"job errors"},
{"upid":UPID_ONE,"starttime":NOW-9000,"endtime":NOW-8900,"status":"OK"},
{"upid":"UPID:pve:1:2:3:vzdump::root@pam:","starttime":NOW-10}]));
m.insert(format!("/nodes/pve/tasks/{}/log", percent_encode(UPID_JOB)), json!([
{"n":1,"t":"INFO: starting new backup job: vzdump 100 101 --storage local"},
{"n":2,"t":"INFO: Starting Backup of VM 100 (qemu)"},
{"n":3,"t":"INFO: Finished Backup of VM 100 (00:00:12)"},
{"n":4,"t":"ERROR: Backup of VM 101 failed - storage full"}]));
m.insert(format!("/nodes/pve/tasks/{}/log", percent_encode(UPID_ONE)), json!([
{"n":1,"t":"INFO: Backup job finished successfully"}]));
m.insert("/nodes/pve/tasks/UPID%3Apve%3A1%3A2%3A3%3Avzdump%3A%3Aroot%40pam%3A/log".into(), json!([]));
Fixture(m)
}
#[test]
fn collects_local_guests_jobs_and_runs() {
let observation = block(collect(&fixture(), NOW));
assert_eq!(observation.quality, Quality::Valid);
let data = observation.data.unwrap();
assert_eq!(data.node, "pve");
assert_eq!(data.cluster.as_deref(), Some("lab"));
assert_eq!(data.guests.iter().map(|g| g.vmid).collect::<Vec<_>>(), [100, 101, 9000]);
let vm = &data.guests[0];
assert_eq!(vm.macs, ["bc:24:11:aa:bb:01", "bc:24:11:aa:bb:02"]);
assert_eq!(vm.smbios_uuid.as_deref(), Some("6e1a2b3c-0000-4000-8000-0000000000aa"));
assert_eq!(data.guests[1].macs, ["bc:24:11:aa:bb:03"]);
let jobs: BTreeMap<_, _> = data.backup_jobs.iter().map(|j| (j.id.as_str(), j)).collect();
assert_eq!(jobs["backup-a"].covered_vmids, [100]);
assert_eq!(jobs["backup-a"].last_expected_run, Some(NOW - 1));
assert!(!jobs["backup-all"].enabled);
assert_eq!(jobs["backup-all"].covered_vmids, [101]);
assert_eq!(jobs["backup-all"].last_expected_run, None);
assert_eq!(jobs["backup-pool"].schedule.as_deref(), Some("mon,tue 02:30"));
assert_eq!(jobs["backup-pool"].covered_vmids, [101]);
assert!(jobs["backup-other-node"].covered_vmids.is_empty());
assert_eq!(data.not_backed_up, [101]);
assert_eq!(data.backup_runs[0].status, "running");
assert_eq!(data.backup_runs[1].status, "error");
assert_eq!(data.backup_runs[1].guests,
[GuestResult { vmid: 100, result: "ok" }, GuestResult { vmid: 101, result: "error" }]);
assert_eq!(data.backup_runs[2].guests, [GuestResult { vmid: 101, result: "ok" }]);
}
#[test]
fn agent_document_passes_the_server_validator() {
let observation = block(collect(&fixture(), NOW));
let data = serde_json::to_value(observation.data.unwrap()).unwrap();
rmm_domain::inventory_document::proxmox::validate(&data).unwrap();
assert!(rmm_domain::inventory_document::proxmox::backup_status(&data).is_some());
}
#[test]
fn missing_local_node_or_api_is_an_error_observation() {
let observation = block(collect(&Fixture(HashMap::new()), NOW));
assert_eq!(observation.quality, Quality::Error);
assert_eq!(observation.error_code.as_deref(), Some("PROXMOX_HTTP_404"));
assert!(observation.data.is_none());
assert_eq!(not_configured().error_code.as_deref(), Some("PROXMOX_NOT_CONFIGURED"));
}
#[test]
fn oversized_observation_keeps_newest_runs_and_marks_truncation() {
let mut data = block(collect(&fixture(), NOW)).data.unwrap();
let guest = data.guests[0].clone();
data.guests = (0..512).map(|i| Guest { vmid: 100 + i, name: "x".repeat(120), ..guest.clone() }).collect();
let observation = fit(Observation::valid(SOURCE, data));
assert!(observation.truncated);
assert!(serde_json::to_vec(&observation).unwrap().len() <= OBSERVATION_MAX_BYTES);
assert_eq!(observation.data.unwrap().backup_runs.len(), 3);
}
#[test]
fn token_header_rejects_malformed_credentials() {
assert_eq!(token_header("rmm-agent@pve!inventory=0f3c-11\n").as_deref(),
Some("PVEAPIToken=rmm-agent@pve!inventory=0f3c-11"));
for bad in ["", "rmm-agent@pve=abc", "rmm-agent!x=abc", "a@pve!x=a b", "a@pve!x=a\r\nX: y"] {
assert!(token_header(bad).is_none(), "{bad}");
}
}
#[test]
fn mac_and_uuid_parsing_is_strict() {
assert_eq!(normalize_mac("BC:24:11:0a:0B:0c").as_deref(), Some("bc:24:11:0a:0b:0c"));
assert!(normalize_mac("bc:24:11:0a:0b").is_none());
assert!(normalize_mac("00:00:00:00:00:00").is_none());
assert!(smbios_uuid("manufacturer=QEMU").is_none());
assert!(smbios_uuid("uuid=00000000-0000-0000-0000-000000000000").is_none());
}
}
+2 -1
View File
@@ -27,7 +27,8 @@ pub fn apt_planning_metadata() -> Result<Vec<u8>> {
Ok(output.stdout)
}
/// Read-only local collection. No shell, package manager or hypervisor access.
/// Read-only local collection. No shell or package manager; Proxmox VE is read only
/// through its local API with a PVEAuditor token (`inventory::proxmox`).
pub fn collect() -> Result<Inventory> {
let os = fs::read_to_string("/etc/os-release").context("read OS release")?;
let hostname = fs::read_to_string("/proc/sys/kernel/hostname")?;
+11 -3
View File
@@ -7,6 +7,7 @@ mod certificate_rotation;
mod helper_sync;
mod https_channel;
mod jobs;
mod proxmox_api;
mod reconcile;
#[cfg(test)]
mod runtime_tests;
@@ -524,14 +525,21 @@ impl<C: reconcile::SyncClock> Agent<C> {
let extended = env::var("RMM_EXTENDED_INVENTORY").unwrap_or_else(|_| "1".into()) == "1";
let binding = self.binding.clone();
let catalog = self.catalog.cached(Utc::now());
let runtime = tokio::runtime::Handle::current();
tokio::task::spawn_blocking(move || {
let collected_at = Utc::now();
let result = rmm_agent_linux::wire::snapshot(extended).and_then(|mut inventory| {
if extended {
inventory["observations"]
let proxmox = runtime.block_on(proxmox_api::observation(
rmm_agent_linux::inventory::proxmox_ve(),
));
let scopes = inventory["observations"]
.as_array_mut()
.context("INVENTORY_OBSERVATIONS")?
.push(apt::planning_observation(binding.as_ref()));
.context("INVENTORY_OBSERVATIONS")?;
scopes.push(apt::planning_observation(binding.as_ref()));
if let Some(observation) = proxmox {
scopes.push(proxmox_api::wire(&observation)?);
}
inventory["collection_completed_at"] = serde_json::json!(Utc::now());
}
if let Some(report) = catalog {
+88
View File
@@ -0,0 +1,88 @@
//! Local, read-only Proxmox VE API client for the `linux.proxmox` observation.
//!
//! Only `https://127.0.0.1:8006` with the cluster CA copied by the installer. The
//! PVEAuditor token arrives as the systemd credential `rmm-proxmox-token`; it is never
//! logged, persisted by the agent or placed in an observation.
use anyhow::{Context, Result, ensure};
use reqwest::{Client, StatusCode};
use rmm_agent_linux::inventory::{Observation, proxmox};
use serde_json::Value;
use std::{path::PathBuf, time::Duration};
const BASE: &str = "https://127.0.0.1:8006/api2/json";
const CREDENTIAL: &str = "rmm-proxmox-token";
const DEFAULT_CA: &str = "/etc/rmm/pve-ca.pem";
const MAX_RESPONSE: usize = 2 * 1024 * 1024;
const TOTAL_BUDGET: Duration = Duration::from_secs(45);
struct LocalApi {
client: Client,
authorization: String,
}
impl proxmox::Api for LocalApi {
async fn get(&self, path: &str) -> Result<Value> {
ensure!(path.starts_with('/') && !path.contains(".."), "PROXMOX_PATH");
let mut response = self.client.get(format!("{BASE}{path}"))
.header(reqwest::header::AUTHORIZATION, &self.authorization)
.send().await.map_err(|_| anyhow::anyhow!("PROXMOX_UNREACHABLE"))?;
match response.status() {
StatusCode::OK => (),
StatusCode::UNAUTHORIZED => anyhow::bail!("PROXMOX_TOKEN_REJECTED"),
StatusCode::FORBIDDEN => anyhow::bail!("PROXMOX_PERMISSION_DENIED"),
status => anyhow::bail!("PROXMOX_HTTP_{}", status.as_u16()),
}
ensure!(response.content_length().is_none_or(|n| n <= MAX_RESPONSE as u64), "PROXMOX_RESPONSE_LIMIT");
let mut body = Vec::new();
while let Some(chunk) = response.chunk().await? {
ensure!(chunk.len() <= MAX_RESPONSE.saturating_sub(body.len()), "PROXMOX_RESPONSE_LIMIT");
body.extend_from_slice(&chunk);
}
let mut value: Value = serde_json::from_slice(&body).map_err(|_| anyhow::anyhow!("PROXMOX_API_SHAPE"))?;
Ok(value["data"].take())
}
}
fn credential_path() -> Option<PathBuf> {
std::env::var_os("CREDENTIALS_DIRECTORY").map(|d| PathBuf::from(d).join(CREDENTIAL))
}
fn client(ca: &[u8]) -> Result<Client> {
Ok(Client::builder()
.https_only(true)
.tls_built_in_root_certs(false)
.add_root_certificate(reqwest::Certificate::from_pem(ca)?)
.no_proxy()
.redirect(reqwest::redirect::Policy::none())
.connect_timeout(Duration::from_secs(5))
.timeout(Duration::from_secs(15))
.build()?)
}
/// `None` on hosts without Proxmox VE: no scope is reported there at all.
pub async fn observation(proxmox_ve: bool) -> Option<Observation<proxmox::Proxmox>> {
if !proxmox_ve {
return None;
}
let Some(token) = credential_path().and_then(|p| std::fs::read_to_string(p).ok()) else {
return Some(proxmox::not_configured());
};
let Some(authorization) = proxmox::token_header(&token) else {
return Some(proxmox::failed("PROXMOX_TOKEN_INVALID"));
};
let ca_path = std::env::var("RMM_PROXMOX_CA_FILE").unwrap_or_else(|_| DEFAULT_CA.into());
let api = match std::fs::read(&ca_path).context("ca").and_then(|ca| client(&ca)) {
Ok(client) => LocalApi { client, authorization },
Err(_) => return Some(proxmox::failed("PROXMOX_CA_UNAVAILABLE")),
};
let now = chrono::Utc::now().timestamp();
Some(tokio::time::timeout(TOTAL_BUDGET, proxmox::collect(&api, now)).await
.unwrap_or_else(|_| proxmox::failed("PROXMOX_TIMEOUT")))
}
/// Wire form with the scope label the server's `linux.base` validation expects.
pub fn wire(observation: &Observation<proxmox::Proxmox>) -> Result<Value> {
let mut value = serde_json::to_value(observation)?;
value["scope"] = Value::String("linux.proxmox".into());
Ok(value)
}
+6
View File
@@ -1,11 +1,13 @@
//! Additive bounded passive metadata; the strict original Inventory stays intact.
mod opnsense;
pub mod proxmox;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
pub const SOFTWARE_OBSERVATION_MAX_BYTES: usize = 128 * 1024;
pub const LINUX_SOFTWARE_OBSERVATION_MAX_BYTES: usize = 256 * 1024;
pub const PROXMOX_OBSERVATION_MAX_BYTES: usize = 128 * 1024;
pub fn firmware_identifier(value: &str) -> Option<String> {
let value = value.trim_matches(|c: char| c == '\0' || c.is_whitespace());
@@ -173,6 +175,7 @@ pub fn validate_for_scope(
for item in observations {
let max_bytes = match (scope, item["scope"].as_str()) {
("linux.base", Some("linux.software")) => LINUX_SOFTWARE_OBSERVATION_MAX_BYTES,
("linux.base", Some("linux.proxmox")) => PROXMOX_OBSERVATION_MAX_BYTES,
("windows.base", Some("windows.software")) => SOFTWARE_OBSERVATION_MAX_BYTES,
_ => 32768,
};
@@ -214,6 +217,9 @@ pub fn validate_for_scope(
return Err("INVALID_AGENT_UPDATE_CATALOG_REPORT");
}
}
if o.scope == "linux.proxmox" && o.quality == "valid" {
proxmox::validate(&o.data)?;
}
if !o.scope.starts_with(prefix)
|| o.scope.len() > 64
|| !(o
@@ -0,0 +1,257 @@
//! Strict `linux.proxmox` wire document and the deterministic backup evaluation.
//! The agent reports raw scheduler data; whether every scheduled backup ran is
//! decided here so the server, API and UI share one rule.
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::collections::{BTreeMap, BTreeSet};
/// Runs that start shortly before the computed due time still count (clock skew).
const START_TOLERANCE_SECONDS: i64 = 120;
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Proxmox {
pub node: String,
pub cluster: Option<String>,
pub version: Option<String>,
pub guests: Vec<Guest>,
pub backup_jobs: Vec<BackupJob>,
pub backup_runs: Vec<BackupRun>,
pub not_backed_up: Vec<u32>,
}
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Guest {
pub vmid: u32,
pub name: String,
pub kind: String,
pub status: String,
pub template: bool,
pub cpus: Option<u32>,
pub memory_bytes: Option<u64>,
pub disk_bytes: Option<u64>,
pub uptime_seconds: Option<u64>,
pub pool: Option<String>,
pub macs: Vec<String>,
pub smbios_uuid: Option<String>,
}
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct BackupJob {
pub id: String,
pub enabled: bool,
pub schedule: Option<String>,
pub storage: Option<String>,
pub mode: Option<String>,
pub selection: String,
pub covered_vmids: Vec<u32>,
pub next_run: Option<i64>,
pub last_expected_run: Option<i64>,
}
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct BackupRun {
pub upid: String,
pub started_at: i64,
pub ended_at: Option<i64>,
pub status: String,
pub message: Option<String>,
pub guests: Vec<GuestResult>,
}
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct GuestResult {
pub vmid: u32,
pub result: String,
}
fn clean(s: &str, limit: usize) -> bool {
!s.trim().is_empty() && s.len() <= limit && !s.chars().any(char::is_control)
}
fn opt(s: &Option<String>, limit: usize) -> bool {
s.as_deref().is_none_or(|s| clean(s, limit))
}
pub fn is_mac(s: &str) -> bool {
s.len() == 17 && s.split(':').count() == 6
&& s.split(':').all(|p| p.len() == 2 && p.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
}
fn vmid(id: u32) -> bool {
(100..1_000_000_000).contains(&id)
}
/// Validates the `data` member of a valid `linux.proxmox` observation.
pub fn validate(data: &Value) -> Result<(), &'static str> {
let err = "INVALID_PROXMOX_OBSERVATION";
let p: Proxmox = serde_json::from_value(data.clone()).map_err(|_| err)?;
let guests_ok = p.guests.len() <= 512 && p.guests.iter().all(|g| {
vmid(g.vmid) && clean(&g.name, 128) && matches!(g.kind.as_str(), "qemu" | "lxc")
&& clean(&g.status, 32) && opt(&g.pool, 64) && g.macs.len() <= 32
&& g.macs.iter().all(|m| is_mac(m))
&& g.smbios_uuid.as_deref().is_none_or(|u| uuid::Uuid::parse_str(u).is_ok_and(|x| x.hyphenated().to_string() == u))
}) && p.guests.windows(2).all(|w| w[0].vmid < w[1].vmid);
let jobs_ok = p.backup_jobs.len() <= 64 && p.backup_jobs.iter().all(|j| {
clean(&j.id, 64) && opt(&j.schedule, 128) && opt(&j.storage, 64) && opt(&j.mode, 16)
&& matches!(j.selection.as_str(), "all" | "pool" | "vmid")
&& j.covered_vmids.len() <= 512 && j.covered_vmids.iter().all(|id| vmid(*id))
});
let runs_ok = p.backup_runs.len() <= 64 && p.backup_runs.iter().all(|r| {
clean(&r.upid, 160) && r.upid.starts_with("UPID:") && r.started_at > 0
&& r.ended_at.is_none_or(|e| e >= r.started_at)
&& matches!(r.status.as_str(), "ok" | "warning" | "error" | "running")
&& (r.status == "running") == r.ended_at.is_none()
&& opt(&r.message, 256) && r.guests.len() <= 512
&& r.guests.iter().all(|g| vmid(g.vmid) && matches!(g.result.as_str(), "ok" | "error"))
});
if !clean(&p.node, 64) || !opt(&p.cluster, 64) || !opt(&p.version, 32)
|| !guests_ok || !jobs_ok || !runs_ok
|| p.not_backed_up.len() > 512 || !p.not_backed_up.iter().all(|id| vmid(*id))
{
return Err(err);
}
Ok(())
}
/// Status per job and guest plus the overall answer "did every scheduled backup run?".
/// job: ok | failed | missed | running | pending (not yet due) | disabled | unknown
pub fn backup_status(data: &Value) -> Option<Value> {
let p: Proxmox = serde_json::from_value(data.clone()).ok()?;
let mut last_success: BTreeMap<u32, i64> = BTreeMap::new();
for run in &p.backup_runs {
for g in run.guests.iter().filter(|g| g.result == "ok") {
let at = run.ended_at.unwrap_or(run.started_at);
last_success.entry(g.vmid).and_modify(|t| *t = (*t).max(at)).or_insert(at);
}
}
let mut jobs = Vec::new();
let mut all_ran = true;
let mut problems = 0usize;
for job in &p.backup_jobs {
let mut guests = Vec::new();
let status = if !job.enabled {
"disabled"
} else if job.schedule.is_none() {
"unknown"
} else if let Some(due) = job.last_expected_run {
let since = due - START_TOLERANCE_SECONDS;
let window: Vec<&BackupRun> = p.backup_runs.iter().filter(|r| r.started_at >= since).collect();
let running = window.iter().any(|r| r.status == "running");
let mut states = BTreeSet::new();
for id in &job.covered_vmids {
// Newest statement about this guest inside the due window wins.
let result = window.iter()
.filter_map(|r| r.guests.iter().find(|g| g.vmid == *id).map(|g| (r.started_at, g.result.as_str())))
.max_by_key(|(at, _)| *at).map(|(_, r)| r);
let state = match (result, running) {
(Some("ok"), _) => "ok",
(Some(_), _) => "failed",
(None, true) => "running",
(None, false) => "missed",
};
states.insert(state);
guests.push(json!({"vmid":id,"status":state,"last_success_at":last_success.get(id)}));
}
if states.contains("failed") { "failed" }
else if states.contains("missed") { "missed" }
else if states.contains("running") { "running" }
else { "ok" }
} else {
"pending"
};
if matches!(status, "failed" | "missed" | "unknown") {
all_ran = false;
problems += 1;
}
jobs.push(json!({"id":job.id,"status":status,"last_expected_run":job.last_expected_run,
"next_run":job.next_run,"guests":guests}));
}
let enabled = p.backup_jobs.iter().filter(|j| j.enabled).count();
Some(json!({
"all_scheduled_backups_ran": if enabled == 0 { Value::Null } else { Value::Bool(all_ran) },
"enabled_jobs": enabled,
"problem_jobs": problems,
"jobs": jobs,
"last_success_at": last_success,
}))
}
#[cfg(test)]
mod tests {
use super::*;
fn sample() -> Value {
json!({"node":"pve","cluster":null,"version":"9.2.2",
"guests":[
{"vmid":100,"name":"debian","kind":"qemu","status":"running","template":false,"cpus":1,
"memory_bytes":1,"disk_bytes":1,"uptime_seconds":5,"pool":null,
"macs":["bc:24:11:88:35:97"],"smbios_uuid":"787f4ae9-446f-4fac-b3d8-4074170bf823"},
{"vmid":101,"name":"alpine","kind":"lxc","status":"running","template":false,"cpus":1,
"memory_bytes":1,"disk_bytes":1,"uptime_seconds":5,"pool":null,"macs":[],"smbios_uuid":null}],
"backup_jobs":[
{"id":"a","enabled":true,"schedule":"*/2:00","storage":"local","mode":"snapshot",
"selection":"vmid","covered_vmids":[100],"next_run":2000,"last_expected_run":1000},
{"id":"b","enabled":true,"schedule":"daily","storage":"local","mode":"snapshot",
"selection":"all","covered_vmids":[100,101],"next_run":5000,"last_expected_run":900},
{"id":"c","enabled":false,"schedule":"daily","storage":null,"mode":null,
"selection":"all","covered_vmids":[101],"next_run":null,"last_expected_run":null},
{"id":"d","enabled":true,"schedule":"sat 03:00","storage":null,"mode":null,
"selection":"vmid","covered_vmids":[101],"next_run":9000,"last_expected_run":null}],
"backup_runs":[
{"upid":"UPID:pve:1:2:3:vzdump::root@pam:","started_at":1001,"ended_at":1050,"status":"error",
"message":"job errors","guests":[{"vmid":100,"result":"ok"},{"vmid":101,"result":"error"}]},
{"upid":"UPID:pve:1:2:4:vzdump:100:root@pam:","started_at":100,"ended_at":120,"status":"ok",
"message":null,"guests":[{"vmid":100,"result":"ok"}]}],
"not_backed_up":[]})
}
#[test]
fn accepts_agent_shape_and_rejects_unsafe_values() {
assert!(validate(&sample()).is_ok());
for (pointer, bad) in [
("/guests/0/macs/0", json!("BC:24:11:88:35:97")),
("/guests/0/kind", json!("docker")),
("/guests/0/vmid", json!(5)),
("/guests/0/smbios_uuid", json!("not-a-uuid")),
("/backup_runs/0/status", json!("running")),
("/backup_jobs/0/selection", json!("tag")),
("/node", json!("pve\nX")),
] {
let mut doc = sample();
*doc.pointer_mut(pointer).unwrap() = bad;
assert!(validate(&doc).is_err(), "{pointer}");
}
let mut doc = sample();
doc["extra"] = json!(1);
assert!(validate(&doc).is_err());
}
#[test]
fn evaluates_due_runs_per_job_and_guest() {
let status = backup_status(&sample()).unwrap();
let jobs: BTreeMap<String, Value> = status["jobs"].as_array().unwrap().iter()
.map(|j| (j["id"].as_str().unwrap().to_owned(), j.clone())).collect();
assert_eq!(jobs["a"]["status"], "ok");
assert_eq!(jobs["b"]["status"], "failed");
assert_eq!(jobs["b"]["guests"][1]["status"], "failed");
assert_eq!(jobs["c"]["status"], "disabled");
assert_eq!(jobs["d"]["status"], "pending");
assert_eq!(status["all_scheduled_backups_ran"], false);
assert_eq!(status["last_success_at"]["100"], 1050);
}
#[test]
fn missing_and_running_runs_are_distinguished() {
let mut doc = sample();
doc["backup_runs"] = json!([]);
let status = backup_status(&doc).unwrap();
assert_eq!(status["jobs"][0]["status"], "missed");
doc["backup_runs"] = json!([{"upid":"UPID:pve:9:9:9:vzdump::root@pam:","started_at":1000,
"ended_at":null,"status":"running","message":null,"guests":[]}]);
assert_eq!(backup_status(&doc).unwrap()["jobs"][0]["status"], "running");
doc["backup_jobs"] = json!([]);
assert!(backup_status(&doc).unwrap()["all_scheduled_backups_ran"].is_null());
}
}
+3
View File
@@ -190,6 +190,9 @@ pub async fn ingest(
.fetch_one(&mut *tx)
.await?;
ensure!(stored == hash, "message identity conflict");
if matches!(s.scope.as_str(), "linux.base" | "windows.base") {
crate::proxmox_links::reconcile(&mut tx, tenant).await;
}
}
Some(Payload::JobAccepted(_) | Payload::JobStateChanged(_) | Payload::JobResult(_)) => {
crate::job_gateway::event(&mut tx, tenant, agent, e).await?
+47
View File
@@ -494,6 +494,52 @@ def provision_serial_credential():
save(dropin, content)
def provision_proxmox_credential():
# Proxmox VE hosts: a dedicated read-only API token (PVEAuditor) lets the
# unprivileged agent list guests and backup jobs. The secret is only shown by
# Proxmox at creation, so an existing token without a local copy is rotated.
pveum = Path('/usr/sbin/pveum')
if not (Path('/usr/bin/pveversion').is_file() and pveum.is_file()):
return
user, name = 'rmm-discovery@pve', 'inventory'
target, ca = ROOT / 'proxmox-token', ROOT / 'pve-ca.pem'
dropin = UNIT_DIR / (SERVICE + '.d') / '41-proxmox-api.conf'
content = f'[Service]\nLoadCredential=rmm-proxmox-token:{target}\nEnvironment=RMM_PROXMOX_CA_FILE={ca}\n'.encode()
require(not dropin.parent.is_symlink(), 'proxmox credential directory conflict')
def pve(*args):
return subprocess.run([str(pveum), *args], check=True, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, timeout=60).stdout
try:
save(ca, Path('/etc/pve/pve-root-ca.pem').read_bytes(), 0o644)
current = target.read_text().strip() if target.is_file() else ''
if not current.startswith(f'{user}!{name}='):
users = json.loads(pve('user', 'list', '--output-format', 'json'))
if not any(u.get('userid') == user for u in users):
pve('user', 'add', user, '--comment', 'Rust Discovery inventory (read-only)')
tokens = json.loads(pve('user', 'token', 'list', user, '--output-format', 'json'))
if any(t.get('tokenid') == name for t in tokens):
pve('user', 'token', 'remove', user, name)
created = json.loads(pve('user', 'token', 'add', user, name, '--privsep', '1',
'--comment', 'Rust Discovery agent', '--output-format', 'json'))
secret = created['value']
require(re.fullmatch('[0-9a-f-]{36}', secret), 'unexpected proxmox token format')
save(target, f'{user}!{name}={secret}\n'.encode(), 0o600)
# A privilege-separated token holds the intersection of user and token rights.
pve('acl', 'modify', '/', '--users', user, '--roles', 'PVEAuditor')
pve('acl', 'modify', '/', '--tokens', f'{user}!{name}', '--roles', 'PVEAuditor')
except (OSError, ValueError, KeyError, subprocess.SubprocessError):
print('Proxmox VE read access could not be prepared; guest and backup inventory stays unavailable',
file=sys.stderr)
return
if dropin.exists() or dropin.is_symlink():
require(not dropin.is_symlink() and dropin.read_bytes() == content, 'proxmox credential configuration conflict')
else:
dropin.parent.mkdir(mode=0o755, exist_ok=True)
save(dropin, content)
def enable():
for name, data in units().items():
path = UNIT_DIR / name
@@ -502,6 +548,7 @@ def enable():
else:
save(path, data.encode())
provision_serial_credential()
provision_proxmox_credential()
service('daemon-reload')
service('enable', '--now', SERVICE)
+23 -9
View File
@@ -208,6 +208,9 @@ struct HypervisorAssignment {
// null clears the relation. A missing field is a malformed update.
#[serde(deserialize_with = "required_hypervisor_value")]
hypervisor_asset_id: Option<Uuid>,
/// true hands the decision back to automatic Proxmox detection (requires null id).
#[serde(default)]
automatic: bool,
}
fn required_hypervisor_value<'de, D: serde::Deserializer<'de>>(value: D) -> Result<Option<Uuid>, D::Error> {
@@ -227,24 +230,35 @@ async fn assign_hypervisor(
// Match the asset lock order for simultaneous edits of the same two devices.
let ids = [asset, input.hypervisor_asset_id.unwrap_or(asset)];
let rows: Vec<(Uuid, Option<Uuid>)> = sqlx::query_as(
"SELECT asset_id,hypervisor_asset_id FROM assets
if input.automatic && input.hypervisor_asset_id.is_some() {
return Err(Error(StatusCode::UNPROCESSABLE_ENTITY, "AUTOMATIC_REQUIRES_NULL_HYPERVISOR"));
}
let rows: Vec<(Uuid, Option<Uuid>, Option<String>)> = sqlx::query_as(
"SELECT asset_id,hypervisor_asset_id,hypervisor_source FROM assets
WHERE tenant_id=$1 AND asset_id=ANY($2) ORDER BY asset_id FOR UPDATE",
)
.bind(tenant).bind(ids.as_slice()).fetch_all(&mut *tx).await?;
let previous = rows.into_iter().find(|(id, _)| *id == asset)
.ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?.1;
let (_, previous, previous_source) = rows.into_iter().find(|(id, _, _)| *id == asset)
.ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?;
crate::devices::validate_vm_host_assignment(
&mut tx, tenant, asset, pair.agent_id, input.hypervisor_asset_id,
).await?;
if previous != input.hypervisor_asset_id {
sqlx::query("UPDATE assets SET hypervisor_asset_id=$3 WHERE tenant_id=$1 AND asset_id=$2")
.bind(tenant).bind(asset).bind(input.hypervisor_asset_id).execute(&mut *tx).await?;
let source = (!input.automatic).then_some("manual");
if previous != input.hypervisor_asset_id || previous_source.as_deref() != source {
sqlx::query("UPDATE assets SET hypervisor_asset_id=$3,hypervisor_source=$4 WHERE tenant_id=$1 AND asset_id=$2")
.bind(tenant).bind(asset).bind(input.hypervisor_asset_id).bind(source).execute(&mut *tx).await?;
audit(&mut tx, &p, EVENT, json!({"asset_id":asset,"agent_id":pair.agent_id,
"previous_hypervisor_asset_id":previous,"hypervisor_asset_id":input.hypervisor_asset_id})).await?;
"previous_hypervisor_asset_id":previous,"hypervisor_asset_id":input.hypervisor_asset_id,
"previous_source":previous_source,"source":source.unwrap_or("automatic")})).await?;
}
if input.automatic {
crate::proxmox_links::reconcile(&mut tx, tenant).await;
}
let (current, current_source): (Option<Uuid>, Option<String>) = sqlx::query_as(
"SELECT hypervisor_asset_id,hypervisor_source FROM assets WHERE tenant_id=$1 AND asset_id=$2")
.bind(tenant).bind(asset).fetch_one(&mut *tx).await?;
tx.commit().await?;
Ok(Json(json!({"asset_id":asset,"hypervisor_asset_id":input.hypervisor_asset_id})))
Ok(Json(json!({"asset_id":asset,"hypervisor_asset_id":current,"hypervisor_source":current_source})))
}
async fn remove_device(
+1 -1
View File
@@ -3,7 +3,7 @@ WITH classified AS (
a.last_authenticated_at,a.last_authenticated_certificate_sha256,a.certificate_sha256,
a.enrollment_generation,a.assignment_version,a.capabilities,a.reported_agent_version,
a.system_usage,a.system_usage_observed_at,
asset.archived_at,asset.hypervisor_asset_id,asset.purpose,t.name AS customer_name,
asset.archived_at,asset.hypervisor_asset_id,asset.hypervisor_source,asset.purpose,t.name AS customer_name,
CASE
WHEN a.revoked_at IS NOT NULL THEN 'revoked'
WHEN asset.archived_at IS NOT NULL THEN 'archived'
+134
View File
@@ -261,6 +261,12 @@ pub async fn detail(
.ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?;
let hosts = assigned_hosts(&mut tx, tenant, now, std::slice::from_ref(&row)).await?;
let mut item = project(&row, now, true, &hosts);
if item["proxmox"]["data"].is_object() {
let rows: Vec<(Uuid, Uuid, Option<String>, Option<String>, Value)> =
sqlx::query_as(include_str!("proxmox_guest_devices.sql"))
.bind(tenant).bind(asset).fetch_all(&mut *tx).await?;
item["proxmox"]["guest_devices"] = proxmox_guest_devices(&item["proxmox"]["data"], &rows);
}
item["recent_jobs"] = if p.permits_scope("operations:read")
&& crate::permissions::allowed(&mut tx, &p.name, "operations:read").await?
{
@@ -282,6 +288,25 @@ pub async fn detail(
Ok(Json(item))
}
/// Linked devices per reported guest, matched by the MACs both sides report.
fn proxmox_guest_devices(
data: &Value,
rows: &[(Uuid, Uuid, Option<String>, Option<String>, Value)],
) -> Value {
let mut result = Vec::new();
for guest in data["guests"].as_array().into_iter().flatten() {
let macs: Vec<&str> = guest["macs"].as_array().into_iter().flatten()
.filter_map(Value::as_str).collect();
let linked = rows.iter().find(|(_, _, _, _, device)| device.as_array().into_iter().flatten()
.filter_map(Value::as_str).any(|m| macs.contains(&m)));
if let (Some(vmid), Some((asset_id, agent_id, source, hostname, _))) = (guest["vmid"].as_u64(), linked) {
result.push(json!({"vmid":vmid,"asset_id":asset_id,"agent_id":agent_id,
"hostname":hostname,"source":source}));
}
}
Value::Array(result)
}
fn observed<'a>(data: &'a Value, scope: &str) -> &'a Value {
data["observations"]
.as_array()
@@ -569,12 +594,33 @@ fn project(row: &PgRow, now: DateTime<Utc>, full: bool, hosts: &HashMap<Uuid, Ho
} else { Value::Null };
item["disks_truncated"] = json!(scope["truncated"] == true);
}
if let Some(scope) = data["observations"].as_array().and_then(|scopes|
scopes.iter().find(|s| s["scope"] == "linux.proxmox")) {
let status = (scope["quality"] == "valid")
.then(|| rmm_domain::inventory_document::proxmox::backup_status(&scope["data"]))
.flatten();
item["proxmox_backup"] = status.as_ref().map_or(Value::Null, |s| json!({
"all_scheduled_backups_ran":s["all_scheduled_backups_ran"],
"problem_jobs":s["problem_jobs"],"enabled_jobs":s["enabled_jobs"]}));
if full {
item["proxmox"] = json!({
"quality":scope["quality"],"error_code":scope["error_code"],
"observed_at":scope["observed_at"],"truncated":scope["truncated"],
"data":if scope["quality"] == "valid" { scope["data"].clone() } else { Value::Null },
"backup_status":status,"guest_devices":[]});
}
}
if device_type == Some(DeviceType::Virtual) && row.get::<String, _>("lifecycle") == "current" {
let assigned_id: Option<Uuid> = row.get("hypervisor_asset_id");
let assigned = assigned_id.and_then(|id| hosts.get(&id));
item["hypervisor"] = hypervisor_display(&data, assigned);
let source = row.get::<Option<String>, _>("hypervisor_source");
if item["hypervisor"]["kind"] == "device" {
item["hypervisor"]["source"] = json!(source);
}
if full {
item["assigned_hypervisor_asset_id"] = json!(assigned_id);
item["hypervisor_source"] = json!(source);
}
}
if full {
@@ -668,6 +714,94 @@ mod tests {
assert!(hypervisor_display(&data, None).is_null());
}
#[tokio::test]
#[ignore = "requires the disposable RLS database from tests/local_access_database.py"]
async fn proxmox_guest_macs_link_vms_automatically_but_never_override_people() {
let admin = sqlx::PgPool::connect(&std::env::var("RMM_TEST_REPAIR_ADMIN_URL").unwrap())
.await.unwrap();
let app = sqlx::PgPool::connect(&std::env::var("RMM_TEST_REPAIR_APP_URL").unwrap())
.await.unwrap();
let (tenant, other) = (Uuid::new_v4(), Uuid::new_v4());
let (host, vm, manual_vm, foreign_vm, twin_a, twin_b) =
(Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4());
for customer in [tenant, other] {
sqlx::query("INSERT INTO tenants(tenant_id,name) VALUES($1,'Proxmox link test')")
.bind(customer).execute(&admin).await.unwrap();
}
let guests = |macs: &[&str]| json!({"node":"pve","guests":macs.iter().enumerate().map(|(i, m)|
json!({"vmid":100 + i,"macs":[m]})).collect::<Vec<_>>()});
let device = |kind: &str, mac: &str, proxmox: Option<Value>| {
let mut scopes = vec![
json!({"scope":"linux.hardware","quality":"valid","data":{"device_type":kind}}),
json!({"scope":"linux.interfaces","quality":"valid","data":[{"name":"eth0","mac":mac}]}),
];
if let Some(data) = proxmox {
scopes.push(json!({"scope":"linux.proxmox","quality":"valid","data":data}));
}
json!({"hostname":"h","os":"Debian","root_available_bytes":1,"root_total_bytes":2,"observations":scopes})
};
let insert = |customer: Uuid, id: Uuid, data: Value, sequence: i64| {
let admin = admin.clone();
async move {
sqlx::query("INSERT INTO observations(tenant_id,agent_id,message_id,boot_id,sequence,observed_at,source_id,quality,completeness,snapshot_id,data,payload_sha256) VALUES($1,$2,$3,$4,$5,now(),'linux.base','valid','partial',$6,$7,$8)")
.bind(customer).bind(id).bind(Uuid::new_v4()).bind(Uuid::new_v4()).bind(sequence)
.bind(Uuid::new_v4()).bind(data).bind("0".repeat(64)).execute(&admin).await.unwrap();
}
};
let all = ["bc:24:11:00:00:01", "bc:24:11:00:00:02", "bc:24:11:00:00:03", "bc:24:11:00:00:04"];
for (customer, id, data) in [
(tenant, host, device("hypervisor", "52:54:00:00:00:99", Some(guests(&all)))),
(tenant, vm, device("virtual", "BC:24:11:00:00:01", None)),
(tenant, manual_vm, device("virtual", "bc:24:11:00:00:02", None)),
(other, foreign_vm, device("virtual", "bc:24:11:00:00:03", None)),
(tenant, twin_a, device("virtual", "bc:24:11:00:00:04", None)),
(tenant, twin_b, device("virtual", "bc:24:11:00:00:04", None)),
] {
sqlx::query("INSERT INTO assets(tenant_id,asset_id) VALUES($1,$2)")
.bind(customer).bind(id).execute(&admin).await.unwrap();
sqlx::query("INSERT INTO agent_installations(tenant_id,asset_id,agent_id,certificate_sha256,last_contact_at,last_authenticated_at,last_authenticated_certificate_sha256) VALUES($1,$2,$2,$3,now(),now(),$3)")
.bind(customer).bind(id).bind(rmm_domain::jobs::hash(format!("{customer}:{id}").as_bytes()))
.execute(&admin).await.unwrap();
insert(customer, id, data, 1).await;
}
sqlx::query("UPDATE assets SET hypervisor_source='manual' WHERE asset_id=$1")
.bind(manual_vm).execute(&admin).await.unwrap();
let link = |id: Uuid| {
let admin = admin.clone();
async move {
sqlx::query_as::<_, (Option<Uuid>, Option<String>)>(
"SELECT hypervisor_asset_id,hypervisor_source FROM assets WHERE asset_id=$1")
.bind(id).fetch_one(&admin).await.unwrap()
}
};
let mut tx = rmm_persistence::tenant_tx(&app, tenant).await.unwrap();
crate::proxmox_links::reconcile(&mut tx, tenant).await;
tx.commit().await.unwrap();
assert_eq!(link(vm).await, (Some(host), Some("proxmox".into())));
assert_eq!(link(manual_vm).await, (None, Some("manual".into())));
assert_eq!(link(foreign_vm).await, (None, None));
assert_eq!(link(twin_a).await, (None, None), "duplicate MACs are ambiguous");
let audits: i64 = sqlx::query_scalar("SELECT count(*) FROM audit_events WHERE tenant_id=$1 AND event_type='device_hypervisor_detected'")
.bind(tenant).fetch_one(&admin).await.unwrap();
assert_eq!(audits, 1);
// Idempotent: a second pass changes nothing.
let mut tx = rmm_persistence::tenant_tx(&app, tenant).await.unwrap();
crate::proxmox_links::reconcile(&mut tx, tenant).await;
tx.commit().await.unwrap();
let audits: i64 = sqlx::query_scalar("SELECT count(*) FROM audit_events WHERE tenant_id=$1")
.bind(tenant).fetch_one(&admin).await.unwrap();
assert_eq!(audits, 1);
// The guest left the host: the automatic link is released.
insert(tenant, host, device("hypervisor", "52:54:00:00:00:99", Some(guests(&all[1..]))), 2).await;
let mut tx = rmm_persistence::tenant_tx(&app, tenant).await.unwrap();
crate::proxmox_links::reconcile(&mut tx, tenant).await;
tx.commit().await.unwrap();
assert_eq!(link(vm).await, (None, None));
}
#[tokio::test]
#[ignore = "requires the disposable RLS database from tests/local_access_database.py"]
async fn host_links_resolve_outside_the_page_and_stay_inside_the_customer() {
+1
View File
@@ -27,6 +27,7 @@ mod monitoring;
mod oidc;
mod pagination;
mod permissions;
mod proxmox_links;
mod root_policy;
mod managed_scripts;
mod scheduler;
@@ -0,0 +1,28 @@
-- Current devices of customer $1 linked to host $2, with the MACs they report themselves.
SELECT asset.asset_id, inst.agent_id, asset.hypervisor_source,
inventory.data->>'hostname' AS hostname,
COALESCE((
SELECT jsonb_agg(DISTINCT lower(i->>'mac'))
FROM jsonb_array_elements(CASE WHEN jsonb_typeof(inventory.data->'observations')='array'
THEN inventory.data->'observations' ELSE '[]'::jsonb END) o,
jsonb_array_elements(CASE
WHEN jsonb_typeof(o->'data')='array' THEN o->'data'
WHEN jsonb_typeof(o#>'{data,entries}')='array' THEN o#>'{data,entries}'
ELSE '[]'::jsonb END) i
WHERE o->>'scope' IN ('linux.interfaces','windows.interfaces') AND o->>'quality'='valid'
AND i->>'mac' IS NOT NULL
), '[]'::jsonb) AS macs
FROM assets asset
JOIN LATERAL (
SELECT a.agent_id, a.revoked_at FROM agent_installations a
WHERE a.tenant_id=asset.tenant_id AND a.asset_id=asset.asset_id AND NOT a.customer_transfer_pending
ORDER BY a.enrollment_generation DESC, a.created_at DESC, a.agent_id LIMIT 1
) inst ON inst.revoked_at IS NULL
LEFT JOIN LATERAL (
SELECT data FROM observations
WHERE tenant_id=asset.tenant_id AND agent_id=inst.agent_id AND source_id IN ('linux.base','windows.base')
ORDER BY observed_at DESC, received_at DESC, sequence DESC LIMIT 1
) inventory ON true
WHERE asset.tenant_id=$1 AND asset.hypervisor_asset_id=$2 AND asset.archived_at IS NULL
ORDER BY asset.asset_id
LIMIT 1024
+24
View File
@@ -0,0 +1,24 @@
//! Automatic VM -> Proxmox host mapping from the hosts' `linux.proxmox` guest lists.
//! Runs inside the ingesting customer transaction behind a savepoint: a failed
//! reconciliation never blocks acknowledging the inventory snapshot itself.
use sqlx::{Acquire, Postgres, Transaction};
use uuid::Uuid;
pub async fn reconcile(tx: &mut Transaction<'_, Postgres>, tenant: Uuid) {
let result = async {
let mut savepoint = tx.begin().await?;
let events: Vec<Uuid> = sqlx::query_scalar(include_str!("proxmox_links.sql"))
.bind(tenant)
.fetch_all(&mut *savepoint)
.await?;
savepoint.commit().await?;
Ok::<_, sqlx::Error>(events.len())
}
.await;
match result {
Ok(0) => (),
Ok(changed) => eprintln!("proxmox guest links updated: {changed}"),
// Database detail stays out of the log line; the snapshot is still acknowledged.
Err(_) => eprintln!("proxmox guest link reconciliation skipped"),
}
}
+103
View File
@@ -0,0 +1,103 @@
-- Automatic VM -> Proxmox host links for one customer ($1). A link is set only for a
-- unique MAC match between a host's current guest list and a current virtual device of
-- the same customer. Manual decisions (hypervisor_source='manual') are never touched.
WITH current_installation AS (
SELECT asset.asset_id, asset.hypervisor_asset_id, asset.hypervisor_source, inst.agent_id
FROM assets asset
JOIN LATERAL (
SELECT a.agent_id, a.revoked_at
FROM agent_installations a
WHERE a.tenant_id=asset.tenant_id AND a.asset_id=asset.asset_id
AND NOT a.customer_transfer_pending
AND a.last_authenticated_at IS NOT NULL
ORDER BY a.enrollment_generation DESC, a.created_at DESC, a.agent_id
LIMIT 1
) inst ON inst.revoked_at IS NULL
WHERE asset.tenant_id=$1 AND asset.archived_at IS NULL
),
latest AS (
SELECT c.*, inventory.data
FROM current_installation c
JOIN LATERAL (
SELECT data FROM observations
WHERE tenant_id=$1 AND agent_id=c.agent_id AND source_id IN ('linux.base','windows.base')
ORDER BY observed_at DESC, received_at DESC, sequence DESC
LIMIT 1
) inventory ON true
),
scopes AS (
SELECT l.asset_id, o
FROM latest l,
jsonb_array_elements(CASE WHEN jsonb_typeof(l.data->'observations')='array'
THEN l.data->'observations' ELSE '[]'::jsonb END) o
WHERE o->>'quality'='valid'
),
proxmox_hosts AS (
SELECT asset_id, o->'data' AS data FROM scopes WHERE o->>'scope'='linux.proxmox'
),
guest_macs AS (
SELECT DISTINCT h.asset_id AS host_asset_id, lower(mac) AS mac
FROM proxmox_hosts h,
jsonb_array_elements(h.data->'guests') g,
jsonb_array_elements_text(g->'macs') mac
),
virtual_devices AS (
SELECT asset_id FROM scopes
WHERE o->>'scope' IN ('linux.hardware','windows.hardware') AND o#>>'{data,device_type}'='virtual'
),
device_macs AS (
SELECT DISTINCT s.asset_id, lower(i->>'mac') AS mac
FROM scopes s
JOIN virtual_devices v ON v.asset_id=s.asset_id,
jsonb_array_elements(CASE
WHEN jsonb_typeof(s.o->'data')='array' THEN s.o->'data'
WHEN jsonb_typeof(s.o#>'{data,entries}')='array' THEN s.o#>'{data,entries}'
ELSE '[]'::jsonb END) i
WHERE s.o->>'scope' IN ('linux.interfaces','windows.interfaces')
AND i->>'mac' ~* '^[0-9a-f]{2}(:[0-9a-f]{2}){5}$'
AND lower(i->>'mac') <> '00:00:00:00:00:00'
),
-- A MAC that more than one device or more than one host claims proves nothing.
unique_macs AS (
SELECT d.asset_id, g.host_asset_id
FROM device_macs d JOIN guest_macs g ON g.mac=d.mac
WHERE d.asset_id <> g.host_asset_id
AND (SELECT count(*) FROM device_macs d2 WHERE d2.mac=d.mac)=1
AND (SELECT count(*) FROM guest_macs g2 WHERE g2.mac=d.mac)=1
),
matches AS (
SELECT asset_id, min(host_asset_id::text)::uuid AS host_asset_id
FROM unique_macs GROUP BY asset_id HAVING count(DISTINCT host_asset_id)=1
),
desired AS (
-- New or changed automatic links.
SELECT l.asset_id, l.hypervisor_asset_id AS previous, m.host_asset_id AS next
FROM latest l JOIN matches m ON m.asset_id=l.asset_id
WHERE l.hypervisor_source IS DISTINCT FROM 'manual'
AND (l.hypervisor_asset_id IS DISTINCT FROM m.host_asset_id OR l.hypervisor_source IS NULL)
UNION ALL
-- The assigned host reports a valid guest list that no longer contains this device.
SELECT l.asset_id, l.hypervisor_asset_id, NULL
FROM latest l
WHERE l.hypervisor_source='proxmox'
AND NOT EXISTS (SELECT FROM matches m WHERE m.asset_id=l.asset_id)
AND EXISTS (SELECT FROM proxmox_hosts h WHERE h.asset_id=l.hypervisor_asset_id)
AND EXISTS (SELECT FROM device_macs d WHERE d.asset_id=l.asset_id)
),
changed AS (
UPDATE assets a
SET hypervisor_asset_id=d.next,
hypervisor_source=CASE WHEN d.next IS NULL THEN NULL ELSE 'proxmox' END
FROM desired d
WHERE a.tenant_id=$1 AND a.asset_id=d.asset_id
RETURNING a.asset_id, d.previous, d.next
)
INSERT INTO audit_events(tenant_id,event_id,principal,event_type,data,created_at)
SELECT $1, gen_random_uuid(), 'system:proxmox-guest-detection',
CASE WHEN next IS NULL THEN 'device_hypervisor_released' ELSE 'device_hypervisor_detected' END,
jsonb_build_object('asset_id',asset_id,'previous_hypervisor_asset_id',previous,
'hypervisor_asset_id',next,'match','mac'),
now()
FROM changed
WHERE previous IS DISTINCT FROM next
RETURNING event_id
+45
View File
@@ -0,0 +1,45 @@
# Proxmox-VE-Host
Ein Proxmox-VE-Host ist ein Debian-System. Er verwendet deshalb den regulären Linux-Agenten, seinen Helper und seinen Updater. Zusätzlich liest der Agent über die lokale Proxmox-API die gehosteten Gäste, die geplanten Backupjobs und die Ergebnisse der letzten vzdump-Läufe. Er meldet sie als Inventarbereich `linux.proxmox`. Die WebUI zeigt diese Daten in den Gerätedetails des Hosts. Der Agent ordnet die gemeldeten VMs automatisch dem Host zu. [Sammelmodul](../../crates/agent-linux/src/inventory/proxmox.rs) · [API-Zugriff](../../crates/agent/src/proxmox_api.rs)
## Aufnahme
Für die Aufnahme den gemeinsamen [HTTPS-Installer](../../docs/development.md#linux-gerät-per-https-aufnehmen) als `root` auf dem Proxmox-Host ausführen. Der Installer erkennt Proxmox VE an `pveversion` und `pveum` und richtet einen nur lesenden Zugang ein:
- Proxmox-Benutzer `rmm-discovery@pve` und das privilegiengetrennte API-Token `rmm-discovery@pve!inventory`. Beide erhalten auf `/` ausschließlich die Rolle `PVEAuditor`. Bei einem privilegiengetrennten Token gilt die Schnittmenge aus Benutzer- und Tokenrechten. Deshalb braucht auch der Benutzer die Rolle.
- Den Tokenwert schreibt er nach `/opt/rust-discovery-client/proxmox-token` (Eigentümer root, Modus 0600). Die Cluster-CA landet als `/opt/rust-discovery-client/pve-ca.pem`.
- Das systemd-Drop-in `rmm-discovery-agent.service.d/41-proxmox-api.conf` übergibt den Token mit `LoadCredential=rmm-proxmox-token` an den Dienst und setzt `RMM_PROXMOX_CA_FILE`.
Der Agent läuft weiter unprivilegiert als `rmm-discovery`. Er verbindet sich nur mit `https://127.0.0.1:8006` und prüft das Zertifikat ausschließlich gegen die kopierte Cluster-CA. Token und Tokenwert erscheinen weder im Inventar noch im Log. Bei einer erneuten Installation bleiben ein vorhandener Token und die Geräteidentität erhalten. Fehlt die lokale Kopie, erzeugt der Installer das Token neu, weil Proxmox den Wert nur bei der Erstellung ausgibt.
## Gemeldete Daten
- **Gäste des lokalen Nodes:** VMID, Name, VM oder Container, Status, Vorlage, vCPU, RAM, Disk, Pool, MAC-Adressen der `netN`-Schnittstellen und für QEMU die SMBIOS-UUID. Höchstens 512 Gäste. Gäste auf anderen Cluster-Nodes meldet der Agent des jeweiligen Nodes.
- **Backupjobs** aus `/cluster/backup`: Zeitplan, Storage, Modus, Auswahl (alle, Pool oder VMIDs, abzüglich Ausnahmen) und die danach gesicherten lokalen Gäste. Den letzten fälligen Zeitpunkt berechnet der Proxmox-Scheduler selbst über `/cluster/jobs/schedule-analyze`.
- **vzdump-Läufe** der letzten acht Tage (höchstens 64) mit Start, Ende und Gesamtstatus. Das Ergebnis je Gast stammt aus den Zeilen `Finished Backup of VM` bzw. `Backup of VM … failed` des Tasklogs.
- **Gäste ohne Backupjob** aus `/cluster/backup-info/not-backed-up`.
Der Server bewertet jeden aktiven Job: **Gelaufen**, wenn jeder gesicherte Gast seit dem letzten fälligen Zeitpunkt (zwei Minuten Toleranz) erfolgreich gesichert wurde. **Fehlgeschlagen** bei einem gemeldeten Fehler, **Verpasst** ohne Lauf, **Läuft** bei aktivem vzdump. Ein Job, der in den letzten acht Tagen noch nicht fällig war, gilt als **Noch nicht fällig**. „Alle geplanten Backups sind gelaufen“ steht nur, wenn kein aktiver Job fehlgeschlagen oder verpasst ist. [Bewertung](../../crates/domain/src/inventory_document/proxmox.rs)
## Zuordnung der VMs
Nach jeder Linux- oder Windows-Inventarmeldung vergleicht der Server die MAC-Adressen der aktuellen Proxmox-Gastlisten mit den Netzwerkkarten der aktuellen virtuellen Geräte desselben Kunden. Bei einem eindeutigen Treffer trägt er den Proxmox-Host als Hypervisor ein (`hypervisor_source = proxmox`) und auditiert `device_hypervisor_detected`. Eine MAC, die mehrere Geräte oder mehrere Hosts melden, führt zu keiner Zuordnung. Verschwindet der Gast aus der gültigen Gastliste seines Hosts, wird die automatische Zuordnung gelöst. Eine manuelle Auswahl unter **Gerät verwalten → Hypervisor zuordnen** hat Vorrang. Die Option **Automatisch (Proxmox-Gastliste)** gibt die Entscheidung an die Erkennung zurück. [Abgleich](../../crates/server/src/proxmox_links.sql)
## Diagnose
| Anzeige im Gerätedetail | Ursache |
| --- | --- |
| „kein Lesezugang eingerichtet“ (`PROXMOX_NOT_CONFIGURED`) | Credential fehlt. HTTPS-Installer erneut als root ausführen und den Agentdienst neu starten. |
| `PROXMOX_TOKEN_REJECTED` | Token gelöscht oder abgelaufen. `/opt/rust-discovery-client/proxmox-token` entfernen und den Installer erneut ausführen. |
| `PROXMOX_PERMISSION_DENIED` | Der Benutzer oder das Token hat keine Rolle `PVEAuditor` auf `/`. |
| `PROXMOX_CA_UNAVAILABLE`, `PROXMOX_UNREACHABLE` | CA-Kopie fehlt bzw. `pveproxy` ist auf Port 8006 nicht erreichbar. |
Zum Widerrufen `pveum user token remove rmm-discovery@pve inventory` ausführen. Die übrige Inventur läuft dann weiter, der Proxmox-Bereich meldet einen Fehler.
## Testhost auf dem Entwicklungsnotebook
VM `proxmox` auf `qemu:///system`: 4 vCPU (`host-passthrough`, verschachtelte Virtualisierung), 4 GiB RAM, 64 GiB qcow2 im Pool `default`, Netz `default` mit fester DHCP-Reservierung `192.168.122.50` (MAC `52:54:00:50:7e:01`). Basis ist das offizielle `proxmox-ve_9.2-1.iso` (SHA-256 `4e88fe416df9b527624a175f24c9aa07c714d3332afb1ee3dbf3879573ef2c6c`). Die Installation erfolgte unbeaufsichtigt mit dem `proxmox-auto-install-assistant` aus dem Proxmox-Repository. Die Paketquelle ist `pve-no-subscription`. FQDN `pve.discovery.lan`, WebUI `https://192.168.122.50:8006`.
Testobjekte: VM 100 `debian-guest` (Debian-13-Cloud-Image, 1 GiB, cloud-init) und Container 101 `alpine-ct` (Alpine 3.24, ohne Backupjob). Der Backupjob `backup-debian` sichert VM 100 alle zwei Stunden (`*/2:00`) nach `local`.
SSH-Zugang, Root-Passwort und Hostpin liegen im privaten Zugangsverzeichnis (`proxmox-vm.conf`, `proxmox-dev-key`, `proxmox-dev-root`, `proxmox-dev.known_hosts`). `tools/dev_stage.py proxmox …` verwendet diese Dateien. Start bei Bedarf: `virsh -c qemu:///system start proxmox`.
+1
View File
@@ -12,6 +12,7 @@
| MCP und Administrator-Skripte | [Werkzeuge](../crates/server/src/mcp.rs), [Tokenrechte](../crates/server/src/mcp_tokens.rs), [Helper und zentrale Geräteregel](../crates/server/src/managed_scripts.rs) |
| Geräteaufnahme und Releasewechsel | [HTTPS-Installer und Lebenszyklus](../crates/server/src/bootstrap), [Releasekatalog](../crates/server/src/agent_updates.rs), [Signaturprüfung](../crates/updater/src/manifest.rs) |
| Native Laufzeiten | [Linux-Agent](../crates/agent/src/main.rs), [Linux-Inventar und Skripte](../crates/agent-linux/src), [Windows-Agent](../crates/agent-windows/src/runtime.rs), [Agentprotokoll](../proto/BACKEND_CONTRACT.md) |
| Proxmox-Host und VM-Zuordnung | [Sammelmodul](../crates/agent-linux/src/inventory/proxmox.rs), [Validierung und Backupbewertung](../crates/domain/src/inventory_document/proxmox.rs), [automatische Zuordnung](../crates/server/src/proxmox_links.sql), [Detailansicht](../web/src/proxmox.tsx), [Betrieb](../deploy/proxmox/README.md) |
## Einen vorhandenen Auftrag nachvollziehen
+2 -1
View File
@@ -11,6 +11,7 @@ Die Werkzeuge werden im Repository als Eigentümer der lokalen Entwicklungsprofi
| `server` | Dedizierter ARM64-Host `discovery.ease-technologies.de` | `server.conf`, vorhandener SSH-Schlüssel und geprüfter Hostkey |
| `linux` | Cloud-Linux-Gast `dev-znuny-db` | `linux-vm.conf`, vorhandener SSH-Schlüssel und geprüfter Hostkey |
| `windows` | Windows-11-Gast `discwindowstest` | `windows-dev-access.json`, `windows-dev.known_hosts`, Alias `rmm-windows-dev` und SSH-Rückkanal über den Server |
| `proxmox` | Lokale Proxmox-VE-9.2-VM `pve.discovery.lan` (`192.168.122.50`) auf dem Notebook | `proxmox-vm.conf`, eigener Schlüssel `proxmox-dev-key`, Hostpin `proxmox-dev.known_hosts` (beim ersten Start im NAT-Netz `default` der frisch installierten VM erfasst) |
Der folgende Befehl liest vom Wurzelverzeichnis des Worktrees aus den Hostnamen der Linux-Test-VM.
@@ -23,7 +24,7 @@ subprocess.run([*ssh_prefix("linux"), "hostname"], check=True, timeout=20)
PY
```
`ssh_prefix` verwendet Batchbetrieb, bestehende Schlüssel und strikte Hostprüfung. Die Hostpins für Server und Linux stehen im vorhandenen SSH-Truststore des Benutzers (`~/.ssh/known_hosts`). Windows verwendet die oben genannte separate Hostpindatei. Für Windows wird der geprüfte Proxyweg mit dem gespeicherten Profil abgeglichen. Vor Änderungen an einem Pin den neuen Fingerabdruck unabhängig mit dem Zieladministrator bestätigen. [SSH-Auflösung und Staging](../tools/dev_stage.py)
`ssh_prefix` verwendet Batchbetrieb, bestehende Schlüssel und strikte Hostprüfung. Die Hostpins für Server und Linux stehen im vorhandenen SSH-Truststore des Benutzers (`~/.ssh/known_hosts`). Windows und Proxmox verwenden die oben genannten separaten Hostpindateien. [Proxmox-Testhost](../deploy/proxmox/README.md#testhost-auf-dem-entwicklungsnotebook) Für Windows wird der geprüfte Proxyweg mit dem gespeicherten Profil abgeglichen. Vor Änderungen an einem Pin den neuen Fingerabdruck unabhängig mit dem Zieladministrator bestätigen. [SSH-Auflösung und Staging](../tools/dev_stage.py)
## Interne Test-WebUI
+10
View File
@@ -0,0 +1,10 @@
SET LOCAL lock_timeout = '3s';
SET LOCAL statement_timeout = '30s';
-- NULL: no automatic decision yet, 'proxmox': set from a Proxmox host's guest list,
-- 'manual': chosen by a person and never overwritten by automatic detection.
ALTER TABLE assets
ADD COLUMN hypervisor_source text,
ADD CONSTRAINT assets_hypervisor_source_check
CHECK (hypervisor_source IN ('manual','proxmox'));
UPDATE assets SET hypervisor_source='manual' WHERE hypervisor_asset_id IS NOT NULL;
GRANT UPDATE (hypervisor_source) ON assets TO rmm_app;
+21 -1
View File
@@ -386,10 +386,25 @@ test('shows real VM hosts and the Hetzner placeholder without adding a device',
lifecycle: 'current', status: 'online', recent_jobs: [], volumes: [] };
const vm = { ...base, hostname: 'Test-VM', asset_id: 'vm-asset', agent_id: 'vm-agent', device_type: 'virtual' };
const pve = { ...base, hostname: 'pve-01', asset_id: 'pve-asset', agent_id: 'pve-agent',
device_type: 'hypervisor', os: 'Proxmox VE' };
device_type: 'hypervisor', os: 'Proxmox VE', tenant_id: tenant,
proxmox: { quality: 'valid', error_code: null, observed_at: new Date().toISOString(), truncated: false,
data: { node: 'pve-01', cluster: null, version: '9.2.2', not_backed_up: [101],
guests: [
{ vmid: 100, name: 'Test-VM', kind: 'qemu', status: 'running', template: false, cpus: 2,
memory_bytes: 2 ** 31, disk_bytes: 2 ** 33, macs: ['bc:24:11:00:00:01'] },
{ vmid: 101, name: 'alpine-ct', kind: 'lxc', status: 'stopped', template: false, cpus: 1,
memory_bytes: 2 ** 27, disk_bytes: 2 ** 30, macs: [] }],
backup_jobs: [{ id: 'backup-nightly', enabled: true, schedule: '21:00', storage: 'local',
selection: 'vmid', covered_vmids: [100], last_expected_run: 1795118400, next_run: 1795204800 }],
backup_runs: [] },
backup_status: { all_scheduled_backups_ran: false, enabled_jobs: 1, problem_jobs: 1,
last_success_at: {}, jobs: [{ id: 'backup-nightly', status: 'missed',
guests: [{ vmid: 100, status: 'missed', last_success_at: null }] }] },
guest_devices: [{ vmid: 100, asset_id: 'vm-asset', agent_id: 'vm-agent', hostname: 'Test-VM', source: 'proxmox' }] } };
const placeholder = { kind: 'placeholder', provider: 'hetzner', hostname: 'Hetzner Cloud' };
let assigned = false;
const guest = () => ({ ...vm, assigned_hypervisor_asset_id: assigned ? pve.asset_id : null,
hypervisor_source: assigned ? 'manual' : null,
hypervisor: assigned ? { kind: 'device', hostname: pve.hostname, asset_id: pve.asset_id, agent_id: pve.agent_id } : placeholder });
const listing = (items: unknown[]) => ({ items, next_cursor: null, truncated: false,
completeness: 'complete', as_of: new Date().toISOString() });
@@ -445,6 +460,11 @@ test('shows real VM hosts and the Hetzner placeholder without adding a device',
await expect(vmRow).not.toContainText('Hetzner Cloud');
await hostLink.click();
await expect(page.getByRole('heading', { name: pve.hostname })).toBeVisible();
await expect(page.getByRole('heading', { name: 'Virtuelle Maschinen und Container' })).toBeVisible();
await expect(page.getByRole('row').filter({ hasText: 'alpine-ct' })).toContainText('Container');
await expect(page.getByRole('row').filter({ hasText: 'backup-nightly' })).toContainText('Verpasst');
await expect(page.getByText('Nicht alle geplanten Backups sind gelaufen.')).toBeVisible();
await expect(page.getByRole('link', { name: 'Test-VM' })).toBeVisible();
await page.getByRole('button', { name: 'Zur Geräteliste' }).click();
await page.getByRole('button', { name: vm.hostname }).click();
await page.getByText('Gerät verwalten', { exact: true }).click();
+7 -2
View File
@@ -30,12 +30,17 @@ def credentials_directory():
def ssh_prefix(target):
credentials = credentials_directory()
config = load_config(credentials / ("linux-vm.conf" if target == "linux" else "server.conf"))
profile = {"linux": "linux-vm.conf", "proxmox": "proxmox-vm.conf"}.get(target, "server.conf")
config = load_config(credentials / profile)
host = config["username"] + "@" + config["address"]
key = str(Path(config["ssh_key_path"]).expanduser())
base = ["ssh", "-F", "/dev/null", "-T"]
direct = [*base, "-p", config.get("port", "22"), "-i", key, "-o", "StrictHostKeyChecking=yes",
"-o", "BatchMode=yes", "-o", "ForwardAgent=no", "-o", "IdentitiesOnly=yes"]
if target == "proxmox":
# Local test host: its own pin file, not the user's global known_hosts.
return [*direct, "-o", "UserKnownHostsFile=" + str(credentials / "proxmox-dev.known_hosts"),
"-o", "GlobalKnownHostsFile=/dev/null", "-o", "ConnectTimeout=10", host]
if target != "windows":
return [*direct, "-o", "ConnectTimeout=10", host]
# Match the pinned access registered by deploy/windows/prepare_dev_access.py.
@@ -154,7 +159,7 @@ def main():
"Ziel: rmm-dev-stage/<SHA-256>/<Dateiname> im SSH-Benutzerprofil. "
"Identische Dateien werden wiederverwendet. Dienste und Releases werden separat aktiviert."))
parser.add_argument("--plan", action="store_true", help="Nur lokale Hashes und Zielpfade anzeigen")
parser.add_argument("target", choices=("server", "linux", "windows"), help="Entwicklungsziel")
parser.add_argument("target", choices=("server", "linux", "windows", "proxmox"), help="Entwicklungsziel")
parser.add_argument("files", nargs="+", type=Path, metavar="DATEI", help="Vorhandene lokale Artefakte")
args = parser.parse_args()
for path in args.files:
+11 -5
View File
@@ -4,6 +4,8 @@ import { NavIcon } from './navigation';
import { ErrorBox, errorText, useResource } from './resource';
type Host = { asset_id: string; agent_id: string; hostname: string };
/** Select value that hands the decision back to automatic Proxmox detection. */
const AUTO = 'automatic';
function host(value: unknown): Host | null {
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
@@ -24,7 +26,7 @@ export function HypervisorLabel({ device }: { device: RecordValue }) {
return <span className="vm-hypervisor">
<NavIcon name="geraete" /><span>Hypervisor <a href={'#' + path} onClick={event => event.stopPropagation()}>
{target.hostname}
</a></span>
</a>{info.source === 'proxmox' && <span className="muted"> · automatisch über Proxmox erkannt</span>}</span>
</span>;
}
return info.kind === 'placeholder' && info.provider === 'hetzner' ? (
@@ -53,7 +55,8 @@ export function HypervisorAssignment({ device, customer, asset, agent, auth }: {
const [busy, setBusy] = useState(false);
const [notice, setNotice] = useState('');
const [error, setError] = useState<string | null>(null);
const assigned = typeof device.assigned_hypervisor_asset_id === 'string' ? device.assigned_hypervisor_asset_id : '';
const automatic = device.hypervisor_source !== 'manual';
const assigned = automatic ? AUTO : typeof device.assigned_hypervisor_asset_id === 'string' ? device.assigned_hypervisor_asset_id : '';
const value = draft ?? assigned;
useEffect(() => {
@@ -70,7 +73,7 @@ export function HypervisorAssignment({ device, customer, asset, agent, auth }: {
}, [customer, open, query]);
const assignedHost = host(device.hypervisor);
const hosts = options.data?.hosts ?? [];
const selectedMissing = !!value && !hosts.some(item => item.asset_id === value);
const selectedMissing = !!value && value !== AUTO && !hosts.some(item => item.asset_id === value);
const canSave = value !== assigned && (!value || !selectedMissing);
return <details onToggle={e => {
@@ -91,9 +94,11 @@ export function HypervisorAssignment({ device, customer, asset, agent, auth }: {
setNotice('');
try {
await request(tenantPath(customer, '/devices/' + encodeURIComponent(asset) + '/hypervisor?agent_id=' + encodeURIComponent(agent)), {
tenantId: customer, csrf: auth.csrf_token, body: { hypervisor_asset_id: value || null }
tenantId: customer, csrf: auth.csrf_token,
body: value === AUTO ? { hypervisor_asset_id: null, automatic: true } : { hypervisor_asset_id: value || null }
});
setNotice(value ? 'Hypervisor zugeordnet.' : 'Hostzuordnung entfernt.');
setNotice(value === AUTO ? 'Automatische Zuordnung über Proxmox aktiviert.'
: value ? 'Hypervisor zugeordnet.' : 'Hostzuordnung entfernt.');
} catch (e) {
setError(assignmentError(e));
} finally {
@@ -106,6 +111,7 @@ export function HypervisorAssignment({ device, customer, asset, agent, auth }: {
{options.data?.truncated && <p className="muted">Weitere Hypervisoren lassen sich über die Suche finden.</p>}
<label>Hypervisor auswählen<select aria-label="Hypervisor auswählen" value={value}
onChange={e => { setDraft(e.target.value); setNotice(''); setError(null); }} disabled={busy}>
<option value={AUTO}>Automatisch (Proxmox-Gastliste)</option>
<option value="">Kein konkreter Hypervisor</option>
{selectedMissing && <option value={value} disabled>
{assignedHost?.asset_id === value ? assignedHost.hostname : 'Zugeordneter Host außerhalb der Treffer'}
+2
View File
@@ -18,6 +18,7 @@ import { CatalogCheckNotice } from './catalog-check';
import { devicePlatform } from './script-catalog';
import { DeviceInventoryPanels, systemDetails } from './device-inventory';
import { OPNsenseDetails } from './opnsense';
import { ProxmoxDetails } from './proxmox';
import { DeviceCustomerTransfer } from './device-customer-transfer';
import { HypervisorAssignment, HypervisorLabel } from './device-hypervisor';
import { ErrorBox, errorText, useResource } from './resource';
@@ -340,6 +341,7 @@ function DeviceDetail({
onSaved={() => { setPurposeSaved(true); detail.reload(); }}
/>
<OPNsenseDetails device={d} />
<ProxmoxDetails device={d} />
<DeviceInventoryPanels device={d} />
{volumes.length > 0 && (
<section>
+40
View File
@@ -0,0 +1,40 @@
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, it } from 'vitest';
import { ProxmoxDetails } from './proxmox';
const data = { node: 'pve', cluster: null, version: '9.2.2', not_backed_up: [101],
guests: [
{ vmid: 100, name: 'debian-guest', kind: 'qemu', status: 'running', template: false, cpus: 1,
memory_bytes: 2 ** 30, disk_bytes: 2 ** 33, macs: ['bc:24:11:88:35:97'] },
{ vmid: 101, name: 'alpine-ct', kind: 'lxc', status: 'running', template: false, cpus: 1,
memory_bytes: 2 ** 27, disk_bytes: 2 ** 30, macs: [] }],
backup_jobs: [{ id: 'backup-debian', enabled: true, schedule: '*/2:00', storage: 'local',
selection: 'vmid', covered_vmids: [100], last_expected_run: 1795172400, next_run: 1795179600 }],
backup_runs: [] };
it('lists guests, linked devices and an overall backup answer', () => {
const view = renderToStaticMarkup(<ProxmoxDetails device={{ tenant_id: 't', proxmox: {
quality: 'valid', observed_at: '2026-11-20T12:00:00Z', data,
backup_status: { all_scheduled_backups_ran: true, last_success_at: { '100': 1795172488 },
jobs: [{ id: 'backup-debian', status: 'ok', guests: [{ vmid: 100, status: 'ok' }] }] },
guest_devices: [{ vmid: 100, asset_id: 'a', agent_id: 'b', hostname: 'debian-guest' }] } }} />);
expect(view).toContain('Alle geplanten Backups sind gelaufen.');
expect(view).toContain('href="#geraete/t/a/b"');
expect(view).toContain('Container');
expect(view).toMatch(/Ohne Backupjob<\/h3><p>101 alpine-ct/);
expect(view).toContain('Gelaufen');
});
it('names failed guests and explains a missing read token', () => {
const failed = renderToStaticMarkup(<ProxmoxDetails device={{ proxmox: { quality: 'valid', data,
backup_status: { all_scheduled_backups_ran: false, last_success_at: {},
jobs: [{ id: 'backup-debian', status: 'failed', guests: [{ vmid: 100, status: 'failed' }] }] },
guest_devices: [] } }} />);
expect(failed).toContain('Nicht alle geplanten Backups sind gelaufen.');
expect(failed).toContain('100 debian-guest: Fehlgeschlagen');
expect(failed).toContain('nicht zugeordnet');
const missing = renderToStaticMarkup(<ProxmoxDetails device={{ proxmox: {
quality: 'unsupported', error_code: 'PROXMOX_NOT_CONFIGURED', data: null } }} />);
expect(missing).toContain('kein Lesezugang');
expect(renderToStaticMarkup(<ProxmoxDetails device={{}} />)).toBe('');
});
+114
View File
@@ -0,0 +1,114 @@
import { record, type RecordValue } from './api';
const dateFormat = new Intl.DateTimeFormat('de-DE', { dateStyle: 'short', timeStyle: 'short' });
const gib = new Intl.NumberFormat('de-DE', { maximumFractionDigits: 1 });
const JOB_STATUS: Record<string, [string, string]> = {
ok: ['Gelaufen', 'online'],
failed: ['Fehlgeschlagen', 'failed'],
missed: ['Verpasst', 'failed'],
running: ['Läuft', 'historic'],
pending: ['Noch nicht fällig', ''],
disabled: ['Deaktiviert', ''],
unknown: ['Unbekannt', 'historic'],
};
const GUEST_STATUS: Record<string, string> = { running: 'Läuft', stopped: 'Gestoppt', paused: 'Pausiert' };
function list(value: unknown): RecordValue[] {
return Array.isArray(value) ? value.filter(v => v && typeof v === 'object' && !Array.isArray(v)).map(v => record(v)) : [];
}
function epoch(value: unknown) {
return typeof value === 'number' && Number.isFinite(value) && value > 0 ? dateFormat.format(value * 1000) : '–';
}
function size(value: unknown) {
return typeof value === 'number' && value > 0 ? gib.format(value / 2 ** 30) + ' GiB' : '–';
}
function text(value: unknown) {
return typeof value === 'string' && value.trim() ? value : '–';
}
function Badge({ status }: { status: unknown }) {
const [title, tone] = JOB_STATUS[typeof status === 'string' ? status : 'unknown'] ?? ['Unbekannt', 'historic'];
return <span className={'presence ' + tone}><i />{title}</span>;
}
function deviceLink(tenant: unknown, link: RecordValue | undefined) {
if (!link || typeof tenant !== 'string' || typeof link.asset_id !== 'string' || typeof link.agent_id !== 'string') return null;
const path = ['geraete', tenant, link.asset_id, link.agent_id].map(encodeURIComponent).join('/');
return <a href={'#' + path}>{text(link.hostname)}</a>;
}
/** Hosted guests and scheduled vzdump backups reported by a Proxmox VE host. */
export function ProxmoxDetails({ device }: { device: RecordValue }) {
if (!device.proxmox || typeof device.proxmox !== 'object') return null;
const report = record(device.proxmox);
if (report.quality !== 'valid' || !report.data) {
const reason = report.error_code === 'PROXMOX_NOT_CONFIGURED'
? 'Für diesen Proxmox-Host ist kein Lesezugang eingerichtet. Der HTTPS-Installer richtet ihn bei der Aufnahme ein.'
: 'Nicht ermittelbar' + (typeof report.error_code === 'string' ? ` (${report.error_code})` : '') + '.';
return <section><h2>Proxmox VE</h2><p>{reason}</p></section>;
}
const data = record(report.data);
const status = report.backup_status ? record(report.backup_status) : {};
const jobStatus = new Map(list(status.jobs).map(j => [j.id, j]));
const lastSuccess = status.last_success_at ? record(status.last_success_at) : {};
const links = new Map(list(report.guest_devices).map(l => [l.vmid, l]));
const guests = list(data.guests);
const names = new Map(guests.map(g => [g.vmid, text(g.name)]));
const jobs = list(data.backup_jobs);
const notBackedUp = Array.isArray(data.not_backed_up) ? data.not_backed_up : [];
const allRan = status.all_scheduled_backups_ran;
const guestName = (id: unknown) => `${String(id)} ${names.get(id) ?? ''}`.trim();
return <>
<section>
<h2>Virtuelle Maschinen und Container</h2>
<p className="muted">Node {text(data.node)}{typeof data.cluster === 'string' ? ` · Cluster ${data.cluster}` : ''}
{typeof data.version === 'string' ? ` · Proxmox VE ${data.version}` : ''} · erhoben {typeof report.observed_at === 'string' ? dateFormat.format(Date.parse(report.observed_at)) : '–'}
{report.truncated === true ? ' · Auszug – unvollständige Liste' : ''}</p>
{guests.length === 0 ? <p>Keine Gäste auf diesem Node.</p> : <div className="table"><table>
<thead><tr><th>VMID</th><th>Name</th><th>Typ</th><th>Status</th><th>vCPU</th><th>RAM</th><th>Disk</th><th>Gerät im Bestand</th><th>Letzte Sicherung</th></tr></thead>
<tbody>{guests.map(g => <tr key={String(g.vmid)}>
<td>{String(g.vmid)}</td>
<td>{text(g.name)}{g.template === true && <span className="muted"> · Vorlage</span>}</td>
<td>{g.kind === 'lxc' ? 'Container' : 'VM'}</td>
<td>{GUEST_STATUS[String(g.status)] ?? text(g.status)}</td>
<td>{typeof g.cpus === 'number' ? g.cpus : '–'}</td>
<td>{size(g.memory_bytes)}</td>
<td>{size(g.disk_bytes)}</td>
<td>{deviceLink(device.tenant_id, links.get(g.vmid)) ?? <span className="muted">nicht zugeordnet</span>}</td>
<td>{epoch(lastSuccess[String(g.vmid)])}</td>
</tr>)}</tbody>
</table></div>}
</section>
<section>
<h2>Geplante Backups</h2>
<p role="status">{allRan === true ? <><Badge status="ok" /> Alle geplanten Backups sind gelaufen.</>
: allRan === false ? <><Badge status="failed" /> Nicht alle geplanten Backups sind gelaufen.</>
: 'Keine aktiven Backupjobs für diesen Node.'}</p>
{jobs.length > 0 && <div className="table"><table>
<thead><tr><th>Job</th><th>Zeitplan</th><th>Storage</th><th>Gäste</th><th>Zuletzt fällig</th><th>Ergebnis</th><th>Nächster Lauf</th></tr></thead>
<tbody>{jobs.map(job => {
const evaluated = jobStatus.get(job.id);
const problems = list(evaluated?.guests).filter(g => g.status !== 'ok');
const covered = Array.isArray(job.covered_vmids) ? job.covered_vmids : [];
return <tr key={String(job.id)}>
<td>{text(job.id)}</td>
<td><code>{text(job.schedule)}</code></td>
<td>{text(job.storage)}</td>
<td>{covered.length ? covered.map(guestName).join(', ') : <span className="muted">keine lokalen Gäste</span>}
{job.selection === 'all' && <span className="muted"> (alle)</span>}</td>
<td>{epoch(job.last_expected_run)}</td>
<td><Badge status={evaluated?.status} />
{problems.length > 0 && <ul className="compact">{problems.map(g =>
<li key={String(g.vmid)}>{guestName(g.vmid)}: {JOB_STATUS[String(g.status)]?.[0] ?? text(g.status)}</li>)}</ul>}</td>
<td>{epoch(job.next_run)}</td>
</tr>;
})}</tbody>
</table></div>}
{notBackedUp.length > 0 && <>
<h3>Ohne Backupjob</h3>
<p>{notBackedUp.map(guestName).join(', ')}</p>
</>}
</section>
</>;
}
+2
View File
@@ -116,6 +116,8 @@ section.fleet { padding:0; overflow:hidden; }
.presence i { width:6px; height:6px; border-radius:50%; background:currentColor; }
.presence.online { color:#236343; background:#e6f4e9; }
.presence.historic { color:#80581c; background:#faf1df; }
.presence.failed { color:#7b3029; background:#fdf1ee; }
ul.compact { margin:4px 0 0; padding-left:18px; font-size:.85rem; }
.fleet small { font-size:.75rem; margin-top:3px; }
.list-message,.history-hint,.empty-list,.fleet > .error { margin:14px 20px; }
.history-hint,.list-footer { color:var(--subtle); font-size:.83rem; }