Keep the last valid CPU reading during RAM-only heartbeats
Rust development slice / linux (push) Failing after 8s

This commit is contained in:
2026-11-18 18:46:04 +01:00
parent b3fe35b86b
commit 7006ce7420
3 changed files with 30 additions and 20 deletions
+25 -17
View File
@@ -147,10 +147,12 @@ pub async fn ingest(
match &e.payload {
Some(Payload::Heartbeat(h)) => {
Uuid::parse_str(&h.instance_id)?;
let usage = h.system_usage.as_ref().and_then(system_usage);
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=COALESCE($2,system_usage),
system_usage_observed_at=CASE WHEN $2::jsonb IS NULL THEN system_usage_observed_at ELSE $3 END
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?;
}
@@ -204,7 +206,7 @@ pub async fn ingest(
))
}
fn system_usage(sample: &SystemUsage) -> Option<Value> {
fn system_usage(sample: &SystemUsage, observed: DateTime<Utc>) -> Option<Value> {
let cpu = sample
.cpu_usage_basis_points
.filter(|&value| value <= 10_000);
@@ -212,14 +214,16 @@ fn system_usage(sample: &SystemUsage) -> Option<Value> {
.ram_available_bytes
.zip(sample.ram_total_bytes)
.filter(|&(available, total)| total > 0 && available <= total);
if cpu.is_none() && memory.is_none() {
return None;
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));
}
Some(json!({
"cpu_usage_percent": cpu.map(|value| f64::from(value) / 100.0),
"ram_available_bytes": memory.map(|(available, _)| available),
"ram_total_bytes": memory.map(|(_, total)| total),
}))
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)]
@@ -233,13 +237,17 @@ mod tests {
ram_available_bytes: Some(0),
ram_total_bytes: Some(1),
};
assert_eq!(
system_usage(&sample),
Some(json!({"cpu_usage_percent": 0.0, "ram_available_bytes": 0, "ram_total_bytes": 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);
assert!(system_usage(&sample).unwrap()["cpu_usage_percent"].is_null());
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), None);
assert_eq!(system_usage(&sample, now), None);
}
}
+4 -2
View File
@@ -358,6 +358,8 @@ fn project(row: &PgRow, now: DateTime<Utc>, full: bool) -> Value {
.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()
@@ -383,8 +385,8 @@ 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()),
"cpu_usage_percent":usage["cpu_usage_percent"],
"cpu_usage_observed_at":usage["cpu_usage_percent"].is_number().then_some(usage_at).flatten(),
"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))),
+1 -1
View File
@@ -9,7 +9,7 @@ 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. Die Werte sind optional. Das Gateway speichert nur die jüngste gültige Meldung je authentisierter Installation. Ein zusätzlicher Poll-Heartbeat ohne Ressourcendaten lässt den gespeicherten Messwert bestehen.
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)