Show known hypervisors and the Hetzner placeholder for virtual machines
This commit is contained in:
@@ -10,6 +10,8 @@ Jede Installation ist an Kunde, Gerät und Agentenidentität gebunden. Die Stand
|
||||
|
||||
Der Agent meldet den Gerätetyp mit dem passiven Hardwareinventar. `physical` bezeichnet einen physischen Rechner, `virtual` ein virtualisiertes System und `hypervisor` eine erkannte Hostrolle. Proxmox VE erscheint als `hypervisor` mit `Proxmox VE` in der Spalte OS. Eine erkannte Hostrolle hat Vorrang, auch bei verschachtelter Virtualisierung. Bei fehlender Angabe zeigt die WebUI „Nicht gemeldet“. Die Geräteabfragen in WebUI und MCP verwenden denselben gespeicherten Typ. [Inventarprojektion](crates/server/src/devices.rs)
|
||||
|
||||
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.
|
||||
|
||||
Die RAM-Spalte zeigt den für Anwendungen verfügbaren und den gesamten physischen Arbeitsspeicher in GiB. Wie beim Speicherplatz zeigt ein Balken den belegten Anteil. Die CPU-Spalte ergänzt die zuletzt gemessene Systemauslastung als Prozentwert. Die Agenten gewinnen sie aus den CPU-Zeitdifferenzen zwischen zwei Heartbeats im Abstand von ungefähr 30 Sekunden. Linux liefert systemweite Werte. Windows liefert den Wert, wenn alle logischen CPUs zu einer einzigen Prozessorgruppe gehören. Vor dem ersten aussagekräftigen Intervall bleibt die Auslastung offen. Die WebUI und MCP lesen dieselbe letzte Messung. Für Agenten ohne Ressourcenmeldung stammen verfügbare RAM-Werte aus dem vorhandenen Inventar. [Inventarprojektion](crates/server/src/devices.rs)
|
||||
|
||||
Kunden lassen sich in der WebUI anlegen und umbenennen. Unter **Gerät verwalten → Kunden wechseln** wählt eine berechtigte Person den Zielkunden. Der Server prüft die Rechte zur Geräteverwaltung im bisherigen Kunden und zur Geräteaufnahme im Zielkunden. Der bereits installierte Agent empfängt den Wechsel über seine authentisierte Verbindung und erhält ein neues Zertifikat für eine neue Kopplung. Nach der ersten Inventarmeldung beim Zielkunden bestätigt die Person den Abschluss in der WebUI. Der Server sperrt die bisherige Geräteidentität. Inventar und Auftragsergebnisse der bisherigen Kopplung bleiben beim bisherigen Kunden. Noch nicht abgeschlossene Aufträge, ungeklärte Versuche und gültige offene Genehmigungen müssen vor dem Wechsel abgeschlossen werden. Gerätegebundene erhöhte Rechte erfordern eine eigene Bindung für die neue Kopplung.
|
||||
|
||||
@@ -26,6 +26,10 @@ pub fn routes(r: Router<crate::State>) -> Router<crate::State> {
|
||||
post(revoke_device),
|
||||
)
|
||||
.route("/api/v1/tenants/{tenant}/devices/{asset}", delete(remove_device))
|
||||
.route(
|
||||
"/api/v1/tenants/{tenant}/devices/{asset}/hypervisor",
|
||||
post(assign_hypervisor),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/tenants/{tenant}/devices/{asset}/archive",
|
||||
post(archive_device),
|
||||
@@ -134,6 +138,51 @@ struct Pairing {
|
||||
agent_id: Uuid,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct HypervisorAssignment {
|
||||
// null clears the relation. A missing field is a malformed update.
|
||||
#[serde(deserialize_with = "required_hypervisor_value")]
|
||||
hypervisor_asset_id: Option<Uuid>,
|
||||
}
|
||||
|
||||
fn required_hypervisor_value<'de, D: serde::Deserializer<'de>>(value: D) -> Result<Option<Uuid>, D::Error> {
|
||||
Option::deserialize(value)
|
||||
}
|
||||
|
||||
async fn assign_hypervisor(
|
||||
State(s): State<crate::State>,
|
||||
h: HeaderMap,
|
||||
Path((tenant, asset)): Path<(Uuid, Uuid)>,
|
||||
Query(pair): Query<Pairing>,
|
||||
Json(input): Json<HypervisorAssignment>,
|
||||
) -> Result<Json<Value>, Error> {
|
||||
const EVENT: &str = "device_hypervisor_assigned";
|
||||
let (p, mut tx) = context(&s, &h, tenant, "devices:revoke", EVENT).await?;
|
||||
crate::permissions::require_principal(&mut tx, &p, "inventory:read").await?;
|
||||
|
||||
// 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
|
||||
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;
|
||||
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?;
|
||||
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?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(Json(json!({"asset_id":asset,"hypervisor_asset_id":input.hypervisor_asset_id})))
|
||||
}
|
||||
|
||||
async fn remove_device(
|
||||
State(s): State<crate::State>,
|
||||
h: HeaderMap,
|
||||
|
||||
@@ -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,t.name AS customer_name,
|
||||
asset.archived_at,asset.hypervisor_asset_id,t.name AS customer_name,
|
||||
CASE
|
||||
WHEN a.revoked_at IS NOT NULL THEN 'revoked'
|
||||
WHEN asset.archived_at IS NOT NULL THEN 'archived'
|
||||
|
||||
+227
-10
@@ -14,6 +14,7 @@ use rmm_domain::inventory_document::DeviceType;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::{Postgres, Row, Transaction, postgres::PgRow};
|
||||
use std::collections::HashMap;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Default, Deserialize, Serialize, schemars::JsonSchema, Clone, Copy)]
|
||||
@@ -121,10 +122,7 @@ pub async fn list(
|
||||
};
|
||||
tenants.sort_unstable();
|
||||
tenants.dedup();
|
||||
let hostname = q.q.as_deref().unwrap_or("").trim();
|
||||
if hostname.len() > 255 || hostname.chars().any(char::is_control) {
|
||||
return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
|
||||
}
|
||||
let hostname = hostname_filter(q.q.as_deref())?;
|
||||
let binding = json!([tenant, tenants, q.view, q.status, hostname]);
|
||||
let scope = format!(
|
||||
"device-fleet:{}",
|
||||
@@ -180,6 +178,7 @@ pub async fn list(
|
||||
}
|
||||
.rows(&mut tx)
|
||||
.await?;
|
||||
let hosts = assigned_hosts(&mut tx, customer, page.as_of, &rows).await?;
|
||||
tx.commit().await?;
|
||||
for row in rows {
|
||||
if items.len() == capacity {
|
||||
@@ -187,7 +186,7 @@ pub async fn list(
|
||||
break;
|
||||
}
|
||||
last = Some((customer, row.get::<Uuid, _>("agent_id")));
|
||||
items.push(project(&row, page.as_of, tenant.is_some()));
|
||||
items.push(project(&row, page.as_of, tenant.is_some(), &hosts));
|
||||
}
|
||||
if truncated {
|
||||
break;
|
||||
@@ -236,7 +235,8 @@ pub async fn detail(
|
||||
.await?
|
||||
.pop()
|
||||
.ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?;
|
||||
let mut item = project(&row, now, true);
|
||||
let hosts = assigned_hosts(&mut tx, tenant, now, std::slice::from_ref(&row)).await?;
|
||||
let mut item = project(&row, now, true, &hosts);
|
||||
item["volumes"] = volumes(&item["inventory"]);
|
||||
item["recent_jobs"] = if p.permits_scope("operations:read")
|
||||
&& crate::permissions::allowed(&mut tx, &p.name, "operations:read").await?
|
||||
@@ -294,6 +294,135 @@ fn device_type(hardware: &Value) -> Option<DeviceType> {
|
||||
DeviceType::deserialize(&hardware["device_type"]).ok()
|
||||
}
|
||||
|
||||
fn inventory_device_type(data: &Value) -> Option<DeviceType> {
|
||||
device_type(observed(data, "linux.hardware"))
|
||||
.or_else(|| device_type(observed(data, "windows.hardware")))
|
||||
}
|
||||
|
||||
fn hostname_filter(query: Option<&str>) -> Result<&str, Error> {
|
||||
let hostname = query.unwrap_or("").trim();
|
||||
if hostname.len() > 255 || hostname.chars().any(char::is_control) {
|
||||
return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
|
||||
}
|
||||
Ok(hostname)
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Host {
|
||||
asset_id: Uuid,
|
||||
agent_id: Uuid,
|
||||
hostname: String,
|
||||
}
|
||||
|
||||
async fn hypervisors(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
tenant: Uuid,
|
||||
as_of: DateTime<Utc>,
|
||||
ids: Option<&[Uuid]>,
|
||||
hostname: &str,
|
||||
limit: i64,
|
||||
) -> Result<Vec<Host>, Error> {
|
||||
let rows: Vec<(Uuid, Uuid, String)> = sqlx::query_as(include_str!("hypervisors.sql"))
|
||||
.bind(tenant)
|
||||
.bind(as_of)
|
||||
.bind(ids)
|
||||
.bind(hostname)
|
||||
.bind(limit)
|
||||
.fetch_all(&mut **tx)
|
||||
.await?;
|
||||
Ok(rows.into_iter().map(|(asset_id, agent_id, hostname)| Host {
|
||||
asset_id, agent_id, hostname,
|
||||
}).collect())
|
||||
}
|
||||
|
||||
async fn assigned_hosts(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
tenant: Uuid,
|
||||
as_of: DateTime<Utc>,
|
||||
rows: &[PgRow],
|
||||
) -> Result<HashMap<Uuid, Host>, Error> {
|
||||
let mut ids: Vec<Uuid> = rows.iter().filter_map(|row| row.get("hypervisor_asset_id")).collect();
|
||||
ids.sort_unstable();
|
||||
ids.dedup();
|
||||
if ids.is_empty() {
|
||||
return Ok(HashMap::new());
|
||||
}
|
||||
Ok(hypervisors(tx, tenant, as_of, Some(&ids), "", ids.len() as i64)
|
||||
.await?.into_iter().map(|host| (host.asset_id, host)).collect())
|
||||
}
|
||||
|
||||
fn hypervisor_display(data: &Value, assigned: Option<&Host>) -> Value {
|
||||
if inventory_device_type(data) != Some(DeviceType::Virtual) {
|
||||
return Value::Null;
|
||||
}
|
||||
if let Some(host) = assigned {
|
||||
return json!({"kind":"device","asset_id":host.asset_id,
|
||||
"agent_id":host.agent_id,"hostname":host.hostname});
|
||||
}
|
||||
let linux = observed(data, "linux.hardware");
|
||||
let windows = observed(data, "windows.hardware");
|
||||
let manufacturer = linux["manufacturer"].as_str()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.or_else(|| linux["readable_dmi"]["sys_vendor"].as_str())
|
||||
.or_else(|| windows["manufacturer"].as_str());
|
||||
if manufacturer.is_some_and(|name| matches!(name.trim().to_ascii_lowercase().as_str(),
|
||||
"hetzner" | "hetzner cloud" | "hetzner online" | "hetzner online gmbh")) {
|
||||
return json!({"kind":"placeholder","provider":"hetzner","hostname":"Hetzner Cloud"});
|
||||
}
|
||||
Value::Null
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct HypervisorFilter {
|
||||
q: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn hypervisor_options(
|
||||
State(s): State<crate::State>,
|
||||
h: HeaderMap,
|
||||
Path(tenant): Path<Uuid>,
|
||||
Query(query): Query<HypervisorFilter>,
|
||||
) -> Result<Json<Value>, Error> {
|
||||
let p = crate::jobs::principal(&s, &h, false).await?;
|
||||
crate::jobs::scope(&p, tenant, false)?;
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
|
||||
crate::permissions::require_principal(&mut tx, &p, "inventory:read").await?;
|
||||
let mut hosts = hypervisors(&mut tx, tenant, Utc::now(), None,
|
||||
hostname_filter(query.q.as_deref())?, 51).await?;
|
||||
let truncated = hosts.len() > 50;
|
||||
hosts.truncate(50);
|
||||
tx.commit().await?;
|
||||
Ok(Json(json!({"items":hosts,"truncated":truncated})))
|
||||
}
|
||||
|
||||
pub(crate) async fn validate_vm_host_assignment(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
tenant: Uuid,
|
||||
asset: Uuid,
|
||||
agent: Uuid,
|
||||
host: Option<Uuid>,
|
||||
) -> Result<(), Error> {
|
||||
let now = Utc::now();
|
||||
let row = Selection {
|
||||
tenant, asset: Some(asset), agent: Some(agent), view: Some(View::Current),
|
||||
status: None, hostname: "", last: Uuid::nil(), as_of: now, limit: 1,
|
||||
}.rows(tx).await?.pop().ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?;
|
||||
let data = row.get::<Option<Value>, _>("data").unwrap_or(Value::Null);
|
||||
if inventory_device_type(&data) != Some(DeviceType::Virtual) {
|
||||
return Err(Error(StatusCode::CONFLICT, "HYPERVISOR_REQUIRES_VM"));
|
||||
}
|
||||
if let Some(host) = host {
|
||||
if asset == host {
|
||||
return Err(Error(StatusCode::CONFLICT, "INVALID_HYPERVISOR"));
|
||||
}
|
||||
if hypervisors(tx, tenant, now, Some(&[host]), "", 1).await?.is_empty() {
|
||||
return Err(Error(StatusCode::NOT_FOUND, "HYPERVISOR_UNAVAILABLE"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn os_label(data: &Value) -> Option<String> {
|
||||
let linux_hardware = observed(data, "linux.hardware");
|
||||
if linux_hardware["proxmox_ve"].as_bool() == Some(true)
|
||||
@@ -348,7 +477,7 @@ fn os_label(data: &Value) -> Option<String> {
|
||||
Some("Linux".to_owned())
|
||||
}
|
||||
}
|
||||
fn project(row: &PgRow, now: DateTime<Utc>, full: bool) -> Value {
|
||||
fn project(row: &PgRow, now: DateTime<Utc>, full: bool, hosts: &HashMap<Uuid, Host>) -> Value {
|
||||
let data = row.get::<Option<Value>, _>("data").unwrap_or(Value::Null);
|
||||
let cpu = observed(&data, "linux.cpu");
|
||||
let windows = observed(&data, "windows.hardware");
|
||||
@@ -365,8 +494,7 @@ fn project(row: &PgRow, now: DateTime<Utc>, full: bool) -> Value {
|
||||
.as_u64()
|
||||
.or_else(|| linux_memory["total_bytes"].as_u64())
|
||||
.or_else(|| windows["memory_total_bytes"].as_u64());
|
||||
let device_type =
|
||||
device_type(observed(&data, "linux.hardware")).or_else(|| device_type(windows));
|
||||
let device_type = inventory_device_type(&data);
|
||||
let last = row.get::<Option<DateTime<Utc>>, _>("last_contact_at");
|
||||
let revoked = row.get::<Option<DateTime<Utc>>, _>("revoked_at");
|
||||
let presence = match (revoked, last.map(|t| (now - t).num_seconds())) {
|
||||
@@ -397,6 +525,14 @@ fn project(row: &PgRow, now: DateTime<Utc>, full: bool) -> Value {
|
||||
"source_id":row.get::<Option<String>,_>("source_id"),"quality":if data.is_null(){"unknown"}else{"valid"},
|
||||
"completeness":"partial","health":"unknown"
|
||||
});
|
||||
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);
|
||||
if full {
|
||||
item["assigned_hypervisor_asset_id"] = json!(assigned_id);
|
||||
}
|
||||
}
|
||||
if full {
|
||||
item["inventory"] = data;
|
||||
item["capabilities"] = row.get("capabilities");
|
||||
@@ -457,6 +593,87 @@ mod tests {
|
||||
assert_eq!(device_type(&json!({"device_type":"desktop"})), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hetzner_placeholder_requires_a_valid_guest_and_yields_to_a_registered_host() {
|
||||
let mut data = json!({"observations":[{"scope":"linux.hardware","quality":"valid",
|
||||
"data":{"device_type":"virtual","readable_dmi":{"sys_vendor":" Hetzner "}}}]});
|
||||
assert_eq!(hypervisor_display(&data, None)["kind"], "placeholder");
|
||||
let host = Host { asset_id: Uuid::new_v4(), agent_id: Uuid::new_v4(), hostname: "pve01".into() };
|
||||
assert_eq!(hypervisor_display(&data, Some(&host))["asset_id"], json!(host.asset_id));
|
||||
data["observations"][0]["data"]["device_type"] = json!("physical");
|
||||
assert!(hypervisor_display(&data, None).is_null());
|
||||
data["observations"][0]["data"]["device_type"] = json!("virtual");
|
||||
data["observations"][0]["quality"] = json!("error");
|
||||
assert!(hypervisor_display(&data, None).is_null());
|
||||
data["observations"][0] = json!({"scope":"windows.hardware","quality":"valid",
|
||||
"data":{"device_type":"virtual","manufacturer":"HETZNER ONLINE GMBH"}});
|
||||
assert_eq!(hypervisor_display(&data, None)["hostname"], "Hetzner Cloud");
|
||||
data["observations"][0]["data"]["manufacturer"] = json!("Other company");
|
||||
assert!(hypervisor_display(&data, None).is_null());
|
||||
}
|
||||
|
||||
#[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() {
|
||||
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 = Uuid::new_v4();
|
||||
let other = Uuid::new_v4();
|
||||
let mut ids = [Uuid::new_v4(), Uuid::new_v4()];
|
||||
ids.sort_unstable();
|
||||
let [vm, host] = ids;
|
||||
let foreign_host = Uuid::new_v4();
|
||||
for customer in [tenant, other] {
|
||||
sqlx::query("INSERT INTO tenants(tenant_id,name) VALUES($1,'Hypervisor test')")
|
||||
.bind(customer).execute(&admin).await.unwrap();
|
||||
}
|
||||
for (customer, id, name, kind) in [
|
||||
(tenant, vm, "guest", "virtual"),
|
||||
(tenant, host, "hypervisor-1", "hypervisor"),
|
||||
(other, foreign_host, "hypervisor-2", "hypervisor"),
|
||||
] {
|
||||
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) VALUES($1,$2,$2,$3,now(),now())")
|
||||
.bind(customer).bind(id).bind(rmm_domain::jobs::hash(format!("{customer}:{id}").as_bytes()))
|
||||
.execute(&admin).await.unwrap();
|
||||
let data = json!({"hostname":name,"os":"Ubuntu","root_available_bytes":10,"root_total_bytes":20,
|
||||
"observations":[{"scope":"linux.hardware","quality":"valid",
|
||||
"data":{"device_type":kind,"manufacturer":"Hetzner"}}]});
|
||||
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,1,now(),'linux.base','valid','partial',$5,$6,$7)")
|
||||
.bind(customer).bind(id).bind(Uuid::new_v4()).bind(Uuid::new_v4())
|
||||
.bind(Uuid::new_v4()).bind(data).bind("0".repeat(64)).execute(&admin).await.unwrap();
|
||||
}
|
||||
let mut tx = rmm_persistence::tenant_tx(&app, tenant).await.unwrap();
|
||||
assert!(validate_vm_host_assignment(&mut tx, tenant, vm, vm, Some(foreign_host)).await.is_err());
|
||||
assert!(validate_vm_host_assignment(&mut tx, tenant, vm, vm, Some(vm)).await.is_err());
|
||||
validate_vm_host_assignment(&mut tx, tenant, vm, vm, Some(host)).await.unwrap();
|
||||
|
||||
sqlx::query("UPDATE assets SET hypervisor_asset_id=$2 WHERE asset_id=$1")
|
||||
.bind(vm).bind(host).execute(&mut *tx).await.unwrap();
|
||||
let q = Selection { tenant, asset: None, agent: None, view: Some(View::Current), status: None,
|
||||
hostname: "", last: Uuid::nil(), as_of: Utc::now(), limit: 1 };
|
||||
let page = q.rows(&mut tx).await.unwrap();
|
||||
assert_eq!(page[0].get::<Uuid,_>("asset_id"), vm);
|
||||
let hosts = assigned_hosts(&mut tx, tenant, q.as_of, &page).await.unwrap();
|
||||
assert_eq!(project(&page[0], q.as_of, false, &hosts)["hypervisor"]["hostname"], "hypervisor-1");
|
||||
let options = hypervisors(&mut tx, tenant, q.as_of, None, "HYPERVISOR", 51).await.unwrap();
|
||||
assert_eq!(options.len(), 1);
|
||||
assert_eq!(options[0].asset_id, host);
|
||||
|
||||
sqlx::query("UPDATE assets SET archived_at=now() WHERE asset_id=$1")
|
||||
.bind(host).execute(&mut *tx).await.unwrap();
|
||||
let hosts = assigned_hosts(&mut tx, tenant, q.as_of, &page).await.unwrap();
|
||||
assert_eq!(project(&page[0], q.as_of, false, &hosts)["hypervisor"]["kind"], "placeholder");
|
||||
|
||||
let result = sqlx::query("UPDATE assets SET hypervisor_asset_id=$2 WHERE asset_id=$1")
|
||||
.bind(vm).bind(foreign_host).execute(&mut *tx).await.unwrap_err();
|
||||
assert_eq!(result.as_database_error().unwrap().code().as_deref(), Some("23503"));
|
||||
tx.rollback().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires the disposable RLS database from tests/local_access_database.py"]
|
||||
async fn visibility_is_filtered_before_the_cursor_limit() {
|
||||
@@ -499,7 +716,7 @@ mod tests {
|
||||
limit: 1,
|
||||
};
|
||||
let row = q.rows(&mut tx).await.unwrap().pop().unwrap();
|
||||
let summary = project(&row, q.as_of, false);
|
||||
let summary = project(&row, q.as_of, false, &HashMap::new());
|
||||
assert_eq!(summary["status"], "offline");
|
||||
assert_eq!(summary["ram_total_bytes"], 1024);
|
||||
assert_eq!(summary["cpu_model"], "Test CPU");
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
SELECT asset.asset_id, host.agent_id, inventory.data->>'hostname' AS hostname
|
||||
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 a.created_at<=$2
|
||||
AND a.last_authenticated_at IS NOT NULL AND a.last_contact_at IS NOT NULL
|
||||
ORDER BY a.enrollment_generation DESC, a.created_at DESC, a.agent_id
|
||||
LIMIT 1
|
||||
) host ON host.revoked_at IS NULL
|
||||
JOIN LATERAL (
|
||||
SELECT data FROM observations
|
||||
WHERE tenant_id=asset.tenant_id AND agent_id=host.agent_id AND received_at<=$2
|
||||
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.archived_at IS NULL
|
||||
AND ($3::uuid[] IS NULL OR asset.asset_id=ANY($3))
|
||||
AND nullif(btrim(inventory.data->>'hostname'),'') IS NOT NULL
|
||||
AND ($4='' OR strpos(lower(inventory.data->>'hostname'), lower($4))>0)
|
||||
AND EXISTS (
|
||||
SELECT FROM jsonb_array_elements(CASE WHEN jsonb_typeof(inventory.data->'observations')='array'
|
||||
THEN inventory.data->'observations' ELSE '[]'::jsonb END) o
|
||||
WHERE o->>'scope' IN ('linux.hardware','windows.hardware')
|
||||
AND o->>'quality'='valid' AND o#>>'{data,device_type}'='hypervisor'
|
||||
)
|
||||
ORDER BY lower(inventory.data->>'hostname'), asset.asset_id
|
||||
LIMIT $5
|
||||
@@ -217,6 +217,7 @@ async fn main() -> Result<()> {
|
||||
.route("/api/v1/tenants/{tenant}", axum::routing::patch(customers::rename))
|
||||
.route("/api/v1/devices", get(devices::all))
|
||||
.route("/api/v1/tenants/{tenant}/devices", get(devices::page))
|
||||
.route("/api/v1/tenants/{tenant}/hypervisors", get(devices::hypervisor_options))
|
||||
.route("/api/v1/tenants/{tenant}/devices/{asset}", get(devices::detail));
|
||||
routes = mcp_tokens::routes(routes);
|
||||
routes = routes.route("/auth/local/login", post(auth::local_login));
|
||||
|
||||
@@ -31,6 +31,7 @@ Alle acht Versuche lieferten Exitcode 0. Bei beiden Neustarts wurde die Wiederan
|
||||
| Erweitertes Inventar in den Gerätedetails | OS-Installationsdatum, letzter Neustart, Hersteller, BIOS-Seriennummer, verfügbares Garantieende, Netzwerkkarten mit IP-Adressen, durchsuchbare Software und angemeldete Benutzer. Beide Linux-Geräte melden den Zeitstempel des Root-Dateisystems als geschätztes Installationsdatum. Quelle `1f60183` wurde am 18. November um 19:23 UTC mit Serverhash `8a821863…` und Schema 41 aktiviert. Interne API, öffentliche API und Gateway wurden mit bestandenem Healthcheck gestartet. Der öffentliche WebUI-Index stimmte mit dem Build überein. 80 WebUI-Tests, 73 Linux- und Domänentests, 15 Bootstrap-Tests und zwei native Windows-Inventartests bestanden. Die vorhandene Windows-Kopplung meldet mit `0.1.19` neun Netzwerkkarten und drei systemweit registrierte Programme. Um 19:29 UTC meldete dieselbe Linux-x64-Kopplung nach dem regulären signierten Update auf `0.1.0-mvp.12` zwei Netzwerkkarten und alle 1.372 erfassten DEB-Pakete. Das Agent- und Helperpaar meldete sich bereit. Die Linux-Inventur holt durch ausstehende Meldungen verschobene Erfassungen nach. Die ARM64-Kopplung meldet mit `0.1.0-arm64.6` drei Netzwerkkarten und 893 DEB-Pakete. Beide Linux-Geräte melden ihre BIOS-Seriennummer. Der Windows-Gast meldet keine Seriennummer. Alle drei Geräte meldeten keine angemeldeten Benutzer und keine Garantiedaten. Für eine automatische Garantieabfrage fehlt eine Herstellerquelle. Die öffentliche WebUI zeigte die Details und fand jeweils einen tatsächlichen Softwareeintrag über die Suche auf dem Desktop und bei 390 px Breite. Die drei signierten Releases sind als Installer-Starter veröffentlicht. Linux x64 und Windows sind auch im Katalog von Development B veröffentlicht. [Geräteansicht](../web/src/device-inventory.tsx) · [Linux-Inventar](../crates/agent-linux/src/inventory.rs) · [Windows-Inventar](../crates/agent-windows/src/inventory.rs) |
|
||||
| RAM und CPU-Auslastung in der Übersicht | RAM als verfügbar / gesamt in GiB mit demselben Belegungsbalken wie beim Speicherplatz. Die CPU-Spalte zeigt die letzte gemessene Auslastung in Prozent. Am 18. November wurde `6ed57c4` mit Schema 41 produktiv aktiviert. Beide TLS-Healthchecks und der öffentliche WebUI-Index stimmten mit dem Build überein. Die öffentliche Übersicht zeigte die RAM-Balken auf Desktop und bei 390 px Breite für alle drei Geräte. Die Detailansicht und die automatische Aktualisierung wurden in Chromium auf Linux x64 und ARM64 nachgelesen. OTRS meldete um 18:05 UTC nach dem signierten Wechsel auf `0.1.0-arm64.3` `6,2 / 7,6 GiB` und `1,1 %`. Um 18:06 UTC meldeten Linux x64 `0.1.0-mvp.9`, Windows `0.1.18` und ARM64 frische CPU-Werte und waren authentisiert erreichbar. [Geräteansicht](../web/src/devices.tsx) · [Geräteprojektion](../crates/server/src/devices.rs) |
|
||||
| Gerätetyp in der Übersicht | Spalte „Type“ nach „Hostname“ mit `physical`, `virtual` und `hypervisor`. Erkannte Proxmox-VE-Hosts zeigen `Proxmox VE` als OS. Am 18. November wurde `c599baa` auf dem öffentlichen Server aktiviert. Der Serverrunner bestätigte API, Gateway und öffentlichen API-Dienst mit Binärhash `4f9c8c60…`. Der öffentliche WebUI-Index stimmte mit dem gebauten Bundle überein. Die unveränderten Geräteidentitäten meldeten nach regulärem signierten Update `virtual` auf Linux mit `0.1.0-mvp.7` um 16:45 UTC und Windows mit `0.1.17` um 16:47 UTC. Geräteliste, Details, Mobilansicht mit 390 px und Historie sind in der öffentlichen WebUI geprüft. Beide Pakete sind in Development A und B und als Starter für leere Kataloge veröffentlicht. Die Typen `physical` und `hypervisor` sind mit Testdaten geprüft. Die Feldabnahme auf einem physischen Gerät und einem Proxmox-VE-Host steht aus. [Inventarprojektion](../crates/server/src/devices.rs) · [Geräteansicht](../web/src/devices.tsx) |
|
||||
| Hostzuordnung bei VMs | Die WebUI zeigt einen zugeordneten Hypervisor direkt an der VM. Der Browser prüfte Zuordnung, Verlinkung, Entfernen und den Platzhalter für Hetzner-VMs bei 390 px Breite. Die Kundengrenze wird bei Abfrage und Zuordnung geprüft. [Geräteansicht](../web/src/device-hypervisor.tsx) · [Hostsuche](../crates/server/src/hypervisors.sql) |
|
||||
| Von der Auswahl zur Ausgabe | Die WebUI bindet die ausgewählte Skriptversion, zeigt den Inhalt vor Genehmigung und verlinkt das Ergebnis je Gerät. Ein abgelehnter Antrag erzeugte null Jobs. [Auftragsablauf](evidence/webui-auftragsablauf-20261117.json) · [Ergebnislinks und Entscheidungen](evidence/webui-order-history-20261118.json) Auf OTRS ARM64 wurde der Root-Skript-Helper nachträglich mit dem HTTPS-Installer aktiviert. Die zentrale Geräteregel bindet das berechtigte WebUI-Konto an diese Installation und den signierten Helper. Die öffentliche WebUI-Vorschau akzeptierte Root für OTRS. Die Probe blieb bei einer Vorschau und erzeugte null Anträge, Jobs, Outbox-Einträge und Startgrants. [OTRS-Nachweis](evidence/linux-arm64-otrs-root-helper-20261118.json) |
|
||||
| Frische Installation und periodisches Agentupdate | Beide VMs wurden über HTTPS aufgenommen und übernahmen anschließend ein signiertes Folgepaket mit derselben Geräteidentität. Auf Windows ist der öffentliche GNU-Kanal einschließlich Prüfung des offiziellen Schlüssels belegt. [Linux](evidence/linux-public-installer-update-20261117.json) · [Windows GNU](evidence/windows-gnu-official-vm-20261118.json). ARM64 erweitert denselben HTTPS-Installer mit automatischer Architekturerkennung. Release `0.1.0-arm64.1` ist veröffentlicht und als Starter verfügbar. Auf Ubuntu 22.04.5 ARM64 wurden die öffentlichen Downloads, die Signaturprüfung, die Ablehnung einer veränderten Agentdatei und der native Start aller drei Dateien im Prüfmodus beobachtet. OTRS ist mit Gerätezertifikat aufgenommen und meldet authentisierte Heartbeats. Die erste Kontaktprüfung wartet seit der Korrektur auf das Zertifikat. Der öffentliche Installer lief auf OTRS erneut ohne Traceback und ohne neuen Einmalcode. Der ARM64-Katalogabruf ist bestätigt. Ein späterer Versionswechsel auf ARM64 steht aus. [ARM64-Release](evidence/linux-arm64-installer-20261118.json) · [Geräteaufnahme und Nachtest](evidence/linux-arm64-enrollment-heartbeat-20261118.json) |
|
||||
| Betriebssystemupdate per PowerShell | Die Windows-Updatevorlage installierte KB890830 v5.147 als SYSTEM. Ergebnis und Windows-Ereignis 19 bestätigen die Installation. [Installationsbeleg](evidence/windows-update-installation-20261117.json) |
|
||||
|
||||
@@ -8,6 +8,12 @@ Die öffentliche WebUI verwendet ein lokales Benutzerkonto mit Passwort und eine
|
||||
|
||||
Berechtigte Benutzer können Kunden anlegen und umbenennen. Zur Aufnahme den Zielkunden wählen und unter **Verwaltung → Geräteaufnahme** einen Einmalcode erzeugen. Der Code gilt für diesen Kunden und verfällt bei erfolgreicher Aufnahme oder nach 15 Minuten. Die WebUI zeigt für die veröffentlichten Plattformen Download und Installationsbefehl. Auf dem neuen Gerät das HTTPS-Skript mit Administratorrechten aufrufen und den Code am Prompt eingeben. Für lokale Administrator-Skripte die dafür angebotene Installationsoption wählen. Der Windows-Kanal ist `x86_64-pc-windows-gnu`. [Linux-Installer](https://discovery.ease-technologies.de:8443/install/linux.sh) · [Windows-Installer](https://discovery.ease-technologies.de:8443/install/windows.ps1)
|
||||
|
||||
### Hypervisor einer VM zuordnen
|
||||
|
||||
Eine VM unter **Geräte** öffnen und unter **Gerät verwalten → Hypervisor zuordnen** einen Host aus demselben Kundenbestand auswählen. Die Zuordnung speichern. Der Hostname erscheint unter dem VM-Namen in der Übersicht und öffnet die Details des Hypervisors. **Kein konkreter Hypervisor** entfernt die gespeicherte Zuordnung.
|
||||
|
||||
Bei einer VM mit dem gemeldeten Hersteller Hetzner erscheint ohne verfügbaren konkreten Host **Hetzner Cloud · Platzhalter**. Die Anzeige steht für den Anbieter. Die Auswahl eines echten Hypervisors hat Vorrang.
|
||||
|
||||
### Kunden eines bestehenden Geräts wechseln
|
||||
|
||||
1. In **Geräte** den Hostnamen öffnen und **Gerät verwalten → Kunden wechseln** wählen. Der Agent benötigt eine Version mit Unterstützung für den Kundenwechsel.
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
ALTER TABLE assets
|
||||
ADD COLUMN hypervisor_asset_id uuid,
|
||||
ADD CONSTRAINT assets_hypervisor_not_self CHECK (hypervisor_asset_id <> asset_id),
|
||||
ADD CONSTRAINT assets_same_customer_hypervisor
|
||||
FOREIGN KEY (tenant_id, hypervisor_asset_id) REFERENCES assets(tenant_id, asset_id)
|
||||
ON DELETE SET NULL (hypervisor_asset_id);
|
||||
|
||||
CREATE INDEX assets_hypervisor_reference ON assets (tenant_id, hypervisor_asset_id)
|
||||
WHERE hypervisor_asset_id IS NOT NULL;
|
||||
GRANT UPDATE (hypervisor_asset_id) ON assets TO rmm_app;
|
||||
@@ -292,3 +292,81 @@ test('moves an existing pairing through the WebUI and waits for target inventory
|
||||
await expect(page.getByRole('link', { name: 'Neue Kopplung öffnen' })).toHaveAttribute('href',
|
||||
'#geraete/' + target.tenant_id + '/new-asset/new-agent');
|
||||
});
|
||||
|
||||
test('shows real VM hosts and the Hetzner placeholder without adding a device', async ({ page }) => {
|
||||
const tenant = '11111111-1111-4111-8111-111111111111';
|
||||
const path = '/api/v1/tenants/' + tenant;
|
||||
const customer = { tenant_id: tenant, name: 'Testkunde' };
|
||||
const base = { ...customer, customer_name: customer.name,
|
||||
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' };
|
||||
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: 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() });
|
||||
|
||||
await page.route(origin + '/auth/config', r => r.fulfill({ json: {
|
||||
local_login_enabled: true, oidc_configured: false, oidc_login_url: null, dev_login_enabled: false
|
||||
} }));
|
||||
await page.route(origin + '/auth/session', r => r.fulfill({ json: {
|
||||
principal: 'inventory-owner', tenant_id: tenant, csrf_token: 'host-assignment-fixture',
|
||||
testsimulation: false, permissions: ['inventory:read', 'devices:revoke']
|
||||
} }));
|
||||
await page.route(origin + '/api/v1/**', r => {
|
||||
const req = r.request(), url = new URL(req.url());
|
||||
if (url.pathname === '/api/v1/tenants') return r.fulfill({ json: listing([customer]) });
|
||||
if (url.pathname === '/api/v1/devices' || url.pathname === path + '/devices') {
|
||||
return r.fulfill({ json: listing([guest(), pve]) });
|
||||
}
|
||||
if (url.pathname === path + '/devices/' + vm.asset_id) return r.fulfill({ json: guest() });
|
||||
if (url.pathname === path + '/devices/' + pve.asset_id) return r.fulfill({ json: pve });
|
||||
if (url.pathname === path + '/hypervisors') {
|
||||
expect(req.headers()['x-rmm-tenant']).toBe(tenant);
|
||||
return r.fulfill({ json: { items: [pve], truncated: false } });
|
||||
}
|
||||
if (url.pathname === path + '/devices/' + vm.asset_id + '/hypervisor') {
|
||||
expect(req.method()).toBe('POST');
|
||||
expect(req.headers()['x-csrf-token']).toBe('host-assignment-fixture');
|
||||
expect(url.searchParams.get('agent_id')).toBe(vm.agent_id);
|
||||
const target = req.postDataJSON().hypervisor_asset_id;
|
||||
expect(target).toBe(assigned ? null : pve.asset_id);
|
||||
assigned = target === pve.asset_id;
|
||||
return r.fulfill({ json: { asset_id: vm.asset_id, hypervisor_asset_id: target } });
|
||||
}
|
||||
return r.fulfill({ status: 404, json: { code: 'NOT_FOUND' } });
|
||||
});
|
||||
|
||||
await page.goto(origin + '/#geraete');
|
||||
const vmRow = page.getByRole('row').filter({ has: page.getByRole('button', { name: vm.hostname }) });
|
||||
await expect(vmRow).toContainText('Hetzner Cloud');
|
||||
await expect(vmRow).toContainText('Platzhalter');
|
||||
await expect(page.getByRole('button', { name: 'Hetzner Cloud' })).toHaveCount(0);
|
||||
await expect(page.locator('.fleet-table tbody tr')).toHaveCount(2);
|
||||
await page.getByRole('button', { name: vm.hostname }).click();
|
||||
await page.getByText('Gerät verwalten', { exact: true }).click();
|
||||
await page.getByText('Hypervisor zuordnen', { exact: true }).click();
|
||||
const hostInput = page.getByRole('combobox', { name: 'Hypervisor auswählen' });
|
||||
await hostInput.selectOption(pve.asset_id);
|
||||
await page.getByRole('button', { name: 'Zuordnung speichern' }).click();
|
||||
await expect(page.getByText('Hypervisor zugeordnet.', { exact: true })).toBeVisible();
|
||||
await page.getByRole('button', { name: 'Zur Geräteliste' }).click();
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
const hostLink = vmRow.getByRole('link', { name: pve.hostname });
|
||||
await expect(hostLink).toBeVisible();
|
||||
await expect(vmRow).not.toContainText('Hetzner Cloud');
|
||||
await hostLink.click();
|
||||
await expect(page.getByRole('heading', { name: pve.hostname })).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();
|
||||
await page.getByText('Hypervisor zuordnen', { exact: true }).click();
|
||||
await hostInput.selectOption('');
|
||||
await page.getByRole('button', { name: 'Zuordnung speichern' }).click();
|
||||
await expect(page.getByText('Hostzuordnung entfernt.', { exact: true })).toBeVisible();
|
||||
await page.getByRole('button', { name: 'Zur Geräteliste' }).click();
|
||||
await expect(vmRow).toContainText('Hetzner Cloud');
|
||||
});
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { ApiError, record, request, tenantPath, type RecordValue, type Session } from './api';
|
||||
import { NavIcon } from './navigation';
|
||||
import { ErrorBox, errorText, useResource } from './resource';
|
||||
|
||||
type Host = { asset_id: string; agent_id: string; hostname: string };
|
||||
|
||||
function host(value: unknown): Host | null {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
|
||||
const row = record(value);
|
||||
const { asset_id, agent_id, hostname } = row;
|
||||
return typeof asset_id === 'string' && typeof agent_id === 'string' && typeof hostname === 'string'
|
||||
? { asset_id, agent_id, hostname }
|
||||
: null;
|
||||
}
|
||||
|
||||
export function HypervisorLabel({ device }: { device: RecordValue }) {
|
||||
if (device.device_type !== 'virtual' || !device.hypervisor) return null;
|
||||
const info = record(device.hypervisor);
|
||||
if (info.kind === 'device') {
|
||||
const target = host(info);
|
||||
if (!target || typeof device.tenant_id !== 'string') return null;
|
||||
const path = ['geraete', device.tenant_id, target.asset_id, target.agent_id].map(encodeURIComponent).join('/');
|
||||
return <span className="vm-hypervisor">
|
||||
<NavIcon name="geraete" /><span>Hypervisor <a href={'#' + path} onClick={event => event.stopPropagation()}>
|
||||
{target.hostname}
|
||||
</a></span>
|
||||
</span>;
|
||||
}
|
||||
return info.kind === 'placeholder' && info.provider === 'hetzner' ? (
|
||||
<span className="vm-hypervisor">
|
||||
<NavIcon name="geraete" /><span>Hypervisor <strong>Hetzner Cloud</strong> <span className="muted">· Platzhalter</span></span>
|
||||
</span>
|
||||
) : null;
|
||||
}
|
||||
|
||||
function assignmentError(e: unknown) {
|
||||
if (e instanceof ApiError) {
|
||||
if (e.code === 'HYPERVISOR_UNAVAILABLE') return 'Dieser Hypervisor ist im Kundenbestand derzeit nicht verfügbar.';
|
||||
if (e.code === 'HYPERVISOR_REQUIRES_VM') return 'Die Installation meldet sich derzeit als anderer Gerätetyp.';
|
||||
if (e.code === 'NOT_FOUND') return 'Diese VM-Kopplung ist nicht mehr im Bestand.';
|
||||
}
|
||||
return errorText(e);
|
||||
}
|
||||
|
||||
export function HypervisorAssignment({ device, customer, asset, agent, auth }: {
|
||||
device: RecordValue; customer: string; asset: string; agent: string; auth: Session;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [search, setSearch] = useState('');
|
||||
const [query, setQuery] = useState('');
|
||||
const [draft, setDraft] = useState<string | null>(null);
|
||||
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 value = draft ?? assigned;
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setQuery(search.trim()), 220);
|
||||
return () => clearTimeout(timer);
|
||||
}, [search]);
|
||||
|
||||
const options = useResource(async signal => {
|
||||
if (!open) return null;
|
||||
const data = record(await request(tenantPath(customer, '/hypervisors?q=' + encodeURIComponent(query)),
|
||||
{ tenantId: customer, signal }));
|
||||
if (!Array.isArray(data.items)) throw new Error('Die Hypervisor-Liste konnte nicht gelesen werden.');
|
||||
return { hosts: data.items.map(host).filter((item): item is Host => item !== null), truncated: data.truncated === true };
|
||||
}, [customer, open, query]);
|
||||
const assignedHost = host(device.hypervisor);
|
||||
const hosts = options.data?.hosts ?? [];
|
||||
const selectedMissing = !!value && !hosts.some(item => item.asset_id === value);
|
||||
const canSave = value !== assigned && (!value || !selectedMissing);
|
||||
|
||||
return <details onToggle={e => {
|
||||
setOpen(e.currentTarget.open);
|
||||
if (!e.currentTarget.open) {
|
||||
setDraft(null);
|
||||
setSearch('');
|
||||
setNotice('');
|
||||
setError(null);
|
||||
}
|
||||
}}>
|
||||
<summary>Hypervisor zuordnen</summary>
|
||||
{open && <form onSubmit={async e => {
|
||||
e.preventDefault();
|
||||
if (!canSave || busy) return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
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 }
|
||||
});
|
||||
setNotice(value ? 'Hypervisor zugeordnet.' : 'Hostzuordnung entfernt.');
|
||||
} catch (e) {
|
||||
setError(assignmentError(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}>
|
||||
<label>Hypervisor suchen<input type="search" maxLength={120} value={search}
|
||||
onChange={e => setSearch(e.target.value)} /></label>
|
||||
<ErrorBox error={error ?? options.error} />
|
||||
{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="">Kein konkreter Hypervisor</option>
|
||||
{selectedMissing && <option value={value} disabled>
|
||||
{assignedHost?.asset_id === value ? assignedHost.hostname : 'Zugeordneter Host außerhalb der Treffer'}
|
||||
</option>}
|
||||
{hosts.map(item => <option key={item.asset_id} value={item.asset_id}>{item.hostname}</option>)}
|
||||
</select></label>
|
||||
<button className="primary" disabled={busy || !canSave}>Zuordnung speichern</button>
|
||||
{notice && <p role="status">{notice}</p>}
|
||||
</form>}
|
||||
</details>;
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import { CatalogCheckNotice } from './catalog-check';
|
||||
import { devicePlatform } from './script-catalog';
|
||||
import { DeviceInventoryPanels, systemDetails } from './device-inventory';
|
||||
import { DeviceCustomerTransfer } from './device-customer-transfer';
|
||||
import { HypervisorAssignment, HypervisorLabel } from './device-hypervisor';
|
||||
import { ErrorBox, errorText, useResource } from './resource';
|
||||
import { NavIcon, orderDetailRoute } from './navigation';
|
||||
import { orderTitle, Status } from './order-presentation';
|
||||
@@ -206,6 +207,7 @@ function DeviceDetail({
|
||||
<div>
|
||||
<h1>{label(d.hostname)}</h1>
|
||||
<Presence d={d} />
|
||||
<HypervisorLabel device={d} />
|
||||
</div>
|
||||
</div>
|
||||
<section>
|
||||
@@ -280,6 +282,8 @@ function DeviceDetail({
|
||||
<details open={managing} onToggle={e => setManaging(e.currentTarget.open)}>
|
||||
<summary>Gerät verwalten</summary>
|
||||
<ErrorBox error={error} />
|
||||
{d.device_type === 'virtual' && d.lifecycle === 'current' &&
|
||||
<HypervisorAssignment device={d} customer={customer} asset={asset} agent={agent} auth={scoped} />}
|
||||
<DeviceCustomerTransfer auth={scoped} customer={customer} asset={asset} agent={agent}
|
||||
customers={customers} active={d.lifecycle === 'current'}
|
||||
supported={Array.isArray(d.capabilities) && d.capabilities.includes('device.customer_transfer/1')} />
|
||||
@@ -601,6 +605,7 @@ export function Devices({
|
||||
>
|
||||
{label(d.hostname)}
|
||||
</button>
|
||||
<HypervisorLabel device={d} />
|
||||
</td>
|
||||
<td data-label="Type">{label(d.device_type)}</td>
|
||||
<td data-label="OS">{label(d.os)}</td>
|
||||
|
||||
@@ -94,6 +94,8 @@ section.fleet { padding:0; overflow:hidden; }
|
||||
.fleet-table th:last-child,.fleet-table td:last-child { padding-right:18px; }
|
||||
.fleet-table tbody tr { cursor:pointer; } .fleet-table tbody tr:hover,.fleet-table tr:focus-within { background:#f2f7f4; }
|
||||
.release-table tbody tr { cursor:auto; }
|
||||
.vm-hypervisor { display:flex; align-items:baseline; gap:6px; margin-top:5px; color:var(--subtle); font-size:.78rem; overflow-wrap:anywhere; }
|
||||
.vm-hypervisor .nav-icon { width:13px; height:13px; flex:none; align-self:flex-start; margin-top:2px; }
|
||||
.fleet-table .target-col { width:35px; }
|
||||
.fleet-table td[data-label="Type"] { overflow-wrap:anywhere; }
|
||||
.fleet-table input[type=checkbox] { margin:0; }
|
||||
|
||||
Reference in New Issue
Block a user