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 mdadm RAID fallback discovery

rcourtman641660dced3c
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 890548d49c..b19d4adddb 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -316,6 +316,11 @@ profile and assignment columns, but embedded table framing must route through
or no-data results, and partial or plain-text smartctl output must still
preserve model, serial, health, and temperature data through the same
host-agent runtime boundary instead of leaving monitoring to guess.
+ Runtime RAID collection uses `/proc/mdstat` as the canonical discovery
+ baseline for Linux md arrays. `mdadm --detail` may enrich level, state,
+ member, UUID, and rebuild fields when available, but missing or failing
+ mdadm detail probes must not hide a kernel-reported md array from the
+ unified agent report.
Server-side lifecycle admission must preserve that same continuity across
Pulse restart and upgrade. When a standalone host comes back with the same
durable machine/report identity and token continuity, the shared admission
diff --git a/internal/hostagent/agent_metrics_test.go b/internal/hostagent/agent_metrics_test.go
index 917f68f222..3e7ec8890e 100644
--- a/internal/hostagent/agent_metrics_test.go
+++ b/internal/hostagent/agent_metrics_test.go
@@ -151,6 +151,44 @@ func TestBuildReport(t *testing.T) {
mc.raidArraysFn = nil
})
+ t.Run("RAID collection preserves mdstat fallback topology", func(t *testing.T) {
+ mc.raidArraysFn = func(ctx context.Context) ([]agentshost.RAIDArray, error) {
+ return []agentshost.RAIDArray{
+ {
+ Device: "/dev/md0",
+ Level: "raid10",
+ State: "active",
+ TotalDevices: 4,
+ ActiveDevices: 4,
+ WorkingDevices: 4,
+ Devices: []agentshost.RAIDDevice{
+ {Device: "/dev/sda1", State: "active sync", Slot: 0},
+ {Device: "/dev/sdb1", State: "active sync", Slot: 1},
+ {Device: "/dev/sdc1", State: "active sync", Slot: 2},
+ {Device: "/dev/sdd1", State: "active sync", Slot: 3},
+ },
+ },
+ }, nil
+ }
+
+ report, err := agent.buildReport(context.Background())
+ if err != nil {
+ t.Fatalf("buildReport failed: %v", err)
+ }
+
+ if len(report.RAID) != 1 {
+ t.Fatalf("expected 1 RAID array, got %d", len(report.RAID))
+ }
+ array := report.RAID[0]
+ if array.Device != "/dev/md0" || array.Level != "raid10" || array.State != "active" {
+ t.Fatalf("unexpected RAID array summary: %+v", array)
+ }
+ if array.TotalDevices != 4 || array.ActiveDevices != 4 || len(array.Devices) != 4 {
+ t.Fatalf("unexpected RAID array topology: %+v", array)
+ }
+ mc.raidArraysFn = nil
+ })
+
// Test case 4: Ceph collection
t.Run("Ceph collection", func(t *testing.T) {
mc.cephStatusFn = func(ctx context.Context) (*CephClusterStatus, error) {
diff --git a/internal/hostagent/mdadm.go b/internal/hostagent/mdadm.go
index 53f63f5729..3bc5c07e8a 100644
--- a/internal/hostagent/mdadm.go
+++ b/internal/hostagent/mdadm.go
@@ -2,7 +2,6 @@ package hostagent
import (
"context"
- "errors"
"fmt"
"io"
"os"
@@ -19,8 +18,11 @@ import (
// Pre-compiled regexes for performance (avoid recompilation on each call)
var (
- mdDeviceRe = regexp.MustCompile(`^(md\d+)\s*:`)
+ mdDeviceRe = regexp.MustCompile(`^\s*(md\d+)\s*:`)
mdArrayPathRe = regexp.MustCompile(`^/dev/md\d+$`)
+ mdCountRe = regexp.MustCompile(`\[(\d+)/(\d+)\]\s+\[([U_]+)\]`)
+ mdTokenRe = regexp.MustCompile(`^([A-Za-z0-9_.!/-]+)\[(\d+)\](.*)$`)
+ progressRe = regexp.MustCompile(`=\s*([0-9]+(?:\.[0-9]+)?)%`)
slotRe = regexp.MustCompile(`^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(.+?)\s+(/dev/.+)$`)
speedRe = regexp.MustCompile(`speed=(\S+)`)
// /proc/mdstat progress line action.
@@ -62,38 +64,34 @@ var commonMdadmPaths = []string{
}
// CollectArrays discovers and collects status for all mdadm RAID arrays on the system.
-// Returns an empty slice if mdadm is not available or no arrays are found.
+// Returns an empty slice when no arrays are found. If mdadm is unavailable,
+// /proc/mdstat still provides a baseline topology report.
func CollectRAIDArrays(ctx context.Context) ([]agentshost.RAIDArray, error) {
- // Check if mdadm is available
- if !isMdadmAvailable(ctx) {
- return nil, nil
- }
-
- // Get list of arrays from /proc/mdstat
- devices, err := listArrayDevices(ctx)
+ mdstatArrays, err := listMDStatArrays(ctx)
if err != nil {
return nil, fmt.Errorf("list array devices: %w", err)
}
- if len(devices) == 0 {
+ if len(mdstatArrays) == 0 {
return nil, nil
}
+ // /proc/mdstat is the canonical discovery source. mdadm enriches that
+ // baseline when available, but a detail probe failure must not hide a
+ // kernel-reported array from Pulse.
+ if !isMdadmAvailable(ctx) {
+ return mdstatArrays, nil
+ }
+
// Collect detailed info for each array
- var arrays []agentshost.RAIDArray
- var detailErrs []error
- for _, device := range devices {
- array, err := collectArrayDetail(ctx, device)
+ arrays := make([]agentshost.RAIDArray, 0, len(mdstatArrays))
+ for _, fallback := range mdstatArrays {
+ array, err := collectArrayDetail(ctx, fallback.Device)
if err != nil {
- detailErrs = append(detailErrs, fmt.Errorf("collect detail for %s: %w", device, err))
+ arrays = append(arrays, fallback)
continue
}
- arrays = append(arrays, array)
- }
-
- // Keep best-effort behavior for partial success, but surface failures when all detail probes fail.
- if len(arrays) == 0 && len(detailErrs) > 0 {
- return nil, fmt.Errorf("collect mdadm array details: %w", errors.Join(detailErrs...))
+ arrays = append(arrays, mergeMDStatFallback(array, fallback))
}
return arrays, nil
@@ -115,22 +113,244 @@ func isMdadmAvailable(ctx context.Context) bool {
// listArrayDevices scans /proc/mdstat to find all md devices
func listArrayDevices(_ context.Context) ([]string, error) {
+ arrays, err := listMDStatArrays(context.Background())
+ if err != nil {
+ return nil, err
+ }
+
+ devices := make([]string, 0, len(arrays))
+ for _, array := range arrays {
+ devices = append(devices, array.Device)
+ }
+
+ return devices, nil
+}
+
+// listMDStatArrays scans /proc/mdstat and returns a baseline array report for
+// every md device the kernel currently exposes.
+func listMDStatArrays(_ context.Context) ([]agentshost.RAIDArray, error) {
output, err := readProcMDStat()
if err != nil {
return nil, err
}
+ return parseMDStatArrays(string(output)), nil
+}
+
+func parseMDStatArrays(output string) []agentshost.RAIDArray {
+ lines := strings.Split(output, "\n")
+ arrays := make([]agentshost.RAIDArray, 0)
- // Parse /proc/mdstat to find device names
- // Lines like: md0 : active raid1 sdb1[1] sda1[0]
- var devices []string
- for _, line := range strings.Split(string(output), "\n") {
+ for i := 0; i < len(lines); {
+ line := strings.TrimSpace(lines[i])
matches := mdDeviceRe.FindStringSubmatch(line)
- if len(matches) > 1 {
- devices = append(devices, "/dev/"+matches[1])
+ if len(matches) <= 1 {
+ i++
+ continue
+ }
+
+ section := []string{line}
+ i++
+ for i < len(lines) {
+ next := strings.TrimSpace(lines[i])
+ if next == "" || strings.HasPrefix(next, "Personalities") || strings.HasPrefix(next, "unused devices") {
+ break
+ }
+ if mdDeviceRe.MatchString(next) {
+ break
+ }
+ section = append(section, next)
+ i++
}
+
+ arrays = append(arrays, parseMDStatArraySection(matches[1], section))
}
- return devices, nil
+ return arrays
+}
+
+func parseMDStatArraySection(deviceName string, section []string) agentshost.RAIDArray {
+ array := agentshost.RAIDArray{
+ Device: "/dev/" + deviceName,
+ Devices: []agentshost.RAIDDevice{},
+ }
+ if len(section) == 0 {
+ return array
+ }
+
+ header := section[0]
+ _, fieldsRaw, ok := strings.Cut(header, ":")
+ if !ok {
+ return array
+ }
+
+ fields := strings.Fields(fieldsRaw)
+ if len(fields) > 0 {
+ array.State = strings.ToLower(fields[0])
+ }
+
+ levelIndex := -1
+ for i, field := range fields {
+ if isMDStatLevelToken(field) {
+ levelIndex = i
+ array.Level = strings.ToLower(field)
+ break
+ }
+ }
+
+ deviceStart := 1
+ if levelIndex >= 0 {
+ deviceStart = levelIndex + 1
+ }
+ for _, field := range fields[deviceStart:] {
+ device, ok := parseMDStatDeviceToken(field, array.State)
+ if ok {
+ array.Devices = append(array.Devices, device)
+ }
+ }
+
+ for _, line := range section[1:] {
+ if matches := mdCountRe.FindStringSubmatch(line); len(matches) > 3 {
+ total, _ := strconv.Atoi(matches[1])
+ active, _ := strconv.Atoi(matches[2])
+ array.TotalDevices = total
+ array.ActiveDevices = active
+ if total > active && !strings.Contains(array.State, "degraded") {
+ array.State = appendMDStatState(array.State, "degraded")
+ }
+ }
+
+ if array.Operation == "" {
+ if matches := mdstatOperationRe.FindStringSubmatch(line); len(matches) > 1 {
+ array.Operation = strings.ToLower(matches[1])
+ }
+ }
+ if array.RebuildSpeed == "" {
+ if matches := speedRe.FindStringSubmatch(line); len(matches) > 1 {
+ array.RebuildSpeed = matches[1]
+ }
+ }
+ if array.RebuildPercent == 0 {
+ if matches := progressRe.FindStringSubmatch(line); len(matches) > 1 {
+ array.RebuildPercent, _ = strconv.ParseFloat(matches[1], 64)
+ }
+ }
+ }
+
+ var workingDevices, failedDevices, spareDevices int
+ for _, device := range array.Devices {
+ state := strings.ToLower(device.State)
+ switch {
+ case strings.Contains(state, "faulty"):
+ failedDevices++
+ case strings.Contains(state, "spare"):
+ spareDevices++
+ workingDevices++
+ default:
+ workingDevices++
+ }
+ }
+ if array.ActiveDevices == 0 {
+ array.ActiveDevices = workingDevices - spareDevices
+ }
+ if array.TotalDevices == 0 {
+ array.TotalDevices = array.ActiveDevices
+ }
+ if failedDevices == 0 && array.TotalDevices > array.ActiveDevices {
+ failedDevices = array.TotalDevices - array.ActiveDevices
+ }
+ array.WorkingDevices = workingDevices
+ array.FailedDevices = failedDevices
+ array.SpareDevices = spareDevices
+
+ return array
+}
+
+func parseMDStatDeviceToken(token string, arrayState string) (agentshost.RAIDDevice, bool) {
+ token = strings.Trim(token, ",")
+ matches := mdTokenRe.FindStringSubmatch(token)
+ if len(matches) < 4 {
+ return agentshost.RAIDDevice{}, false
+ }
+
+ slot, err := strconv.Atoi(matches[2])
+ if err != nil {
+ return agentshost.RAIDDevice{}, false
+ }
+
+ state := "active sync"
+ flags := strings.ToUpper(matches[3])
+ switch {
+ case strings.Contains(flags, "F"):
+ state = "faulty"
+ case strings.Contains(flags, "S"):
+ state = "spare"
+ case strings.EqualFold(arrayState, "inactive"):
+ state = "inactive"
+ }
+
+ device := strings.TrimSpace(matches[1])
+ if !strings.HasPrefix(device, "/dev/") {
+ device = "/dev/" + device
+ }
+
+ return agentshost.RAIDDevice{
+ Device: device,
+ State: state,
+ Slot: slot,
+ }, true
+}
+
+func isMDStatLevelToken(token string) bool {
+ token = strings.ToLower(strings.TrimSpace(token))
+ return strings.HasPrefix(token, "raid") || token == "linear" || token == "multipath"
+}
+
+func appendMDStatState(state, suffix string) string {
+ state = strings.TrimSpace(state)
+ if state == "" {
+ return suffix
+ }
+ return state + ", " + suffix
+}
+
+func mergeMDStatFallback(array, fallback agentshost.RAIDArray) agentshost.RAIDArray {
+ if strings.TrimSpace(array.Device) == "" {
+ array.Device = fallback.Device
+ }
+ if strings.TrimSpace(array.Level) == "" {
+ array.Level = fallback.Level
+ }
+ if strings.TrimSpace(array.State) == "" {
+ array.State = fallback.State
+ }
+ if array.TotalDevices == 0 {
+ array.TotalDevices = fallback.TotalDevices
+ }
+ if array.ActiveDevices == 0 {
+ array.ActiveDevices = fallback.ActiveDevices
+ }
+ if array.WorkingDevices == 0 {
+ array.WorkingDevices = fallback.WorkingDevices
+ }
+ if array.FailedDevices == 0 {
+ array.FailedDevices = fallback.FailedDevices
+ }
+ if array.SpareDevices == 0 {
+ array.SpareDevices = fallback.SpareDevices
+ }
+ if len(array.Devices) == 0 {
+ array.Devices = fallback.Devices
+ }
+ if array.RebuildPercent == 0 {
+ array.RebuildPercent = fallback.RebuildPercent
+ }
+ if strings.TrimSpace(array.RebuildSpeed) == "" {
+ array.RebuildSpeed = fallback.RebuildSpeed
+ }
+ if strings.TrimSpace(array.Operation) == "" {
+ array.Operation = fallback.Operation
+ }
+ return array
}
// collectArrayDetail runs mdadm --detail on a specific device and parses the output
diff --git a/internal/hostagent/mdadm_test.go b/internal/hostagent/mdadm_test.go
index de57734818..f56c96b1f9 100644
--- a/internal/hostagent/mdadm_test.go
+++ b/internal/hostagent/mdadm_test.go
@@ -640,7 +640,7 @@ func TestIsMdadmAvailable(t *testing.T) {
func TestListArrayDevices(t *testing.T) {
mdstat := `Personalities : [raid1] [raid6]
md0 : active raid1 sdb1[1] sda1[0]
-md1 : active raid6 sdc1[2] sdb1[1] sda1[0]
+ md1 : active raid6 sdc1[2] sdb1[1] sda1[0]
unused devices: <none>`
withReadProcMDStat(t, func() ([]byte, error) {
return []byte(mdstat), nil
@@ -654,6 +654,49 @@ unused devices: <none>`
}
}
+func TestParseMDStatArraysDebianRAID10(t *testing.T) {
+ mdstat := `Personalities : [raid10]
+md0 : active raid10 sda1[0] sdb1[1] sdc1[2] sdd1[3]
+ 1953258496 blocks super 1.2 512K chunks 2 near-copies [4/4] [UUUU]
+ bitmap: 0/15 pages [0KB], 65536KB chunk
+unused devices: <none>`
+
+ arrays := parseMDStatArrays(mdstat)
+ if len(arrays) != 1 {
+ t.Fatalf("array count = %d, want 1", len(arrays))
+ }
+ array := arrays[0]
+ if array.Device != "/dev/md0" || array.Level != "raid10" || array.State != "active" {
+ t.Fatalf("unexpected mdstat array summary: %+v", array)
+ }
+ if array.TotalDevices != 4 || array.ActiveDevices != 4 || array.WorkingDevices != 4 || array.FailedDevices != 0 {
+ t.Fatalf("unexpected mdstat device counts: %+v", array)
+ }
+ if len(array.Devices) != 4 || array.Devices[0].Device != "/dev/sda1" || array.Devices[3].Slot != 3 {
+ t.Fatalf("unexpected mdstat member devices: %+v", array.Devices)
+ }
+}
+
+func TestParseMDStatArraysDegradedRecovery(t *testing.T) {
+ mdstat := `Personalities : [raid5]
+md2 : active raid5 sdb1[0] sdc1[1] sdd1[2]
+ 5860268032 blocks super 1.2 level 5, 512k chunk, algorithm 2 [4/3] [UUU_]
+ [>....................] recovery = 12.6% (37043392/293039104) finish=127.5min speed=33440K/sec
+unused devices: <none>`
+
+ arrays := parseMDStatArrays(mdstat)
+ if len(arrays) != 1 {
+ t.Fatalf("array count = %d, want 1", len(arrays))
+ }
+ array := arrays[0]
+ if array.State != "active, degraded" || array.FailedDevices != 1 {
+ t.Fatalf("expected degraded state/counts, got %+v", array)
+ }
+ if array.Operation != "recovery" || array.RebuildPercent != 12.6 || array.RebuildSpeed != "33440K/sec" {
+ t.Fatalf("unexpected recovery details: %+v", array)
+ }
+}
+
func TestListArrayDevicesError(t *testing.T) {
withReadProcMDStat(t, func() ([]byte, error) {
return nil, errors.New("read failed")
@@ -694,6 +737,9 @@ func TestCollectArraysNotAvailable(t *testing.T) {
withRunCommandOutput(t, func(ctx context.Context, name string, args ...string) ([]byte, error) {
return nil, errors.New("missing")
})
+ withReadProcMDStat(t, func() ([]byte, error) {
+ return []byte("unused devices: <none>"), nil
+ })
arrays, err := CollectRAIDArrays(context.Background())
if err != nil {
@@ -704,6 +750,31 @@ func TestCollectArraysNotAvailable(t *testing.T) {
}
}
+func TestCollectArraysFallsBackToMDStatWhenMdadmUnavailable(t *testing.T) {
+ withResolveMdadmBinary(t, func() (string, error) { return "", errors.New("missing binary") })
+ withRunCommandOutput(t, func(ctx context.Context, name string, args ...string) ([]byte, error) {
+ t.Fatal("runCommandOutput should not be called when mdadm path resolution fails")
+ return nil, nil
+ })
+ withReadProcMDStat(t, func() ([]byte, error) {
+ return []byte(`Personalities : [raid10]
+md0 : active raid10 sda1[0] sdb1[1] sdc1[2] sdd1[3]
+ 1953258496 blocks super 1.2 512K chunks 2 near-copies [4/4] [UUUU]
+unused devices: <none>`), nil
+ })
+
+ arrays, err := CollectRAIDArrays(context.Background())
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if len(arrays) != 1 {
+ t.Fatalf("array count = %d, want 1: %+v", len(arrays), arrays)
+ }
+ if arrays[0].Device != "/dev/md0" || arrays[0].Level != "raid10" || arrays[0].ActiveDevices != 4 {
+ t.Fatalf("unexpected fallback array: %+v", arrays[0])
+ }
+}
+
func TestCollectArraysListError(t *testing.T) {
withResolveMdadmBinary(t, func() (string, error) { return "mdadm", nil })
withRunCommandOutput(t, func(ctx context.Context, name string, args ...string) ([]byte, error) {
@@ -739,7 +810,8 @@ func TestCollectArraysNoDevices(t *testing.T) {
func TestCollectArraysSkipsDetailError(t *testing.T) {
withResolveMdadmBinary(t, func() (string, error) { return "mdadm", nil })
withReadProcMDStat(t, func() ([]byte, error) {
- return []byte("md0 : active raid1 sda1[0]"), nil
+ return []byte(`md0 : active raid1 sda1[0]
+ 102400000 blocks super 1.2 [2/1] [U_]`), nil
})
withRunCommandOutput(t, func(ctx context.Context, name string, args ...string) ([]byte, error) {
if len(args) > 0 && args[0] == "--version" {
@@ -749,12 +821,14 @@ func TestCollectArraysSkipsDetailError(t *testing.T) {
})
arrays, err := CollectRAIDArrays(context.Background())
- if err == nil {
- // All detail probes failed, so error is expected
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
}
- _ = err
- if arrays != nil {
- t.Fatalf("expected nil arrays, got %v", arrays)
+ if len(arrays) != 1 {
+ t.Fatalf("array count = %d, want 1: %+v", len(arrays), arrays)
+ }
+ if arrays[0].Device != "/dev/md0" || arrays[0].Level != "raid1" || arrays[0].FailedDevices != 1 {
+ t.Fatalf("unexpected fallback array: %+v", arrays[0])
}
}
@@ -825,9 +899,15 @@ func TestCollectArraysPartialSuccessIgnoresDetailErrors(t *testing.T) {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
- if len(arrays) != 1 || arrays[0].Device != "/dev/md1" {
+ if len(arrays) != 2 {
t.Fatalf("unexpected arrays: %v", arrays)
}
+ if arrays[0].Device != "/dev/md0" || arrays[0].Level != "raid1" || arrays[0].State != "active" {
+ t.Fatalf("unexpected mdstat fallback array: %+v", arrays[0])
+ }
+ if arrays[1].Device != "/dev/md1" || arrays[1].State != "clean" {
+ t.Fatalf("unexpected mdadm detail array: %+v", arrays[1])
+ }
}
func TestGetMdstatProgress(t *testing.T) {