Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

fix(hostagent): stop pct df from starving LXC filesystem collection

rcourtman8318c7468796
diff --git a/internal/hostagent/mock_collector_test.go b/internal/hostagent/mock_collector_test.go
index edf8bf113f..7d6e4ddc26 100644
--- a/internal/hostagent/mock_collector_test.go
+++ b/internal/hostagent/mock_collector_test.go
@@ -44,7 +44,15 @@ type mockCollector struct {
name string,
arg ...string,
) (string, error)
- lookPathFn func(file string) (string, error)
+ lookPathFn func(file string) (string, error)
+ filesystemUsageFn func(path string) (hostFilesystemUsage, error)
+}
+
+func (m *mockCollector) FilesystemUsage(path string) (hostFilesystemUsage, error) {
+ if m.filesystemUsageFn != nil {
+ return m.filesystemUsageFn(path)
+ }
+ return hostFilesystemUsage{}, os.ErrNotExist
}
func (m *mockCollector) HostInfo(ctx context.Context) (*gohost.InfoStat, error) {
diff --git a/internal/hostagent/proxmox_lxc_filesystems.go b/internal/hostagent/proxmox_lxc_filesystems.go
index ac58f25662..bf2b6bcad7 100644
--- a/internal/hostagent/proxmox_lxc_filesystems.go
+++ b/internal/hostagent/proxmox_lxc_filesystems.go
@@ -33,24 +33,62 @@ func resolvePctPath(lookPath func(string) (string, error)) (string, error) {
}
const (
- proxmoxLXCQueryTimeout = 10 * time.Second
- proxmoxLXCMaxContainers = 128
- proxmoxLXCMaxDisks = 257
- proxmoxLXCMaxListOutputBytes = 64 * 1024
- proxmoxLXCMaxDFOutputBytes = 64 * 1024
- proxmoxLXCMaxNameBytes = 256
- proxmoxLXCMaxLabelBytes = 512
+ proxmoxLXCQueryTimeout = 10 * time.Second
+ proxmoxLXCContainerQueryTimeout = 5 * time.Second
+ proxmoxLXCCollectionTimeout = 20 * time.Second
+ proxmoxLXCMaxContainers = 128
+ proxmoxLXCMaxDisks = 257
+ proxmoxLXCMaxListOutputBytes = 64 * 1024
+ proxmoxLXCMaxDFOutputBytes = 64 * 1024
+ proxmoxLXCMaxConfigBytes = 64 * 1024
+ proxmoxLXCMaxPIDOutputBytes = 4 * 1024
+ proxmoxLXCMaxNameBytes = 256
+ proxmoxLXCMaxLabelBytes = 512
)
+// proxmoxLXCConfigDir is a pmxcfs symlink to the local node's container
+// configs, so reading through it never picks up guests owned by cluster peers.
+const proxmoxLXCConfigDir = "/etc/pve/lxc"
+
type proxmoxLXCRunningContainer struct {
VMID int
Name string
}
+// hostFilesystemUsage carries statfs-derived usage for one path plus the
+// st_dev identity needed to tell a real mount from its parent filesystem.
+type hostFilesystemUsage struct {
+ TotalBytes int64
+ UsedBytes int64
+ AvailBytes int64
+ Device uint64
+}
+
+// filesystemUsageProber is an optional collector capability. It exists on
+// Linux builds of the default collector; mocks opt in for tests.
+type filesystemUsageProber interface {
+ FilesystemUsage(path string) (hostFilesystemUsage, error)
+}
+
+type proxmoxLXCConfigMount struct {
+ Key string
+ Volume string
+ Path string
+}
+
// collectProxmoxLXCFilesystems auto-detects the local Proxmox Container
-// Toolkit. It lists node-local guests, then runs pct df only for containers
-// that the same list reported as running. Collection is read-only and
-// best-effort; a failed per-container query does not suppress other results.
+// Toolkit. It lists node-local guests, then resolves per-mount usage only for
+// containers that the same list reported as running. Collection is read-only
+// and best-effort; a failed per-container query does not suppress other
+// results.
+//
+// Usage comes from statfs against /proc/<pid>/root when the agent can resolve
+// the container's init PID, because pct df takes the container config lock and
+// costs over a second per guest; that expense starved later containers when
+// every query shared one budget. pct df remains as a per-container fallback
+// for least-privilege installs that cannot traverse /proc/<pid>/root, and each
+// container gets its own deadline so one slow guest cannot consume the whole
+// collection window.
func (a *Agent) collectProxmoxLXCFilesystems(ctx context.Context) *agentshost.ProxmoxLXCInventory {
if a.collector.GOOS() != "linux" {
return nil
@@ -63,16 +101,15 @@ func (a *Agent) collectProxmoxLXCFilesystems(ctx context.Context) *agentshost.Pr
return nil
}
- queryCtx, cancel := context.WithTimeout(ctx, proxmoxLXCQueryTimeout)
- defer cancel()
-
+ listCtx, cancelList := context.WithTimeout(ctx, proxmoxLXCQueryTimeout)
listOutput, err := collectCommandOutputLimited(
- queryCtx,
+ listCtx,
a.collector,
proxmoxLXCMaxListOutputBytes,
pctPath,
"list",
)
+ cancelList()
if err != nil {
a.logger.Debug().Err(err).Msg("Failed to list local Proxmox LXC containers")
return nil
@@ -83,35 +120,31 @@ func (a *Agent) collectProxmoxLXCFilesystems(ctx context.Context) *agentshost.Pr
return nil
}
+ prober, _ := a.collector.(filesystemUsageProber)
+ lxcInfoPath := ""
+ if prober != nil {
+ if resolved, lookErr := a.collector.LookPath("lxc-info"); lookErr == nil {
+ lxcInfoPath = resolved
+ }
+ }
+
+ collectionCtx, cancelCollection := context.WithTimeout(ctx, proxmoxLXCCollectionTimeout)
+ defer cancelCollection()
+
inventory := &agentshost.ProxmoxLXCInventory{
Containers: []agentshost.ProxmoxLXCContainer{},
CollectedAt: a.collector.Now().UTC(),
}
+ skipped := 0
for _, container := range containers {
- if queryCtx.Err() != nil {
- break
- }
- output, outputErr := collectCommandOutputLimited(
- queryCtx,
- a.collector,
- proxmoxLXCMaxDFOutputBytes,
- pctPath,
- "df",
- strconv.Itoa(container.VMID),
- )
- if outputErr != nil {
- a.logger.Debug().
- Err(outputErr).
- Int("vmid", container.VMID).
- Msg("Failed to collect Proxmox LXC filesystem usage")
+ if collectionCtx.Err() != nil {
+ skipped++
continue
}
- disks, parseErr := parseProxmoxLXCDF(output)
- if parseErr != nil || len(disks) == 0 {
- a.logger.Debug().
- Err(parseErr).
- Int("vmid", container.VMID).
- Msg("Failed to parse Proxmox LXC filesystem usage")
+ containerCtx, cancelContainer := context.WithTimeout(collectionCtx, proxmoxLXCContainerQueryTimeout)
+ disks := a.collectProxmoxLXCContainerDisks(containerCtx, prober, lxcInfoPath, pctPath, container.VMID)
+ cancelContainer()
+ if len(disks) == 0 {
continue
}
inventory.Containers = append(inventory.Containers, agentshost.ProxmoxLXCContainer{
@@ -120,10 +153,237 @@ func (a *Agent) collectProxmoxLXCFilesystems(ctx context.Context) *agentshost.Pr
Disks: disks,
})
}
+ if skipped > 0 {
+ a.logger.Warn().
+ Int("collected", len(inventory.Containers)).
+ Int("skipped", skipped).
+ Msg("Proxmox LXC filesystem collection budget exhausted before all running containers were queried")
+ }
return inventory
}
+func (a *Agent) collectProxmoxLXCContainerDisks(
+ ctx context.Context,
+ prober filesystemUsageProber,
+ lxcInfoPath string,
+ pctPath string,
+ vmid int,
+) []agentshost.Disk {
+ if prober != nil && lxcInfoPath != "" {
+ disks, fastErr := a.collectProxmoxLXCContainerDisksFast(ctx, prober, lxcInfoPath, vmid)
+ if fastErr == nil {
+ return disks
+ }
+ a.logger.Debug().
+ Err(fastErr).
+ Int("vmid", vmid).
+ Msg("Proxmox LXC statfs probe unavailable; falling back to pct df")
+ }
+
+ output, outputErr := collectCommandOutputLimited(
+ ctx,
+ a.collector,
+ proxmoxLXCMaxDFOutputBytes,
+ pctPath,
+ "df",
+ strconv.Itoa(vmid),
+ )
+ if outputErr != nil {
+ a.logger.Debug().
+ Err(outputErr).
+ Int("vmid", vmid).
+ Msg("Failed to collect Proxmox LXC filesystem usage")
+ return nil
+ }
+ disks, parseErr := parseProxmoxLXCDF(output)
+ if parseErr != nil || len(disks) == 0 {
+ a.logger.Debug().
+ Err(parseErr).
+ Int("vmid", vmid).
+ Msg("Failed to parse Proxmox LXC filesystem usage")
+ return nil
+ }
+ return disks
+}
+
+// collectProxmoxLXCContainerDisksFast reads the container's config-declared
+// mounts and resolves live usage with statfs through /proc/<pid>/root, which
+// follows into the container's mount namespace without taking the pct config
+// lock. A mount whose device identity matches its parent directory is not a
+// distinct mounted filesystem there — statfs would report the parent's
+// numbers — so it is dropped rather than invented.
+func (a *Agent) collectProxmoxLXCContainerDisksFast(
+ ctx context.Context,
+ prober filesystemUsageProber,
+ lxcInfoPath string,
+ vmid int,
+) ([]agentshost.Disk, error) {
+ raw, err := a.collector.ReadFile(filepath.Join(proxmoxLXCConfigDir, strconv.Itoa(vmid)+".conf"))
+ if err != nil {
+ return nil, fmt.Errorf("read container config: %w", err)
+ }
+ if len(raw) > proxmoxLXCMaxConfigBytes {
+ return nil, fmt.Errorf("container config exceeds %d bytes", proxmoxLXCMaxConfigBytes)
+ }
+ mounts := parseProxmoxLXCConfigMounts(string(raw))
+ if len(mounts) == 0 {
+ return nil, errors.New("no filesystem mounts in container config")
+ }
+
+ pidOutput, err := collectCommandOutputLimited(
+ ctx,
+ a.collector,
+ proxmoxLXCMaxPIDOutputBytes,
+ lxcInfoPath,
+ "-n",
+ strconv.Itoa(vmid),
+ "-p",
+ )
+ if err != nil {
+ return nil, fmt.Errorf("resolve container pid: %w", err)
+ }
+ pid, err := parseLXCInfoPID(pidOutput)
+ if err != nil {
+ return nil, err
+ }
+
+ procRoot := fmt.Sprintf("/proc/%d/root", pid)
+ result := make([]agentshost.Disk, 0, len(mounts))
+ for _, mount := range mounts {
+ if ctx.Err() != nil {
+ return nil, ctx.Err()
+ }
+ target := path.Join(procRoot, mount.Path)
+ usage, usageErr := prober.FilesystemUsage(target)
+ if usageErr != nil || usage.TotalBytes <= 0 {
+ continue
+ }
+ if mount.Path != "/" {
+ parent, parentErr := prober.FilesystemUsage(path.Dir(target))
+ if parentErr != nil || parent.Device == usage.Device {
+ continue
+ }
+ }
+ used := usage.UsedBytes
+ if used < 0 {
+ used = 0
+ }
+ if used > usage.TotalBytes {
+ used = usage.TotalBytes
+ }
+ avail := usage.AvailBytes
+ if avail < 0 {
+ avail = 0
+ }
+ if avail > usage.TotalBytes {
+ avail = usage.TotalBytes
+ }
+ usagePct := 0.0
+ if denominator := used + avail; denominator > 0 {
+ usagePct = float64(used) / float64(denominator) * 100
+ }
+ if usagePct > 100 {
+ usagePct = 100
+ }
+ result = append(result, agentshost.Disk{
+ Device: mount.Volume,
+ Mountpoint: mount.Path,
+ Type: mount.Key,
+ TotalBytes: usage.TotalBytes,
+ UsedBytes: used,
+ FreeBytes: avail,
+ Usage: usagePct,
+ })
+ if len(result) == proxmoxLXCMaxDisks {
+ break
+ }
+ }
+ if len(result) == 0 {
+ return nil, errors.New("no mounted container filesystems resolved")
+ }
+
+ sort.SliceStable(result, func(i, j int) bool {
+ if result[i].Mountpoint == "/" {
+ return true
+ }
+ if result[j].Mountpoint == "/" {
+ return false
+ }
+ return result[i].Mountpoint < result[j].Mountpoint
+ })
+ return result, nil
+}
+
+// parseProxmoxLXCConfigMounts extracts rootfs and mpN entries from the main
+// section of a container config. Parsing stops at the first section header so
+// snapshot and pending sections can never contribute mounts.
+func parseProxmoxLXCConfigMounts(content string) []proxmoxLXCConfigMount {
+ result := make([]proxmoxLXCConfigMount, 0, 4)
+ seen := make(map[string]struct{})
+ for _, rawLine := range strings.Split(content, "\n") {
+ line := strings.TrimSpace(strings.TrimSuffix(rawLine, "\r"))
+ if strings.HasPrefix(line, "[") {
+ break
+ }
+ if line == "" || strings.HasPrefix(line, "#") {
+ continue
+ }
+ key, value, found := strings.Cut(line, ":")
+ if !found {
+ continue
+ }
+ key = strings.ToLower(strings.TrimSpace(key))
+ if key != "rootfs" && !validProxmoxLXCMountKey(key) {
+ continue
+ }
+ parts := strings.Split(strings.TrimSpace(value), ",")
+ volume := strings.TrimSpace(parts[0])
+ if !safeProxmoxLXCText(volume, proxmoxLXCMaxLabelBytes) {
+ continue
+ }
+ mountPath := ""
+ if key == "rootfs" {
+ mountPath = "/"
+ }
+ for _, part := range parts[1:] {
+ optionKey, optionValue, optionFound := strings.Cut(part, "=")
+ if optionFound && strings.TrimSpace(optionKey) == "mp" {
+ mountPath = strings.TrimSpace(optionValue)
+ }
+ }
+ if !validProxmoxLXCMountpoint(mountPath) {
+ continue
+ }
+ dedupeKey := strings.ToLower(mountPath)
+ if _, exists := seen[dedupeKey]; exists {
+ continue
+ }
+ seen[dedupeKey] = struct{}{}
+ result = append(result, proxmoxLXCConfigMount{Key: key, Volume: volume, Path: mountPath})
+ if len(result) == proxmoxLXCMaxDisks {
+ break
+ }
+ }
+ return result
+}
+
+func parseLXCInfoPID(output string) (int, error) {
+ for _, rawLine := range strings.Split(output, "\n") {
+ line := strings.TrimSpace(strings.TrimSuffix(rawLine, "\r"))
+ value, found := strings.CutPrefix(line, "PID:")
+ if !found {
+ continue
+ }
+ pid, err := strconv.Atoi(strings.TrimSpace(value))
+ if err != nil || pid < 2 {
+ return 0, fmt.Errorf("invalid lxc-info pid %q", strings.TrimSpace(value))
+ }
+ return pid, nil
+ }
+ return 0, errors.New("lxc-info output contains no pid")
+}
+
func parseProxmoxLXCRunningContainers(output string) ([]proxmoxLXCRunningContainer, error) {
if len(output) > proxmoxLXCMaxListOutputBytes {
return nil, fmt.Errorf("pct list output exceeds %d bytes", proxmoxLXCMaxListOutputBytes)
diff --git a/internal/hostagent/proxmox_lxc_filesystems_linux.go b/internal/hostagent/proxmox_lxc_filesystems_linux.go
new file mode 100644
index 0000000000..52c9664c25
--- /dev/null
+++ b/internal/hostagent/proxmox_lxc_filesystems_linux.go
@@ -0,0 +1,41 @@
+//go:build linux
+
+package hostagent
+
+import (
+ "fmt"
+ "syscall"
+)
+
+// FilesystemUsage satisfies filesystemUsageProber on Linux. Statfs through a
+// /proc/<pid>/root path traverses into that process's mount namespace, so the
+// numbers match what df reports inside the container.
+func (c *defaultCollector) FilesystemUsage(path string) (hostFilesystemUsage, error) {
+ var fs syscall.Statfs_t
+ if err := syscall.Statfs(path, &fs); err != nil {
+ return hostFilesystemUsage{}, fmt.Errorf("statfs %s: %w", path, err)
+ }
+ var st syscall.Stat_t
+ if err := syscall.Stat(path, &st); err != nil {
+ return hostFilesystemUsage{}, fmt.Errorf("stat %s: %w", path, err)
+ }
+ blockSize := int64(fs.Frsize)
+ if blockSize <= 0 {
+ blockSize = int64(fs.Bsize)
+ }
+ if blockSize <= 0 {
+ return hostFilesystemUsage{}, fmt.Errorf("statfs %s: invalid block size", path)
+ }
+ total := int64(fs.Blocks) * blockSize
+ free := int64(fs.Bfree) * blockSize
+ used := total - free
+ if used < 0 {
+ used = 0
+ }
+ return hostFilesystemUsage{
+ TotalBytes: total,
+ UsedBytes: used,
+ AvailBytes: int64(fs.Bavail) * blockSize,
+ Device: uint64(st.Dev),
+ }, nil
+}
diff --git a/internal/hostagent/proxmox_lxc_filesystems_test.go b/internal/hostagent/proxmox_lxc_filesystems_test.go
index 5b74814ec4..2f4e4d61ae 100644
--- a/internal/hostagent/proxmox_lxc_filesystems_test.go
+++ b/internal/hostagent/proxmox_lxc_filesystems_test.go
@@ -96,6 +96,230 @@ mp0 tank:subvol-100-disk-0 1.0T 512.0G 512.0G 50.0 /srv/data
}
}
+// Regression for the #1477 follow-up: pct df costs over a second per guest,
+// so serial pct df inside one shared budget starved every container after the
+// first handful. With a resolvable init PID the collector must answer from
+// statfs through /proc/<pid>/root and never spawn pct df.
+func TestCollectProxmoxLXCFilesystemsPrefersProcStatfsOverPctDF(t *testing.T) {
+ const pctPath = "/usr/sbin/pct"
+ const lxcInfoPath = "/usr/bin/lxc-info"
+ listOutput := fmt.Sprintf(
+ "%-10s %-10s %-12s %-20s\n%-10d %-10s %-12s %-20s\n%-10d %-10s %-12s %-20s\n",
+ "VMID", "Status", "Lock", "Name",
+ 100, "running", "", "web",
+ 101, "running", "", "db",
+ )
+ configs := map[string]string{
+ "/etc/pve/lxc/100.conf": `arch: amd64
+hostname: web
+rootfs: local-lvm:vm-100-disk-0,size=8G
+mp0: tank:subvol-100-disk-0,mp=/srv/data,size=1T
+mp1: tank:subvol-100-disk-1,mp=/mnt/missing,size=10G
+
+[snap1]
+mp2: tank:snap-only,mp=/snap-only,size=5G
+`,
+ "/etc/pve/lxc/101.conf": "rootfs: local-lvm:vm-101-disk-0,size=4G\n",
+ }
+ usageByPath := map[string]hostFilesystemUsage{
+ "/proc/4242/root": {TotalBytes: 8 << 30, UsedBytes: 2 << 30, AvailBytes: 6 << 30, Device: 11},
+ "/proc/4242/root/srv": {TotalBytes: 8 << 30, UsedBytes: 2 << 30, AvailBytes: 6 << 30, Device: 11},
+ "/proc/4242/root/srv/data": {TotalBytes: 1 << 40, UsedBytes: 512 << 30, AvailBytes: 512 << 30, Device: 12},
+ // mp1 is configured but not mounted in the running container, so the
+ // path resolves to the rootfs device and must be dropped, not reported
+ // with the parent's numbers.
+ "/proc/4242/root/mnt": {TotalBytes: 8 << 30, UsedBytes: 2 << 30, AvailBytes: 6 << 30, Device: 11},
+ "/proc/4242/root/mnt/missing": {TotalBytes: 8 << 30, UsedBytes: 2 << 30, AvailBytes: 6 << 30, Device: 11},
+ "/proc/5252/root": {TotalBytes: 4 << 30, UsedBytes: 1 << 30, AvailBytes: 3 << 30, Device: 21},
+ }
+ collector := &mockCollector{
+ goos: "linux",
+ lookPathFn: func(file string) (string, error) {
+ switch file {
+ case "pct":
+ return pctPath, nil
+ case "lxc-info":
+ return lxcInfoPath, nil
+ }
+ return "", os.ErrNotExist
+ },
+ readFileFn: func(name string) ([]byte, error) {
+ config, ok := configs[name]
+ if !ok {
+ return nil, os.ErrNotExist
+ }
+ return []byte(config), nil
+ },
+ filesystemUsageFn: func(path string) (hostFilesystemUsage, error) {
+ usage, ok := usageByPath[path]
+ if !ok {
+ t.Fatalf("unexpected statfs path %q", path)
+ }
+ return usage, nil
+ },
+ commandCombinedOutputLimitedFn: func(
+ _ context.Context,
+ _ int,
+ name string,
+ args ...string,
+ ) (string, error) {
+ joined := strings.Join(args, " ")
+ switch {
+ case name == pctPath && joined == "list":
+ return listOutput, nil
+ case name == pctPath:
+ t.Fatalf("pct df must not run when the statfs path resolves: %v", args)
+ return "", nil
+ case name == lxcInfoPath && joined == "-n 100 -p":
+ return "PID: 4242\n", nil
+ case name == lxcInfoPath && joined == "-n 101 -p":
+ return "PID: 5252\n", nil
+ default:
+ t.Fatalf("unexpected command: %s %v", name, args)
+ return "", nil
+ }
+ },
+ }
+ agent := &Agent{logger: zerolog.Nop(), collector: collector}
+
+ got := agent.collectProxmoxLXCFilesystems(context.Background())
+ if got == nil || len(got.Containers) != 2 {
+ t.Fatalf("inventory = %+v", got)
+ }
+ web := got.Containers[0]
+ if web.VMID != 100 || len(web.Disks) != 2 {
+ t.Fatalf("web container = %+v", web)
+ }
+ root := web.Disks[0]
+ if root.Mountpoint != "/" || root.Type != "rootfs" || root.Device != "local-lvm:vm-100-disk-0" ||
+ root.TotalBytes != 8<<30 || root.UsedBytes != 2<<30 || root.FreeBytes != 6<<30 || root.Usage != 25 {
+ t.Fatalf("root disk = %+v", root)
+ }
+ data := web.Disks[1]
+ if data.Mountpoint != "/srv/data" || data.Type != "mp0" || data.Device != "tank:subvol-100-disk-0" ||
+ data.TotalBytes != 1<<40 || data.Usage != 50 {
+ t.Fatalf("data disk = %+v", data)
+ }
+ db := got.Containers[1]
+ if db.VMID != 101 || len(db.Disks) != 1 || db.Disks[0].Mountpoint != "/" {
+ t.Fatalf("db container = %+v", db)
+ }
+}
+
+func TestCollectProxmoxLXCFilesystemsFallsBackToPctDFPerContainer(t *testing.T) {
+ const pctPath = "/usr/sbin/pct"
+ const lxcInfoPath = "/usr/bin/lxc-info"
+ listOutput := fmt.Sprintf(
+ "%-10s %-10s %-12s %-20s\n%-10d %-10s %-12s %-20s\n%-10d %-10s %-12s %-20s\n",
+ "VMID", "Status", "Lock", "Name",
+ 100, "running", "", "web",
+ 102, "running", "", "legacy",
+ )
+ var dfQueries []string
+ collector := &mockCollector{
+ goos: "linux",
+ lookPathFn: func(file string) (string, error) {
+ switch file {
+ case "pct":
+ return pctPath, nil
+ case "lxc-info":
+ return lxcInfoPath, nil
+ }
+ return "", os.ErrNotExist
+ },
+ readFileFn: func(name string) ([]byte, error) {
+ if name == "/etc/pve/lxc/100.conf" {
+ return []byte("rootfs: local-lvm:vm-100-disk-0,size=8G\n"), nil
+ }
+ // 102's config is unreadable, so only that container may fall
+ // back to pct df.
+ return nil, os.ErrPermission
+ },
+ filesystemUsageFn: func(path string) (hostFilesystemUsage, error) {
+ if path != "/proc/4242/root" {
+ t.Fatalf("unexpected statfs path %q", path)
+ }
+ return hostFilesystemUsage{TotalBytes: 8 << 30, UsedBytes: 2 << 30, AvailBytes: 6 << 30, Device: 11}, nil
+ },
+ commandCombinedOutputLimitedFn: func(
+ _ context.Context,
+ _ int,
+ name string,
+ args ...string,
+ ) (string, error) {
+ joined := strings.Join(args, " ")
+ switch {
+ case name == pctPath && joined == "list":
+ return listOutput, nil
+ case name == lxcInfoPath && joined == "-n 100 -p":
+ return "PID: 4242\n", nil
+ case name == pctPath && joined == "df 102":
+ dfQueries = append(dfQueries, joined)
+ return `MP Volume Size Used Avail Use% Path
+rootfs local-lvm:vm-102-disk-0 8.0G 2.0G 6.0G 25.0 /
+`, nil
+ default:
+ t.Fatalf("unexpected command: %s %v", name, args)
+ return "", nil
+ }
+ },
+ }
+ agent := &Agent{logger: zerolog.Nop(), collector: collector}
+
+ got := agent.collectProxmoxLXCFilesystems(context.Background())
+ if got == nil || len(got.Containers) != 2 {
+ t.Fatalf("inventory = %+v", got)
+ }
+ if len(dfQueries) != 1 || dfQueries[0] != "df 102" {
+ t.Fatalf("df queries = %v, want exactly one for the fallback container", dfQueries)
+ }
+ if got.Containers[0].VMID != 100 || got.Containers[1].VMID != 102 {
+ t.Fatalf("containers = %+v", got.Containers)
+ }
+}
+
+func TestParseProxmoxLXCConfigMountsStopsAtSectionsAndValidates(t *testing.T) {
+ mounts := parseProxmoxLXCConfigMounts(`# comment
+arch: amd64
+rootfs: local-lvm:vm-100-disk-0,size=8G
+mp0: tank:subvol-100-disk-0,mp=/srv/data,size=1T
+mp1: /host/bind,mp=/shared
+mp2: tank:no-mountpoint,size=5G
+mp3: tank:bad-path,mp=relative,size=5G
+mp4: tank:dupe,mp=/srv/data,size=5G
+unused0: tank:vm-100-disk-9
+[snap1]
+mp5: tank:snap-only,mp=/snap-only,size=5G
+`)
+ if len(mounts) != 3 {
+ t.Fatalf("mounts = %+v", mounts)
+ }
+ if mounts[0].Key != "rootfs" || mounts[0].Path != "/" || mounts[0].Volume != "local-lvm:vm-100-disk-0" {
+ t.Fatalf("rootfs mount = %+v", mounts[0])
+ }
+ if mounts[1].Key != "mp0" || mounts[1].Path != "/srv/data" {
+ t.Fatalf("mp0 mount = %+v", mounts[1])
+ }
+ if mounts[2].Key != "mp1" || mounts[2].Path != "/shared" || mounts[2].Volume != "/host/bind" {
+ t.Fatalf("bind mount = %+v", mounts[2])
+ }
+}
+
+func TestParseLXCInfoPID(t *testing.T) {
+ if pid, err := parseLXCInfoPID("Name: 100\nPID: 4242\n"); err != nil || pid != 4242 {
+ t.Fatalf("pid = %d, err = %v", pid, err)
+ }
+ if _, err := parseLXCInfoPID("PID: 1\n"); err == nil {
+ t.Fatal("expected init pid rejection")
+ }
+ if _, err := parseLXCInfoPID("PID: nope\n"); err == nil {
+ t.Fatal("expected invalid pid error")
+ }
+ if _, err := parseLXCInfoPID("Name: 100\n"); err == nil {
+ t.Fatal("expected missing pid error")
+ }
+}
+
func TestParseProxmoxLXCFilesystemsValidatesAndBoundsInput(t *testing.T) {
list := fmt.Sprintf(
"%-10s %-10s %-12s %-20s\n%-10d %-10s %-12s %-20s\n%-10d %-10s %-12s %-20s\n",