Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
feat(agent): monitor local libvirt domains
[email protected]1b544eb11e5a
diff --git a/docs/UNIFIED_AGENT.md b/docs/UNIFIED_AGENT.mdindex 8710426971..f3889468a5 100644--- a/docs/UNIFIED_AGENT.md+++ b/docs/UNIFIED_AGENT.md@@ -84,10 +84,24 @@ curl -fsSL http://<pulse-ip>:7655/install.sh | \- **Host Metrics**: CPU, memory, disk, network I/O, temperatures- **Docker Monitoring**: Container metrics, health checks, Swarm support (when enabled)- **Kubernetes Monitoring**: Cluster, node, pod, and deployment health (when enabled)+- **Libvirt/KVM Monitoring**: Read-only VM inventory, state, vCPU, memory, and disk/network rates when the Linux host exposes `virsh`- **External Probes** (Pro): runs availability checks assigned to this agent from the Pulse server and reports the results back — see below- **Auto-Update**: Automatically updates when a new version is released- **Multi-Platform**: Linux, macOS, Windows support+On Linux, the host module automatically checks for `virsh`. When the agent can+open the default libvirt connection read-only, defined domains appear as VM+workloads under that host. Collection uses libvirt's bounded bulk statistics+interface and does not grant Pulse VM start, stop, console, or configuration+authority. If `virsh` is absent, the socket is inaccessible, or the driver does+not support the requested statistics, normal host reporting continues without+libvirt inventory.++Appliance packaging can still differ. In particular, a QNAP installation must+make its Container Station libvirt client/socket available to the agent service;+the presence of KVM processes alone is not enough to establish a readable+libvirt connection.+## External Probes (Pro)With the Pro `external_probe` entitlement, availability checks configured indiff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 5ef0ce51b6..95a6f4abae 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -1507,6 +1507,23 @@ the intentionally sparse public response.`sensors.gpu` while mapping only direct `temperature.gpu` readings intoexisting `sensors.temperatureCelsius` `gpu_nvidia_<index>` keys forcompatibility.+ Linux libvirt inventory belongs to the host-agent report as a read-only,+ auto-detected child workload source. `internal/hostagent/libvirt.go` may+ locate only the local `virsh` executable and use its global `--readonly`+ mode with `list --all --name` followed by one `domstats --raw --nowait`+ query over at most 128 validated domain names. The collector has one+ eight-second deadline, bounded list/stat output, fixed state/CPU/balloon/+ interface/block field selection, and no server-authored URI, domain, or+ command input. Missing clients, inaccessible sockets, unsupported drivers,+ partial statistics, or parse failures omit the inventory without failing+ host telemetry. Authenticated ingest derives CPU and I/O rates only after+ two accepted samples and projects the domains as provider-neutral+ `technology=libvirt` VM resources parented to the reporting host. It+ preserves the last successful collection timestamp across a failed query so+ the canonical source-staleness policy degrades the rows instead of making+ every guest disappear, while a successful empty inventory removes them.+ This path does not grant lifecycle, console, XML, snapshot, migration, or+ storage mutation authority.Authenticated server ingest may reduce those typed samples into boundedhost-level GPU utilization, VRAM pressure, and GPU temperature history onthe existing agent identity, but that monitoring projection does not changediff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.mdindex 614a7f0257..8d071ef45e 100644--- a/docs/release-control/v6/internal/subsystems/monitoring.md+++ b/docs/release-control/v6/internal/subsystems/monitoring.md@@ -902,6 +902,19 @@ changes.## Current State+### Local libvirt guests are bounded host-agent observations++Authenticated Linux host reports may carry a read-only libvirt inventory for+at most 128 domains. Server ingest discards source-authored IDs, validates and+deduplicates names, derives stable domain IDs, clamps vCPU and memory values,+and computes CPU and cumulative I/O rates only from two accepted samples.+Missing inventory means collection failed and preserves the last successful+sample with its original collection time; a present empty inventory is an+authoritative removal. Domain metrics use+`<host-id>:libvirt:<domain-id>` consistently for history, metrics storage, and+unified-resource lookup. No libvirt lifecycle or configuration operation is+part of the monitoring contract.+### Custom sensor evidence stays typed through host monitoringAuthenticated host reports now copy bounded `sensors.custom` entries into thediff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.mdindex 064104863a..f0d77a2854 100644--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md@@ -881,6 +881,16 @@ without contention or cross-delivery.## Current State+### Libvirt workload projection stays bounded and allocation-local++The Linux host collector performs one domain-list call and one bulk `domstats`+call under a shared eight-second deadline. It accepts at most 128 validated+domain names and caps combined list and statistics output at 64 KiB and 1 MiB+while the child process runs. Server normalization and registry projection are+single bounded passes over that inventory. The frontend workload mapper reads+the already-loaded provider-neutral VM facet in constant time per row; it adds+no request, subscription, global lookup, or provider-specific scan.+### Custom metric drawer projection remains resource-local and boundedThe Infrastructure detail drawer formats `sensors.custom` from the alreadydiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 52239a061a..14400c7fcf 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -2032,6 +2032,16 @@ capability over storage or recovery data.## Current State+### Provider-neutral libvirt VM facts are observation-only++The shared unified-resource type now includes a provider-neutral+`virtualMachine` facet for runtime state, hypervisor, and vCPU count. Storage+and recovery consumers may preserve or display this facet, but a libvirt+source does not imply snapshots, backup coverage, restore coordinates,+migration support, storage ownership, or lifecycle authority. No libvirt URI,+domain XML, console data, credential, or executable input enters recovery+state through this extension point.+### Unified host read state preserves custom sensor evidenceThe shared host/unified-resource read-state boundary now carries typed customdiff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.mdindex 54ea9dbe25..da2eb72c39 100644--- a/docs/release-control/v6/internal/subsystems/unified-resources.md+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md@@ -1680,6 +1680,18 @@ AI-only summary payloads, or page-local heuristics.## Current State+### Agent libvirt domains use a provider-neutral VM facet++The registry projects a host's validated libvirt domains as `vm` resources+with `technology=libvirt`, a parent relationship to the reporting host, and a+provider-neutral `virtualMachine` facet for runtime state, hypervisor, and+vCPU count. The source ID and metrics target are both+`<host-id>:libvirt:<domain-id>`. CPU and I/O metrics are omitted until the+monitoring layer proves a two-sample rate; memory is emitted only with a+positive maximum. The last successful libvirt collection time, rather than+the host heartbeat, controls guest source freshness. This facet must not+borrow Proxmox or VMware identifiers and carries no mutation capability.+### Agent custom sensors remain typed, cloned host metadata`resourceFromHost` projects `models.HostSensorSummary.Custom` intodiff --git a/frontend-modern/src/hooks/__tests__/useWorkloads.test.ts b/frontend-modern/src/hooks/__tests__/useWorkloads.test.tsindex 83b06950d2..fcff584c11 100644--- a/frontend-modern/src/hooks/__tests__/useWorkloads.test.ts+++ b/frontend-modern/src/hooks/__tests__/useWorkloads.test.ts@@ -160,6 +160,54 @@ describe('useWorkloads', () => {dispose();});+ it('projects agent-reported libvirt VM runtime metadata without Proxmox fields', async () => {+ apiFetchJSONMock.mockResolvedValueOnce({+ data: [+ {+ ...sampleResource,+ id: 'vm-agent-domain-a1b2c3d4',+ name: 'libvirt-app',+ status: 'warning',+ sources: ['agent'],+ parentName: 'qnap-host',+ vmid: undefined,+ node: undefined,+ instance: undefined,+ proxmox: undefined,+ virtualMachine: {+ runtimeState: 'running',+ hypervisor: 'libvirt',+ vcpus: 6,+ },+ },+ ],+ meta: { totalPages: 1 },+ });++ let dispose = () => {};+ let result: ReturnType<UseWorkloadsModule['useWorkloads']> | undefined;+ createRoot((d) => {+ dispose = d;+ const [enabled] = createSignal(true);+ result = useWorkloads(enabled);+ });++ await waitForWorkloadCount(() => result!.workloads().length);++ expect(result!.workloads()).toHaveLength(1);+ expect(result!.workloads()[0]).toMatchObject({+ id: 'vm-agent-domain-a1b2c3d4',+ name: 'libvirt-app',+ node: 'qnap-host',+ status: 'running',+ type: 'vm',+ cpus: 6,+ platformType: 'agent',+ });++ dispose();+ });+it('handles empty responses without mutating into undefined state', async () => {apiFetchJSONMock.mockResolvedValueOnce({data: [],diff --git a/frontend-modern/src/hooks/useWorkloads.ts b/frontend-modern/src/hooks/useWorkloads.tsindex c3d5e7bad5..122f8e08c8 100644--- a/frontend-modern/src/hooks/useWorkloads.ts+++ b/frontend-modern/src/hooks/useWorkloads.ts@@ -106,6 +106,11 @@ type APIResource = {osName?: string;osVersion?: string;};+ virtualMachine?: {+ runtimeState?: string;+ hypervisor?: string;+ vcpus?: number;+ };agent?: {hostname?: string;uptimeSeconds?: number;@@ -453,6 +458,7 @@ const mapResourceToWorkload = (resource: APIResource): WorkloadGuest | null => {instance,status: normalizeWorkloadStatus(resource.proxmox?.runtimeStatus ||+ resource.virtualMachine?.runtimeState ||resource.status ||(platformType === 'vmware-vsphere' ? resource.vmware?.powerState : null),),@@ -465,7 +471,7 @@ const mapResourceToWorkload = (resource: APIResource): WorkloadGuest | null => {? 'pod': 'app-container',cpu: getWorkloadCPUFraction(cpuPercent),- cpus: resource.proxmox?.cpus ?? 1,+ cpus: resource.proxmox?.cpus ?? resource.virtualMachine?.vcpus ?? 1,memory: (() => {const base = buildMetric(resource.metrics?.memory);const cache = resource.proxmox?.memoryCache ?? 0;diff --git a/frontend-modern/src/types/resource.ts b/frontend-modern/src/types/resource.tsindex 234dc2701f..a3e90ec412 100644--- a/frontend-modern/src/types/resource.ts+++ b/frontend-modern/src/types/resource.ts@@ -733,6 +733,12 @@ export interface ResourceProxmoxMeta {};}+export interface ResourceVirtualMachineMeta {+ runtimeState?: string;+ hypervisor?: string;+ vcpus?: number;+}+// Docker runtime, container, and Swarm service projection emitted by the// canonical adapter. Host resources use the runtime fields on the Docker// platform hosts table; `app-container` resources use the container fields@@ -1554,6 +1560,7 @@ export interface Resource {truenas?: ResourceTrueNASMeta;pmg?: ResourcePMGMeta;vmware?: ResourceVMwareMeta;+ virtualMachine?: ResourceVirtualMachineMeta;proxmox?: ResourceProxmoxMeta;pbs?: ResourcePBSMeta;availability?: ResourceAvailabilityMeta;diff --git a/internal/hostagent/agent.go b/internal/hostagent/agent.goindex e19029298a..1a8f082019 100644--- a/internal/hostagent/agent.go+++ b/internal/hostagent/agent.go@@ -1110,6 +1110,11 @@ func (a *Agent) buildReport(ctx context.Context) (agentshost.Report, error) {// Collect Ceph cluster data (best effort - only on Ceph nodes)cephData := a.collectCephStatus(collectCtx, runtimeConfig.disableCeph)+ // Collect local libvirt domain inventory on KVM-capable Linux hosts.+ // The collector uses a read-only connection and its own bounded deadline so+ // an unavailable hypervisor cannot delay the rest of the host report.+ libvirtData := a.collectLibvirtInventory(ctx)+// Collect S.M.A.R.T. disk data after topology owners. Enumeration and each// device probe have their own deadlines; a single shared 10-second budget// caused later disks on larger arrays to be cancelled before their probe.@@ -1137,6 +1142,15 @@ func (a *Agent) buildReport(ctx context.Context) (agentshost.Report, error) {if updatedFrom != "" {a.updatedFrom = ""}+ moduleStatus := a.currentModuleStatus()+ if libvirtData != nil {+ moduleStatus = append(moduleStatus, agentshost.ModuleStatus{+ Name: "libvirt",+ Enabled: true,+ State: "running",+ UpdatedAt: libvirtData.CollectedAt,+ })+ }report := agentshost.Report{Agent: agentshost.AgentInfo{@@ -1151,7 +1165,7 @@ func (a *Agent) buildReport(ctx context.Context) (agentshost.Report, error) {DiskExclude: append([]string(nil), runtimeConfig.diskExclude...),AppliedConfig: runtimeConfig.appliedConfig,Update: a.currentUpdateStatus(),- Modules: a.currentModuleStatus(),+ Modules: moduleStatus,},Host: agentshost.HostInfo{ID: a.machineID,@@ -1182,6 +1196,7 @@ func (a *Agent) buildReport(ctx context.Context) (agentshost.Report, error) {RAID: raidData,Unraid: unraidData,Ceph: cephData,+ Libvirt: libvirtData,ClusterSensors: clusterSensors,// Results stay queued until the primary destination accepts this// report, so a delivery failure retries them instead of losing them.diff --git a/internal/hostagent/libvirt.go b/internal/hostagent/libvirt.gonew file mode 100644index 0000000000..1be97c4551--- /dev/null+++ b/internal/hostagent/libvirt.go@@ -0,0 +1,309 @@+package hostagent++import (+ "context"+ "crypto/sha256"+ "encoding/hex"+ "errors"+ "fmt"+ "math"+ "os"+ "os/exec"+ "sort"+ "strconv"+ "strings"+ "time"+ "unicode/utf8"++ agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"+)++const (+ libvirtQueryTimeout = 8 * time.Second+ libvirtMaxDomains = 128+ libvirtMaxDomainNameBytes = 256+ libvirtMaxListOutputBytes = 64 * 1024+ libvirtMaxStatsOutputBytes = 1024 * 1024+)++var libvirtStatsArgs = []string{+ "--readonly",+ "domstats",+ "--raw",+ "--nowait",+ "--state",+ "--cpu-total",+ "--balloon",+ "--vcpu",+ "--interface",+ "--block",+}++// collectLibvirtInventory auto-detects a local read-only libvirt connection.+// It is deliberately best-effort: hosts without virsh, socket access, or a+// compatible driver continue reporting normal host telemetry.+func (a *Agent) collectLibvirtInventory(ctx context.Context) *agentshost.LibvirtInventory {+ if a.collector.GOOS() != "linux" {+ return nil+ }++ path, err := a.collector.LookPath("virsh")+ if err != nil {+ if !errors.Is(err, exec.ErrNotFound) && !os.IsNotExist(err) {+ a.logger.Debug().Err(err).Msg("Failed to locate virsh for libvirt inventory")+ }+ return nil+ }++ queryCtx, cancel := context.WithTimeout(ctx, libvirtQueryTimeout)+ defer cancel()++ listOutput, err := a.collector.CommandCombinedOutputLimited(+ queryCtx,+ libvirtMaxListOutputBytes,+ path,+ "--readonly",+ "list",+ "--all",+ "--name",+ )+ if err != nil {+ a.logger.Debug().Err(err).Msg("Failed to list local libvirt domains")+ return nil+ }+ names, err := parseLibvirtDomainList(listOutput)+ if err != nil {+ a.logger.Debug().Err(err).Msg("Failed to parse local libvirt domain list")+ return nil+ }++ inventory := &agentshost.LibvirtInventory{+ Domains: []agentshost.LibvirtDomain{},+ CollectedAt: a.collector.Now().UTC(),+ }+ if len(names) == 0 {+ return inventory+ }++ args := make([]string, 0, len(libvirtStatsArgs)+len(names))+ args = append(args, libvirtStatsArgs...)+ args = append(args, names...)+ statsOutput, err := a.collector.CommandCombinedOutputLimited(+ queryCtx,+ libvirtMaxStatsOutputBytes,+ path,+ args...,+ )+ if err != nil {+ a.logger.Debug().Err(err).Msg("Failed to collect local libvirt domain stats")+ return nil+ }+ domains, err := parseLibvirtDomainStats(statsOutput, names)+ if err != nil {+ a.logger.Debug().Err(err).Msg("Failed to parse local libvirt domain stats")+ return nil+ }+ inventory.Domains = domains+ return inventory+}++func parseLibvirtDomainList(output string) ([]string, error) {+ if len(output) > libvirtMaxListOutputBytes {+ return nil, fmt.Errorf("libvirt domain list exceeds %d bytes", libvirtMaxListOutputBytes)+ }++ names := make([]string, 0)+ seen := make(map[string]struct{})+ for _, raw := range strings.Split(strings.TrimSpace(output), "\n") {+ name := strings.TrimSpace(strings.TrimSuffix(raw, "\r"))+ if !validLibvirtDomainName(name) {+ continue+ }+ key := strings.ToLower(name)+ if _, exists := seen[key]; exists {+ continue+ }+ seen[key] = struct{}{}+ names = append(names, name)+ if len(names) == libvirtMaxDomains {+ break+ }+ }+ sort.Slice(names, func(i, j int) bool {+ return strings.ToLower(names[i]) < strings.ToLower(names[j])+ })+ return names, nil+}++func validLibvirtDomainName(name string) bool {+ if name == "" ||+ len(name) > libvirtMaxDomainNameBytes ||+ !utf8.ValidString(name) ||+ strings.HasPrefix(name, "-") {+ return false+ }+ for _, r := range name {+ if r < 0x20 || r == 0x7f {+ return false+ }+ }+ return true+}++func parseLibvirtDomainStats(output string, expectedNames []string) ([]agentshost.LibvirtDomain, error) {+ if len(output) > libvirtMaxStatsOutputBytes {+ return nil, fmt.Errorf("libvirt domain stats exceed %d bytes", libvirtMaxStatsOutputBytes)+ }++ expected := make(map[string]string, len(expectedNames))+ for _, name := range expectedNames {+ if validLibvirtDomainName(name) {+ expected[strings.ToLower(name)] = name+ }+ }++ records := make(map[string]*agentshost.LibvirtDomain, len(expected))+ var current *agentshost.LibvirtDomain+ for _, rawLine := range strings.Split(output, "\n") {+ line := strings.TrimSpace(strings.TrimSuffix(rawLine, "\r"))+ if strings.HasPrefix(line, "Domain: '") && strings.HasSuffix(line, "'") {+ name := strings.TrimSuffix(strings.TrimPrefix(line, "Domain: '"), "'")+ canonical, ok := expected[strings.ToLower(name)]+ if !ok {+ current = nil+ continue+ }+ key := strings.ToLower(canonical)+ if existing := records[key]; existing != nil {+ current = existing+ continue+ }+ domain := agentshost.LibvirtDomain{+ ID: libvirtDomainID(canonical),+ Name: canonical,+ State: "unknown",+ }+ records[key] = &domain+ current = &domain+ continue+ }+ if current == nil {+ continue+ }+ key, value, ok := strings.Cut(line, "=")+ if !ok {+ continue+ }+ applyLibvirtDomainStat(current, strings.TrimSpace(key), strings.TrimSpace(value))+ }++ result := make([]agentshost.LibvirtDomain, 0, len(expected))+ for _, name := range expectedNames {+ if !validLibvirtDomainName(name) {+ continue+ }+ key := strings.ToLower(name)+ if domain := records[key]; domain != nil {+ result = append(result, *domain)+ } else {+ result = append(result, agentshost.LibvirtDomain{+ ID: libvirtDomainID(name),+ Name: name,+ State: "unknown",+ })+ }+ if len(result) == libvirtMaxDomains {+ break+ }+ }+ return result, nil+}++func applyLibvirtDomainStat(domain *agentshost.LibvirtDomain, key, value string) {+ if domain == nil {+ return+ }+ switch key {+ case "state.state":+ if state, ok := parseLibvirtUint(value); ok {+ domain.State = libvirtDomainState(state)+ }+ case "cpu.time":+ if parsed, ok := parseLibvirtUint(value); ok {+ domain.CPUTimeNanoseconds = parsed+ }+ case "vcpu.current":+ if parsed, ok := parseLibvirtUint(value); ok && parsed <= math.MaxInt32 {+ domain.VCPUs = int(parsed)+ }+ case "balloon.current":+ if parsed, ok := parseLibvirtUint(value); ok {+ domain.MemoryCurrentBytes = libvirtKiBToBytes(parsed)+ }+ case "balloon.maximum":+ if parsed, ok := parseLibvirtUint(value); ok {+ domain.MemoryMaximumBytes = libvirtKiBToBytes(parsed)+ }+ default:+ parsed, ok := parseLibvirtUint(value)+ if !ok {+ return+ }+ switch {+ case strings.HasPrefix(key, "net.") && strings.HasSuffix(key, ".rx.bytes"):+ domain.NetworkRXBytes = saturatingAddUint64(domain.NetworkRXBytes, parsed)+ case strings.HasPrefix(key, "net.") && strings.HasSuffix(key, ".tx.bytes"):+ domain.NetworkTXBytes = saturatingAddUint64(domain.NetworkTXBytes, parsed)+ case strings.HasPrefix(key, "block.") && strings.HasSuffix(key, ".rd.bytes"):+ domain.DiskReadBytes = saturatingAddUint64(domain.DiskReadBytes, parsed)+ case strings.HasPrefix(key, "block.") && strings.HasSuffix(key, ".wr.bytes"):+ domain.DiskWriteBytes = saturatingAddUint64(domain.DiskWriteBytes, parsed)+ }+ }+}++func parseLibvirtUint(value string) (uint64, bool) {+ value = strings.TrimSpace(strings.Trim(value, "'\""))+ parsed, err := strconv.ParseUint(value, 10, 64)+ return parsed, err == nil+}++func libvirtDomainState(value uint64) string {+ switch value {+ case 1:+ return "running"+ case 2:+ return "blocked"+ case 3:+ return "paused"+ case 4:+ return "shutting-down"+ case 5:+ return "shutoff"+ case 6:+ return "crashed"+ case 7:+ return "suspended"+ default:+ return "unknown"+ }+}++func libvirtKiBToBytes(value uint64) int64 {+ if value > uint64(math.MaxInt64/1024) {+ return math.MaxInt64+ }+ return int64(value * 1024)+}++func saturatingAddUint64(left, right uint64) uint64 {+ if math.MaxUint64-left < right {+ return math.MaxUint64+ }+ return left + right+}++func libvirtDomainID(name string) string {+ sum := sha256.Sum256([]byte(name))+ return "domain-" + hex.EncodeToString(sum[:8])+}diff --git a/internal/hostagent/libvirt_test.go b/internal/hostagent/libvirt_test.gonew file mode 100644index 0000000000..49539bb116--- /dev/null+++ b/internal/hostagent/libvirt_test.go@@ -0,0 +1,127 @@+package hostagent++import (+ "context"+ "os"+ "slices"+ "strings"+ "testing"+ "time"++ "github.com/rs/zerolog"+)++func TestCollectLibvirtInventoryUsesReadOnlyBoundedBulkStats(t *testing.T) {+ const virshPath = "/usr/bin/virsh"+ now := time.Date(2026, 7, 30, 12, 0, 0, 0, time.UTC)+ var calls [][]string+ collector := &mockCollector{+ goos: "linux",+ nowFn: func() time.Time { return now },+ lookPathFn: func(file string) (string, error) {+ if file == "virsh" {+ return virshPath, nil+ }+ return "", os.ErrNotExist+ },+ commandCombinedOutputFn: func(_ context.Context, name string, args ...string) (string, error) {+ if name != virshPath {+ t.Fatalf("command = %q, want %q", name, virshPath)+ }+ calls = append(calls, append([]string(nil), args...))+ if slices.Equal(args, []string{"--readonly", "list", "--all", "--name"}) {+ return "web vm\r\nalpha\nweb vm\n", nil+ }+ wantPrefix := libvirtStatsArgs+ if len(args) != len(wantPrefix)+2 ||+ !slices.Equal(args[:len(wantPrefix)], wantPrefix) ||+ !slices.Equal(args[len(wantPrefix):], []string{"alpha", "web vm"}) {+ t.Fatalf("unexpected domstats args: %#v", args)+ }+ return `Domain: 'alpha'+ state.state=5+ vcpu.current=2+ balloon.current=1048576+ balloon.maximum=2097152+Domain: 'web vm'+ state.state=1+ cpu.time=3000000000+ vcpu.current=4+ balloon.current=4194304+ balloon.maximum=8388608+ net.0.rx.bytes=100+ net.1.rx.bytes=50+ net.0.tx.bytes=80+ block.0.rd.bytes=4096+ block.1.rd.bytes=1024+ block.0.wr.bytes=2048+`, nil+ },+ }+ agent := &Agent{logger: zerolog.Nop(), collector: collector}++ got := agent.collectLibvirtInventory(context.Background())+ if got == nil || len(got.Domains) != 2 {+ t.Fatalf("inventory = %+v, want two domains", got)+ }+ if !got.CollectedAt.Equal(now) || len(calls) != 2 {+ t.Fatalf("inventory metadata = %+v, calls = %#v", got, calls)+ }+ if got.Domains[0].Name != "alpha" ||+ got.Domains[0].State != "shutoff" ||+ got.Domains[0].VCPUs != 2 ||+ got.Domains[0].MemoryCurrentBytes != 1<<30 ||+ got.Domains[0].MemoryMaximumBytes != 2<<30 {+ t.Fatalf("alpha domain = %+v", got.Domains[0])+ }+ web := got.Domains[1]+ if web.Name != "web vm" ||+ web.State != "running" ||+ web.VCPUs != 4 ||+ web.CPUTimeNanoseconds != 3_000_000_000 ||+ web.NetworkRXBytes != 150 ||+ web.NetworkTXBytes != 80 ||+ web.DiskReadBytes != 5120 ||+ web.DiskWriteBytes != 2048 {+ t.Fatalf("web domain = %+v", web)+ }+ if web.ID == "" || web.ID == got.Domains[0].ID {+ t.Fatalf("domain IDs are not stable and distinct: %+v", got.Domains)+ }+}++func TestParseLibvirtDomainStatsKeepsListedDomainWhenStatsAreMissing(t *testing.T) {+ got, err := parseLibvirtDomainStats(+ "Domain: 'first'\nstate.state=1\nDomain: 'unexpected'\nstate.state=6\n",+ []string{"first", "second"},+ )+ if err != nil {+ t.Fatalf("parseLibvirtDomainStats: %v", err)+ }+ if len(got) != 2 ||+ got[0].Name != "first" ||+ got[0].State != "running" ||+ got[1].Name != "second" ||+ got[1].State != "unknown" {+ t.Fatalf("domains = %+v", got)+ }+}++func TestLibvirtParsingRejectsUnsafeAndOversizedInput(t *testing.T) {+ names, err := parseLibvirtDomainList("good\n-bad-option\nbad\x00name\n")+ if err != nil {+ t.Fatalf("parseLibvirtDomainList: %v", err)+ }+ if !slices.Equal(names, []string{"good"}) {+ t.Fatalf("names = %#v, want only good", names)+ }+ if _, err := parseLibvirtDomainList(strings.Repeat("x", libvirtMaxListOutputBytes+1)); err == nil {+ t.Fatal("expected oversized domain list to fail")+ }+ if _, err := parseLibvirtDomainStats(+ strings.Repeat("x", libvirtMaxStatsOutputBytes+1),+ []string{"good"},+ ); err == nil {+ t.Fatal("expected oversized domain stats to fail")+ }+}diff --git a/internal/hostagent/mock_collector_test.go b/internal/hostagent/mock_collector_test.goindex 49a4087143..3d9053040b 100644--- a/internal/hostagent/mock_collector_test.go+++ b/internal/hostagent/mock_collector_test.go@@ -2,6 +2,7 @@ package hostagentimport ("context"+ "fmt""net""os""time"@@ -28,15 +29,21 @@ type mockCollector struct {readFileFn func(name string) ([]byte, error)netInterfacesFn func() ([]net.Interface, error)- hostnameFn func() (string, error)- lookupIPFn func(host string) ([]net.IP, error)- dialTimeoutFn func(network, address string, timeout time.Duration) (net.Conn, error)- statFn func(name string) (os.FileInfo, error)- mkdirAllFn func(path string, perm os.FileMode) error- chmodFn func(name string, mode os.FileMode) error- writeFileFn func(filename string, data []byte, perm os.FileMode) error- commandCombinedOutputFn func(ctx context.Context, name string, arg ...string) (string, error)- lookPathFn func(file string) (string, error)+ hostnameFn func() (string, error)+ lookupIPFn func(host string) ([]net.IP, error)+ dialTimeoutFn func(network, address string, timeout time.Duration) (net.Conn, error)+ statFn func(name string) (os.FileInfo, error)+ mkdirAllFn func(path string, perm os.FileMode) error+ chmodFn func(name string, mode os.FileMode) error+ writeFileFn func(filename string, data []byte, perm os.FileMode) error+ commandCombinedOutputFn func(ctx context.Context, name string, arg ...string) (string, error)+ commandCombinedOutputLimitedFn func(+ ctx context.Context,+ maxBytes int,+ name string,+ arg ...string,+ ) (string, error)+ lookPathFn func(file string) (string, error)}func (m *mockCollector) HostInfo(ctx context.Context) (*gohost.InfoStat, error) {@@ -193,6 +200,22 @@ func (m *mockCollector) CommandCombinedOutput(ctx context.Context, name string,return "", nil}+func (m *mockCollector) CommandCombinedOutputLimited(+ ctx context.Context,+ maxBytes int,+ name string,+ arg ...string,+) (string, error) {+ if m.commandCombinedOutputLimitedFn != nil {+ return m.commandCombinedOutputLimitedFn(ctx, maxBytes, name, arg...)+ }+ output, err := m.CommandCombinedOutput(ctx, name, arg...)+ if len(output) > maxBytes {+ return output[:maxBytes], fmt.Errorf("command output exceeds %d bytes", maxBytes)+ }+ return output, err+}+func (m *mockCollector) LookPath(file string) (string, error) {if m.lookPathFn != nil {return m.lookPathFn(file)diff --git a/internal/hostagent/sysinfo.go b/internal/hostagent/sysinfo.goindex 2ad60485ed..80cf4f0b99 100644--- a/internal/hostagent/sysinfo.go+++ b/internal/hostagent/sysinfo.go@@ -1,11 +1,14 @@package hostagentimport (+ "bytes""context"+ "fmt""net""os""os/exec""runtime"+ "sync""time""github.com/rcourtman/pulse-go-rewrite/internal/hostmetrics"@@ -38,6 +41,7 @@ type SystemCollector interface {Chmod(name string, mode os.FileMode) errorWriteFile(filename string, data []byte, perm os.FileMode) errorCommandCombinedOutput(ctx context.Context, name string, arg ...string) (string, error)+ CommandCombinedOutputLimited(ctx context.Context, maxBytes int, name string, arg ...string) (string, error)LookPath(file string) (string, error)}@@ -138,6 +142,67 @@ func (c *defaultCollector) CommandCombinedOutput(ctx context.Context, name strinreturn string(out), err}+func (c *defaultCollector) CommandCombinedOutputLimited(+ ctx context.Context,+ maxBytes int,+ name string,+ arg ...string,+) (string, error) {+ if maxBytes <= 0 {+ return "", fmt.Errorf("command output limit must be positive")+ }+ output := &limitedCombinedBuffer{limit: maxBytes}+ cmd := exec.CommandContext(ctx, name, arg...)+ cmd.Stdout = output+ cmd.Stderr = output+ err := cmd.Run()+ if output.Exceeded() {+ return output.String(), fmt.Errorf("command output exceeds %d bytes", maxBytes)+ }+ return output.String(), err+}+func (c *defaultCollector) LookPath(file string) (string, error) {return exec.LookPath(file)}++// limitedCombinedBuffer bounds memory while preserving CombinedOutput-like+// capture of stdout and stderr. Writes beyond the limit are accepted and+// discarded so the child can exit normally or be stopped by its context.+type limitedCombinedBuffer struct {+ mu sync.Mutex+ buffer bytes.Buffer+ limit int+ exceeded bool+}++func (b *limitedCombinedBuffer) Write(p []byte) (int, error) {+ b.mu.Lock()+ defer b.mu.Unlock()++ originalLength := len(p)+ remaining := b.limit - b.buffer.Len()+ if remaining > 0 {+ if remaining < len(p) {+ _, _ = b.buffer.Write(p[:remaining])+ } else {+ _, _ = b.buffer.Write(p)+ }+ }+ if originalLength > remaining {+ b.exceeded = true+ }+ return originalLength, nil+}++func (b *limitedCombinedBuffer) String() string {+ b.mu.Lock()+ defer b.mu.Unlock()+ return b.buffer.String()+}++func (b *limitedCombinedBuffer) Exceeded() bool {+ b.mu.Lock()+ defer b.mu.Unlock()+ return b.exceeded+}diff --git a/internal/hostagent/sysinfo_test.go b/internal/hostagent/sysinfo_test.goindex 9c4661e14c..9560102774 100644--- a/internal/hostagent/sysinfo_test.go+++ b/internal/hostagent/sysinfo_test.go@@ -79,3 +79,19 @@ func TestDefaultCollector_Smoke(t *testing.T) {// Cleanup if possible (best effort)os.Remove("/tmp/pulse-test-file")}++func TestLimitedCombinedBufferCapsCapturedOutput(t *testing.T) {+ buffer := &limitedCombinedBuffer{limit: 5}+ if written, err := buffer.Write([]byte("123")); err != nil || written != 3 {+ t.Fatalf("first write = (%d, %v)", written, err)+ }+ if written, err := buffer.Write([]byte("4567")); err != nil || written != 4 {+ t.Fatalf("second write = (%d, %v)", written, err)+ }+ if got := buffer.String(); got != "12345" {+ t.Fatalf("captured output = %q, want %q", got, "12345")+ }+ if !buffer.Exceeded() {+ t.Fatal("expected buffer to record the output limit was exceeded")+ }+}diff --git a/internal/models/deepcopy.go b/internal/models/deepcopy.goindex 6d3f53d0ee..fd7949c7f4 100644--- a/internal/models/deepcopy.go+++ b/internal/models/deepcopy.go@@ -402,6 +402,7 @@ func cloneHost(src Host) Host {dest.RAID = cloneHostRAIDArrays(src.RAID)dest.Unraid = cloneHostUnraidStorage(src.Unraid)dest.Ceph = cloneHostCephCluster(src.Ceph)+ dest.Libvirt = cloneHostLibvirtInventory(src.Libvirt)dest.PackageUpdates = cloneHostPackageUpdateStatus(src.PackageUpdates)dest.StorageCleanup = cloneHostStorageCleanupStatus(src.StorageCleanup)dest.TokenLastUsedAt = cloneTimePtr(src.TokenLastUsedAt)@@ -411,6 +412,15 @@ func cloneHost(src Host) Host {return dest.NormalizeCollections()}+func cloneHostLibvirtInventory(src *HostLibvirtInventory) *HostLibvirtInventory {+ if src == nil {+ return nil+ }+ dest := *src+ dest.Domains = append([]HostLibvirtDomain(nil), src.Domains...)+ return &dest+}+func cloneHostIdentityConflict(src *HostIdentityConflict) *HostIdentityConflict {if src == nil {return nildiff --git a/internal/models/deepcopy_test.go b/internal/models/deepcopy_test.goindex f383cadd3c..486c608778 100644--- a/internal/models/deepcopy_test.go+++ b/internal/models/deepcopy_test.go@@ -423,3 +423,17 @@ func TestCloneHosts_Nil(t *testing.T) {t.Error("nil should clone to nil")}}++func TestCloneHostLibvirtInventoryIsolation(t *testing.T) {+ src := Host{Libvirt: &HostLibvirtInventory{+ Domains: []HostLibvirtDomain{{ID: "domain-a", Name: "app"}},+ }}+ dst := cloneHost(src)+ if dst.Libvirt == nil || len(dst.Libvirt.Domains) != 1 {+ t.Fatalf("cloned libvirt inventory = %+v", dst.Libvirt)+ }+ dst.Libvirt.Domains[0].Name = "mutated"+ if src.Libvirt.Domains[0].Name != "app" {+ t.Fatal("clone libvirt inventory aliases source domains")+ }+}diff --git a/internal/models/models.go b/internal/models/models.goindex d4ea7cfef2..ce05a9460e 100644--- a/internal/models/models.go+++ b/internal/models/models.go@@ -304,6 +304,7 @@ type Host struct {RAID []HostRAIDArray `json:"raid,omitempty"`Unraid *HostUnraidStorage `json:"unraid,omitempty"`Ceph *HostCephCluster `json:"ceph,omitempty"`+ Libvirt *HostLibvirtInventory `json:"libvirt,omitempty"`Status string `json:"status"`UptimeSeconds int64 `json:"uptimeSeconds,omitempty"`IntervalSeconds int `json:"intervalSeconds,omitempty"`@@ -438,6 +439,10 @@ func (h Host) NormalizeCollections() Host {ceph := h.Ceph.NormalizeCollections()h.Ceph = &ceph}+ if h.Libvirt != nil {+ libvirt := h.Libvirt.NormalizeCollections()+ h.Libvirt = &libvirt+ }if h.Tags == nil {h.Tags = []string{}}@@ -451,6 +456,43 @@ func (h Host) NormalizeCollections() Host {return h}+// HostLibvirtInventory is the normalized server-side view of a local+// read-only libvirt inventory reported by the Unified Agent.+type HostLibvirtInventory struct {+ Domains []HostLibvirtDomain `json:"domains"`+ CollectedAt time.Time `json:"collectedAt"`+}++func (i HostLibvirtInventory) NormalizeCollections() HostLibvirtInventory {+ if i.Domains == nil {+ i.Domains = []HostLibvirtDomain{}+ }+ return i+}++// HostLibvirtDomain carries both cumulative source counters and the+// server-derived point-in-time rates used by the unified VM resource.+type HostLibvirtDomain struct {+ ID string `json:"id"`+ Name string `json:"name"`+ State string `json:"state"`+ VCPUs int `json:"vcpus,omitempty"`+ CPUTimeNanoseconds uint64 `json:"cpuTimeNanoseconds,omitempty"`+ CPUUsagePercent float64 `json:"cpuUsagePercent,omitempty"`+ CPUUsageValid bool `json:"-"`+ MemoryCurrentBytes int64 `json:"memoryCurrentBytes,omitempty"`+ MemoryMaximumBytes int64 `json:"memoryMaximumBytes,omitempty"`+ NetworkRXBytes uint64 `json:"networkRxBytes,omitempty"`+ NetworkTXBytes uint64 `json:"networkTxBytes,omitempty"`+ DiskReadBytes uint64 `json:"diskReadBytes,omitempty"`+ DiskWriteBytes uint64 `json:"diskWriteBytes,omitempty"`+ NetworkInRate float64 `json:"networkInRate,omitempty"`+ NetworkOutRate float64 `json:"networkOutRate,omitempty"`+ DiskReadRate float64 `json:"diskReadRate,omitempty"`+ DiskWriteRate float64 `json:"diskWriteRate,omitempty"`+ IORatesValid bool `json:"-"`+}+// HostIdentityConflict records evidence that reports from more than one// physical machine are being folded into a single host agent record. The// usual cause is template-deployed machines that still share the samediff --git a/internal/monitoring/monitor_agents.go b/internal/monitoring/monitor_agents.goindex 3ff14f0c65..6657f25eeb 100644--- a/internal/monitoring/monitor_agents.go+++ b/internal/monitoring/monitor_agents.go@@ -2721,6 +2721,20 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.}}+ var previousHostModel *models.Host+ for i := range existingHostModels {+ if existingHostModels[i].ID == identifier {+ previousHostModel = &existingHostModels[i]+ break+ }+ }+ libvirtData := m.normalizeAgentLibvirtInventory(+ report.Libvirt,+ identifier,+ previousHostModel,+ observedAt,+ )+agentUpdate := mergeAgentUpdateStatus(previousHostAgentUpdate(m.state.GetHosts(), identifier),convertAgentUpdateStatus(report.Agent.Update),@@ -2771,6 +2785,7 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.RAID: raid,Unraid: unraidData,Ceph: cephData,+ Libvirt: libvirtData,Status: "online",UptimeSeconds: report.Host.UptimeSeconds,IntervalSeconds: report.Agent.IntervalSeconds,@@ -3020,6 +3035,7 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.m.metricsStore.Write("agent", host.ID, "diskwrite", diskWriteRate, now)}}+ m.writeLibvirtDomainMetrics(host, now)}// Store cluster peer sensor data if present and evict stale entriesdiff --git a/internal/monitoring/monitor_host_agents_test.go b/internal/monitoring/monitor_host_agents_test.goindex dc48c8455f..1b82667f31 100644--- a/internal/monitoring/monitor_host_agents_test.go+++ b/internal/monitoring/monitor_host_agents_test.go@@ -710,6 +710,61 @@ func TestApplyHostReportRefreshesUnifiedReadStateWithoutBroadcast(t *testing.T)t.Fatal("accepted host report did not refresh the canonical headless read state")}+func TestApplyHostReportProjectsAndPreservesLibvirtInventory(t *testing.T) {+ monitor := newTestMonitor(t)+ adapter := unifiedresources.NewMonitorAdapter(unifiedresources.NewRegistry(nil))+ monitor.SetResourceStore(adapter)+ now := time.Now().UTC()+ report := agentshost.Report{+ Agent: agentshost.AgentInfo{ID: "libvirt-host-agent", IntervalSeconds: 30},+ Host: agentshost.HostInfo{+ ID: "libvirt-host-machine",+ MachineID: "libvirt-host-machine",+ Hostname: "kvm-host",+ Platform: "linux",+ },+ Libvirt: &agentshost.LibvirtInventory{Domains: []agentshost.LibvirtDomain{{+ Name: "app",+ State: "running",+ VCPUs: 4,+ MemoryCurrentBytes: 2 << 30,+ MemoryMaximumBytes: 4 << 30,+ }}},+ Timestamp: now,+ }++ first, err := monitor.ApplyHostReport(report, nil)+ if err != nil {+ t.Fatalf("ApplyHostReport: %v", err)+ }+ if first.Libvirt == nil ||+ len(first.Libvirt.Domains) != 1 ||+ first.Libvirt.Domains[0].Name != "app" ||+ first.Libvirt.Domains[0].ID == "" {+ t.Fatalf("normalized libvirt inventory = %+v", first.Libvirt)+ }+ firstCollectedAt := first.Libvirt.CollectedAt+ vms := adapter.VMs()+ if len(vms) != 1 ||+ vms[0].Name() != "app" ||+ vms[0].RuntimeStatus() != "running" ||+ vms[0].CPUs() != 4 {+ t.Fatalf("canonical libvirt VM views = %+v", vms)+ }++ report.Libvirt = nil+ report.Timestamp = now.Add(time.Second)+ second, err := monitor.ApplyHostReport(report, nil)+ if err != nil {+ t.Fatalf("ApplyHostReport after collection failure: %v", err)+ }+ if second.Libvirt == nil ||+ len(second.Libvirt.Domains) != 1 ||+ !second.Libvirt.CollectedAt.Equal(firstCollectedAt) {+ t.Fatalf("preserved libvirt inventory = %+v", second.Libvirt)+ }+}+func TestUnifiedAgentHostAndDockerReportsShareOneCanonicalMachine(t *testing.T) {now := time.Now().UTC()hostReport := agentshost.Report{diff --git a/internal/monitoring/monitor_libvirt.go b/internal/monitoring/monitor_libvirt.gonew file mode 100644index 0000000000..6dd306d60d--- /dev/null+++ b/internal/monitoring/monitor_libvirt.go@@ -0,0 +1,215 @@+package monitoring++import (+ "crypto/sha256"+ "encoding/hex"+ "math"+ "sort"+ "strings"+ "time"+ "unicode/utf8"++ "github.com/rcourtman/pulse-go-rewrite/internal/models"+ agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"+)++const (+ maxAgentLibvirtDomains = 128+ maxAgentLibvirtDomainNameBytes = 256+)++func (m *Monitor) normalizeAgentLibvirtInventory(+ report *agentshost.LibvirtInventory,+ hostID string,+ previous *models.Host,+ observedAt time.Time,+) *models.HostLibvirtInventory {+ if report == nil {+ if previous != nil && previous.Libvirt != nil {+ preserved := *previous.Libvirt+ preserved.Domains = append([]models.HostLibvirtDomain(nil), previous.Libvirt.Domains...)+ return &preserved+ }+ return nil+ }++ previousByID := make(map[string]models.HostLibvirtDomain)+ previousAt := time.Time{}+ if previous != nil {+ previousAt = previous.LastSeen+ if previous.Libvirt != nil {+ for _, domain := range previous.Libvirt.Domains {+ previousByID[domain.ID] = domain+ }+ }+ }++ result := &models.HostLibvirtInventory{+ Domains: make([]models.HostLibvirtDomain, 0, min(len(report.Domains), maxAgentLibvirtDomains)),+ CollectedAt: observedAt.UTC(),+ }+ seen := make(map[string]struct{}, len(report.Domains))+ for _, incoming := range report.Domains {+ if len(result.Domains) == maxAgentLibvirtDomains {+ break+ }+ name := strings.TrimSpace(incoming.Name)+ if !validAgentLibvirtDomainName(name) {+ continue+ }+ dedupeKey := strings.ToLower(name)+ if _, exists := seen[dedupeKey]; exists {+ continue+ }+ seen[dedupeKey] = struct{}{}++ domain := models.HostLibvirtDomain{+ ID: agentLibvirtDomainID(name),+ Name: name,+ State: normalizeAgentLibvirtState(incoming.State),+ VCPUs: max(0, min(incoming.VCPUs, 4096)),+ CPUTimeNanoseconds: incoming.CPUTimeNanoseconds,+ MemoryCurrentBytes: max(int64(0), incoming.MemoryCurrentBytes),+ MemoryMaximumBytes: max(int64(0), incoming.MemoryMaximumBytes),+ NetworkRXBytes: incoming.NetworkRXBytes,+ NetworkTXBytes: incoming.NetworkTXBytes,+ DiskReadBytes: incoming.DiskReadBytes,+ DiskWriteBytes: incoming.DiskWriteBytes,+ }+ if domain.MemoryMaximumBytes > 0 && domain.MemoryCurrentBytes > domain.MemoryMaximumBytes {+ domain.MemoryCurrentBytes = domain.MemoryMaximumBytes+ }++ if prior, ok := previousByID[domain.ID]; ok {+ domain.CPUUsagePercent, domain.CPUUsageValid = libvirtCPUUsagePercent(+ prior,+ domain,+ observedAt.Sub(previousAt),+ )+ }++ if m != nil && m.rateTracker != nil {+ diskRead, diskWrite, netIn, netOut := m.rateTracker.CalculateRates(+ "libvirt:"+strings.TrimSpace(hostID)+":"+domain.ID,+ IOMetrics{+ DiskRead: uint64ToInt64(domain.DiskReadBytes),+ DiskWrite: uint64ToInt64(domain.DiskWriteBytes),+ NetworkIn: uint64ToInt64(domain.NetworkRXBytes),+ NetworkOut: uint64ToInt64(domain.NetworkTXBytes),+ Timestamp: observedAt,+ },+ )+ if diskRead >= 0 && diskWrite >= 0 && netIn >= 0 && netOut >= 0 {+ domain.DiskReadRate = diskRead+ domain.DiskWriteRate = diskWrite+ domain.NetworkInRate = netIn+ domain.NetworkOutRate = netOut+ domain.IORatesValid = true+ }+ }++ result.Domains = append(result.Domains, domain)+ }+ sort.Slice(result.Domains, func(i, j int) bool {+ return strings.ToLower(result.Domains[i].Name) < strings.ToLower(result.Domains[j].Name)+ })+ return result+}++func validAgentLibvirtDomainName(name string) bool {+ if name == "" || len(name) > maxAgentLibvirtDomainNameBytes || !utf8.ValidString(name) {+ return false+ }+ for _, r := range name {+ if r < 0x20 || r == 0x7f {+ return false+ }+ }+ return true+}++func normalizeAgentLibvirtState(value string) string {+ switch strings.ToLower(strings.TrimSpace(value)) {+ case "running", "blocked", "paused", "shutting-down", "shutoff", "crashed", "suspended":+ return strings.ToLower(strings.TrimSpace(value))+ default:+ return "unknown"+ }+}++func agentLibvirtDomainID(name string) string {+ sum := sha256.Sum256([]byte(name))+ return "domain-" + hex.EncodeToString(sum[:8])+}++func libvirtCPUUsagePercent(previous, current models.HostLibvirtDomain, elapsed time.Duration) (float64, bool) {+ if elapsed <= 0 || current.CPUTimeNanoseconds < previous.CPUTimeNanoseconds {+ return 0, false+ }+ vcpus := current.VCPUs+ if vcpus <= 0 {+ vcpus = 1+ }+ delta := current.CPUTimeNanoseconds - previous.CPUTimeNanoseconds+ percent := (float64(delta) / float64(elapsed.Nanoseconds()) / float64(vcpus)) * 100+ if math.IsNaN(percent) || math.IsInf(percent, 0) {+ return 0, false+ }+ return math.Max(0, math.Min(100, percent)), true+}++func uint64ToInt64(value uint64) int64 {+ if value > math.MaxInt64 {+ return math.MaxInt64+ }+ return int64(value)+}++func libvirtDomainMetricID(hostID, domainID string) string {+ return strings.TrimSpace(hostID) + ":libvirt:" + strings.TrimSpace(domainID)+}++func (m *Monitor) writeLibvirtDomainMetrics(host models.Host, observedAt time.Time) {+ if m == nil || host.Libvirt == nil {+ return+ }+ for _, domain := range host.Libvirt.Domains {+ metricID := libvirtDomainMetricID(host.ID, domain.ID)+ if domain.CPUUsageValid {+ if m.metricsHistory != nil {+ m.metricsHistory.AddGuestMetric(metricID, "cpu", domain.CPUUsagePercent, observedAt)+ }+ if m.metricsStore != nil {+ m.metricsStore.Write("vm", metricID, "cpu", domain.CPUUsagePercent, observedAt)+ }+ }+ if domain.MemoryMaximumBytes > 0 {+ memoryPercent := math.Max(0, math.Min(+ 100,+ (float64(domain.MemoryCurrentBytes)/float64(domain.MemoryMaximumBytes))*100,+ ))+ if m.metricsHistory != nil {+ m.metricsHistory.AddGuestMetric(metricID, "memory", memoryPercent, observedAt)+ }+ if m.metricsStore != nil {+ m.metricsStore.Write("vm", metricID, "memory", memoryPercent, observedAt)+ }+ }+ if !domain.IORatesValid {+ continue+ }+ for metricType, value := range map[string]float64{+ "netin": domain.NetworkInRate,+ "netout": domain.NetworkOutRate,+ "diskread": domain.DiskReadRate,+ "diskwrite": domain.DiskWriteRate,+ } {+ if m.metricsHistory != nil {+ m.metricsHistory.AddGuestMetric(metricID, metricType, value, observedAt)+ }+ if m.metricsStore != nil {+ m.metricsStore.Write("vm", metricID, metricType, value, observedAt)+ }+ }+ }+}diff --git a/internal/monitoring/monitor_libvirt_test.go b/internal/monitoring/monitor_libvirt_test.gonew file mode 100644index 0000000000..cbf79becc8--- /dev/null+++ b/internal/monitoring/monitor_libvirt_test.go@@ -0,0 +1,110 @@+package monitoring++import (+ "math"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/models"+ agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"+)++func TestNormalizeAgentLibvirtInventoryDerivesCPUAndIORates(t *testing.T) {+ monitor := &Monitor{rateTracker: NewRateTracker()}+ t0 := time.Date(2026, 7, 30, 12, 0, 0, 0, time.UTC)+ firstReport := &agentshost.LibvirtInventory{Domains: []agentshost.LibvirtDomain{{+ Name: "app",+ State: "running",+ VCPUs: 2,+ CPUTimeNanoseconds: 2_000_000_000,+ MemoryCurrentBytes: 2 << 30,+ MemoryMaximumBytes: 4 << 30,+ NetworkRXBytes: 1000,+ NetworkTXBytes: 2000,+ DiskReadBytes: 3000,+ DiskWriteBytes: 4000,+ }}}+ first := monitor.normalizeAgentLibvirtInventory(firstReport, "host-1", nil, t0)+ if first == nil || len(first.Domains) != 1 {+ t.Fatalf("first inventory = %+v", first)+ }+ if first.Domains[0].CPUUsageValid || first.Domains[0].IORatesValid {+ t.Fatalf("first sample invented rates: %+v", first.Domains[0])+ }++ previous := &models.Host{+ ID: "host-1",+ LastSeen: t0,+ Libvirt: first,+ }+ secondReport := &agentshost.LibvirtInventory{Domains: []agentshost.LibvirtDomain{{+ Name: "app",+ State: "running",+ VCPUs: 2,+ CPUTimeNanoseconds: 3_000_000_000,+ MemoryCurrentBytes: 5 << 30,+ MemoryMaximumBytes: 4 << 30,+ NetworkRXBytes: 2000,+ NetworkTXBytes: 4000,+ DiskReadBytes: 6000,+ DiskWriteBytes: 8000,+ }}}+ second := monitor.normalizeAgentLibvirtInventory(secondReport, "host-1", previous, t0.Add(10*time.Second))+ if second == nil || len(second.Domains) != 1 {+ t.Fatalf("second inventory = %+v", second)+ }+ got := second.Domains[0]+ if !got.CPUUsageValid || math.Abs(got.CPUUsagePercent-5) > 0.001 {+ t.Fatalf("CPU usage = (%v, %v), want valid 5%%", got.CPUUsagePercent, got.CPUUsageValid)+ }+ if !got.IORatesValid ||+ got.NetworkInRate != 100 ||+ got.NetworkOutRate != 200 ||+ got.DiskReadRate != 300 ||+ got.DiskWriteRate != 400 {+ t.Fatalf("I/O rates = %+v", got)+ }+ if got.MemoryCurrentBytes != 4<<30 {+ t.Fatalf("memory current = %d, want clamped to maximum", got.MemoryCurrentBytes)+ }+}++func TestNormalizeAgentLibvirtInventoryBoundsAndDeduplicates(t *testing.T) {+ monitor := &Monitor{rateTracker: NewRateTracker()}+ report := &agentshost.LibvirtInventory{Domains: []agentshost.LibvirtDomain{+ {Name: " VM ", State: "CRASHED", VCPUs: 5000},+ {Name: "vm", State: "running"},+ {Name: "bad\x00name", State: "running"},+ }}+ got := monitor.normalizeAgentLibvirtInventory(report, "host-1", nil, time.Now())+ if got == nil || len(got.Domains) != 1 {+ t.Fatalf("inventory = %+v, want one domain", got)+ }+ if got.Domains[0].Name != "VM" || got.Domains[0].State != "crashed" || got.Domains[0].VCPUs != 4096 {+ t.Fatalf("normalized domain = %+v", got.Domains[0])+ }+}++func TestNormalizeAgentLibvirtInventoryPreservesLastSuccessfulSampleOnFailure(t *testing.T) {+ collectedAt := time.Now().Add(-time.Minute).UTC()+ previous := &models.Host{Libvirt: &models.HostLibvirtInventory{+ CollectedAt: collectedAt,+ Domains: []models.HostLibvirtDomain{{+ ID: "domain-a",+ Name: "app",+ }},+ }}+ got := (&Monitor{rateTracker: NewRateTracker()}).normalizeAgentLibvirtInventory(+ nil,+ "host-1",+ previous,+ time.Now(),+ )+ if got == nil || len(got.Domains) != 1 || !got.CollectedAt.Equal(collectedAt) {+ t.Fatalf("preserved inventory = %+v", got)+ }+ got.Domains[0].Name = "mutated"+ if previous.Libvirt.Domains[0].Name != "app" {+ t.Fatal("preserved inventory aliases previous host state")+ }+}diff --git a/internal/unifiedresources/clone.go b/internal/unifiedresources/clone.goindex 57660bf907..e3427d459d 100644--- a/internal/unifiedresources/clone.go+++ b/internal/unifiedresources/clone.go@@ -46,6 +46,10 @@ func cloneResource(in *Resource) Resource {out.Ceph = cloneCephMeta(in.Ceph)out.TrueNAS = cloneTrueNASData(in.TrueNAS)out.VMware = cloneVMwareData(in.VMware)+ if in.VirtualMachine != nil {+ virtualMachine := *in.VirtualMachine+ out.VirtualMachine = &virtualMachine+ }out.Availability = cloneAvailabilityData(in.Availability)out.AvailabilityChecks = cloneAvailabilityDataSlice(in.AvailabilityChecks)out.FacetCounts = resourceFacetCounts(out)diff --git a/internal/unifiedresources/clone_test.go b/internal/unifiedresources/clone_test.goindex 96f6fb131e..1a7c7a080b 100644--- a/internal/unifiedresources/clone_test.go+++ b/internal/unifiedresources/clone_test.go@@ -805,3 +805,23 @@ func TestCloneResourceGivesRelationshipsTheirOwnBackingArray(t *testing.T) {}}}++func TestCloneResourceIsolatesVirtualMachineFacet(t *testing.T) {+ original := Resource{+ ID: "vm-agent-domain-a",+ Type: ResourceTypeVM,+ VirtualMachine: &VirtualMachineData{+ RuntimeState: "running",+ Hypervisor: "libvirt",+ VCPUs: 4,+ },+ }+ cloned := cloneResource(&original)+ if cloned.VirtualMachine == nil {+ t.Fatal("cloned resource lost virtual machine facet")+ }+ cloned.VirtualMachine.RuntimeState = "paused"+ if original.VirtualMachine.RuntimeState != "running" {+ t.Fatal("cloned virtual machine facet aliases original")+ }+}diff --git a/internal/unifiedresources/code_standards_test.go b/internal/unifiedresources/code_standards_test.goindex 6f8fd1c999..ff775d49f3 100644--- a/internal/unifiedresources/code_standards_test.go+++ b/internal/unifiedresources/code_standards_test.go@@ -88,6 +88,34 @@ func TestMetricValueAlwaysCarriesNumericValueWhenObjectExists(t *testing.T) {}}+func TestProviderNeutralVirtualMachineJSONContract(t *testing.T) {+ payload, err := json.Marshal(Resource{+ Type: ResourceTypeVM,+ VirtualMachine: &VirtualMachineData{+ RuntimeState: "running",+ Hypervisor: "libvirt",+ VCPUs: 4,+ },+ })+ if err != nil {+ t.Fatal(err)+ }+ var decoded map[string]any+ if err := json.Unmarshal(payload, &decoded); err != nil {+ t.Fatal(err)+ }+ facet, ok := decoded["virtualMachine"].(map[string]any)+ if !ok ||+ facet["runtimeState"] != "running" ||+ facet["hypervisor"] != "libvirt" ||+ facet["vcpus"] != float64(4) {+ t.Fatalf("provider-neutral VM facet = %#v in %s", facet, payload)+ }+ if _, exists := decoded["proxmox"]; exists {+ t.Fatalf("provider-neutral VM facet fabricated Proxmox metadata: %s", payload)+ }+}+func TestActionTruthTypesStayUnifiedResourceOwned(t *testing.T) {repoRoot := filepath.Join("..", "..")roots := []string{"internal/api", "internal/ai", "internal/agentexec", "internal/hostagent", "internal/dockeragent", "internal/relay", "internal/workflow", "internal/workflows"}diff --git a/internal/unifiedresources/libvirt.go b/internal/unifiedresources/libvirt.gonew file mode 100644index 0000000000..061db87e88--- /dev/null+++ b/internal/unifiedresources/libvirt.go@@ -0,0 +1,98 @@+package unifiedresources++import (+ "math"+ "strings"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/models"+)++func hostLibvirtDomainSourceID(host models.Host, domain models.HostLibvirtDomain) string {+ return strings.TrimSpace(host.ID) + ":libvirt:" + strings.TrimSpace(domain.ID)+}++func (rr *ResourceRegistry) ingestHostLibvirtDomains(host models.Host) {+ if host.Libvirt == nil {+ return+ }+ parentID := rr.sourceResourceID(SourceAgent, host.ID)+ for _, domain := range host.Libvirt.Domains {+ sourceID := hostLibvirtDomainSourceID(host, domain)+ if strings.TrimSpace(host.ID) == "" || strings.TrimSpace(domain.ID) == "" {+ continue+ }+ resource, identity := resourceFromHostLibvirtDomain(host, domain)+ if parentID != "" {+ resource.ParentID = &parentID+ }+ rr.ingest(SourceAgent, sourceID, resource, identity)+ }+}++func resourceFromHostLibvirtDomain(host models.Host, domain models.HostLibvirtDomain) (Resource, ResourceIdentity) {+ metrics := &ResourceMetrics{}+ if domain.CPUUsageValid {+ percent := math.Max(0, math.Min(100, domain.CPUUsagePercent))+ metrics.CPU = &MetricValue{+ Value: percent,+ Percent: percent,+ Unit: "percent",+ Source: SourceAgent,+ }+ }+ if domain.MemoryMaximumBytes > 0 {+ used := max(int64(0), min(domain.MemoryCurrentBytes, domain.MemoryMaximumBytes))+ total := domain.MemoryMaximumBytes+ metrics.Memory = &MetricValue{+ Used: &used,+ Total: &total,+ Percent: math.Max(0, math.Min(100, (float64(used)/float64(total))*100)),+ Unit: "bytes",+ Source: SourceAgent,+ }+ }+ if domain.IORatesValid {+ metrics.NetIn = &MetricValue{Value: max(0, domain.NetworkInRate), Unit: "bytes/s", Source: SourceAgent}+ metrics.NetOut = &MetricValue{Value: max(0, domain.NetworkOutRate), Unit: "bytes/s", Source: SourceAgent}+ metrics.DiskRead = &MetricValue{Value: max(0, domain.DiskReadRate), Unit: "bytes/s", Source: SourceAgent}+ metrics.DiskWrite = &MetricValue{Value: max(0, domain.DiskWriteRate), Unit: "bytes/s", Source: SourceAgent}+ }++ lastSeen := host.LastSeen+ if host.Libvirt != nil && !host.Libvirt.CollectedAt.IsZero() {+ lastSeen = host.Libvirt.CollectedAt+ }+ resource := Resource{+ Type: ResourceTypeVM,+ Technology: "libvirt",+ Name: strings.TrimSpace(domain.Name),+ Status: libvirtResourceStatus(domain.State),+ LastSeen: lastSeen,+ UpdatedAt: time.Now().UTC(),+ Metrics: metrics,+ Tags: []string{"libvirt", "kvm"},+ VirtualMachine: &VirtualMachineData{+ RuntimeState: strings.TrimSpace(domain.State),+ Hypervisor: "libvirt",+ VCPUs: domain.VCPUs,+ },+ }+ identity := ResourceIdentity{+ Hostnames: uniqueStrings([]string{domain.Name}),+ }+ return resource, identity+}++func libvirtResourceStatus(state string) ResourceStatus {+ switch strings.ToLower(strings.TrimSpace(state)) {+ case "running", "blocked":+ return StatusOnline+ case "shutoff":+ return StatusOffline+ case "paused", "shutting-down", "crashed", "suspended":+ return StatusWarning+ default:+ return StatusUnknown+ }+}diff --git a/internal/unifiedresources/libvirt_test.go b/internal/unifiedresources/libvirt_test.gonew file mode 100644index 0000000000..ec85a311b1--- /dev/null+++ b/internal/unifiedresources/libvirt_test.go@@ -0,0 +1,86 @@+package unifiedresources++import (+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/models"+)++func TestRegistryProjectsAgentLibvirtDomainsAsVMResources(t *testing.T) {+ now := time.Now().UTC()+ host := models.Host{+ ID: "host-1",+ Hostname: "kvm-host",+ Status: "online",+ LastSeen: now,+ Libvirt: &models.HostLibvirtInventory{Domains: []models.HostLibvirtDomain{{+ ID: "domain-a",+ Name: "app",+ State: "running",+ VCPUs: 4,+ CPUUsagePercent: 12.5,+ CPUUsageValid: true,+ MemoryCurrentBytes: 2 << 30,+ MemoryMaximumBytes: 4 << 30,+ NetworkInRate: 100,+ NetworkOutRate: 200,+ DiskReadRate: 300,+ DiskWriteRate: 400,+ IORatesValid: true,+ }}},+ }++ registry := NewRegistry(nil)+ registry.IngestSnapshot(models.StateSnapshot{Hosts: []models.Host{host}})+ vms := registry.ListByType(ResourceTypeVM)+ if len(vms) != 1 {+ t.Fatalf("VM resources = %d, want 1: %+v", len(vms), vms)+ }+ vm := vms[0]+ if vm.Name != "app" ||+ vm.Technology != "libvirt" ||+ vm.Status != StatusOnline ||+ vm.VirtualMachine == nil ||+ vm.VirtualMachine.VCPUs != 4 ||+ vm.VirtualMachine.RuntimeState != "running" {+ t.Fatalf("VM resource = %+v", vm)+ }+ if vm.ParentID == nil || *vm.ParentID == "" {+ t.Fatalf("VM parent = %+v, want host resource", vm.ParentID)+ }+ if vm.Metrics == nil ||+ vm.Metrics.CPU == nil ||+ vm.Metrics.CPU.Percent != 12.5 ||+ vm.Metrics.Memory == nil ||+ vm.Metrics.Memory.Percent != 50 ||+ vm.Metrics.NetIn == nil ||+ vm.Metrics.NetIn.Value != 100 {+ t.Fatalf("VM metrics = %+v", vm.Metrics)+ }+ wantMetricID := "host-1:libvirt:domain-a"+ metricsTarget := BuildMetricsTargetForRegistry(registry, vm.ID)+ if metricsTarget == nil ||+ metricsTarget.ResourceType != "vm" ||+ metricsTarget.ResourceID != wantMetricID {+ t.Fatalf("metrics target = %+v, want vm/%s", metricsTarget, wantMetricID)+ }+}++func TestLibvirtResourceStatusMapping(t *testing.T) {+ tests := map[string]ResourceStatus{+ "running": StatusOnline,+ "blocked": StatusOnline,+ "shutoff": StatusOffline,+ "paused": StatusWarning,+ "shutting-down": StatusWarning,+ "crashed": StatusWarning,+ "suspended": StatusWarning,+ "unknown": StatusUnknown,+ }+ for state, want := range tests {+ if got := libvirtResourceStatus(state); got != want {+ t.Errorf("libvirtResourceStatus(%q) = %q, want %q", state, got, want)+ }+ }+}diff --git a/internal/unifiedresources/metrics_targets.go b/internal/unifiedresources/metrics_targets.goindex 96bc3341ad..e4d9930aa1 100644--- a/internal/unifiedresources/metrics_targets.go+++ b/internal/unifiedresources/metrics_targets.go@@ -56,6 +56,11 @@ func BuildMetricsTarget(resource Resource, sourceTargets []SourceTarget) *Metricreturn &MetricsTarget{ResourceType: "vm", ResourceID: resourceID}}}+ if strings.EqualFold(strings.TrimSpace(resource.Technology), "libvirt") {+ if st, ok := bySource[SourceAgent]; ok {+ return &MetricsTarget{ResourceType: "vm", ResourceID: st.SourceID}+ }+ }case ResourceTypeSystemContainer:if st, ok := bySource[SourceProxmox]; ok {return &MetricsTarget{ResourceType: "system-container", ResourceID: st.SourceID}diff --git a/internal/unifiedresources/metrics_targets_test.go b/internal/unifiedresources/metrics_targets_test.goindex f21e97fb27..92adec8c6e 100644--- a/internal/unifiedresources/metrics_targets_test.go+++ b/internal/unifiedresources/metrics_targets_test.go@@ -467,6 +467,22 @@ func TestBuildMetricsTarget_UsesCanonicalAgentMetricIDForTrueNAS(t *testing.T) {}}+func TestBuildMetricsTarget_UsesAgentSourceIDForLibvirtVM(t *testing.T) {+ target := BuildMetricsTarget(+ Resource{Type: ResourceTypeVM, Technology: "libvirt"},+ []SourceTarget{{+ Source: SourceAgent,+ SourceID: " host-1:libvirt:domain-a ",+ }},+ )+ if target == nil {+ t.Fatal("BuildMetricsTarget() returned nil")+ }+ if target.ResourceType != "vm" || target.ResourceID != "host-1:libvirt:domain-a" {+ t.Fatalf("libvirt metrics target = %+v", target)+ }+}+func TestBuildMetricsTarget_UsesCanonicalVMMetricIDForTrueNAS(t *testing.T) {target := BuildMetricsTarget(Resource{diff --git a/internal/unifiedresources/presentation_coalesce.go b/internal/unifiedresources/presentation_coalesce.goindex 8cccc5943a..322b6ca5e9 100644--- a/internal/unifiedresources/presentation_coalesce.go+++ b/internal/unifiedresources/presentation_coalesce.go@@ -290,6 +290,9 @@ func mergePresentationHostResources(left, right Resource) Resource {if merged.VMware == nil {merged.VMware = secondary.VMware}+ if merged.VirtualMachine == nil {+ merged.VirtualMachine = secondary.VirtualMachine+ }if merged.TrueNAS == nil {merged.TrueNAS = secondary.TrueNAS}diff --git a/internal/unifiedresources/registry.go b/internal/unifiedresources/registry.goindex 89e82086da..ed945d3db6 100644--- a/internal/unifiedresources/registry.go+++ b/internal/unifiedresources/registry.go@@ -196,6 +196,7 @@ func (rr *ResourceRegistry) ingestSnapshot(snapshot models.StateSnapshot, thresh}for _, host := range snapshot.Hosts {rr.ingestHost(host)+ rr.ingestHostLibvirtDomains(host)}for _, host := range snapshot.Hosts {rr.ingestHostUnraidStorage(host)@@ -3264,6 +3265,9 @@ func (rr *ResourceRegistry) mergeInto(existing *Resource, incoming Resource, soubreak}existing.Agent = incoming.Agent+ if incoming.VirtualMachine != nil {+ existing.VirtualMachine = incoming.VirtualMachine+ }case SourceDocker:existing.Docker = incoming.Dockercase SourcePBS:diff --git a/internal/unifiedresources/registry_test.go b/internal/unifiedresources/registry_test.goindex 2e2eacfdbb..757993b6fe 100644--- a/internal/unifiedresources/registry_test.go+++ b/internal/unifiedresources/registry_test.go@@ -5821,3 +5821,39 @@ func TestPhysicalDiskRiskProjectionUsesSharedWearoutPredicate(t *testing.T) {})}}++func TestRegistryIngestsAgentLibvirtDomainUnderReportingHost(t *testing.T) {+ now := time.Now().UTC()+ registry := NewRegistry(nil)+ registry.IngestSnapshot(models.StateSnapshot{Hosts: []models.Host{{+ ID: "host-1",+ Hostname: "kvm-host",+ Status: "online",+ LastSeen: now,+ Libvirt: &models.HostLibvirtInventory{+ CollectedAt: now,+ Domains: []models.HostLibvirtDomain{{+ ID: "domain-a",+ Name: "app",+ State: "running",+ VCPUs: 4,+ }},+ },+ }}})++ vms := registry.ListByType(ResourceTypeVM)+ if len(vms) != 1 {+ t.Fatalf("libvirt VM resources = %+v", vms)+ }+ vm := vms[0]+ if vm.Technology != "libvirt" ||+ vm.VirtualMachine == nil ||+ vm.VirtualMachine.VCPUs != 4 ||+ vm.ParentID == nil {+ t.Fatalf("libvirt VM resource = %+v", vm)+ }+ parent, ok := registry.Get(*vm.ParentID)+ if !ok || parent.Type != ResourceTypeAgent || parent.Name != "kvm-host" {+ t.Fatalf("libvirt VM parent = %+v, found=%v", parent, ok)+ }+}diff --git a/internal/unifiedresources/types.go b/internal/unifiedresources/types.goindex 0e4694ec69..c79de737cb 100644--- a/internal/unifiedresources/types.go+++ b/internal/unifiedresources/types.go@@ -90,6 +90,17 @@ type Resource struct {// AvailabilityChecks is the canonical plural facet. Availability remains// the compatibility summary chosen from this set for existing consumers.AvailabilityChecks []AvailabilityData `json:"availabilityChecks,omitempty"`++ VirtualMachine *VirtualMachineData `json:"virtualMachine,omitempty"`+}++// VirtualMachineData carries provider-neutral VM facts that are useful across+// libvirt and future hypervisor adapters without borrowing a Proxmox or VMware+// source facet.+type VirtualMachineData struct {+ RuntimeState string `json:"runtimeState,omitempty"`+ Hypervisor string `json:"hypervisor,omitempty"`+ VCPUs int `json:"vcpus,omitempty"`}// ResourceFacetCounts captures the total count of each resource facet thatdiff --git a/internal/unifiedresources/views.go b/internal/unifiedresources/views.goindex 33015a8008..4368e7b3de 100644--- a/internal/unifiedresources/views.go+++ b/internal/unifiedresources/views.go@@ -98,10 +98,16 @@ func (v VMView) Status() ResourceStatus {}func (v VMView) RuntimeStatus() string {- if v.r == nil || v.r.Proxmox == nil {+ if v.r == nil {return ""}- return strings.TrimSpace(v.r.Proxmox.RuntimeStatus)+ if v.r.Proxmox != nil {+ return strings.TrimSpace(v.r.Proxmox.RuntimeStatus)+ }+ if v.r.VirtualMachine != nil {+ return strings.TrimSpace(v.r.VirtualMachine.RuntimeState)+ }+ return ""}func (v VMView) VMID() int {@@ -154,10 +160,16 @@ func (v VMView) Template() bool {}func (v VMView) CPUs() int {- if v.r == nil || v.r.Proxmox == nil {+ if v.r == nil {return 0}- return v.r.Proxmox.CPUs+ if v.r.Proxmox != nil {+ return v.r.Proxmox.CPUs+ }+ if v.r.VirtualMachine != nil {+ return v.r.VirtualMachine.VCPUs+ }+ return 0}func (v VMView) Uptime() int64 {diff --git a/internal/unifiedresources/views_test.go b/internal/unifiedresources/views_test.goindex 53f5984e91..d33de3da94 100644--- a/internal/unifiedresources/views_test.go+++ b/internal/unifiedresources/views_test.go@@ -2195,3 +2195,20 @@ func TestView_PhysicalDiskViewWearoutPassesThroughRealReadings(t *testing.T) {}}}++func TestView_VMViewUsesProviderNeutralVirtualMachineFallback(t *testing.T) {+ view := NewVMView(&Resource{+ Type: ResourceTypeVM,+ VirtualMachine: &VirtualMachineData{+ RuntimeState: "paused",+ Hypervisor: "libvirt",+ VCPUs: 6,+ },+ })+ if got := view.RuntimeStatus(); got != "paused" {+ t.Fatalf("RuntimeStatus() = %q, want paused", got)+ }+ if got := view.CPUs(); got != 6 {+ t.Fatalf("CPUs() = %d, want 6", got)+ }+}diff --git a/pkg/agents/host/report.go b/pkg/agents/host/report.goindex 7434292b8a..a29e7eaa2f 100644--- a/pkg/agents/host/report.go+++ b/pkg/agents/host/report.go@@ -53,6 +53,7 @@ type Report struct {RAID []RAIDArray `json:"raid,omitempty"`Unraid *UnraidStorage `json:"unraid,omitempty"`Ceph *CephCluster `json:"ceph,omitempty"`+ Libvirt *LibvirtInventory `json:"libvirt,omitempty"`ClusterSensors []ClusterNodeSensors `json:"clusterSensors,omitempty"`// AvailabilityResults carries availability checks the agent executed on// behalf of the server for targets assigned to it. The server owns failure@@ -63,6 +64,30 @@ type Report struct {SequenceID string `json:"sequenceId,omitempty"`}+// LibvirtInventory is the bounded, read-only domain inventory collected from+// a local libvirt connection. A non-nil inventory with no domains means the+// connection was readable but currently has no defined guests.+type LibvirtInventory struct {+ Domains []LibvirtDomain `json:"domains"`+ CollectedAt time.Time `json:"collectedAt"`+}++// LibvirtDomain contains only stable virDomainStats fields. All byte counters+// are cumulative; the server derives rates between accepted reports.+type LibvirtDomain struct {+ ID string `json:"id"`+ Name string `json:"name"`+ State string `json:"state"`+ VCPUs int `json:"vcpus,omitempty"`+ CPUTimeNanoseconds uint64 `json:"cpuTimeNanoseconds,omitempty"`+ MemoryCurrentBytes int64 `json:"memoryCurrentBytes,omitempty"`+ MemoryMaximumBytes int64 `json:"memoryMaximumBytes,omitempty"`+ NetworkRXBytes uint64 `json:"networkRxBytes,omitempty"`+ NetworkTXBytes uint64 `json:"networkTxBytes,omitempty"`+ DiskReadBytes uint64 `json:"diskReadBytes,omitempty"`+ DiskWriteBytes uint64 `json:"diskWriteBytes,omitempty"`+}+// AvailabilityProbeResult is one completed availability check reported by a// remote probe agent. Outcome mirrors the shared probe vocabulary// ("reachable", "unreachable", "indeterminate"); anything else is treated asdiff --git a/pkg/agents/host/report_test.go b/pkg/agents/host/report_test.goindex 3f02e501ec..0ba245267d 100644--- a/pkg/agents/host/report_test.go+++ b/pkg/agents/host/report_test.go@@ -633,3 +633,55 @@ func TestReportAvailabilityResultsJSONRoundTrip(t *testing.T) {t.Fatalf("empty availability results should be omitted: %s", bare)}}++func TestReportLibvirtInventoryJSONRoundTrip(t *testing.T) {+ collectedAt := time.Date(2026, 7, 30, 12, 0, 0, 0, time.UTC)+ report := Report{+ Libvirt: &LibvirtInventory{+ CollectedAt: collectedAt,+ Domains: []LibvirtDomain{{+ ID: "domain-a",+ Name: "app",+ State: "running",+ VCPUs: 4,+ CPUTimeNanoseconds: 3_000_000_000,+ MemoryCurrentBytes: 2 << 30,+ MemoryMaximumBytes: 4 << 30,+ NetworkRXBytes: 100,+ DiskWriteBytes: 200,+ }},+ },+ }++ data, err := json.Marshal(report)+ if err != nil {+ t.Fatalf("marshal report: %v", err)+ }+ var decoded Report+ if err := json.Unmarshal(data, &decoded); err != nil {+ t.Fatalf("unmarshal report: %v", err)+ }+ if decoded.Libvirt == nil ||+ !decoded.Libvirt.CollectedAt.Equal(collectedAt) ||+ len(decoded.Libvirt.Domains) != 1 {+ t.Fatalf("libvirt inventory = %+v", decoded.Libvirt)+ }+ domain := decoded.Libvirt.Domains[0]+ if domain.Name != "app" ||+ domain.State != "running" ||+ domain.VCPUs != 4 ||+ domain.CPUTimeNanoseconds != 3_000_000_000 ||+ domain.MemoryMaximumBytes != 4<<30 ||+ domain.NetworkRXBytes != 100 ||+ domain.DiskWriteBytes != 200 {+ t.Fatalf("libvirt domain = %+v", domain)+ }++ bare, err := json.Marshal(Report{})+ if err != nil {+ t.Fatalf("marshal bare report: %v", err)+ }+ if contains(string(bare), "libvirt") {+ t.Fatalf("nil libvirt inventory should be omitted: %s", bare)+ }+}