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(alerts): skip unchanged JSON recovery replacements

pulse-triage[bot]103076c65be5
diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.md
index 27fd5c156a..beb0cdbceb 100644
--- a/docs/release-control/v6/internal/subsystems/alerts.md
+++ b/docs/release-control/v6/internal/subsystems/alerts.md
@@ -2725,3 +2725,21 @@ widths despite the longer labels. The presentation and Overview delivery-status
tests cover the evidence boundary; `scripts/check-alert-dispatch-copy.mjs`
qualifies the real Overview with scripted API data in Chromium, not installed
notification delivery.
+
+### Unchanged active-alert JSON recovery checkpoints
+
+The recovery-mirror writer canonicalises complete records before comparing
+bounded existing bytes. An identical regular file with mode 0600 is not
+replaced; acknowledgement, metadata and resolved/empty state changes still use
+the atomic synced replacement path. Missing, corrupt, insecure or symlink
+destinations are not accepted as unchanged. Failed writes remain retryable and
+the unchanged path retains directory sync so a prior post-rename sync failure
+is not silently accepted. Windows retains replacement when its reported mode
+does not match POSIX 0600.
+
+`TestActiveMirror*` isolates this JSON path without database workers and covers
+ordering, fresh-manager checkpoints, state changes, file loss/corruption, failed
+rename retry and Unix destination hardening. This addresses one write source
+in #1966, not total installed write amplification: directory metadata handling,
+intent snapshots, changing alert histories and database writes remain separate.
+It changes neither alert latency nor the selected release candidate.
diff --git a/internal/alerts/active_mirror_unchanged_unix_test.go b/internal/alerts/active_mirror_unchanged_unix_test.go
new file mode 100644
index 0000000000..a54272ee9a
--- /dev/null
+++ b/internal/alerts/active_mirror_unchanged_unix_test.go
@@ -0,0 +1,57 @@
+//go:build !windows
+
+package alerts
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestActiveMirrorUnchangedRepairsUnsafeDestination(t *testing.T) {
+ for _, kind := range []string{"permissions", "symlink"} {
+ t.Run(kind, func(t *testing.T) {
+ dir := t.TempDir()
+ m := &Manager{alertsDir: dir}
+ alerts := []*Alert{{ID: "a"}}
+ save := func() {
+ t.Helper()
+ if err := m.writeActiveAlertsRecoveryMirror(alerts); err != nil {
+ t.Fatal(err)
+ }
+ }
+ save()
+ path := filepath.Join(dir, "active-alerts.json")
+ target := path + ".target"
+ if kind == "permissions" {
+ if err := os.Chmod(path, 0644); err != nil {
+ t.Fatal(err)
+ }
+ } else {
+ if err := os.Rename(path, target); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(target, path); err != nil {
+ t.Fatal(err)
+ }
+ }
+ save()
+ info, err := os.Lstat(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !info.Mode().IsRegular() || info.Mode().Perm() != alertsFilePerm {
+ t.Fatalf("unsafe mirror accepted: %v", info.Mode())
+ }
+ if kind == "symlink" {
+ original, err := os.Stat(target)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if os.SameFile(original, info) {
+ t.Fatal("symlink target reused")
+ }
+ }
+ })
+ }
+}
diff --git a/internal/alerts/active_persistence.go b/internal/alerts/active_persistence.go
index 6ecf4a1312..1d4b686f68 100644
--- a/internal/alerts/active_persistence.go
+++ b/internal/alerts/active_persistence.go
@@ -1,9 +1,11 @@
package alerts
import (
+ "bytes"
"encoding/json"
"errors"
"fmt"
+ "io"
"os"
"path/filepath"
"sort"
@@ -162,11 +164,41 @@ func (m *Manager) writeActiveAlertsRecoveryMirrorLocked(alerts []*Alert) error {
return fmt.Errorf("failed to set alerts directory permissions: %w", err)
}
- data, err := json.Marshal(alerts)
+ // Snapshots originate from maps. Canonicalise the complete records rather
+ // than relying on iteration order or assuming legacy IDs are unique.
+ var records []json.RawMessage
+ if alerts != nil {
+ records = make([]json.RawMessage, 0, len(alerts))
+ }
+ for _, alert := range alerts {
+ record, err := json.Marshal(alert)
+ if err != nil {
+ return fmt.Errorf("failed to marshal active alerts: %w", err)
+ }
+ records = append(records, record)
+ }
+ sort.Slice(records, func(i, j int) bool { return bytes.Compare(records[i], records[j]) < 0 })
+ data, err := json.Marshal(records)
if err != nil {
return fmt.Errorf("failed to marshal active alerts: %w", err)
}
+ finalFile := filepath.Join(alertsDir, "active-alerts.json")
+ // Compare the actual file, not a cached hash: missing/corrupt files and
+ // failed writes must be retried. Never accept a symlink or insecure mode
+ // as a completed checkpoint. Bound reads by the expected snapshot size.
+ if info, err := os.Lstat(finalFile); err == nil && info.Mode().IsRegular() &&
+ info.Mode().Perm() == alertsFilePerm && info.Size() == int64(len(data)) {
+ if file, err := os.Open(finalFile); err == nil {
+ existing, readErr := io.ReadAll(io.LimitReader(file, int64(len(data))+1))
+ closeErr := file.Close()
+ if readErr == nil && closeErr == nil && bytes.Equal(existing, data) {
+ // Also retry a directory sync that failed after an earlier rename.
+ return syncActiveAlertsDirectory(alertsDir)
+ }
+ }
+ }
+
// Write to temporary file first, then rename. Use a unique temp file so
// periodic saves, explicit saves, and shutdown saves cannot race on a name.
tmpFile, err := os.CreateTemp(alertsDir, "active-alerts-*.json.tmp")
@@ -209,7 +241,6 @@ func (m *Manager) writeActiveAlertsRecoveryMirrorLocked(alerts []*Alert) error {
return fmt.Errorf("failed to close active alerts temp file %s: %w", tmpName, err)
}
- finalFile := filepath.Join(alertsDir, "active-alerts.json")
if err := replaceActiveAlertsFile(tmpName, finalFile); err != nil {
return fmt.Errorf("failed to rename active alerts file from %s to %s: %w", tmpName, finalFile, err)
}
diff --git a/internal/alerts/alerts_test.go b/internal/alerts/alerts_test.go
index 1763c3f954..0b60ff4bf0 100644
--- a/internal/alerts/alerts_test.go
+++ b/internal/alerts/alerts_test.go
@@ -7,6 +7,7 @@ import (
"os"
"path/filepath"
"reflect"
+ "runtime"
"strings"
"sync"
"testing"
@@ -21118,3 +21119,112 @@ func TestStorageNormalizedOfflineSkipsCapacityEvaluation(t *testing.T) {
})
}
}
+
+// Exercise only the JSON recovery writer: no database or background workers.
+func TestActiveMirrorUnchangedCheckpoint(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("unchanged fast path requires POSIX 0600 mode; Windows retains write-through replacement")
+ }
+ dir := t.TempDir()
+ m := &Manager{alertsDir: dir}
+ a := &Alert{ID: "a", ResourceID: "host-a", Message: "offline", StartTime: time.Now().UTC()}
+ b := &Alert{ID: "b", ResourceID: "host-b", Message: "offline", StartTime: a.StartTime}
+ path := filepath.Join(dir, "active-alerts.json")
+ save := func(alerts []*Alert) os.FileInfo {
+ t.Helper()
+ if err := m.writeActiveAlertsRecoveryMirror(alerts); err != nil {
+ t.Fatal(err)
+ }
+ info, err := os.Stat(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return info
+ }
+ first := save([]*Alert{a, b})
+ for i := 0; i < 20; i++ {
+ after := save([]*Alert{b, a})
+ if !os.SameFile(first, after) {
+ t.Fatal("unchanged snapshot replaced JSON recovery file")
+ }
+ }
+ // A fresh manager must also recognise the existing checkpoint.
+ m = &Manager{alertsDir: dir}
+ if !os.SameFile(first, save([]*Alert{a, b})) {
+ t.Fatal("fresh manager rewrote unchanged mirror")
+ }
+ a.Acknowledged, a.AckUser = true, "operator"
+ save([]*Alert{a, b})
+ check := func(want int, ack bool) {
+ t.Helper()
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got []*Alert
+ if err := json.Unmarshal(data, &got); err != nil {
+ t.Fatal(err)
+ }
+ if len(got) != want {
+ t.Fatalf("alerts = %d, want %d", len(got), want)
+ }
+ for _, alert := range got {
+ if alert.ID == "a" && (alert.Acknowledged != ack || (ack && alert.AckUser != "operator")) {
+ t.Fatal("acknowledgement not persisted")
+ }
+ }
+ }
+ check(2, true)
+ save([]*Alert{a})
+ check(1, true)
+ // File loss and corruption cannot be hidden by an in-memory cache.
+ if err := os.Rename(path, path+".previous"); err != nil {
+ t.Fatal(err)
+ }
+ save([]*Alert{a})
+ check(1, true)
+ if err := os.WriteFile(path, []byte("corrupt"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ save([]*Alert{a})
+ check(1, true)
+ empty := save([]*Alert{})
+ check(0, false)
+ if !os.SameFile(empty, save([]*Alert{})) {
+ t.Fatal("empty checkpoint rewritten")
+ }
+}
+
+func TestActiveMirrorFailedWriteRetries(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "active-alerts.json")
+ if err := os.Mkdir(path, 0700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(path, "sentinel"), []byte("preserve"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ m := &Manager{alertsDir: dir}
+ alerts := []*Alert{{ID: "a"}}
+ if err := m.writeActiveAlertsRecoveryMirror(alerts); err == nil {
+ t.Fatal("expected obstructed rename failure")
+ }
+ if err := os.Rename(path, path+".obstruction"); err != nil {
+ t.Fatal(err)
+ }
+ if err := m.writeActiveAlertsRecoveryMirror(alerts); err != nil {
+ t.Fatal(err)
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got []*Alert
+ if err := json.Unmarshal(data, &got); err != nil || len(got) != 1 || got[0].ID != "a" {
+ t.Fatalf("retry lost state: %s, %v", data, err)
+ }
+ temps, err := filepath.Glob(filepath.Join(dir, "active-alerts-*.json.tmp"))
+ if err != nil || len(temps) != 0 {
+ t.Fatalf("temporary files: %v, %v", temps, err)
+ }
+}