Compare commits

..
Author SHA1 Message Date
kevin_janssen dd59052e7c Record native Windows idle performance and SYSTEM acceptance
Rust development slice / linux (push) Failing after 8s
2026-11-18 21:31:48 +01:00
kevin_janssen a4bcebf440 Slow successful Windows helper time refreshes 2026-11-18 21:19:14 +01:00
kevin_janssen aea2d5b379 Expand the passive inventory shown in device details
Rust development slice / linux (push) Failing after 9s
2026-11-18 20:02:41 +01:00
kevin_janssen 38f43f887a Record the native OTRS closure and dashboard verification
Rust development slice / linux (push) Failing after 8s
2026-11-18 19:08:27 +01:00
kevin_janssen 915e126f24 Reconcile a human closure when the helper has no result
Rust development slice / linux (push) Failing after 9s
2026-11-18 19:03:02 +01:00
kevin_janssen abad2022e2 Record the live RAM and CPU dashboard checks
Rust development slice / linux (push) Failing after 8s
2026-11-18 18:54:40 +01:00
kevin_janssen 6ed57c4d0b Show the same capacity bar for RAM and disk space
Rust development slice / linux (push) Failing after 7s
2026-11-18 18:47:46 +01:00
kevin_janssen 7006ce7420 Keep the last valid CPU reading during RAM-only heartbeats
Rust development slice / linux (push) Failing after 8s
2026-11-18 18:46:04 +01:00
kevin_janssen b3fe35b86b Show available RAM and measured CPU usage for devices
Rust development slice / linux (push) Failing after 8s
2026-11-18 18:37:18 +01:00
31 changed files with 1587 additions and 123 deletions
+5 -1
View File
@@ -10,8 +10,12 @@ 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)
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. Beim Kundenwechsel erhält das Gerät eine neue Kopplung. Eine ausgeschiedene Installation kann nach Widerruf und persönlicher Bestätigung endgültig gelöscht werden. Ein noch gültiger offener Genehmigungsantrag oder ein nicht abgeschlossener Job einschließlich `unknown` sperrt die Löschung. Daten weiterhin beteiligter Zielgeräte bleiben erhalten. [Regeln zur Löschung](migrations/0036_delete_device_pairing.sql)
In den Gerätedetails erscheinen OS-Installationszeit, letzter Systemstart, Hersteller, BIOS-Seriennummer, Netzwerkkarten samt IPv4- und IPv6-Adressen, installierte Software und die bei der letzten Inventur angemeldeten Benutzer. Windows meldet den vom Betriebssystem erfassten Installationszeitpunkt. Linux kennzeichnet den Zeitstempel aus dem Installer-Verzeichnis oder dem Root-Dateisystem als Schätzung. Das Softwareinventar erfasst Linux-Pakete aus dpkg und Windows-Systeminstallationen aus der Uninstall-Registrierung. Begrenzte Meldungen werden ausgewiesen. Herstellergarantie und Firmwaredaten erscheinen bei verfügbarem Befund. Die Daten gehören zum kundengebundenen Inventar des Geräts. [Geräteansicht](web/src/device-inventory.tsx)
## Vom Skript zum Ergebnis
| Schritt | Verhalten |
@@ -24,7 +28,7 @@ Kunden lassen sich in der WebUI anlegen und umbenennen. Beim Kundenwechsel erhä
Linux führt Shellskripte unter dem Dienstkonto oder über den eingerichteten Helper als root aus. Windows führt PowerShell unter LocalService oder über den Helper als SYSTEM aus. Neustart und Installation von Windows-Updates sind Skriptaufträge. Bei einem Neustart kann das Skript bereits vor dem Herunterfahren erfolgreich enden. Der Betriebsnachweis verbindet den neuen Bootbezug mit dem nächsten authentisierten Kontakt und einem Folgeauftrag. [Skriptbibliothek](crates/server/src/script_library.rs) · [Auftragsverarbeitung](crates/server/src/jobs.rs)
Ein Abbruchwunsch wird am Auftrag gespeichert. Bei unterbrochener Rückmeldung gleichen Server, Agent und gegebenenfalls Helper den gespeicherten Versuch ab. Bei `unknown` bleibt die Wirkung ungeklärt. Die WebUI kann einen solchen Fall dokumentiert abschließen. Dieser Abschluss erteilt keine Freigabe für einen weiteren Versuch.
Ein Abbruchwunsch wird am Auftrag gespeichert. Bei unterbrochener Rückmeldung gleichen Server, Agent und gegebenenfalls Helper den gespeicherten Versuch ab. Bei `unknown` bleibt die Wirkung ungeklärt. Die WebUI kann einen solchen Fall dokumentiert abschließen. Agent und Helper übernehmen den Abschluss im signierten Abgleich auch dann, wenn der Agent den Abbruch seiner eigenen Ausführung protokolliert hat und im unabhängig gebundenen Verbrauchsjournal des Helpers ein Ergebnis fehlt. Beide bewahren die ursprünglichen Belege. Der Abschluss erteilt keine Freigabe für einen weiteren Versuch.
## Öffentliche Verwaltung und Berechtigungen
+39 -15
View File
@@ -782,10 +782,10 @@ impl<V: Ed25519Verifier> HelperSync<V> {
let d = decisions
.get(&id)
.context("ROOT_ATTEMPT_OMITTED_FROM_DECISION")?;
validate_summary(row, local)?;
validate_decision(row, local, d)?;
let unreported = validate_summary(row, local)?;
validate_decision(row, local, d, unreported)?;
if d.unlock {
let bytes = unlock_outcome(row, d, current_boot)?;
let bytes = unlock_outcome(row, d, current_boot, unreported.then_some(local))?;
if d.outcome_state == "closed_unknown" {
crate::ledger::retain_closure_original(
&tx,
@@ -1636,22 +1636,33 @@ fn definitive(row: &LocalAttempt) -> bool {
"succeeded" | "failed" | "cancelled" | "expired" | "closed_unknown"
) && !row.outcome_bytes.is_empty()
}
fn validate_summary(row: &LocalAttempt, a: &AttemptView) -> Result<()> {
fn validate_summary(row: &LocalAttempt, a: &AttemptView) -> Result<bool> {
let unreported = row.state == "unknown"
&& row.outcome_sha256.is_empty()
&& row.outcome_bytes.is_empty()
&& row.update_handoff_bytes.is_empty()
&& crate::reconcile::uncertain_agent_outcome(&a.state, &a.outcome_bytes, &a.outcome_sha256);
ensure!(
a.job_payload_hash == row.job_payload_hash
&& a.grant_id == row.grant_id.to_string()
&& a.consumption == "consumed"
&& a.state == row.state
&& a.revision >= row.revision
&& a.original_boot_id == row.original_boot_id.to_string()
&& a.outcome_sha256 == row.outcome_sha256
&& a.update_handoff_bytes == row.update_handoff_bytes
&& (a.outcome_bytes.is_empty() || a.outcome_bytes == row.outcome_bytes),
&& (unreported
|| (a.state == row.state
&& a.outcome_sha256 == row.outcome_sha256
&& (a.outcome_bytes.is_empty() || a.outcome_bytes == row.outcome_bytes))),
"ROOT_SNAPSHOT_REQUEST_MISMATCH"
);
Ok(())
Ok(unreported)
}
fn validate_decision(row: &LocalAttempt, a: &AttemptView, d: &AttemptDecision) -> Result<()> {
fn validate_decision(
row: &LocalAttempt,
a: &AttemptView,
d: &AttemptDecision,
unreported: bool,
) -> Result<()> {
if !row.update_handoff_bytes.is_empty() {
let proof =
rmm_domain::agent_update::UpdateInflightProof::from_bytes(&row.update_handoff_bytes)
@@ -1686,7 +1697,7 @@ fn validate_decision(row: &LocalAttempt, a: &AttemptView, d: &AttemptDecision) -
&& d.original_boot_id == Some(row.original_boot_id)
&& (d.revision >= a.revision || (!d.unlock && d.outcome_state == "unknown"))
&& d.previous_outcome_sha256.as_deref()
== (!row.outcome_sha256.is_empty()).then_some(row.outcome_sha256.as_str()),
== (!a.outcome_sha256.is_empty()).then_some(a.outcome_sha256.as_str()),
"ROOT_SIGNED_ATTEMPT_BINDING"
);
ensure!(
@@ -1697,11 +1708,26 @@ fn validate_decision(row: &LocalAttempt, a: &AttemptView, d: &AttemptDecision) -
),
"UNKNOWN_CANNOT_UNLOCK"
);
ensure!(
!unreported
|| (!d.unlock && d.outcome_state == "unknown")
|| (d.unlock
&& d.outcome_state == "closed_unknown"
&& d.reason == "OPERATOR_CLOSED_UNKNOWN"),
"ROOT_UNREPORTED_OUTCOME_CLOSURE_REQUIRED"
);
Ok(())
}
fn unlock_outcome(row: &LocalAttempt, d: &AttemptDecision, current_boot: Uuid) -> Result<Vec<u8>> {
fn unlock_outcome(
row: &LocalAttempt,
d: &AttemptDecision,
current_boot: Uuid,
unreported: Option<&AttemptView>,
) -> Result<Vec<u8>> {
let bytes = if d.outcome_bytes.is_empty() {
row.outcome_bytes.clone()
unreported
.map_or(&row.outcome_bytes, |a| &a.outcome_bytes)
.clone()
} else {
d.outcome_bytes.clone()
};
@@ -1712,9 +1738,7 @@ fn unlock_outcome(row: &LocalAttempt, d: &AttemptDecision, current_boot: Uuid) -
&& o.state == d.outcome_state,
"ROOT_CANONICAL_UNLOCK_OUTCOME"
);
if bytes != row.outcome_bytes
&& crate::reconcile::operator_closure(&d.reason, &row.state, &o)
{
if bytes != row.outcome_bytes && crate::reconcile::operator_closure(&d.reason, &row.state, &o) {
return Ok(bytes);
}
if bytes != row.outcome_bytes {
+120 -13
View File
@@ -1019,9 +1019,9 @@ impl<V: Ed25519Verifier> ClientSync<V> {
} else {
for d in decision.attempts.iter().filter(|d| d.unlock) {
let grant = d.grant_id.context("UNLOCK_GRANT_MISSING")?;
let (agent,generation,job,attempt,previous):(String,u64,String,String,Option<Vec<u8>>)=tx.query_row(
"SELECT agent,generation,job,attempt,COALESCE((SELECT outcome FROM execution_evidence WHERE execution_evidence.grant_id=consumed.grant_id),result) FROM consumed WHERE grant_id=?1",
[grant.to_string()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?)))?;
let (agent,generation,job,attempt,previous,start):(String,u64,String,String,Option<Vec<u8>>,Option<Vec<u8>>)=tx.query_row(
"SELECT c.agent,c.generation,c.job,c.attempt,COALESCE(e.outcome,c.result),e.start FROM consumed c LEFT JOIN execution_evidence e USING(grant_id) WHERE c.grant_id=?1",
[grant.to_string()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?,r.get(5)?)))?;
ensure!(
agent == self.binding.agent_id.to_string()
&& generation == self.binding.enrollment_generation
@@ -1034,13 +1034,61 @@ impl<V: Ed25519Verifier> ClientSync<V> {
Some(&self.binding),
grant,
)?;
let previous = resolved
.or(previous)
.context("LOCAL_UNLOCK_PREVIOUS_OUTCOME_MISSING")?;
let original = previous.clone();
let prior = canonical_outcome_bytes(&serde_json::from_slice::<ReconciledOutcome>(
&previous,
)?)?;
let previous = resolved.or(previous);
let summary = gate
.request
.attempts
.iter()
.find(|a| a.job_id == job && a.attempt_id == attempt)
.context("LOCAL_UNLOCK_ATTEMPT_MISSING")?;
let closure = d.reason == "OPERATOR_CLOSED_UNKNOWN"
&& d.outcome_state == "closed_unknown"
&& summary.consumption == "consumed"
&& uncertain_agent_outcome(
&summary.state,
&summary.outcome_bytes,
&summary.outcome_sha256,
);
let prior = match &previous {
Some(bytes) => {
let canonical = canonical_outcome_bytes(&serde_json::from_slice(bytes)?)?;
if closure
&& summary.state == "closed_unknown"
&& uncertain_agent_outcome("unknown", &canonical, &hash(&canonical))
{
summary.outcome_bytes.clone()
} else {
canonical
}
}
None => {
ensure!(closure, "LOCAL_UNLOCK_PREVIOUS_OUTCOME_MISSING");
let start: serde_json::Value = serde_json::from_slice(
&start.context("LOCAL_UNLOCK_ORIGINAL_START_MISSING")?,
)?;
let request: crate::auth::Request =
serde_json::from_value(start["request"].clone())?;
let permit: rmm_domain::jobs::ExecutionPermitPayload =
serde_json::from_slice(&request.permit_bytes)?;
let (original, permit) = self.binding.verify_with(
&request,
permit.not_before,
&self.verifier,
)?;
ensure!(
permit.grant_id == grant
&& original.job_id == d.job_id
&& original.attempt_id == d.attempt_id
&& hash(&request.job_bytes) == d.job_payload_hash
&& Some(permit.authorization_id) == d.authorization_id
&& Some(permit.plan_hash.as_str()) == d.plan_hash.as_deref()
&& start["previous_boot_id"].as_str()
== d.original_boot_id.map(|id| id.to_string()).as_deref(),
"LOCAL_UNLOCK_ORIGINAL_START_BINDING"
);
summary.outcome_bytes.clone()
}
};
ensure!(
d.previous_outcome_sha256.as_deref() == Some(hash(&prior).as_str()),
"LOCAL_UNLOCK_PREVIOUS_OUTCOME_MISMATCH"
@@ -1055,7 +1103,8 @@ impl<V: Ed25519Verifier> ClientSync<V> {
terminal(&outcome.state)
&& outcome.state == d.outcome_state
&& canonical_outcome_bytes(&outcome)? == bytes
&& d.outcome_sha256.as_deref() == Some(hash(&bytes).as_str()),
&& d.outcome_sha256.as_deref() == Some(hash(&bytes).as_str())
&& (previous.is_some() || operator_closure(&d.reason, "unknown", &outcome)),
"LOCAL_UNLOCK_CANONICAL_OUTCOME"
);
let preserve = crate::windows_system_nonstart::preserve_original_unlock(
@@ -1065,7 +1114,12 @@ impl<V: Ed25519Verifier> ClientSync<V> {
&bytes,
)?;
if outcome.state == "closed_unknown" {
crate::ledger::retain_closure_original(&tx, grant, &original, &bytes)?;
crate::ledger::retain_closure_original(
&tx,
grant,
previous.as_deref().unwrap_or_default(),
&bytes,
)?;
}
tx.execute(
"UPDATE consumed SET result=?2 WHERE grant_id=?1",
@@ -1304,6 +1358,32 @@ pub(crate) fn operator_closure(
&& outcome.evidence["closed_by_human"] == true
&& outcome.evidence["retry"] == false
}
/// An interrupted agent can record its own uncertainty while the independently
/// consumed helper grant has no result. Neither witness establishes an effect.
pub(crate) fn uncertain_agent_outcome(state: &str, bytes: &[u8], digest: &str) -> bool {
if bytes.is_empty() || hash(bytes) != digest {
return false;
}
let Ok(outcome) = serde_json::from_slice::<ReconciledOutcome>(bytes) else {
return false;
};
canonical_outcome_bytes(&outcome).is_ok_and(|canonical| canonical == bytes)
&& outcome.state == state
&& !outcome.output_truncated
&& !outcome.reboot_required
&& (operator_closure("OPERATOR_CLOSED_UNKNOWN", "unknown", &outcome)
|| (state == "unknown"
&& matches!(
outcome.error_code.as_str(),
"AGENT_PROCESS_INTERRUPTED" | "HELPER_TRANSPORT_EFFECT_UNKNOWN"
)
&& outcome.exit_code.is_none()
&& outcome.stdout.is_empty()
&& outcome.stderr.is_empty()
&& outcome.evidence["postconditions_passed"] == false))
}
fn optional_uuid(s: &str) -> Result<Option<Uuid>> {
if s.is_empty() {
Ok(None)
@@ -1452,6 +1532,24 @@ fn attempts(db: &Connection, ledger: &Connection, binding: &Binding) -> Result<V
result_envelope = Some(envelope);
}
}
// The signed closure projection can commit before either consumption
// ledger. A fresh signed check may then finish the remaining writes.
if state == "closed_unknown"
&& consumption == "consumed"
&& (canonical.is_empty()
|| uncertain_agent_outcome("unknown", &canonical, &hash(&canonical)))
{
let closed: Vec<u8> = db.query_row(
"SELECT outcome FROM reconcile_outcomes WHERE job=?1 AND attempt=?2",
params![offer.job_id, offer.attempt_id],
|r| r.get(0),
)?;
ensure!(
uncertain_agent_outcome(&state, &closed, &hash(&closed)),
"LOCAL_CLOSURE_OUTCOME_MISMATCH"
);
canonical = closed;
}
if !canonical.is_empty() {
let o: ReconciledOutcome = serde_json::from_slice(&canonical)?;
ensure!(o.state == state, "LOCAL_OUTCOME_STATE_MISMATCH");
@@ -1746,6 +1844,15 @@ fn merge_helper(local: &mut [SyncAttempt], helper: &HelperSnapshot) -> Result<()
"HELPER_ATTEMPT_BINDING"
);
if h.consumption != "unconsumed" {
let unreported = h.state == "unknown"
&& h.consumption == "consumed"
&& h.outcome_bytes.is_empty()
&& h.outcome_sha256.is_empty()
&& h.update_handoff_bytes.is_empty()
&& a.consumption == "consumed"
&& a.grant_id == h.grant_id
&& a.original_boot_id == h.original_boot_id
&& uncertain_agent_outcome(&a.state, &a.outcome_bytes, &a.outcome_sha256);
if !h.update_handoff_bytes.is_empty() {
ensure!(
h.state == "running" && a.state == "running" && a.outcome_bytes.is_empty(),
@@ -1756,7 +1863,7 @@ fn merge_helper(local: &mut [SyncAttempt], helper: &HelperSnapshot) -> Result<()
a.grant_id = h.grant_id.clone();
a.consumption = h.consumption.clone();
ensure!(
a.outcome_sha256 == h.outcome_sha256,
a.outcome_sha256 == h.outcome_sha256 || unreported,
"HELPER_OUTCOME_MISMATCH"
);
if a.original_boot_id.is_empty() {
+201
View File
@@ -1485,6 +1485,207 @@ fn persist_original_fixture_result(
fn completion_outcome() -> rmm_agent_core::auth::Outcome {
serde_json::from_slice(&canonical_outcome_bytes(&success()).unwrap()).unwrap()
}
#[test]
fn human_closure_reconciles_agent_interruption_and_a_helper_without_result() {
use rmm_agent_core::helper_reconcile::{self, BootSource, ExecutorLedgerGuard, HelperSync};
struct TestGuard;
impl ExecutorLedgerGuard for TestGuard {
fn check(&self, db: &Connection) -> anyhow::Result<()> {
anyhow::ensure!(
db.is_autocommit(),
"fixture ledger must be outside a transaction"
);
Ok(())
}
}
struct TestBoot(Uuid);
impl BootSource for TestBoot {
fn current_boot(&self) -> anyhow::Result<Uuid> {
Ok(self.0)
}
}
fn map(snapshot: &helper_reconcile::Snapshot) -> HelperSnapshot {
HelperSnapshot {
journal_id: snapshot.journal_id,
checkpoint: snapshot.checkpoint,
previous_decision_id: snapshot.previous_decision_id,
attempts: snapshot
.attempts
.iter()
.map(|a| SyncAttempt {
job_id: a.job_id.to_string(),
attempt_id: a.attempt_id.to_string(),
job_payload_hash: a.job_payload_hash.clone(),
grant_id: a.grant_id.to_string(),
consumption: a.consumption.clone(),
state: a.state.clone(),
revision: a.revision,
original_boot_id: a.original_boot_id.to_string(),
outcome_sha256: a.outcome_sha256.clone(),
outcome_bytes: a.outcome_bytes.clone(),
..Default::default()
})
.collect(),
}
}
let closed = canonical_outcome_bytes(&ReconciledOutcome {
state: "closed_unknown".into(),
stdout: vec![],
stderr: vec![],
exit_code: None,
output_truncated: false,
reboot_required: false,
evidence: serde_json::json!({
"postconditions_passed":false,"effect":"unknown","closed_by_human":true,"retry":false
}),
error_code: "OPERATOR_CLOSED_UNKNOWN".into(),
})
.unwrap();
for interrupt_after_projection in [false, true] {
let mut f = Fixture::new();
reconcile::initialize(&f.db).unwrap();
let (offer, grant, _) = f.add(
"running",
true,
None,
Action::SetServiceState {
unit: "rmm-acceptance.service".into(),
state: "running".into(),
},
);
let grant = grant.unwrap();
let archive = persist_original_fixture_result(
&mut f,
&offer,
&grant,
rmm_agent_core::auth::Outcome::unknown("AGENT_PROCESS_INTERRUPTED"),
);
rmm_agent_core::jobs::ack(&mut f.db, &archive.message_id).unwrap();
let start: Vec<u8> = f
.ledger
.query_row("SELECT start FROM execution_evidence", [], |row| row.get(0))
.unwrap();
let start: serde_json::Value = serde_json::from_slice(&start).unwrap();
let request: Request = serde_json::from_value(start["request"].clone()).unwrap();
let boot = TestBoot(f.channel.boot_id);
let guard = TestGuard;
let mut helper_db = Connection::open_in_memory().unwrap();
rmm_agent_core::ledger::initialize_ledger(&helper_db).unwrap();
rmm_agent_core::ledger::begin_execution(
&mut helper_db,
&grant,
&request,
boot.0,
f.clock.now,
)
.unwrap();
let mut helper = HelperSync::new(f.binding.clone(), &f.clock).unwrap();
let mut client = f.client();
for round in 0..if interrupt_after_projection { 3 } else { 2 } {
let snapshot = map(&helper
.snapshot(
&mut helper_db,
&guard,
f.channel.connection_generation,
&f.clock,
&boot,
)
.unwrap());
assert_eq!(snapshot.attempts[0].state, "unknown");
assert!(snapshot.attempts[0].outcome_bytes.is_empty());
let prepared = client
.prepare(
&mut f.db,
&f.ledger,
f.channel.clone(),
Some(&snapshot),
&f.clock,
)
.unwrap();
let agent_attempt = &prepared.request.attempts[0];
assert!(!agent_attempt.outcome_bytes.is_empty());
let mut d = f.decision(&prepared, round != 0);
d.issued_at = f.clock.now;
if round != 0 {
let attempt = &mut d.attempts[0];
attempt.revision = 3;
attempt.outcome_state = "closed_unknown".into();
attempt.reason = "OPERATOR_CLOSED_UNKNOWN".into();
attempt.unlock = true;
attempt.outcome_sha256 = Some(hash(&closed));
if agent_attempt.state == "unknown" {
attempt.outcome_bytes = closed.clone();
}
}
let signed = f.sign(&d);
client.apply(&mut f.db, &signed, &f.clock).unwrap();
if interrupt_after_projection && round == 1 {
client = f.client();
continue;
}
client.apply_consumption(&mut f.ledger, &f.clock).unwrap();
let raw = prepared.request.encode_to_vec();
let response = helper_reconcile::SignedResponse {
decision_bytes: signed.decision_bytes,
signature: signed.signature,
};
let applied = helper
.apply(&mut helper_db, &guard, &response, &raw, &f.clock, &boot)
.unwrap();
if round == 0 {
assert!(!applied.ready && applied.unlocked_grants.is_empty());
assert!(!client.can_start(&f.channel, false, &f.clock));
} else {
assert!(applied.ready);
assert_eq!(applied.unlocked_grants, vec![grant.grant_id]);
assert!(
helper
.apply(&mut helper_db, &guard, &response, &raw, &f.clock, &boot)
.unwrap()
.unlocked_grants
.is_empty()
);
client.apply_consumption(&mut f.ledger, &f.clock).unwrap();
client.confirm_helper(&map(&applied.snapshot)).unwrap();
assert!(client.can_start(&f.channel, true, &f.clock));
}
}
assert_eq!(
f.db.query_row::<String, _, _>("SELECT state FROM job_attempts", [], |rec| rec.get(0))
.unwrap(),
"closed_unknown"
);
assert_eq!(
f.db.query_row::<Vec<u8>, _, _>("SELECT envelope FROM reconcile_results", [], |rec| {
rec.get(0)
})
.unwrap(),
archive.encode_to_vec()
);
for ledger in [&f.ledger, &helper_db] {
assert_eq!(
ledger
.query_row::<Vec<u8>, _, _>("SELECT result FROM consumed", [], |rec| rec.get(0))
.unwrap(),
closed
);
assert_eq!(
ledger
.query_row::<(Vec<u8>, Vec<u8>), _, _>(
"SELECT original_outcome,closure_outcome FROM unknown_closure_originals",
[],
|rec| Ok((rec.get(0)?, rec.get(1)?))
)
.unwrap(),
(vec![], closed.clone())
);
}
}
}
#[test]
fn crash_after_durable_outcome_before_result_recovers_original_then_signed_sync_closes() {
let mut f = Fixture::new();
+169 -18
View File
@@ -4,12 +4,12 @@ use crate::{
actions::{ServiceUnit, reboot_required},
process,
};
use rmm_domain::inventory_document::DeviceType;
use rmm_domain::inventory_document::{CpuTimes, DeviceType, firmware_identifier};
use std::{
collections::BTreeMap,
ffi::{CStr, CString},
fs,
io::Read,
io::{BufRead, BufReader, Read},
mem::MaybeUninit,
net::{Ipv4Addr, Ipv6Addr},
path::Path,
@@ -169,6 +169,9 @@ pub struct OperatingSystem {
pub hostname: String,
pub boot_id: String,
pub uptime_seconds: f64,
pub booted_at: Option<chrono::DateTime<chrono::Utc>>,
pub installed_at: Option<chrono::DateTime<chrono::Utc>>,
pub install_date_source: Option<&'static str>,
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct Interface {
@@ -260,6 +263,8 @@ pub struct Hardware {
pub readable_dmi: BTreeMap<String, String>,
pub device_type: Option<DeviceType>,
pub proxmox_ve: bool,
pub manufacturer: Option<String>,
pub bios_serial_number: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct LinuxInventory {
@@ -271,6 +276,7 @@ pub struct LinuxInventory {
pub dns: Observation<Dns>,
pub volumes: Observation<Vec<Observation<Volume>>>,
pub software: Observation<Vec<SoftwarePackage>>,
pub users: Observation<Vec<String>>,
pub updates: Observation<UpdateStatus>,
pub hardware: Observation<Hardware>,
pub smart: Observation<()>,
@@ -285,6 +291,7 @@ pub fn collect_native() -> LinuxInventory {
dns: dns(),
volumes: volumes(),
software: software(),
users: logged_in_users(),
updates: updates(),
hardware: hardware(),
smart: Observation::unavailable(
@@ -380,6 +387,22 @@ pub fn capabilities() -> BTreeMap<String, Observation<bool>> {
);
result
}
fn installed_at() -> Option<(chrono::DateTime<chrono::Utc>, &'static str)> {
for (path, source) in [
("/var/log/installer", "installer_directory"),
("/", "root_filesystem"),
] {
if let Some(time) = fs::metadata(path)
.ok()
.and_then(|data| data.created().ok())
.filter(|time| *time > SystemTime::UNIX_EPOCH && *time <= SystemTime::now())
{
return Some((time.into(), source));
}
}
None
}
pub fn operating_system() -> Observation<OperatingSystem> {
let release = read("/etc/os-release", 32 * 1024);
let kernel = read("/proc/sys/kernel/osrelease", 4096);
@@ -417,8 +440,21 @@ pub fn operating_system() -> Observation<OperatingSystem> {
.map(|(k, v)| (k.into(), v.trim_matches('"').into()))
})
.collect();
let booted_at = read("/proc/stat", 256 * 1024)
.data
.as_deref()
.and_then(|stat| {
let seconds = stat
.lines()
.find_map(|line| line.strip_prefix("btime "))?
.trim()
.parse()
.ok()?;
chrono::DateTime::from_timestamp(seconds, 0)
});
let installed = installed_at();
Observation::valid(
"linux.os:/etc/os-release,/proc",
"linux.os:/etc/os-release,/proc,filesystem-birth",
OperatingSystem {
release,
kernel: kernel.trim().into(),
@@ -426,12 +462,109 @@ pub fn operating_system() -> Observation<OperatingSystem> {
hostname: hostname.trim().into(),
boot_id,
uptime_seconds,
booted_at,
installed_at: installed.map(|(time, _)| time),
install_date_source: installed.map(|(_, source)| source),
},
)
} else {
Observation::unavailable("linux.os", Quality::Error, "OS_SOURCE_UNAVAILABLE")
}
}
fn logged_in_users() -> Observation<Vec<String>> {
const LOGINCTL: &str = "/usr/bin/loginctl";
let listed = command(
LOGINCTL,
&["--no-legend", "--no-pager", "list-sessions"],
16 * 1024,
);
let Some(rows) = &listed.data else {
return map(listed, |_| None);
};
let mut ids = rows
.lines()
.filter_map(|line| line.split_whitespace().next());
let mut args = vec![
"--no-pager",
"--all",
"--property=Name,Class,State",
"show-session",
"--",
];
args.extend(
ids.by_ref()
.take(64)
.filter(|id| id.bytes().all(|c| c.is_ascii_alphanumeric())),
);
let limited = listed.truncated || ids.next().is_some();
if args.len() == 5 {
return Observation::valid("linux.logind:loginctl", Vec::new());
}
let mut report = map(command(LOGINCTL, &args, 16 * 1024), |text| {
let users: std::collections::BTreeSet<_> = text
.split("\n\n")
.filter_map(|block| {
let fields: BTreeMap<_, _> = block
.lines()
.filter_map(|line| line.split_once('='))
.collect();
let class = *fields.get("Class")?;
let state = *fields.get("State")?;
let name = *fields.get("Name")?;
(matches!(
class,
"user" | "user-early" | "user-light" | "user-early-light"
) && matches!(state, "online" | "active")
&& !name.is_empty()
&& name.len() <= 255)
.then(|| name.to_owned())
})
.collect();
Some(users.into_iter().collect())
});
report.source_id = "linux.logind:loginctl".into();
if limited && report.data.is_some() {
report = report.partial("SESSION_LIMIT");
report.truncated = true;
}
report
}
fn aggregate_jiffies(stat: &str) -> Option<Vec<u64>> {
stat.lines()
.find(|line| line.starts_with("cpu "))
.and_then(|line| {
line.split_whitespace()
.skip(1)
.map(str::parse)
.collect::<Result<_, _>>()
.ok()
})
}
fn linux_cpu_times(jiffies: &[u64]) -> Option<CpuTimes> {
// Linux already includes guest and guest_nice in user and nice.
let total = jiffies
.iter()
.take(8)
.try_fold(0_u64, |total, ticks| total.checked_add(*ticks))?;
let idle = jiffies
.get(3)?
.checked_add(jiffies.get(4).copied().unwrap_or_default())?;
Some(CpuTimes { total, idle })
}
pub fn cpu_times() -> Option<CpuTimes> {
let mut line = String::new();
BufReader::new(fs::File::open("/proc/stat").ok()?.take(4096))
.read_line(&mut line)
.ok()?;
if !line.ends_with('\n') {
return None;
}
linux_cpu_times(&aggregate_jiffies(&line)?)
}
pub fn cpu() -> Observation<Cpu> {
let info = read("/proc/cpuinfo", 1024 * 1024);
let stat = read("/proc/stat", 256 * 1024);
@@ -460,15 +593,7 @@ pub fn cpu() -> Observation<Cpu> {
.filter(|(k, _)| k.trim() == "model name")
.map(|(_, v)| v.trim().to_owned())
});
let aggregate_jiffies: Option<Vec<u64>> =
stat.lines().find(|l| l.starts_with("cpu ")).and_then(|l| {
l.split_whitespace()
.skip(1)
.map(str::parse)
.collect::<Result<Vec<_>, _>>()
.ok()
});
match aggregate_jiffies {
match aggregate_jiffies(&stat) {
Some(aggregate_jiffies) if logical_processors > 0 => Observation::valid(
"linux.cpu:/proc/cpuinfo,/proc/stat",
Cpu {
@@ -556,11 +681,12 @@ pub fn interfaces() -> Observation<Vec<Interface>> {
}
libc::AF_INET6 => {
let addr = &*item.ifa_addr.cast::<libc::sockaddr_in6>();
addresses.push(format!(
"{}%{}",
Ipv6Addr::from(addr.sin6_addr.s6_addr),
addr.sin6_scope_id
));
let ip = Ipv6Addr::from(addr.sin6_addr.s6_addr);
addresses.push(if addr.sin6_scope_id == 0 {
ip.to_string()
} else {
format!("{ip}%{}", addr.sin6_scope_id)
});
}
_ => {}
}
@@ -1167,7 +1293,20 @@ pub fn hardware() -> Observation<Hardware> {
let proxmox_ve =
Path::new("/usr/bin/pveversion").is_file() && Path::new("/usr/bin/pvedaemon").is_file();
let device_type = machine_type(proxmox_ve);
if readable_dmi.is_empty() && device_type.is_none() {
let manufacturer = readable_dmi
.get("sys_vendor")
.and_then(|value| firmware_identifier(value));
let serial_credential = std::env::var_os("CREDENTIALS_DIRECTORY")
.map(|directory| std::path::PathBuf::from(directory).join("rmm-bios-serial"));
let bios_serial_number = [
Some("/sys/class/dmi/id/product_serial"),
Some("/proc/device-tree/serial-number"),
serial_credential.as_deref().and_then(Path::to_str),
]
.into_iter()
.flatten()
.find_map(|path| sys_text(path).and_then(|value| firmware_identifier(&value)));
if readable_dmi.is_empty() && device_type.is_none() && bios_serial_number.is_none() {
Observation::unavailable(SOURCE, Quality::Unsupported, "HARDWARE_UNAVAILABLE")
} else {
Observation::valid(
@@ -1176,6 +1315,8 @@ pub fn hardware() -> Observation<Hardware> {
readable_dmi,
device_type,
proxmox_ve,
manufacturer,
bios_serial_number,
},
)
.partial("NO_SMART_OR_ENCRYPTION_PROOF")
@@ -1400,6 +1541,16 @@ mod tests {
assert_eq!(request.since_filter, "@100.123457");
assert_eq!(request.until_filter, "@101.987654");
}
#[test]
fn cpu_time_excludes_double_counted_guest_ticks_and_io_wait() {
let before = linux_cpu_times(&[10, 0, 5, 60, 10, 0, 0, 0, 4, 0]).unwrap();
let after = linux_cpu_times(&[30, 0, 5, 120, 30, 0, 0, 0, 20, 0]).unwrap();
assert_eq!(after.usage_since(before), Some(2_000));
assert_eq!(after.usage_since(after), None);
assert_eq!(before.usage_since(after), None);
assert!(linux_cpu_times(&[10, 0, 0]).is_none());
}
#[test]
fn machine_types_distinguish_proxmox_guests_and_probe_failures() {
assert_eq!(machine_type(true), Some(DeviceType::Hypervisor));
+14 -4
View File
@@ -1,5 +1,5 @@
//! Additive JSON observation mapping inside the existing snapshot payload. This
//! does not introduce a protobuf tag, a fabricated receive time or a new scope.
//! does not introduce a protobuf tag or a fabricated receive time.
use anyhow::Result;
use serde_json::{Value, json};
@@ -14,7 +14,12 @@ pub fn observations(inventory: &crate::inventory::LinuxInventory) -> Result<Vec<
observation["scope"] = json!(format!("linux.{name}"));
// Bound each scope independently. Never drop unsupported/error metadata
// or imply that absent/truncated rows were deleted from a device.
while serde_json::to_vec(&observation)?.len() > 32768 {
let max_bytes = if name == "software" {
rmm_domain::inventory_document::SOFTWARE_OBSERVATION_MAX_BYTES
} else {
32768
};
while serde_json::to_vec(&observation)?.len() > max_bytes {
observation["truncated"] = json!(true);
observation["completeness"] = json!("partial");
observation["error_code"] = json!("WIRE_SCOPE_LIMIT");
@@ -49,7 +54,7 @@ mod tests {
fn native_wire_scopes_preserve_quality_time_and_unsupported() {
let native = crate::inventory::collect_native();
let mapped = observations(&native).unwrap();
assert_eq!(mapped.len(), 11);
assert_eq!(mapped.len(), 12);
let smart = mapped.iter().find(|v| v["scope"] == "linux.smart").unwrap();
assert_eq!(smart["quality"], "unsupported");
assert!(smart["data"].is_null());
@@ -61,7 +66,12 @@ mod tests {
);
assert!(!observation["source_id"].as_str().unwrap().is_empty());
assert!(observation.get("received_at").is_none());
assert!(serde_json::to_vec(observation).unwrap().len() <= 32768);
let limit = if observation["scope"] == "linux.software" {
rmm_domain::inventory_document::SOFTWARE_OBSERVATION_MAX_BYTES
} else {
32768
};
assert!(serde_json::to_vec(observation).unwrap().len() <= limit);
}
let base = snapshot(false).unwrap();
assert!(serde_json::from_value::<rmm_domain::Inventory>(base).is_ok());
+1 -1
View File
@@ -52,7 +52,7 @@ rcgen = { version = "=0.14.10", default-features = false, features = ["crypto",
cc = "=1.11.1"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_ApplicationInstallationAndServicing", "Win32_System_EventLog", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Pipes", "Win32_System_SystemInformation", "Win32_System_Registry", "Win32_System_Memory", "Win32_System_Services", "Win32_System_Threading", "Win32_System_Shutdown"] }
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_NetworkManagement_IpHelper", "Win32_NetworkManagement_Ndis", "Win32_Networking_WinSock", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_ApplicationInstallationAndServicing", "Win32_System_EventLog", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Pipes", "Win32_System_RemoteDesktop", "Win32_System_SystemInformation", "Win32_System_Registry", "Win32_System_Memory", "Win32_System_Services", "Win32_System_Threading", "Win32_System_Shutdown"] }
[[example]]
name = "windows_reviewed_recovery"
@@ -185,6 +185,7 @@ mod native {
Payload::Heartbeat(Heartbeat {
instance_id: Uuid::new_v4().to_string(),
uptime_seconds: 1,
system_usage: None,
}),
)?;
let acknowledgement = send(client, &heartbeat).await?;
+90 -42
View File
@@ -2,7 +2,9 @@
//! uninstall commands; registry entries are evidence, not verified MSI state.
use anyhow::{Result, ensure};
use chrono::Utc;
use rmm_domain::inventory_document::DeviceType;
use rmm_domain::inventory_document::{
CpuTimes, DeviceType, SOFTWARE_OBSERVATION_MAX_BYTES, firmware_identifier,
};
use serde_json::{Value, json};
use std::{
mem::{size_of, zeroed},
@@ -10,8 +12,12 @@ use std::{
time::{Duration, Instant},
};
use windows_sys::Win32::{
Foundation::{ERROR_FILE_NOT_FOUND, ERROR_NO_MORE_ITEMS, ERROR_SUCCESS},
System::{Registry::*, SystemInformation::*},
Foundation::{ERROR_FILE_NOT_FOUND, ERROR_NO_MORE_ITEMS, ERROR_SUCCESS, FILETIME},
System::{
Registry::*,
SystemInformation::*,
Threading::{GetActiveProcessorGroupCount, GetSystemTimes},
},
};
struct Registry(HKEY);
@@ -116,13 +122,77 @@ fn classify_machine(
(!manufacturer.is_empty() && !product.is_empty()).then_some(DeviceType::Physical)
}
fn machine_type() -> Option<DeviceType> {
fn machine_type(manufacturer: Option<&str>, product: Option<&str>) -> Option<DeviceType> {
let hyper_v_host = open(
HKEY_LOCAL_MACHINE,
r"SYSTEM\CurrentControlSet\Services\vmms",
KEY_WOW64_64KEY,
)
.is_ok();
classify_machine(
hyper_v_host,
non_microsoft_hypervisor(),
manufacturer,
product,
)
}
fn memory_status() -> Result<MEMORYSTATUSEX> {
let mut memory: MEMORYSTATUSEX = unsafe { zeroed() };
memory.dwLength = size_of::<MEMORYSTATUSEX>() as u32;
ensure!(
unsafe { GlobalMemoryStatusEx(&mut memory) } != 0
&& memory.ullTotalPhys > 0
&& memory.ullAvailPhys <= memory.ullTotalPhys
&& memory.dwMemoryLoad <= 100,
"NATIVE_HARDWARE_QUERY"
);
Ok(memory)
}
pub fn physical_memory() -> Option<(u64, u64)> {
let memory = memory_status().ok()?;
Some((memory.ullAvailPhys, memory.ullTotalPhys))
}
pub fn cpu_times() -> Option<CpuTimes> {
// GetSystemTimes on a multi-group machine only reports the caller's group.
if unsafe { GetActiveProcessorGroupCount() } != 1 {
return None;
}
let (mut idle, mut kernel, mut user) = (
FILETIME::default(),
FILETIME::default(),
FILETIME::default(),
);
if unsafe { GetSystemTimes(&mut idle, &mut kernel, &mut user) } == 0 {
return None;
}
let ticks =
|time: FILETIME| (u64::from(time.dwHighDateTime) << 32) | u64::from(time.dwLowDateTime);
// Windows includes idle time in the kernel counter.
Some(CpuTimes {
total: ticks(kernel).checked_add(ticks(user))?,
idle: ticks(idle),
})
}
fn hardware() -> Result<Value> {
let mut system: SYSTEM_INFO = unsafe { zeroed() };
unsafe {
GetNativeSystemInfo(&mut system);
}
ensure!(system.dwNumberOfProcessors > 0, "NATIVE_HARDWARE_QUERY");
let memory = memory_status()?;
let cpu_model = open(
HKEY_LOCAL_MACHINE,
r"HARDWARE\DESCRIPTION\System\CentralProcessor\0",
KEY_WOW64_64KEY,
)
.ok()
.and_then(|key| text(key.0, "ProcessorNameString").ok().flatten())
.map(|name| name.trim().to_owned())
.filter(|name| !name.is_empty());
let bios = open(
HKEY_LOCAL_MACHINE,
r"HARDWARE\DESCRIPTION\System\BIOS",
@@ -133,48 +203,24 @@ fn machine_type() -> Option<DeviceType> {
bios.as_ref()
.and_then(|key| text(key.0, name).ok().flatten())
};
classify_machine(
hyper_v_host,
non_microsoft_hypervisor(),
read("SystemManufacturer").as_deref(),
read("SystemProductName").as_deref(),
)
}
fn hardware() -> Result<Value> {
let mut system: SYSTEM_INFO = unsafe { zeroed() };
unsafe {
GetNativeSystemInfo(&mut system);
}
let mut memory: MEMORYSTATUSEX = unsafe { zeroed() };
memory.dwLength = size_of::<MEMORYSTATUSEX>() as u32;
ensure!(
unsafe { GlobalMemoryStatusEx(&mut memory) } != 0
&& system.dwNumberOfProcessors > 0
&& memory.ullTotalPhys > 0
&& memory.ullAvailPhys <= memory.ullTotalPhys
&& memory.dwMemoryLoad <= 100,
"NATIVE_HARDWARE_QUERY"
);
let cpu_model = open(
HKEY_LOCAL_MACHINE,
r"HARDWARE\DESCRIPTION\System\CentralProcessor\0",
KEY_WOW64_64KEY,
)
.ok()
.and_then(|key| text(key.0, "ProcessorNameString").ok().flatten())
.map(|name| name.trim().to_owned())
.filter(|name| !name.is_empty());
let manufacturer = read("SystemManufacturer").and_then(|value| firmware_identifier(&value));
let product = read("SystemProductName");
let bios_serial_number = read("SystemSerialNumber")
.and_then(|value| firmware_identifier(&value))
.or_else(crate::inventory_sources::bios_serial);
Ok(
json!({"cpu_model":cpu_model, "logical_processors_visible":system.dwNumberOfProcessors,
"memory_total_bytes":memory.ullTotalPhys,"memory_available_bytes":memory.ullAvailPhys,
"memory_load_percent":memory.dwMemoryLoad,"device_type":machine_type()}),
"memory_load_percent":memory.dwMemoryLoad,
"device_type":machine_type(manufacturer.as_deref(),product.as_deref()),
"manufacturer":manufacturer,"bios_serial_number":bios_serial_number}),
)
}
fn software() -> Result<Value> {
let began = Instant::now();
let mut entries = Vec::new();
let mut entry_bytes = 0;
let mut errors = 0u32;
let mut scanned = 0u32;
let mut truncated = false;
@@ -196,7 +242,7 @@ fn software() -> Result<Value> {
}
};
for index in 0..2048 {
if began.elapsed() > Duration::from_millis(250) || entries.len() >= 64 {
if began.elapsed() > Duration::from_millis(250) {
truncated = true;
break;
}
@@ -238,12 +284,12 @@ fn software() -> Result<Value> {
})();
match entry {
Ok(Some(entry)) => {
entries.push(entry);
if serde_json::to_vec(&entries)?.len() > 12288 {
entries.pop();
entry_bytes += serde_json::to_vec(&entry)?.len() + 1;
if entry_bytes > SOFTWARE_OBSERVATION_MAX_BYTES - 2048 {
truncated = true;
break;
}
entries.push(entry);
}
Ok(None) => {}
Err(_) => errors += 1,
@@ -274,7 +320,7 @@ pub fn observations() -> Vec<Value> {
[
(
"windows.hardware",
"windows.win32:GetNativeSystemInfo+GlobalMemoryStatusEx;registry:CentralProcessor,BIOS,vmms;cpuid",
"windows.win32:GetNativeSystemInfo+GlobalMemoryStatusEx+GetSystemFirmwareTable;registry:CentralProcessor,BIOS,vmms;cpuid",
hardware as Provider,
),
(
@@ -282,6 +328,8 @@ pub fn observations() -> Vec<Value> {
"windows.registry:HKLM.Uninstall:64+32",
software as Provider,
),
("windows.interfaces", "windows.win32:GetAdaptersAddresses", crate::inventory_sources::interfaces as Provider),
("windows.users", "windows.win32:WTSEnumerateSessions", crate::inventory_sources::users as Provider),
]
.into_iter()
.map(|(scope, source, collect)| {
@@ -0,0 +1,266 @@
//! Local read-only inventory providers. Each result is bounded independently.
use anyhow::{Context, Result, ensure};
use rmm_domain::inventory_document::firmware_identifier;
use serde_json::{Value, json};
use std::{
collections::BTreeSet,
ffi::c_void,
mem::size_of,
net::{Ipv4Addr, Ipv6Addr},
ptr, slice,
};
use windows_sys::Win32::{
Foundation::{ERROR_BUFFER_OVERFLOW, ERROR_NO_DATA, ERROR_SUCCESS},
NetworkManagement::IpHelper::*,
Networking::WinSock::{
AF_INET, AF_INET6, AF_UNSPEC, SOCKADDR_IN, SOCKADDR_IN6, SOCKET_ADDRESS,
},
System::{
RemoteDesktop::*,
SystemInformation::{GetSystemFirmwareTable, RSMB},
},
};
pub(crate) fn bios_serial() -> Option<String> {
let length = unsafe { GetSystemFirmwareTable(RSMB, 0, ptr::null_mut(), 0) };
if !(8..=1024 * 1024).contains(&length) {
return None;
}
let mut data = vec![0; length as usize];
if unsafe { GetSystemFirmwareTable(RSMB, 0, data.as_mut_ptr(), length) } != length {
return None;
}
let count = u32::from_le_bytes(data[4..8].try_into().ok()?) as usize;
smbios_serial(data.get(8..)?.get(..count)?)
}
fn smbios_serial(mut table: &[u8]) -> Option<String> {
while let Some(header) = table.get(..4) {
let length = usize::from(header[1]);
if length < 4 || header[0] == 127 {
break;
}
let strings = table.get(length..)?;
let end = strings.windows(2).position(|pair| pair == [0, 0])?;
if header[0] == 1 {
let offset = usize::from(*table.get(..length)?.get(7)?).checked_sub(1)?;
let serial = strings[..end].split(|&c| c == 0).nth(offset)?;
return firmware_identifier(std::str::from_utf8(serial).ok()?);
}
table = strings.get(end + 2..)?;
}
None
}
// Pointer fields returned by IP Helper refer into its caller-provided buffer.
fn at<T>(buffer: &[u64], pointer: *const T) -> Option<&T> {
let offset = (pointer as usize).checked_sub(buffer.as_ptr() as usize)?;
if offset.checked_add(size_of::<T>())? > std::mem::size_of_val(buffer) || !pointer.is_aligned()
{
return None;
}
Some(unsafe { &*pointer })
}
fn wide_name(buffer: &[u64], pointer: *const u16) -> Option<String> {
let mut text = Vec::new();
for i in 0..256 {
let character = *at(buffer, pointer.wrapping_add(i))?;
if character == 0 {
return (!text.is_empty()).then(|| String::from_utf16_lossy(&text));
}
text.push(character);
}
None
}
fn ip_address(buffer: &[u64], address: SOCKET_ADDRESS) -> Option<String> {
let sockaddr = at(buffer, address.lpSockaddr)?;
match sockaddr.sa_family {
AF_INET if address.iSockaddrLength >= size_of::<SOCKADDR_IN>() as i32 => {
let ipv4 = at(buffer, address.lpSockaddr.cast::<SOCKADDR_IN>())?;
Some(Ipv4Addr::from(unsafe { ipv4.sin_addr.S_un.S_addr }.to_ne_bytes()).to_string())
}
AF_INET6 if address.iSockaddrLength >= size_of::<SOCKADDR_IN6>() as i32 => {
let ipv6 = at(buffer, address.lpSockaddr.cast::<SOCKADDR_IN6>())?;
let ip = Ipv6Addr::from(unsafe { ipv6.sin6_addr.u.Byte });
let scope = unsafe { ipv6.Anonymous.sin6_scope_id };
Some(if scope == 0 {
ip.to_string()
} else {
format!("{ip}%{scope}")
})
}
_ => None,
}
}
pub(crate) fn interfaces() -> Result<Value> {
let mut bytes = 15360_u32;
let mut buffer = vec![0_u64; (bytes as usize).div_ceil(8)];
let flags = GAA_FLAG_SKIP_ANYCAST
| GAA_FLAG_SKIP_MULTICAST
| GAA_FLAG_SKIP_DNS_SERVER
| GAA_FLAG_INCLUDE_ALL_INTERFACES;
let mut status = unsafe {
GetAdaptersAddresses(
u32::from(AF_UNSPEC),
flags,
ptr::null(),
buffer.as_mut_ptr().cast(),
&mut bytes,
)
};
if status == ERROR_BUFFER_OVERFLOW && bytes <= 1024 * 1024 {
buffer.resize((bytes as usize).div_ceil(8), 0);
status = unsafe {
GetAdaptersAddresses(
u32::from(AF_UNSPEC),
flags,
ptr::null(),
buffer.as_mut_ptr().cast(),
&mut bytes,
)
};
}
if status == ERROR_NO_DATA {
return Ok(json!({"entries":[],"truncated":false}));
}
ensure!(status == ERROR_SUCCESS, "ADAPTER_ADDRESSES");
let mut current = buffer.as_ptr().cast::<IP_ADAPTER_ADDRESSES_LH>();
let mut entries = Vec::new();
let mut truncated = false;
let mut size = 0;
while !current.is_null() && entries.len() < 128 {
let adapter = at(&buffer, current).context("ADAPTER_POINTER")?;
let mut next = adapter.FirstUnicastAddress.cast_const();
let mut addresses = BTreeSet::new();
for _ in 0..64 {
if next.is_null() {
break;
}
let address = at(&buffer, next).context("ADAPTER_ADDRESS_POINTER")?;
if let Some(ip) = ip_address(&buffer, address.Address) {
addresses.insert(ip);
}
next = address.Next.cast_const();
}
truncated |= !next.is_null();
let name = wide_name(&buffer, adapter.FriendlyName)
.or_else(|| wide_name(&buffer, adapter.Description))
.unwrap_or_else(|| {
format!("Adapter {}", unsafe {
adapter.Anonymous1.Anonymous.IfIndex
})
});
let mac = adapter
.PhysicalAddress
.get(..adapter.PhysicalAddressLength as usize)
.filter(|bytes| !bytes.is_empty())
.map(|bytes| {
bytes
.iter()
.map(|byte| format!("{byte:02x}"))
.collect::<Vec<_>>()
.join(":")
});
let entry = json!({"name":name,"addresses":addresses,"mac":mac});
size += serde_json::to_vec(&entry)?.len() + 1;
if size > 30 * 1024 {
truncated = true;
break;
}
entries.push(entry);
current = adapter.Next.cast_const();
}
Ok(json!({"entries":entries,"truncated":truncated || !current.is_null()}))
}
struct WtsMemory(*mut c_void);
impl Drop for WtsMemory {
fn drop(&mut self) {
if !self.0.is_null() {
unsafe { WTSFreeMemory(self.0) };
}
}
}
fn session_text(id: u32, class: WTS_INFO_CLASS) -> Option<String> {
let mut text = ptr::null_mut();
let mut bytes = 0;
if unsafe { WTSQuerySessionInformationW(ptr::null_mut(), id, class, &mut text, &mut bytes) }
== 0
{
return None;
}
let _guard = WtsMemory(text.cast());
if text.is_null() || !(2..=512).contains(&bytes) || bytes % 2 != 0 {
return None;
}
let units = unsafe { slice::from_raw_parts(text, (bytes / 2) as usize) };
String::from_utf16(units.split(|c| *c == 0).next()?).ok()
}
pub(crate) fn users() -> Result<Value> {
let mut list = ptr::null_mut();
let mut count = 0;
ensure!(
unsafe { WTSEnumerateSessionsW(ptr::null_mut(), 0, 1, &mut list, &mut count) } != 0,
"SESSION_QUERY"
);
let _guard = WtsMemory(list.cast());
let mut entries = BTreeSet::new();
let mut errors = 0;
let mut truncated = count > 256;
if count != 0 {
ensure!(!list.is_null(), "SESSION_LIST");
for session in unsafe { slice::from_raw_parts(list, count.min(256) as usize) } {
if session.SessionId == 0
|| ![WTSActive, WTSConnected, WTSDisconnected].contains(&session.State)
{
continue;
}
match session_text(session.SessionId, WTSUserName) {
Some(name) if !name.is_empty() => {
let account = match session_text(session.SessionId, WTSDomainName) {
Some(domain) if !domain.is_empty() => format!("{domain}\\{name}"),
_ => name,
};
if entries.len() >= 64 {
truncated = true;
break;
}
if account.len() <= 255 && !account.chars().any(char::is_control) {
entries.insert(account);
} else {
errors += 1;
}
}
Some(_) => {}
None => errors += 1,
}
}
}
ensure!(
errors == 0 || !entries.is_empty(),
"SESSION_INFORMATION_UNAVAILABLE"
);
Ok(json!({"entries":entries,"read_errors":errors,"truncated":truncated}))
}
#[cfg(test)]
mod tests {
use super::smbios_serial;
#[test]
fn reads_the_system_serial_and_rejects_incomplete_entries() {
assert_eq!(
smbios_serial(b"\x01\x08\x00\x00\x01\x00\x00\x02Vendor\0ABC-123\0\0").as_deref(),
Some("ABC-123")
);
assert_eq!(
smbios_serial(b"\x01\x08\x00\x00\x01\x00\x00\x02Vendor\0ABC-123\0"),
None
);
}
}
+1
View File
@@ -24,6 +24,7 @@ pub mod helper_system;
pub mod windows_update_setup;
#[cfg(windows)]
pub mod inventory;
mod inventory_sources;
#[cfg(windows)]
pub mod job_binding;
pub mod journal;
+27 -4
View File
@@ -1,6 +1,6 @@
//! Read-only Windows APIs. The kernel's recorded startup time identifies the boot.
use anyhow::{Context, Result, ensure};
use chrono::Utc;
use chrono::{DateTime, Utc};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use std::{ffi::c_void, os::windows::ffi::OsStrExt, path::Path, ptr, time::Duration};
@@ -261,7 +261,23 @@ pub(crate) fn computer_name(format: COMPUTER_NAME_FORMAT) -> Result<String> {
Ok(String::from_utf16(&name[..len as usize])?)
}
fn install_date() -> Option<DateTime<Utc>> {
let key = wide(r"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
let name = wide("InstallDate");
let mut seconds = 0_u32;
let mut bytes = size_of::<u32>() as u32;
let status = unsafe { RegGetValueW(HKEY_LOCAL_MACHINE,key.as_ptr(),name.as_ptr(),RRF_RT_REG_DWORD,
ptr::null_mut(),ptr::from_mut(&mut seconds).cast(),&mut bytes) };
(status == 0 && bytes as usize == size_of::<u32>() && seconds > 0)
.then(|| DateTime::from_timestamp(i64::from(seconds), 0))
.flatten().filter(|time| *time <= Utc::now())
}
pub fn snapshot() -> Result<Value> {
snapshot_with_boot(None)
}
pub fn snapshot_with_boot(booted_at: Option<DateTime<Utc>>) -> Result<Value> {
let started = Utc::now();
let hostname = computer_name(ComputerNameDnsHostname)?;
let volume = wide(std::env::var("SystemDrive").context("SYSTEM_DRIVE")? + "\\");
@@ -281,7 +297,7 @@ pub fn snapshot() -> Result<Value> {
let mut snapshot = json!({"os":os,"hostname":hostname,"architecture":std::env::consts::ARCH,"root_total_bytes":total,"root_available_bytes":available,"root_available_inodes":null,
"collection_started_at":started,"collection_completed_at":completed,
"observations":[
{"scope":"windows.os","source_id":"windows.registry:CurrentVersion;GetComputerNameExW","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"product_name":product,"display_version":display,"build":build}},
{"scope":"windows.os","source_id":"windows.registry:CurrentVersion;GetComputerNameExW;Kernel-General/12","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"product_name":product,"display_version":display,"build":build,"installed_at":install_date(),"booted_at":booted_at}},
{"scope":"windows.volumes","source_id":"windows.win32:GetDiskFreeSpaceExW","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"system_volume_total_bytes":total,"system_volume_available_bytes":available}},
{"scope":"windows.inodes","source_id":"windows.win32","observed_at":completed,"quality":"unsupported","completeness":"unknown","truncated":false,"error_code":"NOT_APPLICABLE","data":null}
]});
@@ -292,7 +308,7 @@ pub fn snapshot() -> Result<Value> {
snapshot["collection_completed_at"] = json!(Utc::now());
Ok(snapshot)
}
pub async fn boot_id() -> Result<String> {
pub async fn boot_identity() -> Result<(String, DateTime<Utc>)> {
// Fixed passive query only. Never interpolates a job or caller-supplied code.
// Avoid Win32_Product: it can cause MSI consistency checks and repairs.
let executable = Path::new(&std::env::var("SystemRoot")?)
@@ -328,7 +344,14 @@ if ($nodes.Count -ne 1) { throw 'BOOT_START_TIME' }
.try_into()?;
bytes[6] = (bytes[6] & 15) | 0x80;
bytes[8] = (bytes[8] & 63) | 0x80;
Ok(uuid::Uuid::from_bytes(bytes).to_string())
let ticks = text.parse::<i64>()?.checked_sub(621_355_968_000_000_000).context("BOOT_EPOCH")?;
let time = DateTime::from_timestamp(ticks.div_euclid(10_000_000), ticks.rem_euclid(10_000_000) as u32 * 100)
.context("BOOT_EPOCH")?;
Ok((uuid::Uuid::from_bytes(bytes).to_string(),time))
}
pub async fn boot_id() -> Result<String> {
boot_identity().await.map(|(id, _)| id)
}
#[cfg(test)]
+23 -9
View File
@@ -8,7 +8,7 @@ use rmm_agent_core::{
reconcile::{self, SyncClock},
};
use rmm_agent_windows::certificate_rotation::{ProtectedKeyFiles, RotationStore};
use rmm_agent_windows::{CAPABILITIES, job_binding::readonly_binding, journal::Journal, native};
use rmm_agent_windows::{CAPABILITIES, inventory, job_binding::readonly_binding, journal::Journal, native};
use rmm_domain::jobs::{Action, ExecutionPermitPayload};
use rmm_protocol::*;
use rusqlite::{Connection, OptionalExtension};
@@ -631,6 +631,7 @@ struct Agent {
certificates: RotationStore,
key_files: ProtectedKeyFiles,
boot: String,
booted_at: chrono::DateTime<Utc>,
instance: String,
started: Instant,
binding: Option<Binding>,
@@ -934,7 +935,7 @@ impl Agent {
let _ = time_helper.time_close(generation).await;
}
helper_report.record(&helper_state, "system_helper", &result);
tokio::time::sleep(mode.interval(result.is_ok())).await;
tokio::time::sleep(mode.helper_interval(result.is_ok())).await;
}
let _ = time_helper.time_close(generation).await;
}));
@@ -2420,8 +2421,8 @@ impl Agent {
if self.journal.count()? > 0 || !jobs::events(self.journal.connection())?.is_empty() {
return Ok(false);
}
let data = serde_json::to_vec(&native::snapshot()?)?;
ensure!(data.len() <= 32768, "WINDOWS_INVENTORY_LIMIT");
let data = serde_json::to_vec(&native::snapshot_with_boot(Some(self.booted_at))?)?;
ensure!(data.len() <= 256 * 1024, "WINDOWS_INVENTORY_LIMIT");
let envelope = self.envelope(
generation,
Payload::InventorySnapshot(InventorySnapshot {
@@ -2537,7 +2538,7 @@ impl Agent {
};
self.renew_certificate(admission.as_deref()).await?;
}
self.boot = native::boot_id().await?;
(self.boot, self.booted_at) = native::boot_identity().await?;
let advertised = self.capabilities();
let hello = self.envelope(
0,
@@ -2602,6 +2603,7 @@ impl Agent {
let mut rotation_at = Instant::now();
let mut rotation_after = Duration::from_secs(30);
let mut heartbeat = Instant::now() - Duration::from_secs(60);
let mut previous_cpu = None;
let mut heartbeat_after = Duration::from_secs(30);
let mut tick = tokio::time::interval(Duration::from_millis(20));
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
@@ -2776,9 +2778,19 @@ impl Agent {
// inventory offline. Retry setup at the next heartbeat.
eprintln!("PASSIVE_SIGNED_TIME_UNAVAILABLE");
}
let cpu = inventory::cpu_times();
let cpu_usage_basis_points = cpu.zip(previous_cpu)
.and_then(|(current, previous)| current.usage_since(previous));
previous_cpu = cpu;
let memory = inventory::physical_memory();
let payload = Payload::Heartbeat(Heartbeat {
instance_id: self.instance.clone(),
uptime_seconds: self.started.elapsed().as_secs(),
system_usage: Some(SystemUsage {
cpu_usage_basis_points,
ram_available_bytes: memory.map(|(available, _)| available),
ram_total_bytes: memory.map(|(_, total)| total),
}),
});
let h = self.envelope(generation, payload)?;
channel.send(&h).await?;
@@ -2788,6 +2800,7 @@ impl Agent {
Payload::Heartbeat(Heartbeat {
instance_id: self.instance.clone(),
uptime_seconds: self.started.elapsed().as_secs(),
system_usage: None,
}),
)?;
channel.poll(poll).await?;
@@ -2807,7 +2820,7 @@ impl Agent {
self.replay(&channel, generation).await?;
replay = Instant::now();
}
if !stop.load(Ordering::SeqCst) && inventory.elapsed() >= Duration::from_secs(86400) {
if !stop.load(Ordering::SeqCst) && inventory.elapsed() >= Duration::from_secs(300) {
self.queue_inventory(generation)?;
inventory = Instant::now();
}
@@ -2917,7 +2930,7 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
let identity = enrollment(&config, &ca).await?;
let mut journal=journal;
journal.pin_identity(&identity.agent_id)?;
let boot = native::boot_id().await?;
let (boot, booted_at) = native::boot_identity().await?;
let binding=config.job_binding_file.as_deref().map(readonly_binding).transpose()?;
#[cfg(feature = "system-helper")]
let binding = if let Some(policy) = &config.localservice_time_policy {
@@ -2967,6 +2980,7 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
certificates,
key_files,
boot,
booted_at,
instance: Uuid::new_v4().to_string(),
started: Instant::now(), binding, ledger, _ledger_file:ledger_file, clock, sync,
#[cfg(feature="system-helper")]
@@ -3063,8 +3077,8 @@ pub fn main() -> Result<()> {
}
if args == ["--native-probe"] {
let runtime = tokio::runtime::Runtime::new()?;
let boot = runtime.block_on(native::boot_id())?;
let inventory = native::snapshot()?;
let (boot, booted_at) = runtime.block_on(native::boot_identity())?;
let inventory = native::snapshot_with_boot(Some(booted_at))?;
println!(
"{}",
serde_json::json!({"platform":"windows","architecture":std::env::consts::ARCH,"hostname_available":!inventory["hostname"].as_str().unwrap_or("").is_empty(),"system_volume_available":inventory["root_available_bytes"].as_u64().is_some(),"inodes":null,"boot_id":boot,"capabilities":CAPABILITIES,"jobs_supported":false})
+29
View File
@@ -31,6 +31,15 @@ impl SamplingMode {
(Self::Jobs, false) => Duration::from_millis(500),
}
}
pub fn helper_interval(self, verified: bool) -> std::time::Duration {
match (self, verified) {
// Each refresh verifies both service images over the pipe. A held
// signed time sample remains usable for up to five minutes.
(Self::Jobs, true) => std::time::Duration::from_secs(5),
_ => self.interval(verified),
}
}
}
fn independent_time_key(time_key_hex: &str, job_key_hex: &str) -> Result<[u8; 32]> {
@@ -1637,6 +1646,26 @@ mod tests {
}
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn helper_sampling_spaces_successes_and_retries_failures_quickly() {
use std::time::Duration;
assert_eq!(
SamplingMode::Jobs.helper_interval(true),
Duration::from_secs(5)
);
assert_eq!(
SamplingMode::Jobs.helper_interval(false),
Duration::from_millis(500)
);
for verified in [false, true] {
assert_eq!(
SamplingMode::Passive.helper_interval(verified),
Duration::from_secs(30)
);
}
}
fn sample(ns: u64) -> Sample {
Sample {
wall_utc_ns: 1_800_000_000_000_000_000 + ns as i64,
+12
View File
@@ -649,6 +649,7 @@ impl<C: reconcile::SyncClock> Agent<C> {
let mut inventory_at = Instant::now();
let mut update_at = Instant::now();
let mut heartbeat_at = Instant::now();
let mut previous_cpu = None;
let mut heartbeat_after = Duration::from_millis(rand::random_range(27_000..33_000));
let mut tick = tokio::time::interval(Duration::from_secs(5));
let mut sync_at = Instant::now();
@@ -809,11 +810,21 @@ impl<C: reconcile::SyncClock> Agent<C> {
}
if first_heartbeat || heartbeat_at.elapsed() >= heartbeat_after {
first_heartbeat = false;
let cpu = rmm_agent_linux::inventory::cpu_times();
let cpu_usage_basis_points = cpu.zip(previous_cpu)
.and_then(|(current, previous)| current.usage_since(previous));
previous_cpu = cpu;
let memory = rmm_agent_linux::inventory::memory().data;
let heartbeat = self.envelope(
generation,
Payload::Heartbeat(Heartbeat {
instance_id: self.instance.clone(),
uptime_seconds: self.started.elapsed().as_secs(),
system_usage: Some(SystemUsage {
cpu_usage_basis_points,
ram_available_bytes: memory.as_ref().and_then(|m| m.available_bytes),
ram_total_bytes: memory.map(|m| m.total_bytes),
}),
}),
)?;
ws.send(&heartbeat).await?;
@@ -823,6 +834,7 @@ impl<C: reconcile::SyncClock> Agent<C> {
Payload::Heartbeat(Heartbeat {
instance_id: self.instance.clone(),
uptime_seconds: self.started.elapsed().as_secs(),
system_usage: None,
}),
)?;
ws.poll(poll).await?;
+36 -1
View File
@@ -3,6 +3,20 @@ use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
pub const SOFTWARE_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());
let lower = value.to_ascii_lowercase();
(!value.is_empty()
&& value.len() <= 255
&& !value.chars().any(char::is_control)
&& !matches!(lower.as_str(), "none" | "unknown" | "not specified" | "not applicable"
| "default string" | "to be filled by o.e.m." | "system serial number")
&& !value.bytes().all(|b| b == b'0'))
.then(|| value.to_owned())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum DeviceType {
@@ -11,6 +25,22 @@ pub enum DeviceType {
Hypervisor,
}
#[derive(Clone, Copy)]
pub struct CpuTimes {
pub total: u64,
pub idle: u64,
}
impl CpuTimes {
pub fn usage_since(self, previous: Self) -> Option<u32> {
let total = self.total.checked_sub(previous.total)?;
let idle = self.idle.checked_sub(previous.idle)?;
let busy = total.checked_sub(idle)?;
(total != 0)
.then(|| ((u128::from(busy) * 10_000 + u128::from(total / 2)) / u128::from(total)) as u32)
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Observation {
@@ -136,10 +166,15 @@ pub fn validate_for_scope(
}
let mut scopes = std::collections::BTreeSet::new();
for item in observations {
let max_bytes = match (scope, item["scope"].as_str()) {
("linux.base", Some("linux.software")) | ("windows.base", Some("windows.software")) =>
SOFTWARE_OBSERVATION_MAX_BYTES,
_ => 32768,
};
if serde_json::to_vec(item)
.map_err(|_| "INVALID_OBSERVATION")?
.len()
> 32768
> max_bytes
{
return Err("OBSERVATION_SIZE");
}
+12
View File
@@ -81,6 +81,17 @@ pub struct Heartbeat {
pub instance_id: String,
#[prost(uint64, tag = "2")]
pub uptime_seconds: u64,
#[prost(message, optional, tag = "3")]
pub system_usage: Option<SystemUsage>,
}
#[derive(Clone, PartialEq, Message)]
pub struct SystemUsage {
#[prost(uint32, optional, tag = "1")]
pub cpu_usage_basis_points: Option<u32>,
#[prost(uint64, optional, tag = "2")]
pub ram_available_bytes: Option<u64>,
#[prost(uint64, optional, tag = "3")]
pub ram_total_bytes: Option<u64>,
}
#[derive(Clone, PartialEq, Message)]
pub struct InventorySnapshot {
@@ -156,6 +167,7 @@ mod tests {
payload: Some(Payload::Heartbeat(Heartbeat {
instance_id: "x".into(),
uptime_seconds: 1,
system_usage: None,
})),
..Default::default()
};
+55 -1
View File
@@ -4,6 +4,7 @@ use chrono::{DateTime, Utc};
use prost::Message;
use rmm_domain::MAX_MESSAGE;
use rmm_protocol::*;
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use sqlx::Row;
use uuid::Uuid;
@@ -146,7 +147,14 @@ pub async fn ingest(
match &e.payload {
Some(Payload::Heartbeat(h)) => {
Uuid::parse_str(&h.instance_id)?;
sqlx::query("UPDATE agent_installations SET last_contact_at=now() WHERE agent_id=$1 AND revoked_at IS NULL").bind(agent).execute(&mut *tx).await?;
let usage = h.system_usage.as_ref().and_then(|sample| system_usage(sample, observed));
sqlx::query("UPDATE agent_installations SET last_contact_at=now(),
system_usage=CASE WHEN $2::jsonb IS NULL THEN system_usage
ELSE COALESCE(system_usage,'{}'::jsonb) || $2 END,
system_usage_observed_at=CASE WHEN $2::jsonb ? 'ram_available_bytes'
THEN $3 ELSE system_usage_observed_at END
WHERE agent_id=$1 AND revoked_at IS NULL")
.bind(agent).bind(usage).bind(observed).execute(&mut *tx).await?;
}
Some(Payload::InventorySnapshot(s)) => {
ensure!(
@@ -197,3 +205,49 @@ pub async fn ingest(
e.connection_generation,
))
}
fn system_usage(sample: &SystemUsage, observed: DateTime<Utc>) -> Option<Value> {
let cpu = sample
.cpu_usage_basis_points
.filter(|&value| value <= 10_000);
let memory = sample
.ram_available_bytes
.zip(sample.ram_total_bytes)
.filter(|&(available, total)| total > 0 && available <= total);
let mut usage = serde_json::Map::new();
if let Some(cpu) = cpu {
usage.insert("cpu_usage_percent".into(), json!(f64::from(cpu) / 100.0));
usage.insert("cpu_usage_observed_at".into(), json!(observed));
}
if let Some((available, total)) = memory {
usage.insert("ram_available_bytes".into(), json!(available));
usage.insert("ram_total_bytes".into(), json!(total));
}
(!usage.is_empty()).then_some(Value::Object(usage))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepts_zero_usage_and_ignores_invalid_metrics_without_losing_the_heartbeat() {
let mut sample = SystemUsage {
cpu_usage_basis_points: Some(0),
ram_available_bytes: Some(0),
ram_total_bytes: Some(1),
};
let now = Utc::now();
let measured = system_usage(&sample, now).unwrap();
assert_eq!(measured["cpu_usage_percent"], json!(0.0));
assert_eq!(measured["cpu_usage_observed_at"], json!(now));
assert_eq!(measured["ram_available_bytes"], json!(0));
assert_eq!(measured["ram_total_bytes"], json!(1));
sample.cpu_usage_basis_points = Some(10_001);
let partial = system_usage(&sample, now).unwrap();
assert!(partial.get("cpu_usage_percent").is_none());
assert!(partial.get("cpu_usage_observed_at").is_none());
sample.ram_available_bytes = Some(2);
assert_eq!(system_usage(&sample, now), None);
}
}
+25
View File
@@ -470,6 +470,30 @@ WantedBy=timers.target
}
def provision_serial_credential():
# DMI serial files usually require root. Pass this one value to the agent
# through systemd's read-only per-service credentials directory.
source = Path('/sys/class/dmi/id/product_serial')
try:
with source.open('rb') as stream:
serial = stream.read(256).strip()
except OSError:
return
if not serial or len(serial) >= 255:
return
target = ROOT / 'bios-serial'
dropin = UNIT_DIR / (SERVICE + '.d') / '40-inventory-serial.conf'
content = f'[Service]\nLoadCredential=rmm-bios-serial:{target}\n'.encode()
require(not dropin.parent.is_symlink(), 'hardware credential directory conflict')
if dropin.exists() or dropin.is_symlink():
require(not dropin.is_symlink() and dropin.read_bytes() == content, 'hardware credential configuration conflict')
else:
dropin.parent.mkdir(mode=0o755, exist_ok=True)
save(target, serial, 0o600)
if not dropin.exists():
save(dropin, content)
def enable():
for name, data in units().items():
path = UNIT_DIR / name
@@ -477,6 +501,7 @@ def enable():
require(path.read_bytes() == data.encode(), 'service file conflict: ' + name)
else:
save(path, data.encode())
provision_serial_credential()
service('daemon-reload')
service('enable', '--now', SERVICE)
+1
View File
@@ -2,6 +2,7 @@ WITH classified AS (
SELECT a.tenant_id,a.asset_id,a.agent_id,a.created_at,a.revoked_at,a.last_contact_at,
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,
CASE
WHEN a.revoked_at IS NOT NULL THEN 'revoked'
+20 -2
View File
@@ -352,6 +352,19 @@ fn project(row: &PgRow, now: DateTime<Utc>, full: bool) -> Value {
let data = row.get::<Option<Value>, _>("data").unwrap_or(Value::Null);
let cpu = observed(&data, "linux.cpu");
let windows = observed(&data, "windows.hardware");
let linux_memory = observed(&data, "linux.memory");
let usage = row
.get::<Option<Value>, _>("system_usage")
.unwrap_or(Value::Null);
let usage_at: Option<DateTime<Utc>> = row.get("system_usage_observed_at");
let inventory_at: Option<DateTime<Utc>> = row.get("observed_at");
let cpu_observed_at = usage["cpu_usage_observed_at"].as_str();
let cpu_usage = cpu_observed_at.and_then(|_| usage["cpu_usage_percent"].as_f64());
let ram_available = usage["ram_available_bytes"].as_u64();
let ram_total = usage["ram_total_bytes"]
.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 last = row.get::<Option<DateTime<Utc>>, _>("last_contact_at");
@@ -372,9 +385,14 @@ fn project(row: &PgRow, now: DateTime<Utc>, full: bool) -> Value {
"disk_free_bytes":data["root_available_bytes"].as_u64(),"disk_total_bytes":data["root_total_bytes"].as_u64(),
"cpu_model":cpu["model"].as_str().or_else(||windows["cpu_model"].as_str()),
"cpu_logical_count":cpu["logical_processors"].as_u64().or_else(||windows["logical_processors_visible"].as_u64()),
"ram_total_bytes":observed(&data,"linux.memory")["total_bytes"].as_u64().or_else(||windows["memory_total_bytes"].as_u64()),
"cpu_usage_percent":cpu_usage,
"cpu_usage_observed_at":cpu_observed_at,
"ram_total_bytes":ram_total,
"ram_available_bytes":ram_available.or_else(|| linux_memory["available_bytes"].as_u64().or_else(||windows["memory_available_bytes"].as_u64())
.filter(|available| ram_total.is_some_and(|total| *available <= total))),
"ram_observed_at":if ram_available.is_some() {usage_at} else {inventory_at},
"last_contact_at":last,"agent_version":row.get::<Option<String>,_>("reported_agent_version"),
"presence":presence,"observed_at":row.get::<Option<DateTime<Utc>>,_>("observed_at"),
"presence":presence,"observed_at":inventory_at,
"received_at":row.get::<Option<DateTime<Utc>>,_>("received_at"),
"source_id":row.get::<Option<String>,_>("source_id"),"quality":if data.is_null(){"unknown"}else{"valid"},
"completeness":"partial","health":"unknown"
@@ -0,0 +1,206 @@
{
"windows": {
"sample_ended_utc": "2026-11-18T20:14:29.0871148Z",
"source": "Win32_Process cumulative UserModeTime, KernelModeTime and ReadTransferCount",
"duration_seconds": 20.141969,
"logical_cpus": 2,
"version": "0.1.19",
"target": "x86_64-pc-windows-gnu",
"build_revision": "aea2d5b37979fc2c039f88e96e7c070e2337cc98",
"processes": {
"agent": {
"pid": 3164,
"image_bytes": 31698869,
"image_sha256": "10ae59a18e1f6aa765d68e739dc10aa5156d06e9c131f09fea948c24508e1a54",
"cpu_seconds_delta": 6.125,
"read_bytes_delta": 6280095709,
"cpu_percent_of_guest": 15.2,
"read_mib_per_second": 297.35
},
"helper": {
"pid": 1600,
"image_bytes": 27260060,
"image_sha256": "f3f1cda6531ee695936442fc24404387a550f43b3b1afb337a709a6a59694060",
"cpu_seconds_delta": 6.3125,
"read_bytes_delta": 7294039909,
"cpu_percent_of_guest": 15.67,
"read_mib_per_second": 345.36
},
"updater": {
"pid": 2384,
"cpu_seconds_delta": 0,
"read_bytes_delta": 0,
"cpu_percent_of_guest": 0
}
},
"local_readiness_utc": "2026-11-18T20:15:08.153963300Z",
"clock_qualified": true,
"agent_sync_ready": true,
"helper_sync_ready": true,
"nonterminal_local_attempts": 0,
"authenticated_server_contact_utc": "2026-11-18T20:14:59.659919Z",
"active_server_jobs": 0,
"transport": "https"
},
"cloud_linux": {
"source": "process CPU counters from /proc for the enrolled agent and its managed script helper",
"duration_seconds": 20.046738,
"logical_cpus": 2,
"agent_cpu_percent_of_guest": 0.074825,
"helper_cpu_percent_of_guest": 0
},
"source_findings": {
"successful_helper_time_refresh_delay_ms": 20,
"successful_enrolled_agent_time_refresh_delay_ms": 5000,
"max_held_time_evidence_age_seconds": 300,
"pipe_calls_per_successful_helper_time_refresh": 2,
"agent_reads_per_second_in_units_of_helper_image": 11.44,
"helper_reads_per_second_in_units_of_agent_image": 11.42
},
"limits": "ReadTransferCount includes logical I/O, including cached reads. Dividing by peer image size estimates operation frequency. No file-level trace or CPU stack sampling was taken. No corrected build was deployed or measured.",
"fix": {
"build_revision": "a4bcebf4406c8dc6c0c4e0dcaceedb37683710e2",
"release_id": "ec1c16b2-7cdb-4c7e-babb-ab8eb51ec740",
"release_sequence": 21,
"version": "0.1.20",
"successful_helper_time_refresh_delay_ms": 5000,
"failed_helper_time_refresh_delay_ms": 500,
"passive_helper_time_refresh_delay_ms": 30000,
"checks": {
"windows_gnu_release_built": true,
"windows_library_test_binary_built": true,
"cadence_test_passed_as_standalone_rust_test": true,
"full_windows_unit_test_binary_executed": false,
"full_suite_limit": "Linux compilation needs Windows inventory APIs and installed Wine could not load the Windows test binary."
},
"activation": {
"method": "signed normal release pull for Windows GNU in Development A",
"agent_id": "239ffa87-642f-40cd-9cbf-d48557dc0193",
"asset_id": "fab8b229-4eea-4af8-9362-a3aea4a8f709",
"observed_at_utc": "2026-11-18T20:25:45.3055012Z",
"services": [
{
"name": "RmmDiscoveryReleasePull",
"pid": 2384,
"state": "Running",
"sha256": "575ceb6a0b76c835d28646a498dfa73e88fb5de6343b77bf11d5eefea3fc68b1"
},
{
"name": "RmmDiscoverySystemHelper",
"pid": 5832,
"state": "Running",
"sha256": "990616a6f879d65268ef5a0d31fbf2313af6ae48e70e9a6ed1b2077ea66a194b"
},
{
"name": "RmmDiscoveryWindows",
"pid": 4112,
"state": "Running",
"sha256": "0db90e56ddfc262bd25fd0389a52002611e50be2ae242392b9cecf18fc1e962c"
}
],
"updater_pid_retained": true,
"boot_restarted": false,
"clock_qualified": true,
"transition_pending": false
},
"cpu_after_activation": {
"start_utc": "2026-11-18T20:26:12.8649479Z",
"end_utc": "2026-11-18T20:27:13.6089619Z",
"duration_seconds": 60.508365,
"logical_cpus": 2,
"processes": {
"rmm-updater-windows.exe": {
"pid": 2384,
"cpu_seconds_delta": 0.0,
"cpu_percent_of_guest": 0.0,
"read_bytes_delta": 0,
"read_mib_s": 0.0
},
"rmm-helper-windows.exe": {
"pid": 5832,
"cpu_seconds_delta": 4.40625,
"cpu_percent_of_guest": 3.641,
"read_bytes_delta": 2134329196,
"read_mib_s": 33.639
},
"rmm-agent-windows.exe": {
"pid": 4112,
"cpu_seconds_delta": 4.25,
"cpu_percent_of_guest": 3.5119,
"read_bytes_delta": 1136185938,
"read_mib_s": 17.907
}
}
},
"cpu_steady_after_test_order": {
"start_utc": "2026-11-18T20:29:25.5814828Z",
"end_utc": "2026-11-18T20:30:26.1736831Z",
"duration_seconds": 60.386439,
"logical_cpus": 2,
"processes": {
"rmm-updater-windows.exe": {
"pid": 2384,
"cpu_seconds_delta": 0.0,
"cpu_percent_of_guest": 0.0,
"read_bytes_delta": 0,
"read_mib_s": 0.0
},
"rmm-helper-windows.exe": {
"pid": 5832,
"cpu_seconds_delta": 3.28125,
"cpu_percent_of_guest": 2.7169,
"read_bytes_delta": 2126724397,
"read_mib_s": 33.587
},
"rmm-agent-windows.exe": {
"pid": 4112,
"cpu_seconds_delta": 2.78125,
"cpu_percent_of_guest": 2.3029,
"read_bytes_delta": 1140038852,
"read_mib_s": 18.004
}
}
},
"system_order": {
"operation_id": "6760c9b2-e005-437d-8ae6-1191e5c7972e",
"job_id": "778e34f6-e4cc-44d9-b6c0-75e2a559e3a7",
"attempt_id": "2a4d1878-74db-43c5-a5ad-202e4bee2e43",
"plan_hash": "669a2934ab1e07dbe290bd6adea8c321415ffcf2731a1e4800e305b94a6b1c21",
"stdout": "Windows-Konto S-1-5-18",
"exit_code": 0,
"state": "succeeded",
"observed_at": "2026-11-18T20:29:13.872Z",
"script_sha256": "8a0c76004a480aa11f6c768b2984e2cf2c01431009ccdbfb1607825133fcbc4f",
"runtime_limit_seconds": 30,
"preapproval": {
"jobs": 0,
"outbox": 0,
"grants": 0
},
"approval": {
"principal": "simulated-testprincipal-a",
"approval_origin": "dev_test_browser_simulation",
"testsimulation": true,
"plan_hash": "669a2934ab1e07dbe290bd6adea8c321415ffcf2731a1e4800e305b94a6b1c21"
},
"jobs": 1,
"grants": 1
},
"policy_verification": {
"scope_pins_temporarily_rebound": 3,
"existing_release_anchor_restored": true,
"same_fixed_system_script_accepted_in_preview_with_restored_anchor": true,
"preview_submitted": false
},
"final_gateway": {
"auth_contact": "2026-11-18T20:30:25.083449+00:00",
"contact": "2026-11-18T20:30:04.483106+00:00",
"generation": 74,
"active_jobs": 0,
"helper_ready": true,
"ready": true,
"transport": "https",
"system_run_script": true
}
}
}
+4
View File
@@ -27,10 +27,14 @@ Alle acht Versuche lieferten Exitcode 0. Bei beiden Neustarts wurde die Wiederan
| Funktion | Beobachtung und Beleg |
| --- | --- |
| Öffentliche Verwaltung und Kundengrenzen | HTTPS-WebUI mit Passwort/TOTP, MCP mit widerrufbarem Token. Gerätebestand, Historie, eingeschränkter und kundenübergreifender Zugriff sowie Widerruf sind geprüft. [Öffentlicher Zugang](evidence/public-access-20261117.json) · [Kunden und Geräte](evidence/customer-fleet-20261117.json) |
| Erweitertes Inventar in den Gerätedetails | OS-Installationsdatum, letzter Neustart, Hersteller, BIOS-Seriennummer, verfügbare Garantieinformationen, Netzwerk, Software und angemeldete Benutzer. [Geräteansicht](../web/src/device-inventory.tsx) |
| 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) |
| 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) |
| Windows im Leerlauf | Windows GNU `0.1.20` aus `a4bcebf` aktualisiert den signierten Zeitbeleg des Helpers nach erfolgreicher Abfrage im Abstand von fünf Sekunden. Der Testgast übernahm das Paket mit derselben Geräteidentität. Im Leerlauf sank die CPU-Last des Agenten von 15,20 % auf 2,30 % und die des Helpers von 15,67 % auf 2,72 %. Der in der internen Entwicklungs-WebUI genehmigte PowerShell-Testauftrag meldete `S-1-5-18` mit Exitcode 0 und einem Startgrant. Beide Dienste blieben synchron. [Leerlaufmessung und SYSTEM-Test](evidence/windows-idle-cpu-20261118.json) |
| Wiederanlauf | Nach einem Gatewaywechsel wurde der Windows-Agent ohne manuellen Dienstneustart wieder bereit. Der Helper glich seine bereits quittierte Ergebnismeldung ab. [Gatewaywechsel](evidence/windows-gateway-clock-recovery-20261117.json) · [Helper-Abgleich](evidence/windows-helper-result-recovery-20261118.json) |
| WebUI-Abschluss eines ungeklärten Versuchs | Auf OTRS ARM64 war derselbe Versuch zentral als `closed_unknown` abgeschlossen und lokal wegen unterschiedlicher Befunde noch blockiert. Der Agent hatte eine archivierte Unterbrechungsmeldung, beide Verbrauchsjournale hatten den ursprünglichen Start und kein Ergebnis. 71 Tests zu `915e126` prüfen den signierten Abschluss in Agent und Helper, den Erhalt der Originale und den Wiederanlauf nach unterbrochenen Journalaktualisierungen. Am 18. November um 18:05 UTC startete das bestehende Gerät einmal kontrolliert unter exklusiver Startsperre mit dem über mTLS abgerufenen signierten Paar `0.1.0-arm64.3`. Beide Verbrauchsjournale übernahmen den bereits vorhandenen WebUI-Abschluss. Die archivierte Originalmeldung, die Startbelege und die Geräteidentität waren unverändert nachweisbar. Der native Updater meldete `idle`, Agent und Helper waren nach dem Abgleich bereit und der reguläre Updatetimer war aktiv. Linux x64 übernahm `0.1.0-mvp.9` über den regulären Timer. [Geräteabgleich](../crates/agent-core/tests/reconcile.rs) |
[Produktvertrag](../Rust_RMM_Implementierungsspezifikation.md) · [Übergabe für die Weiterentwicklung](handover.md)
+5
View File
@@ -0,0 +1,5 @@
ALTER TABLE agent_installations
ADD COLUMN system_usage jsonb,
ADD COLUMN system_usage_observed_at timestamptz;
GRANT UPDATE(system_usage, system_usage_observed_at) ON agent_installations TO rmm_app;
+2
View File
@@ -9,6 +9,8 @@ Linux- und Windows-Agenten bauen die Verbindung zum Gateway ausgehend auf. Eine
| `POST /agent/v1/messages` | Ein `ClientHello` eröffnet die Verbindung. Weitere `MessageBatch`-Anfragen übertragen unter anderem Inventar, Abgleich, Auftragsstatus und Ergebnisse. | Ein `MessageBatch` enthält die Antworten des Servers. |
| `POST /agent/v1/poll` | Ein `PollRequest` enthält einen Heartbeat und die gewünschte Wartezeit von 0 bis 25 Sekunden. | Das Gateway bestätigt den Heartbeat und liefert vorhandene Arbeit mit derselben Antwort. Im Leerlauf genügt die Bestätigung. |
Heartbeats können eine passive Ressourcenmessung übermitteln. `cpu_usage_basis_points` liegt zwischen 0 und 10.000, `ram_available_bytes` und `ram_total_bytes` bilden gemeinsam einen Messwert. Das Gateway speichert je authentisierter Installation den letzten gültigen CPU-Wert und das letzte gültige RAM-Wertepaar mit ihrem jeweiligen Zeitpunkt. Ein zusätzlicher Poll-Heartbeat ohne Ressourcendaten lässt die gespeicherten Messwerte bestehen.
Beide Endpunkte verwenden `application/x-protobuf` und Protokollversion 1. Eine Nachricht trägt unter anderem die Gerätekennung, die Generationen von Einschreibung und Verbindung, die Boot-ID, Sequenznummer und Nachrichten-ID. Für gespeicherte Meldungen wie ein Skriptergebnis bestätigt der Server die ursprüngliche Nachrichten-ID. [HTTP-Verarbeitung](../crates/server/src/agent_http.rs) · [Speicherung und Bestätigung](../crates/server/src/agent_service.rs)
## Vom Antrag bis zum Ergebnis
+10 -1
View File
@@ -31,7 +31,16 @@ message Envelope {
}
message ClientHello { string agent_version = 1; repeated string capabilities = 2; }
message ServerHello { uint64 connection_generation = 1; uint32 max_message_bytes = 2; }
message Heartbeat { string instance_id = 1; uint64 uptime_seconds = 2; }
message Heartbeat {
string instance_id = 1;
uint64 uptime_seconds = 2;
SystemUsage system_usage = 3;
}
message SystemUsage {
optional uint32 cpu_usage_basis_points = 1;
optional uint64 ram_available_bytes = 2;
optional uint64 ram_total_bytes = 3;
}
// Single-chunk root inventory scope only; JSON is schema rmm.linux.base/1.
message InventorySnapshot {
string snapshot_id = 1;
+10 -1
View File
@@ -56,7 +56,9 @@ test('creates and renames a customer, opens its inventory, and hides editing for
if (!customer) throw new Error('Kunde fehlt im Testbestand');
return route.fulfill({ json: listing([{
tenant_id: customerId, customer_name: customer.name, asset_id: 'device-1', agent_id: 'agent-1',
lifecycle: 'current', status: 'online', hostname: 'NORD-PC', device_type: 'hypervisor', os: 'Proxmox VE'
lifecycle: 'current', status: 'online', hostname: 'NORD-PC', device_type: 'hypervisor', os: 'Proxmox VE',
ram_available_bytes: 6 * 2 ** 30, ram_total_bytes: 16 * 2 ** 30, cpu_usage_percent: 0,
disk_free_bytes: 24 * 2 ** 30, disk_total_bytes: 32 * 2 ** 30
}]) });
}
if (method === 'POST' || method === 'PATCH') {
@@ -108,6 +110,13 @@ test('creates and renames a customer, opens its inventory, and hides editing for
await expect(headers.nth(1)).toHaveText('Type');
await expect(device.getByRole('cell').nth(2)).toHaveText('hypervisor');
await expect(device.getByRole('cell').nth(3)).toHaveText('Proxmox VE');
const memory = device.locator('[data-label="RAM frei / gesamt"]');
await expect(memory).toHaveText('6 / 16 GiB');
await expect(memory.locator('.capacity-track')).toHaveAttribute('title', '37,5 % frei');
await expect(memory.locator('.capacity-track i')).toHaveAttribute('style', 'width: 62.5%;');
await expect(device.locator('[data-label="Speicher frei / gesamt"] .capacity-track i'))
.toHaveAttribute('style', 'width: 25%;');
await expect(device.getByText('Auslastung 0 %', { exact: true })).toBeVisible();
const navigation = page.getByRole('navigation', { name: 'Hauptnavigation' });
await navigation.getByRole('link', { name: 'Aufträge', exact: true }).click();
await expect(page.getByRole('combobox', { name: 'Kunde', exact: true })).toHaveValue(customerId);
+46
View File
@@ -0,0 +1,46 @@
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, it } from 'vitest';
import { DeviceInventoryPanels, systemDetails } from './device-inventory';
const report = (scope: string, data: unknown, truncated = false, quality = 'valid') =>
({ scope, data, truncated, quality, observed_at: '2026-11-18T08:00:00Z' });
it('reads current and older Linux snapshots, and labels approximate installation time', () => {
const device = { inventory: { observations: [
report('linux.os', { installed_at: '2025-03-12T10:00:00Z', install_date_source: 'root_filesystem', uptime_seconds: 60 }),
report('linux.hardware', { readable_dmi: { sys_vendor: 'Vendor' } }),
report('linux.interfaces', [{ name: 'eth0', addresses: ['192.0.2.1', '2001:db8::1%0'] }]),
report('linux.users', ['alice']),
report('linux.software', [{ name: 'openssh-server', version: '1.2', architecture: 'arm64' }], true)
] } };
expect(systemDetails(device, value => typeof value === 'string' ? value : 'Nicht gemeldet')).toEqual([
['OS installiert am', '2025-03-12T10:00:00Z · geschätzt (Root-Dateisystem)'],
['Letzter Neustart', '2026-11-18T07:59:00.000Z'],
['Hersteller', 'Vendor'],
['BIOS-Seriennummer', 'Nicht gemeldet'],
['Garantie bis', 'Nicht gemeldet']
]);
const view = renderToStaticMarkup(<DeviceInventoryPanels device={device} />);
expect(view).toContain('192.0.2.1, 2001:db8::1');
expect(view).toContain('alice');
expect(view).toContain('openssh-server');
expect(view).toContain('einen Teil der gefundenen Einträge');
});
it('shows Windows adapters, serial and registry software, with unknown distinct from empty sessions', () => {
const device = { inventory: { observations: [
report('windows.os', { booted_at: '2026-11-18T08:00:00Z' }),
report('windows.hardware', { manufacturer: 'Vendor', bios_serial_number: 'ABC123' }),
report('windows.interfaces', { entries: [{ name: 'Ethernet', addresses: ['192.0.2.2'] }] }),
report('windows.users', null, false, 'permission_denied'),
report('windows.software', { entries: [{ display_name: 'Produkt', publisher: 'Hersteller' }] })
] } };
const view = renderToStaticMarkup(<DeviceInventoryPanels device={device} />);
expect(view).toContain('Ethernet');
expect(view).toContain('Produkt');
expect(view).toContain('Nicht gemeldet');
expect(view).not.toContain('Keine Benutzer angemeldet');
expect(systemDetails(device, String)).toContainEqual(['BIOS-Seriennummer', 'ABC123']);
device.inventory.observations[3] = report('windows.users', { entries: [] });
expect(renderToStaticMarkup(<DeviceInventoryPanels device={device} />)).toContain('Keine Benutzer angemeldet');
});
+132
View File
@@ -0,0 +1,132 @@
import { useState, type ReactNode } from 'react';
import type { RecordValue } from './api';
const unreported = 'Nicht gemeldet';
const pageSize = 25;
function object(value: unknown): RecordValue {
return value && typeof value === 'object' && !Array.isArray(value) ? value as RecordValue : {};
}
function text(value: unknown): string | undefined {
return typeof value === 'string' && value.trim() ? value.trim() : undefined;
}
function values(value: unknown) {
return Array.isArray(value) ? value.flatMap(value => text(value) ?? []) : [];
}
function observation(device: RecordValue, name: string) {
const observations = object(device.inventory).observations;
return Array.isArray(observations) ? observations.map(object).find(item =>
item.quality === 'valid' && (item.scope === 'linux.' + name || item.scope === 'windows.' + name)
) : undefined;
}
export function systemDetails(device: RecordValue, formatTime: (value: unknown) => string) {
const os = observation(device, 'os');
const system = object(os?.data);
const hardware = object(observation(device, 'hardware')?.data);
const installed = formatTime(system.installed_at);
const source = system.install_date_source === 'root_filesystem' ? 'Root-Dateisystem'
: system.install_date_source === 'installer_directory' ? 'Installer-Verzeichnis' : null;
let booted = formatTime(system.booted_at);
if (booted === unreported && os?.scope === 'linux.os' && typeof system.uptime_seconds === 'number') {
const captured = Date.parse(text(os.observed_at) ?? '');
const estimated = captured - system.uptime_seconds * 1000;
if (system.uptime_seconds >= 0 && Number.isFinite(estimated) && estimated >= 0) {
booted = formatTime(new Date(estimated).toISOString());
}
}
return [
['OS installiert am', source && installed !== unreported ? installed + ' · geschätzt (' + source + ')' : installed],
['Letzter Neustart', booted],
['Hersteller', text(hardware.manufacturer) ?? text(object(hardware.readable_dmi).sys_vendor) ?? unreported],
['BIOS-Seriennummer', text(hardware.bios_serial_number) ?? unreported],
['Garantie bis', formatTime(hardware.warranty_expires_at)]
];
}
function entries(report: RecordValue | undefined): unknown[] | null {
const rows = Array.isArray(report?.data) ? report.data : object(report?.data).entries;
return Array.isArray(rows) ? rows : null;
}
function note(report: RecordValue | undefined) {
const readErrors = object(report?.data).read_errors;
return report?.truncated === true || (typeof readErrors === 'number' && readErrors > 0);
}
function InventoryTable({ headings, children }: { headings: string[]; children: ReactNode }) {
return <div className="table"><table>
<thead><tr>{headings.map(label => <th scope="col" key={label}>{label}</th>)}</tr></thead>
<tbody>{children}</tbody>
</table></div>;
}
function Software({ report }: { report: RecordValue | undefined }) {
const [query, setQuery] = useState('');
const [page, setPage] = useState(0);
const rows = entries(report)?.flatMap(entry => {
const row = object(entry);
const name = text(row.name) ?? text(row.display_name);
if (!name) return [];
return [{ name, version: text(row.version), publisher: text(row.publisher), architecture: text(row.architecture) }];
}).sort((left, right) => left.name.localeCompare(right.name, 'de'));
const matching = (rows ?? []).filter(row => Object.values(row).some(value =>
value?.toLocaleLowerCase('de').includes(query.trim().toLocaleLowerCase('de'))
));
const lastPage = Math.max(0, Math.ceil(matching.length / pageSize) - 1);
const current = Math.min(page, lastPage);
return <details>
<summary>Installierte Software{rows ? ' (' + rows.length + ')' : ''}</summary>
{note(report) && <p className="muted">Die Meldung enthält einen Teil der gefundenen Einträge.</p>}
{rows === undefined ? <p>{unreported}</p> : rows.length === 0 ? <p>Keine Softwareeinträge gemeldet.</p> : <>
<label>Software suchen
<input type="search" value={query} maxLength={120} onChange={e => { setQuery(e.target.value); setPage(0); }} />
</label>
{matching.length ? <InventoryTable headings={['Name', 'Version', 'Herausgeber', 'Architektur']}>
{matching.slice(current * pageSize, (current + 1) * pageSize).map((row, index) => <tr key={index}>
<td>{row.name}</td>
<td>{row.version ?? '–'}</td>
<td>{row.publisher ?? '–'}</td>
<td>{row.architecture ?? '–'}</td>
</tr>)}
</InventoryTable> : <p>Keine Treffer.</p>}
{lastPage > 0 && <div className="list-footer">
<span>Seite {current + 1} von {lastPage + 1}</span>
<div>
<button className="quiet" disabled={current === 0} onClick={() => setPage(current - 1)}>Zurück</button>
<button className="quiet" disabled={current === lastPage} onClick={() => setPage(current + 1)}>Weiter</button>
</div>
</div>}
</>}
</details>;
}
export function DeviceInventoryPanels({ device }: { device: RecordValue }) {
const network = observation(device, 'interfaces');
const interfaces = entries(network)?.map(object).filter(row => text(row.name));
const sessions = observation(device, 'users');
const users = values(entries(sessions)).sort((a, b) => a.localeCompare(b, 'de'));
return <>
<section>
<h2>Netzwerkkarten und IP-Adressen</h2>
{note(network) && <p className="muted">Die Meldung enthält einen Teil der Netzwerkkarten oder Adressen.</p>}
{interfaces === undefined ? <p>{unreported}</p> : interfaces.length === 0 ? <p>Keine Netzwerkkarten gemeldet.</p> :
<InventoryTable headings={['Netzwerkkarte', 'MAC-Adresse', 'IP-Adressen']}>
{interfaces.map((row, index) => <tr key={index}>
<td>{text(row.name)}</td>
<td>{text(row.mac) ?? '–'}</td>
<td>{values(row.addresses).map(address => address.replace(/%0$/, '')).join(', ') || 'Keine Adresse gemeldet'}</td>
</tr>)}
</InventoryTable>}
</section>
<section>
<h2>Angemeldete Benutzer</h2>
{note(sessions) && <p className="muted">Die Meldung enthält einen Teil der Sitzungen.</p>}
{users.length ? <ul>{users.map(name => <li key={name}>{name}</li>)}</ul>
: <p>{entries(sessions) && !note(sessions) ? 'Keine Benutzer angemeldet.' : unreported}</p>}
</section>
<section><Software report={observation(device, 'software')} /></section>
</>;
}
+24 -9
View File
@@ -16,6 +16,7 @@ import { AdminControl } from './management';
import { allowed } from './safety';
import { CatalogCheckNotice } from './catalog-check';
import { devicePlatform } from './script-catalog';
import { DeviceInventoryPanels, systemDetails } from './device-inventory';
import { ErrorBox, errorText, useResource } from './resource';
import { NavIcon, orderDetailRoute } from './navigation';
import { orderTitle, Status } from './order-presentation';
@@ -43,6 +44,15 @@ function capacity(free: unknown, total: unknown) {
t = gib(total);
return f === null && t === null ? unknown : `${f ?? '–'} / ${t ?? '–'} GiB`;
}
function cpuUsage(value: unknown) {
return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 100
? `${number.format(value)} %`
: unknown;
}
function measuredAt(value: unknown) {
const observed = time(value);
return observed === unknown ? undefined : `Gemessen am ${observed}`;
}
function cpu(d: RecordValue) {
const model = label(d.cpu_model),
count = d.cpu_logical_count;
@@ -76,14 +86,13 @@ function Presence({ d }: { d: RecordValue }) {
</span>
);
}
function Storage({ d }: { d: RecordValue }) {
const free = d.disk_free_bytes,
total = d.disk_total_bytes;
function Capacity({ free, total }: { free: unknown; total: unknown }) {
return (
<>
<span>{capacity(free, total)}</span>
{typeof free === 'number' &&
typeof total === 'number' &&
Number.isFinite(total) &&
free >= 0 &&
free <= total &&
total > 0 && (
@@ -171,8 +180,10 @@ function DeviceDetail({
['Kunde', label(d.customer_name)],
['Type', label(d.device_type)],
['Betriebssystem', label(d.os)],
['RAM', gib(d.ram_total_bytes) === null ? unknown : gib(d.ram_total_bytes) + ' GiB'],
...systemDetails(d, time),
['RAM frei / gesamt', capacity(d.ram_available_bytes, d.ram_total_bytes)],
['CPU', [cpu(d).primary, cpu(d).secondary].filter(Boolean).join(' · ')],
['CPU-Auslastung', [cpuUsage(d.cpu_usage_percent), measuredAt(d.cpu_usage_observed_at)].filter(Boolean).join(' · ')],
['Speicher frei / gesamt', capacity(d.disk_free_bytes, d.disk_total_bytes)],
['Letzter Kontakt', time(d.last_contact_at)],
['Inventar erhoben', time(d.observed_at)],
@@ -205,6 +216,7 @@ function DeviceDetail({
))}
</dl>
</section>
<DeviceInventoryPanels device={d} />
{volumes.length > 0 && (
<section>
<h2>Laufwerke</h2>
@@ -534,7 +546,7 @@ export function Devices({
<span className="sr-only">Ziel auswählen</span>
</th>
)}
{['Hostname', 'Type', 'OS', 'Status', 'Speicher frei / gesamt', 'RAM', 'CPU', 'Kunde'].map(
{['Hostname', 'Type', 'OS', 'Status', 'Speicher frei / gesamt', 'RAM frei / gesamt', 'CPU', 'Kunde'].map(
(h) => (
<th scope="col" key={h}>
{h}
@@ -591,15 +603,18 @@ export function Devices({
<small>Zuletzt {time(d.last_contact_at)}</small>
)}
</td>
<td data-label="Speicher frei / gesamt" className="storage">
<Storage d={d} />
<td data-label="Speicher frei / gesamt" className="capacity-cell">
<Capacity free={d.disk_free_bytes} total={d.disk_total_bytes} />
</td>
<td data-label="RAM">
{gib(d.ram_total_bytes) === null ? unknown : gib(d.ram_total_bytes) + ' GiB'}
<td data-label="RAM frei / gesamt" className="capacity-cell" title={measuredAt(d.ram_observed_at)}>
<Capacity free={d.ram_available_bytes} total={d.ram_total_bytes} />
</td>
<td data-label="CPU">
{model.primary}
{model.secondary && <small>{model.secondary}</small>}
<small title={measuredAt(d.cpu_usage_observed_at)}>
Auslastung {cpuUsage(d.cpu_usage_percent)}
</small>
</td>
<td data-label="Kunde">{label(d.customer_name)}</td>
</tr>
+1 -1
View File
@@ -98,7 +98,7 @@ section.fleet { padding:0; overflow:hidden; }
.fleet-table td[data-label="Type"] { overflow-wrap:anywhere; }
.fleet-table input[type=checkbox] { margin:0; }
.host-link { padding:0; background:none; color:var(--accent); text-align:left; font-weight:680; margin:0; overflow-wrap:anywhere; }
.fleet-table .storage { font-variant-numeric:tabular-nums; }
.fleet-table .capacity-cell { font-variant-numeric:tabular-nums; }
.capacity-track { display:block; width:min(90px,100%); border-radius:2px; background:#e1ebe6; height:4px; margin-top:6px; overflow:hidden; }
.capacity-track i { display:block; height:100%; background:#659d84; }
.presence { display:inline-flex; align-items:center; gap:5px; border-radius:20px; padding:2px 8px; background:#edf1ef; color:#4d5f59; font-size:.8rem; font-weight:650; }