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
Honour saved PMG collection scope without inventing recovery
pulse-triage[bot]64364d97c89c
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 9ee7744b7e..11e5c3b27e 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -15,6 +15,15 @@## Purpose+### PMG scope persistence does not change agent authority++Shared node-settings and connection API code now preserves explicit PMG+collection choices via the internal saved-scope discriminator and effective+legacy default. This affects PMG API reads only: no agent enrolment, credential,+command, install or helper lifecycle policy changes. PMG failed-save and scope+readback controls live in `internal/api/configapi/pmg_scope_test.go`; installed+agent acceptance remains independent.+### Installer identity recovery accounts for the whole legacy fileThe descriptor-safe collector command remains the primary agent-ID reader. Itsdiff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.mdindex d9a7cb4671..797cc0e062 100644--- a/docs/release-control/v6/internal/subsystems/alerts.md+++ b/docs/release-control/v6/internal/subsystems/alerts.md@@ -15,6 +15,21 @@## Purpose+### PMG collection opt-outs are not recovery evidence++Missing node queues (including an entirely disabled collector) cannot resolve+aggregate queue-depth or oldest-message alerts: recovery and lower severity+require every discovered node's observation. A partial non-negative reading+is a lower bound and can still establish the highest configured severity+(critical when configured, otherwise warning), never downgrade or resolve it.+Observed per-node queues retain their existing independent evaluation. Missing quarantine totals preserve both category alerts+and add no zero growth sample; a successful complete zero remains real recovery+evidence. Explicit alert-policy disablement and the existing offline policy+remain separate and unchanged. `pmg_collection_test.go` and the corrected+nil-quarantine control in `alerts_test.go` cover missing/partial datasets and+complete oldest-message recovery, known-high partial activation and refusal+to downgrade a critical alert using an incomplete lower reading.+### Connection confirmations cannot span unknown or disabled observationsThe existing PVE/PBS/PMG/vSphere/TrueNAS connection-degraded detector requiresdiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 849ed4ce55..77d3781787 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -20,6 +20,22 @@## Purpose+### PMG scope readback preserves explicit all-off settings++Existing node add/update payloads keep their four boolean collection options.+PMG saves persist the internal `monitoringConfigured` discriminator: legacy+all-zero entries retain the existing mail-statistics default, while a saved+all-off scope remains off through readback and restart. Partial scope patches+first materialise that legacy default, then apply the supplied options; omitted+options and unrelated edits do not erase an opt-out. PMG additions/edits publish+the new runtime connection only after the durable save succeeds. Nodes and+connection aggregation use the same effective mail-statistics rule.++`configapi/pmg_scope_test.go`, `connections_aggregator_test.go` and the PMG+branch controls cover defaults, saved/partial/failed patches and readback.+`TestContract_PMGUncollectedDatasetsRemainAbsent` preserves missing optional+readings across the existing PMG endpoint; it adds no route or payload dataset.+### Origin-trust reversal and consistent webhook placeholders`POST /api/system/settings/update` treats the presence of a stringdiff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.mdindex 2d8f03230c..665f5688ed 100644--- a/docs/release-control/v6/internal/subsystems/monitoring.md+++ b/docs/release-control/v6/internal/subsystems/monitoring.md@@ -17,6 +17,31 @@## Purpose+### PMG saved collection scope and incomplete observations++The PMG poller snapshots the selected connection's saved scope once per poll.+Mail statistics, mail-count trends and spam-score reads follow `MonitorMailStats`;+each discovered node's queue read follows `MonitorQueues`; both quarantine+category reads follow `MonitorQuarantine`; domain reads follow `MonitorDomainStats`.+Disabled datasets make no requests and supply no current observation. Version,+cluster discovery and configuration-backup reads remain independent of these+four switches; pausing the connection prevents every subsequent ordinary poll.+An edit or pause does not revoke an already running poll's snapshot.++A successful version read still establishes online connection health, not+complete collection. Downstream read failures are retained as failed poll+evidence, with missing fields instead of synthetic zero readings. Quarantine+totals require both category reads. Collector controls in `monitor_pmg_test.go`+cover sixteen scopes, next-poll edits/pause/resume, in-flight snapshots, each+read failure, recovery, legacy defaults and cancelled/unknown connections.+These synthetic controls are not native PMG or installed privacy acceptance.++The PMG client rejects omitted/null object payloads for version, mail, queue+and quarantine instead of materialising them as zero structs. Explicit+successful zero objects remain observations. `TestPMGCollectionMissingObjectData`+and `TestPMGCollectionObservedZeroData` in `pkg/pmg/client_test.go` exercise the+real request/decoder boundary using an in-memory HTTP transport, with no listener.+### Guest configuration reads preserve installation and node identityResolving omitted placement for the existing guest-config read honours everydiff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.mdindex f7cfae04e8..ec4758f57b 100644--- a/docs/release-control/v6/internal/subsystems/security-privacy.md+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md@@ -18,6 +18,19 @@## Purpose+### Existing PMG collection choices constrain provider reads++The owning PMG collector honours the saved mail, queue, quarantine and domain+switches at its read boundary. `PMGInstance.MonitoringConfigured` distinguishes+new explicit all-off choices from old configurations that stored only zero+booleans: those old ambiguous entries retain the existing mail-statistics+default until a collection option is saved. This is not retrospective proof of+intent or privacy. The discriminator survives encrypted node persistence and+reload, covered in `TestPMGCollectionPersistenceDefaults` in `config_load_test.go`.+Scope changes apply to subsequent polls, not requests already in flight;+pausing remains the boundary for all ordinary reads. Authentication, TLS and+permissions are unchanged, and no live mail/privacy acceptance is claimed.+### Removing browser-origin trust is a durable explicit patchThe system settings handler accepts an explicit empty string fordiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 8223a8aaeb..2dccd38abf 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -21,6 +21,16 @@## Purpose+### PMG collection scope remains separate from backup recovery++Shared node-settings and connections code preserves PMG collection opt-outs+without changing storage identity, capacity, History or recovery semantics.+The four mail/queue/quarantine/domain switches do not disable PMG configuration+backup discovery, and pausing the PMG connection still prevents subsequent+ordinary polls including backup reads. `TestPMGCollectionScope` in+`monitor_pmg_test.go` checks independent backup reads in every scope; no backup+restore, mail manipulation or native recovery is introduced or proved.+### Persisted trust edits and restart consistencyThe shared `internal/api/` settings path durably saves an explicit emptydiff --git a/internal/alerts/alerts_test.go b/internal/alerts/alerts_test.goindex 73287bfaa7..7d07c2f84e 100644--- a/internal/alerts/alerts_test.go+++ b/internal/alerts/alerts_test.go@@ -19424,7 +19424,7 @@ func TestCheckPMGQuarantineBacklog(t *testing.T) {spamQuarantineState := buildCanonicalStateID("pmg1", "pmg1-quarantine-spam")virusQuarantineState := buildCanonicalStateID("pmg1", "pmg1-quarantine-virus")- t.Run("nil quarantine clears alerts", func(t *testing.T) {+ t.Run("nil quarantine preserves alerts", func(t *testing.T) {m := newTestManager(t)// Create an existing quarantine alert@@ -19453,11 +19453,11 @@ func TestCheckPMGQuarantineBacklog(t *testing.T) {_, virusExists := testLookupActiveAlert(t, m, virusQuarantineState)m.mu.RUnlock()- if spamExists {- t.Error("spam alert should be cleared when quarantine is nil")+ if !spamExists {+ t.Error("spam alert must be preserved when quarantine is nil")}- if virusExists {- t.Error("virus alert should be cleared when quarantine is nil")+ if !virusExists {+ t.Error("virus alert must be preserved when quarantine is nil")}})diff --git a/internal/alerts/pmg.go b/internal/alerts/pmg.goindex 9fc67d80ec..5895dfe1f0 100644--- a/internal/alerts/pmg.go+++ b/internal/alerts/pmg.go@@ -179,6 +179,33 @@ func (m *Manager) clearPMGOfflineAlert(pmg models.PMGInstance) {m.clearResourceOfflineAlert(pmg.ID, pmg.Name, pmg.Host, "PMG", offlineRecoveryConfirmationsDefault)}+// pmgQueuesComplete requires observations from every discovered node before+// evaluating aggregate queue health. Missing/disabled collection is not zero.+func pmgQueuesComplete(pmg models.PMGInstance) bool {+ if len(pmg.Nodes) == 0 {+ return false+ }+ for _, node := range pmg.Nodes {+ if node.QueueStatus == nil {+ return false+ }+ }+ return true+}++// A partial non-negative queue reading is a lower bound. It can establish the+// highest configured severity, but never recovery or a lower severity that+// could downgrade an alert supported by the missing node.+func pmgQueueMetricEvaluable(pmg models.PMGInstance, value, warning, critical int) bool {+ if pmgQueuesComplete(pmg) {+ return true+ }+ if critical > 0 {+ return value >= critical+ }+ return warning > 0 && value >= warning+}+// checkPMGQueueDepths checks PMG mail queue depths and creates alerts// Evaluates all queue types (total, deferred, hold) independentlyfunc (m *Manager) checkPMGQueueDepths(pmg models.PMGInstance, defaults PMGThresholdConfig) {@@ -193,12 +220,18 @@ func (m *Manager) checkPMGQueueDepths(pmg models.PMGInstance, defaults PMGThresh}}- m.checkPMGQueueDepth(pmg, defaults.QueueTotalWarning, defaults.QueueTotalCritical, totalQueue, "queue-total", "queue-depth",- "PMG %s has %d total messages in queue (threshold: %d)", "total_queue")- m.checkPMGQueueDepth(pmg, defaults.DeferredQueueWarn, defaults.DeferredQueueCritical, totalDeferred, "queue-deferred", "queue-deferred",- "PMG %s has %d deferred messages (threshold: %d)", "deferred_queue")- m.checkPMGQueueDepth(pmg, defaults.HoldQueueWarn, defaults.HoldQueueCritical, totalHold, "queue-hold", "queue-hold",- "PMG %s has %d held messages (threshold: %d)", "hold_queue")+ if pmgQueueMetricEvaluable(pmg, totalQueue, defaults.QueueTotalWarning, defaults.QueueTotalCritical) {+ m.checkPMGQueueDepth(pmg, defaults.QueueTotalWarning, defaults.QueueTotalCritical, totalQueue, "queue-total", "queue-depth",+ "PMG %s has %d total messages in queue (threshold: %d)", "total_queue")+ }+ if pmgQueueMetricEvaluable(pmg, totalDeferred, defaults.DeferredQueueWarn, defaults.DeferredQueueCritical) {+ m.checkPMGQueueDepth(pmg, defaults.DeferredQueueWarn, defaults.DeferredQueueCritical, totalDeferred, "queue-deferred", "queue-deferred",+ "PMG %s has %d deferred messages (threshold: %d)", "deferred_queue")+ }+ if pmgQueueMetricEvaluable(pmg, totalHold, defaults.HoldQueueWarn, defaults.HoldQueueCritical) {+ m.checkPMGQueueDepth(pmg, defaults.HoldQueueWarn, defaults.HoldQueueCritical, totalHold, "queue-hold", "queue-hold",+ "PMG %s has %d held messages (threshold: %d)", "hold_queue")+ }}func thresholdForCanonicalSeverity(severity alertspecs.AlertSeverity, warningThreshold, criticalThreshold float64) float64 {@@ -336,6 +369,10 @@ func (m *Manager) checkPMGOldestMessage(pmg models.PMGInstance, defaults PMGThre}}+ if !pmgQueueMetricEvaluable(pmg, int(oldestAge/60), defaults.OldestMessageWarnMins, defaults.OldestMessageCritMins) {+ return+ }+if oldestAge == 0 {// No messages in queue, clear any existing alertalertID := fmt.Sprintf("%s-oldest-message", pmg.ID)@@ -595,8 +632,7 @@ func calculateMedianInt(values []int) int {// checkPMGQuarantineBacklog checks quarantine backlog and growth ratesfunc (m *Manager) checkPMGQuarantineBacklog(pmg models.PMGInstance, defaults PMGThresholdConfig) {if pmg.Quarantine == nil {- m.clearAlert(buildCanonicalStateID(pmg.ID, fmt.Sprintf("%s-quarantine-spam", pmg.ID)))- m.clearAlert(buildCanonicalStateID(pmg.ID, fmt.Sprintf("%s-quarantine-virus", pmg.ID)))+ // A disabled or failed collector supplies no recovery evidence.return}diff --git a/internal/alerts/pmg_collection_test.go b/internal/alerts/pmg_collection_test.gonew file mode 100644index 0000000000..cacb6f6623--- /dev/null+++ b/internal/alerts/pmg_collection_test.go@@ -0,0 +1,80 @@+package alerts++import (+ "github.com/rcourtman/pulse-go-rewrite/internal/models"+ "testing"+ "time"+)++func TestPMGCollectionMissingReadingsPreserveAlerts(t *testing.T) {+ for _, tc := range []struct {+ name string+ nodes []models.PMGNodeStatus+ }{+ {"disabled", []models.PMGNodeStatus{{Name: "one"}, {Name: "two"}}},+ {"missing-cluster", nil},+ {"partial-node", []models.PMGNodeStatus{{Name: "one", QueueStatus: &models.PMGQueueStatus{}}, {Name: "two"}}},+ } {+ t.Run(tc.name, func(t *testing.T) {+ m := newTestManager(t)+ ids := []string{"gateway-queue-total", "gateway-queue-deferred", "gateway-queue-hold", "gateway-oldest-message", "gateway-quarantine-spam", "gateway-quarantine-virus"}+ m.mu.Lock()+ for _, id := range ids {+ key := buildCanonicalStateID("gateway", id)+ m.activeAlerts[key] = &Alert{ID: key, ResourceID: "gateway", Type: id, StartTime: time.Now()}+ }+ m.mu.Unlock()+ v := models.PMGInstance{ID: "gateway", Status: "online", ConnectionHealth: "healthy", Nodes: tc.nodes}+ thresholds := PMGThresholdConfig{QueueTotalWarning: 1, DeferredQueueWarn: 1, HoldQueueWarn: 1, OldestMessageWarnMins: 1}+ m.checkPMGQueueDepths(v, thresholds)+ m.checkPMGOldestMessage(v, thresholds)+ m.checkPMGQuarantineBacklog(v, thresholds)+ m.mu.RLock()+ defer m.mu.RUnlock()+ for _, id := range ids {+ if _, exists := testLookupActiveAlert(t, m, buildCanonicalStateID("gateway", id)); !exists {+ t.Errorf("missing data resolved %s", id)+ }+ }+ if len(m.pmgQuarantineHistory["gateway"]) != 0 {+ t.Fatal("missing quarantine added zero growth sample")+ }+ })+ }+}+func TestPMGCollectionObservedZeroRecoversOldest(t *testing.T) {+ m := newTestManager(t)+ key := buildCanonicalStateID("gateway", "gateway-oldest-message")+ m.mu.Lock()+ m.activeAlerts[key] = &Alert{ID: key, ResourceID: "gateway", Type: "message-age"}+ m.mu.Unlock()+ v := models.PMGInstance{ID: "gateway", Nodes: []models.PMGNodeStatus{{Name: "one", QueueStatus: &models.PMGQueueStatus{}}, {Name: "two", QueueStatus: &models.PMGQueueStatus{}}}}+ m.checkPMGOldestMessage(v, PMGThresholdConfig{OldestMessageWarnMins: 1})+ m.mu.RLock()+ defer m.mu.RUnlock()+ if _, exists := testLookupActiveAlert(t, m, key); exists {+ t.Fatal("fresh complete zero did not resolve oldest alert")+ }+}++func TestPMGCollectionPartialQueueLowerBound(t *testing.T) {+ m := newTestManager(t)+ v := models.PMGInstance{ID: "gateway", Name: "gateway", Nodes: []models.PMGNodeStatus{{Name: "one", QueueStatus: &models.PMGQueueStatus{Total: 200}}, {Name: "two"}}}+ m.checkPMGQueueDepths(v, PMGThresholdConfig{QueueTotalWarning: 10, QueueTotalCritical: 50})+ key := buildCanonicalStateID("gateway", "gateway-queue-total")+ m.mu.RLock()+ alert := testRequireActiveAlert(t, m, key)+ m.mu.RUnlock()+ if alert.Level != AlertLevelCritical || alert.Value != 200 {+ t.Fatalf("known-high partial observation=%+v", alert)+ }+ // The next partial lower bound must not resolve or downgrade critical state.+ v.Nodes[0].QueueStatus.Total = 20+ m.checkPMGQueueDepths(v, PMGThresholdConfig{QueueTotalWarning: 10, QueueTotalCritical: 50})+ m.mu.RLock()+ defer m.mu.RUnlock()+ after := testRequireActiveAlert(t, m, key)+ if after.Level != AlertLevelCritical || after.Value != 200 {+ t.Fatalf("partial warning downgraded critical state=%+v", after)+ }+}diff --git a/internal/api/configapi/config_handlers.go b/internal/api/configapi/config_handlers.goindex b1771b2421..1121ee0fc7 100644--- a/internal/api/configapi/config_handlers.go+++ b/internal/api/configapi/config_handlers.go@@ -1687,10 +1687,7 @@ func (h *ConfigHandlers) GetAllNodesForAPI(ctx context.Context) []NodeResponse {// Add PMG nodesfor i, pmgInst := range h.getConfig(ctx).PMGInstances {- monitorMailStats := pmgInst.MonitorMailStats- if !pmgInst.MonitorMailStats && !pmgInst.MonitorQueues && !pmgInst.MonitorQuarantine && !pmgInst.MonitorDomainStats {- monitorMailStats = true- }+ monitorMailStats := pmgInst.MailStatsEnabled()node := NodeResponse{ID: generateNodeID("pmg", i),diff --git a/internal/api/configapi/config_node_handlers.go b/internal/api/configapi/config_node_handlers.goindex 01aaaf198e..2bcaf0aeb4 100644--- a/internal/api/configapi/config_node_handlers.go+++ b/internal/api/configapi/config_node_handlers.go@@ -263,6 +263,7 @@ func (h *ConfigHandlers) handleAddNode(w http.ResponseWriter, r *http.Request) {// Limit request body to 32KB to prevent memory exhaustionr.Body = http.MaxBytesReader(w, r.Body, 32*1024)+ var pendingPMG []config.PMGInstancevar req NodeConfigRequestif err := json.NewDecoder(r.Body).Decode(&req); err != nil {log.Error().Err(err).Msg("Failed to decode add node request")@@ -736,23 +737,34 @@ func (h *ConfigHandlers) handleAddNode(w http.ResponseWriter, r *http.Request) {TokenValue: pmgTokenValue,Fingerprint: req.Fingerprint,VerifySSL: verifySSL,+ MonitoringConfigured: true,MonitorMailStats: monitorMailStats,MonitorQueues: monitorQueues,MonitorQuarantine: monitorQuarantine,MonitorDomainStats: monitorDomainStats,TemperatureMonitoringEnabled: req.TemperatureMonitoringEnabled,}- h.getConfig(r.Context()).PMGInstances = append(h.getConfig(r.Context()).PMGInstances, pmgInstance)+ pendingPMG = append(append([]config.PMGInstance(nil), h.getConfig(r.Context()).PMGInstances...), pmgInstance)}// Save configuration to disk using our persistence instanceh.normalizePVEConfigState(r.Context())- if err := h.getPersistence(r.Context()).SaveNodesConfig(h.getConfig(r.Context()).PVEInstances, h.getConfig(r.Context()).PBSInstances, h.getConfig(r.Context()).PMGInstances); err != nil {+ pmgToSave := h.getConfig(r.Context()).PMGInstances+ if pendingPMG != nil {+ pmgToSave = pendingPMG+ }+ if err := h.getPersistence(r.Context()).SaveNodesConfig(h.getConfig(r.Context()).PVEInstances, h.getConfig(r.Context()).PBSInstances, pmgToSave); err != nil {log.Error().Err(err).Msg("Failed to save nodes configuration")http.Error(w, "Failed to save configuration", http.StatusInternalServerError)return}+ if pendingPMG != nil {+ config.Mu.Lock()+ h.getConfig(r.Context()).PMGInstances = pendingPMG+ config.Mu.Unlock()+ }+// Reload monitor with new configurationif h.reloadFunc != nil {if err := h.reloadFunc(); err != nil {@@ -1418,6 +1430,7 @@ func (h *ConfigHandlers) handleUpdateNode(w http.ResponseWriter, r *http.Request// Limit request body to 32KB to prevent memory exhaustionr.Body = http.MaxBytesReader(w, r.Body, 32*1024)+ var pendingPMG []config.PMGInstancevar req NodeConfigRequestif err := json.NewDecoder(r.Body).Decode(&req); err != nil {http.Error(w, "Invalid request body", http.StatusBadRequest)@@ -1618,6 +1631,14 @@ func (h *ConfigHandlers) handleUpdateNode(w http.ResponseWriter, r *http.Requestif req.VerifySSL != nil {updated.VerifySSL = *req.VerifySSL}+ if req.MonitorMailStats != nil || req.MonitorQueues != nil ||+ req.MonitorQuarantine != nil || req.MonitorDomainStats != nil {+ // Materialise the effective legacy default before applying a partial+ // patch. An unrelated false flag must not silently turn mail stats off.+ updated.MonitorMailStats = current.MailStatsEnabled()+ updated.MonitoringConfigured = true+ }+if req.MonitorMailStats != nil {updated.MonitorMailStats = *req.MonitorMailStats}@@ -1637,7 +1658,8 @@ func (h *ConfigHandlers) handleUpdateNode(w http.ResponseWriter, r *http.Requestupdated.Disabled = !*req.Enabled}- *pmgInst = updated+ pendingPMG = append([]config.PMGInstance(nil), h.getConfig(r.Context()).PMGInstances...)+ pendingPMG[index] = updated} else {http.Error(w, "Node not found", http.StatusNotFound)return@@ -1645,11 +1667,20 @@ func (h *ConfigHandlers) handleUpdateNode(w http.ResponseWriter, r *http.Request// Save configuration to disk using our persistence instanceh.normalizePVEConfigState(r.Context())- if err := h.getPersistence(r.Context()).SaveNodesConfig(h.getConfig(r.Context()).PVEInstances, h.getConfig(r.Context()).PBSInstances, h.getConfig(r.Context()).PMGInstances); err != nil {+ pmgToSave := h.getConfig(r.Context()).PMGInstances+ if pendingPMG != nil {+ pmgToSave = pendingPMG+ }+ if err := h.getPersistence(r.Context()).SaveNodesConfig(h.getConfig(r.Context()).PVEInstances, h.getConfig(r.Context()).PBSInstances, pmgToSave); err != nil {log.Error().Err(err).Msg("Failed to save nodes configuration")http.Error(w, "Failed to save configuration", http.StatusInternalServerError)return}+ if pendingPMG != nil {+ config.Mu.Lock()+ h.getConfig(r.Context()).PMGInstances = pendingPMG+ config.Mu.Unlock()+ }// IMPORTANT: Preserve alert overrides when updating nodes// This fixes issue #440 where PBS alert thresholds were being reset@@ -1841,7 +1872,9 @@ func (h *ConfigHandlers) handleDeleteNode(w http.ResponseWriter, r *http.Request} else if nodeType == "pmg" && index < len(h.getConfig(r.Context()).PMGInstances) {deletedNodeHost = h.getConfig(r.Context()).PMGInstances[index].Hostlog.Info().Str("nodeID", nodeID).Int("index", index).Msg("Deleting PMG node")+ config.Mu.Lock()h.getConfig(r.Context()).PMGInstances = append(h.getConfig(r.Context()).PMGInstances[:index], h.getConfig(r.Context()).PMGInstances[index+1:]...)+ config.Mu.Unlock()} else {log.Warn().Str("nodeID", nodeID).diff --git a/internal/api/configapi/pmg_scope_test.go b/internal/api/configapi/pmg_scope_test.gonew file mode 100644index 0000000000..890001449b--- /dev/null+++ b/internal/api/configapi/pmg_scope_test.go@@ -0,0 +1,107 @@+package configapi++import (+ "bytes"+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+)++func TestPMGCollectionScopeSavedPatch(t *testing.T) {+ cfg := &config.Config{DataPath: t.TempDir(), PMGInstances: []config.PMGInstance{{Name: "gateway", Host: "https://example.invalid:8006"}}}+ h := newTestConfigHandlers(t, cfg)+ for _, tc := range []struct {+ name string+ patch string+ wantMail, configured, queues bool+ }{+ {"unrelated-edit", `{"guestURL":"https://example.invalid"}`, true, false, false},+ {"partial-false-preserves-legacy-default", `{"monitorQueues":false}`, true, true, false},+ {"explicit-all-off", `{"monitorMailStats":false,"monitorQueues":false,"monitorQuarantine":false,"monitorDomainStats":false}`, false, true, false},+ {"omission-preserves-opt-out", `{"guestURL":"https://example.invalid/new"}`, false, true, false},+ {"select-queues", `{"monitorQueues":true}`, false, true, true},+ } {+ t.Run(tc.name, func(t *testing.T) {+ w := httptest.NewRecorder()+ r := httptest.NewRequest(http.MethodPut, "/api/config/nodes/pmg-0", bytes.NewBufferString(tc.patch))+ h.HandleUpdateNode(w, r)+ if w.Code != http.StatusOK {+ t.Fatalf("status=%d body=%s", w.Code, w.Body.String())+ }+ got := cfg.PMGInstances[0]+ if got.MailStatsEnabled() != tc.wantMail || got.MonitoringConfigured != tc.configured || got.MonitorQueues != tc.queues {+ t.Fatalf("runtime scope=%+v", got)+ }+ nodes := h.GetAllNodesForAPI(context.Background())+ if len(nodes) != 1 || nodes[0].MonitorMailStats != tc.wantMail || nodes[0].MonitorQueues != tc.queues {+ t.Fatalf("readback scope=%+v", nodes)+ }+ saved, err := config.NewConfigPersistence(cfg.DataPath).LoadNodesConfig()+ if err != nil {+ t.Fatal(err)+ }+ if len(saved.PMGInstances) != 1 || saved.PMGInstances[0] != got {+ t.Fatalf("durable scope=%+v want=%+v", saved.PMGInstances, got)+ }+ })+ }+}+func TestPMGCollectionScopeFailedSave(t *testing.T) {+ cfg := &config.Config{DataPath: t.TempDir(), PMGInstances: []config.PMGInstance{{Name: "gateway", Host: "https://example.invalid:8006"}}}+ h := newTestConfigHandlers(t, cfg)+ if err := os.Mkdir(filepath.Join(cfg.DataPath, "nodes.enc"), 0700); err != nil {+ t.Fatal(err)+ }+ before := cfg.PMGInstances[0]+ w := httptest.NewRecorder()+ r := httptest.NewRequest(http.MethodPut, "/api/config/nodes/pmg-0", bytes.NewBufferString(`{"monitorMailStats":false,"enabled":false}`))+ h.HandleUpdateNode(w, r)+ if w.Code != http.StatusInternalServerError {+ t.Fatalf("expected failed save, got %d", w.Code)+ }+ if cfg.PMGInstances[0] != before {+ t.Fatal("failed save changed live collection scope/pause")+ }+}+func TestPMGCollectionScopeNewConnection(t *testing.T) {+ for _, tc := range []struct {+ name string+ options map[string]any+ wantMail bool+ }{+ {"default", nil, true},+ {"explicit-all-off", map[string]any{"monitorMailStats": false, "monitorQueues": false, "monitorQuarantine": false, "monitorDomainStats": false}, false},+ } {+ t.Run(tc.name, func(t *testing.T) {+ cfg := &config.Config{DataPath: t.TempDir()}+ h := newTestConfigHandlers(t, cfg)+ body := map[string]any{"type": "pmg", "name": "gateway", "host": "https://example.invalid:8006", "user": "fixture@pmg", "password": "synthetic-password"}+ for k, v := range tc.options {+ body[k] = v+ }+ b, _ := json.Marshal(body)+ w := httptest.NewRecorder()+ r := httptest.NewRequest(http.MethodPost, "/api/config/nodes", bytes.NewReader(b))+ h.HandleAddNode(w, r)+ if w.Code != http.StatusCreated {+ t.Fatalf("status=%d body=%s", w.Code, w.Body.String())+ }+ if len(cfg.PMGInstances) != 1 || !cfg.PMGInstances[0].MonitoringConfigured || cfg.PMGInstances[0].MailStatsEnabled() != tc.wantMail {+ t.Fatalf("new scope=%+v", cfg.PMGInstances)+ }+ saved, err := config.NewConfigPersistence(cfg.DataPath).LoadNodesConfig()+ if err != nil {+ t.Fatal(err)+ }+ if len(saved.PMGInstances) != 1 || saved.PMGInstances[0].MailStatsEnabled() != tc.wantMail || !saved.PMGInstances[0].MonitoringConfigured {+ t.Fatal("new scope not durable")+ }+ })+ }+}diff --git a/internal/api/connections_aggregator.go b/internal/api/connections_aggregator.goindex 03fccb1eca..dd07879e2c 100644--- a/internal/api/connections_aggregator.go+++ b/internal/api/connections_aggregator.go@@ -296,7 +296,7 @@ func buildPMGConnection(inst config.PMGInstance, health map[string]monitoring.Inenabled := !inst.Disabledsurfaces := []string{"mailStats", "queues", "quarantine", "domainStats"}scope := map[string]bool{- "mailStats": inst.MonitorMailStats,+ "mailStats": inst.MailStatsEnabled(),"queues": inst.MonitorQueues,"quarantine": inst.MonitorQuarantine,"domainStats": inst.MonitorDomainStats,diff --git a/internal/api/connections_aggregator_pmg_branchcov0722am_test.go b/internal/api/connections_aggregator_pmg_branchcov0722am_test.goindex eb25662ff9..2d1f458986 100644--- a/internal/api/connections_aggregator_pmg_branchcov0722am_test.go+++ b/internal/api/connections_aggregator_pmg_branchcov0722am_test.go@@ -128,9 +128,14 @@ func TestBranchcov0722PMGConnectionScopeFlags(t *testing.T) {inst config.PMGInstancewantOn map[string]bool}{+ {+ name: "legacy_default",+ inst: config.PMGInstance{Name: "m", Host: "h.lan"},+ wantOn: map[string]bool{"mailStats": true, "queues": false, "quarantine": false, "domainStats": false},+ },{name: "all_flags_off",- inst: config.PMGInstance{Name: "m", Host: "h.lan"},+ inst: config.PMGInstance{Name: "m", Host: "h.lan", MonitoringConfigured: true},wantOn: map[string]bool{"mailStats": false, "queues": false, "quarantine": false, "domainStats": false,},diff --git a/internal/api/connections_aggregator_test.go b/internal/api/connections_aggregator_test.goindex c5cb88f8d0..0afda6ee35 100644--- a/internal/api/connections_aggregator_test.go+++ b/internal/api/connections_aggregator_test.go@@ -1450,3 +1450,22 @@ func TestBuildConnections_ScalesStaleThresholdWithPollingIntervals(t *testing.T)t.Fatalf("pbs state = %q, want stale under the floor threshold", state)}}++func TestPMGCollectionConnectionScopeMatchesLegacyAndExplicitDefaults(t *testing.T) {+ for _, tc := range []struct {+ name string+ cfg config.PMGInstance+ wantMail bool+ }{+ {"legacy", config.PMGInstance{Name: "gateway"}, true},+ {"explicit-off", config.PMGInstance{Name: "gateway", MonitoringConfigured: true}, false},+ {"queues-only", config.PMGInstance{Name: "gateway", MonitorQueues: true}, false},+ } {+ t.Run(tc.name, func(t *testing.T) {+ got := buildPMGConnection(tc.cfg, nil, time.Now(), time.Minute)+ if got.Scope["mailStats"] != tc.wantMail || got.Scope["queues"] != tc.cfg.MonitorQueues {+ t.Fatalf("connection scope=%v", got.Scope)+ }+ })+ }+}diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex d4bb96175d..a17fec2df6 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -27030,3 +27030,28 @@ func TestContractDeployEnrolledCollectorReducesItsAuthorityAfterItsFirstReport(tt.Fatalf("runtime role after reduction = %q, want %q", got, agenttokens.CredentialKindMonitoringCollector)}}++func TestContract_PMGUncollectedDatasetsRemainAbsent(t *testing.T) {+ source := models.PMGInstance{ID: "pmg-scope", Name: "gateway", Status: "online", ConnectionHealth: "healthy", Nodes: []models.PMGNodeStatus{{Name: "one", Status: "online"}}}+ registry := unifiedresources.NewRegistry(nil)+ registry.IngestSnapshot(models.StateSnapshot{PMGInstances: []models.PMGInstance{source}})+ monitor := &monitoring.Monitor{}+ setUnexportedField(t, monitor, "resourceStore", unifiedresources.NewMonitorAdapter(registry))+ router := &Router{monitor: monitor}+ rec := httptest.NewRecorder()+ router.handleListPMGInstances(rec, httptest.NewRequest(http.MethodGet, "/api/pmg/instances?id=pmg-scope", nil))+ if rec.Code != http.StatusOK {+ t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())+ }+ var resp PMGInstancesResponse+ if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {+ t.Fatal(err)+ }+ if len(resp.Data) != 1 {+ t.Fatalf("data=%+v", resp.Data)+ }+ got := resp.Data[0]+ if got.Status != "online" || got.ConnectionHealth != "healthy" || got.MailStats != nil || got.Quarantine != nil || len(got.Nodes) != 1 || got.Nodes[0].QueueStatus != nil || len(got.MailCount) != 0 || len(got.DomainStats) != 0 {+ t.Fatalf("missing dataset became zero/healthy data: %+v", got)+ }+}diff --git a/internal/config/config.go b/internal/config/config.goindex a5eb3a80cc..ba1d11da1e 100644--- a/internal/config/config.go+++ b/internal/config/config.go@@ -676,6 +676,11 @@ type PMGInstance struct {Fingerprint stringVerifySSL bool+ // MonitoringConfigured distinguishes an explicit all-off scope from legacy+ // entries which predate collection options. Older all-zero entries keep+ // the existing mail-statistics default until their scope is saved.+ MonitoringConfigured bool `json:"monitoringConfigured,omitempty"`+MonitorMailStats boolMonitorQueues boolMonitorQuarantine bool@@ -687,6 +692,12 @@ type PMGInstance struct {Disabled bool `json:"disabled,omitempty"`}+// MailStatsEnabled resolves the legacy default without overriding a saved opt-out.+func (i PMGInstance) MailStatsEnabled() bool {+ return i.MonitorMailStats || (!i.MonitoringConfigured && !i.MonitorQueues &&+ !i.MonitorQuarantine && !i.MonitorDomainStats)+}+// Global persistence instance for savingvar globalPersistence *ConfigPersistencediff --git a/internal/config/config_load_test.go b/internal/config/config_load_test.goindex f2b8c53cae..22d5cc9b7f 100644--- a/internal/config/config_load_test.go+++ b/internal/config/config_load_test.go@@ -690,3 +690,37 @@ func TestPVEInstanceVerifySSLExplicitRoundTrips(t *testing.T) {assert.False(t, legacy.VerifySSL)assert.False(t, legacy.VerifySSLExplicit, "a record without the field is not an explicit choice")}++func TestPMGCollectionPersistenceDefaults(t *testing.T) {+ for _, tc := range []struct {+ name string+ cfg PMGInstance+ wantMail bool+ }{+ {"legacy-default", PMGInstance{}, true},+ {"legacy-selected-queues", PMGInstance{MonitorQueues: true}, false},+ {"explicit-all-off", PMGInstance{MonitoringConfigured: true}, false},+ {"explicit-mail", PMGInstance{MonitoringConfigured: true, MonitorMailStats: true}, true},+ } {+ t.Run(tc.name, func(t *testing.T) {+ tc.cfg.Name = "gateway"+ tc.cfg.Host = "https://example.invalid:8006"+ cp := NewConfigPersistence(t.TempDir())+ if err := cp.SaveNodesConfig(nil, nil, []PMGInstance{tc.cfg}); err != nil {+ t.Fatal(err)+ }+ // New persistence owner models restart, not reuse of in-memory flags.+ loaded, err := NewConfigPersistence(cp.configDir).LoadNodesConfig()+ if err != nil {+ t.Fatal(err)+ }+ if len(loaded.PMGInstances) != 1 {+ t.Fatal("scope missing after reload")+ }+ got := loaded.PMGInstances[0]+ if got.MonitoringConfigured != tc.cfg.MonitoringConfigured || got.MailStatsEnabled() != tc.wantMail || got.MonitorQueues != tc.cfg.MonitorQueues {+ t.Fatalf("scope after restart=%+v", got)+ }+ })+ }+}diff --git a/internal/monitoring/monitor_pbs_pmg.go b/internal/monitoring/monitor_pbs_pmg.goindex 0f3c048ca5..be87ec3fb5 100644--- a/internal/monitoring/monitor_pbs_pmg.go+++ b/internal/monitoring/monitor_pbs_pmg.go@@ -668,8 +668,24 @@ func (m *Monitor) publishPBSConnectionOutcome(instance models.PBSInstance, pollE}}+// pmgPollClient is the existing read-only PMG collection boundary.+type pmgPollClient interface {+ GetVersion(context.Context) (*pmg.VersionInfo, error)+ GetClusterStatus(context.Context, bool) ([]pmg.ClusterStatusEntry, error)+ GetQueueStatus(context.Context, string) (*pmg.QueueStatusEntry, error)+ ListBackups(context.Context, string) ([]pmg.BackupEntry, error)+ GetMailStatistics(context.Context, string) (*pmg.MailStatistics, error)+ GetMailCount(context.Context, int) ([]pmg.MailCountEntry, error)+ GetSpamScores(context.Context) ([]pmg.SpamScore, error)+ GetQuarantineStatus(context.Context, string) (*pmg.QuarantineStatus, error)+ ListRelayDomains(context.Context) ([]pmg.RelayDomainEntry, error)+ GetDomainStatistics(context.Context, int64, int64) ([]pmg.DomainStatisticsEntry, error)+}++var _ pmgPollClient = (*pmg.Client)(nil)+// pollPMGInstance polls a single Proxmox Mail Gateway instance-func (m *Monitor) pollPMGInstance(ctx context.Context, instanceName string, client *pmg.Client) {+func (m *Monitor) pollPMGInstance(ctx context.Context, instanceName string, client pmgPollClient) {defer recoverFromPanic(fmt.Sprintf("pollPMGInstance-%s", instanceName))start := time.Now()@@ -716,13 +732,20 @@ func (m *Monitor) pollPMGInstance(ctx context.Context, instanceName string, clielog.Debug().Str("instance", instanceName).Msg("polling PMG instance")}+ // Each poll uses one saved scope snapshot. A later edit/pause applies to+ // the next poll and does not revoke requests already in flight.var instanceCfg *config.PMGInstance- for idx := range m.config.PMGInstances {- if m.config.PMGInstances[idx].Name == instanceName {- instanceCfg = &m.config.PMGInstances[idx]- break+ config.Mu.RLock()+ if m.config != nil {+ for _, cfg := range m.config.PMGInstances {+ if cfg.Name == instanceName {+ snapshot := cfg+ instanceCfg = &snapshot+ break+ }}}+ config.Mu.RUnlock()if instanceCfg == nil {log.Error().Str("instance", instanceName).Msg("PMG instance config not found")@@ -775,7 +798,16 @@ func (m *Monitor) pollPMGInstance(ctx context.Context, instanceName string, cliem.setProviderConnectionHealth(InstanceTypePMG, instanceName, true)m.resetAuthFailures(instanceName, "pmg")+ // A successful version read establishes connection health, not complete+ // downstream collection. Preserve missing readings and report failed polls.+ recordReadError := func(operation string, err error) {+ if err != nil {+ pollErr = stderrors.Join(pollErr, errors.WrapAPIError(operation, instanceName, err, 0))+ }+ }+cluster, err := client.GetClusterStatus(ctx, true)+ recordReadError("pmg_cluster_status", err)if err != nil {if debugEnabled {log.Debug().Err(err).Str("instance", instanceName).Msg("failed to retrieve PMG cluster status")@@ -799,24 +831,27 @@ func (m *Monitor) pollPMGInstance(ctx context.Context, instanceName string, cliebackupNodes[entry.Name] = struct{}{}- // Fetch queue status for this node- if queueData, qErr := client.GetQueueStatus(ctx, entry.Name); qErr != nil {- if debugEnabled {- log.Debug().Err(qErr).- Str("instance", instanceName).- Str("node", entry.Name).- Msg("Failed to fetch PMG queue status")- }- } else if queueData != nil {- total := queueData.Active.Int64() + queueData.Deferred.Int64() + queueData.Hold.Int64() + queueData.Incoming.Int64()- node.QueueStatus = &models.PMGQueueStatus{- Active: queueData.Active.Int(),- Deferred: queueData.Deferred.Int(),- Hold: queueData.Hold.Int(),- Incoming: queueData.Incoming.Int(),- Total: int(total),- OldestAge: queueData.OldestAge.Int64(),- UpdatedAt: time.Now(),+ if instanceCfg.MonitorQueues {+ // Fetch queue status for this node+ if queueData, qErr := client.GetQueueStatus(ctx, entry.Name); qErr != nil {+ recordReadError("pmg_queue_status", qErr)+ if debugEnabled {+ log.Debug().Err(qErr).+ Str("instance", instanceName).+ Str("node", entry.Name).+ Msg("Failed to fetch PMG queue status")+ }+ } else if queueData != nil {+ total := queueData.Active.Int64() + queueData.Deferred.Int64() + queueData.Hold.Int64() + queueData.Incoming.Int64()+ node.QueueStatus = &models.PMGQueueStatus{+ Active: queueData.Active.Int(),+ Deferred: queueData.Deferred.Int(),+ Hold: queueData.Hold.Int(),+ Incoming: queueData.Incoming.Int(),+ Total: int(total),+ OldestAge: queueData.OldestAge.Int64(),+ UpdatedAt: time.Now(),+ }}}@@ -842,6 +877,7 @@ func (m *Monitor) pollPMGInstance(ctx context.Context, instanceName string, cliebackups, backupErr := client.ListBackups(ctx, nodeName)if backupErr != nil {+ recordReadError("pmg_backups", backupErr)if debugEnabled {log.Debug().Err(backupErr).Str("instance", instanceName).@@ -877,87 +913,99 @@ func (m *Monitor) pollPMGInstance(ctx context.Context, instanceName string, clieMsg("PMG backups polled")}- if stats, err := client.GetMailStatistics(ctx, ""); err != nil {- log.Warn().Err(err).Str("instance", instanceName).Msg("failed to fetch PMG mail statistics")- } else if stats != nil {- pmgInst.MailStats = &models.PMGMailStats{- Timeframe: "day",- CountTotal: stats.Count.Float64(),- CountIn: stats.CountIn.Float64(),- CountOut: stats.CountOut.Float64(),- SpamIn: stats.SpamIn.Float64(),- SpamOut: stats.SpamOut.Float64(),- VirusIn: stats.VirusIn.Float64(),- VirusOut: stats.VirusOut.Float64(),- BouncesIn: stats.BouncesIn.Float64(),- BouncesOut: stats.BouncesOut.Float64(),- BytesIn: stats.BytesIn.Float64(),- BytesOut: stats.BytesOut.Float64(),- GreylistCount: stats.GreylistCount.Float64(),- JunkIn: stats.JunkIn.Float64(),- AverageProcessTimeMs: stats.AvgProcessSec.Float64() * 1000,- RBLRejects: stats.RBLRejects.Float64(),- PregreetRejects: stats.Pregreet.Float64(),- UpdatedAt: time.Now(),- }- }-- if counts, err := client.GetMailCount(ctx, 86400); err != nil {- if debugEnabled {- log.Debug().Err(err).Str("instance", instanceName).Msg("failed to fetch PMG mail count data")- }- } else if len(counts) > 0 {- points := make([]models.PMGMailCountPoint, 0, len(counts))- for _, entry := range counts {- ts := time.Unix(entry.Time.Int64(), 0)- points = append(points, models.PMGMailCountPoint{- Timestamp: ts,- Count: entry.Count.Float64(),- CountIn: entry.CountIn.Float64(),- CountOut: entry.CountOut.Float64(),- SpamIn: entry.SpamIn.Float64(),- SpamOut: entry.SpamOut.Float64(),- VirusIn: entry.VirusIn.Float64(),- VirusOut: entry.VirusOut.Float64(),- RBLRejects: entry.RBLRejects.Float64(),- Pregreet: entry.PregreetReject.Float64(),- BouncesIn: entry.BouncesIn.Float64(),- BouncesOut: entry.BouncesOut.Float64(),- Greylist: entry.GreylistCount.Float64(),- Index: entry.Index.Int(),- Timeframe: "hour",- WindowStart: ts,- })+ if instanceCfg.MailStatsEnabled() {+ if stats, err := client.GetMailStatistics(ctx, ""); err != nil {+ recordReadError("pmg_mail_statistics", err)+ log.Warn().Err(err).Str("instance", instanceName).Msg("failed to fetch PMG mail statistics")+ } else if stats != nil {+ pmgInst.MailStats = &models.PMGMailStats{+ Timeframe: "day",+ CountTotal: stats.Count.Float64(),+ CountIn: stats.CountIn.Float64(),+ CountOut: stats.CountOut.Float64(),+ SpamIn: stats.SpamIn.Float64(),+ SpamOut: stats.SpamOut.Float64(),+ VirusIn: stats.VirusIn.Float64(),+ VirusOut: stats.VirusOut.Float64(),+ BouncesIn: stats.BouncesIn.Float64(),+ BouncesOut: stats.BouncesOut.Float64(),+ BytesIn: stats.BytesIn.Float64(),+ BytesOut: stats.BytesOut.Float64(),+ GreylistCount: stats.GreylistCount.Float64(),+ JunkIn: stats.JunkIn.Float64(),+ AverageProcessTimeMs: stats.AvgProcessSec.Float64() * 1000,+ RBLRejects: stats.RBLRejects.Float64(),+ PregreetRejects: stats.Pregreet.Float64(),+ UpdatedAt: time.Now(),+ }}- pmgInst.MailCount = points- }- if scores, err := client.GetSpamScores(ctx); err != nil {- if debugEnabled {- log.Debug().Err(err).Str("instance", instanceName).Msg("failed to fetch PMG spam score distribution")- }- } else if len(scores) > 0 {- buckets := make([]models.PMGSpamBucket, 0, len(scores))- for _, bucket := range scores {- buckets = append(buckets, models.PMGSpamBucket{- Score: bucket.Level,- Count: float64(bucket.Count.Int()),- })+ if counts, err := client.GetMailCount(ctx, 86400); err != nil {+ recordReadError("pmg_mail_count", err)+ if debugEnabled {+ log.Debug().Err(err).Str("instance", instanceName).Msg("failed to fetch PMG mail count data")+ }+ } else if len(counts) > 0 {+ points := make([]models.PMGMailCountPoint, 0, len(counts))+ for _, entry := range counts {+ ts := time.Unix(entry.Time.Int64(), 0)+ points = append(points, models.PMGMailCountPoint{+ Timestamp: ts,+ Count: entry.Count.Float64(),+ CountIn: entry.CountIn.Float64(),+ CountOut: entry.CountOut.Float64(),+ SpamIn: entry.SpamIn.Float64(),+ SpamOut: entry.SpamOut.Float64(),+ VirusIn: entry.VirusIn.Float64(),+ VirusOut: entry.VirusOut.Float64(),+ RBLRejects: entry.RBLRejects.Float64(),+ Pregreet: entry.PregreetReject.Float64(),+ BouncesIn: entry.BouncesIn.Float64(),+ BouncesOut: entry.BouncesOut.Float64(),+ Greylist: entry.GreylistCount.Float64(),+ Index: entry.Index.Int(),+ Timeframe: "hour",+ WindowStart: ts,+ })+ }+ pmgInst.MailCount = points+ }++ if scores, err := client.GetSpamScores(ctx); err != nil {+ recordReadError("pmg_spam_scores", err)+ if debugEnabled {+ log.Debug().Err(err).Str("instance", instanceName).Msg("failed to fetch PMG spam score distribution")+ }+ } else if len(scores) > 0 {+ buckets := make([]models.PMGSpamBucket, 0, len(scores))+ for _, bucket := range scores {+ buckets = append(buckets, models.PMGSpamBucket{+ Score: bucket.Level,+ Count: float64(bucket.Count.Int()),+ })+ }+ pmgInst.SpamDistribution = buckets}- pmgInst.SpamDistribution = buckets- }- quarantine := models.PMGQuarantineTotals{}- if spamStatus, err := client.GetQuarantineStatus(ctx, "spam"); err == nil && spamStatus != nil {- quarantine.Spam = int(spamStatus.Count.Int64())}- if virusStatus, err := client.GetQuarantineStatus(ctx, "virus"); err == nil && virusStatus != nil {- quarantine.Virus = int(virusStatus.Count.Int64())++ if instanceCfg.MonitorQuarantine {+ spamStatus, spamErr := client.GetQuarantineStatus(ctx, "spam")+ virusStatus, virusErr := client.GetQuarantineStatus(ctx, "virus")+ recordReadError("pmg_spam_quarantine", spamErr)+ recordReadError("pmg_virus_quarantine", virusErr)+ // Totals and growth require both categories. Never publish a failed+ // category as zero or clear its alert using a partial observation.+ if spamErr == nil && virusErr == nil && spamStatus != nil && virusStatus != nil {+ pmgInst.Quarantine = &models.PMGQuarantineTotals{+ Spam: int(spamStatus.Count.Int64()), Virus: int(virusStatus.Count.Int64()),+ }+ }}- pmgInst.Quarantine = &quarantineif instanceCfg.MonitorDomainStats {if domains, err := client.ListRelayDomains(ctx); err != nil {+ recordReadError("pmg_relay_domains", err)if debugEnabled {log.Debug().Err(err).Str("instance", instanceName).Msg("failed to fetch PMG relay domains")}@@ -975,6 +1023,7 @@ func (m *Monitor) pollPMGInstance(ctx context.Context, instanceName string, clieend := time.Now()start := end.Add(-24 * time.Hour)if stats, err := client.GetDomainStatistics(ctx, start.Unix(), end.Unix()); err != nil {+ recordReadError("pmg_domain_statistics", err)if debugEnabled {log.Debug().Err(err).Str("instance", instanceName).Msg("failed to fetch PMG domain statistics")}diff --git a/internal/monitoring/monitor_pmg_test.go b/internal/monitoring/monitor_pmg_test.goindex 43aa450604..6be3796c0a 100644--- a/internal/monitoring/monitor_pmg_test.go+++ b/internal/monitoring/monitor_pmg_test.go@@ -2,14 +2,18 @@ package monitoringimport ("context"+ "encoding/json"+ "errors""fmt""net/http""net/http/httptest"+ "reflect""strings""testing""time""github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/models""github.com/rcourtman/pulse-go-rewrite/pkg/pmg")@@ -265,3 +269,270 @@ func TestPollPMGInstanceRecordsAuthFailures(t *testing.T) {t.Error("expected ConsecutiveFailures > 0 after auth failure, got 0")}}++// Uses the real poll consumer with a typed, read-only provider boundary. No+// listener, mail, credentials, external services or native appliance is used.+type pmgScopeFixture struct {+ calls map[string]int+ fail string+ onVersion func()+}++func (f *pmgScopeFixture) read(key, data string, out any) error {+ f.calls[key]+++ if f.fail == key {+ return errors.New("fixture collection refused")+ }+ return json.Unmarshal([]byte(data), out)+}+func (f *pmgScopeFixture) GetVersion(context.Context) (*pmg.VersionInfo, error) {+ var v pmg.VersionInfo+ err := f.read("version", `{"version":"8.3"}`, &v)+ if f.onVersion != nil {+ f.onVersion()+ }+ return &v, err+}+func (f *pmgScopeFixture) GetClusterStatus(_ context.Context, single bool) ([]pmg.ClusterStatusEntry, error) {+ if !single {+ return nil, errors.New("single-node query omitted")+ }+ var v []pmg.ClusterStatusEntry+ err := f.read("cluster", `[{"name":"one","type":"master"},{"name":"two","type":"slave"}]`, &v)+ return v, err+}+func (f *pmgScopeFixture) GetQueueStatus(_ context.Context, node string) (*pmg.QueueStatusEntry, error) {+ var v pmg.QueueStatusEntry+ err := f.read("queue/"+node, `{"active":20,"deferred":10,"hold":5,"incoming":2,"oldest_age":7200}`, &v)+ return &v, err+}+func (f *pmgScopeFixture) ListBackups(_ context.Context, node string) ([]pmg.BackupEntry, error) {+ var v []pmg.BackupEntry+ err := f.read("backup/"+node, `[{"filename":"fixture.tgz","timestamp":1700000000,"size":123}]`, &v)+ return v, err+}+func (f *pmgScopeFixture) GetMailStatistics(_ context.Context, frame string) (*pmg.MailStatistics, error) {+ if frame != "" {+ return nil, errors.New("unexpected timeframe")+ }+ var v pmg.MailStatistics+ err := f.read("mail", `{"count":123,"avptime":0.5}`, &v)+ return &v, err+}+func (f *pmgScopeFixture) GetMailCount(_ context.Context, span int) ([]pmg.MailCountEntry, error) {+ if span != 86400 {+ return nil, errors.New("wrong collection window")+ }+ var v []pmg.MailCountEntry+ err := f.read("count", `[{"time":1700000000,"count":123}]`, &v)+ return v, err+}+func (f *pmgScopeFixture) GetSpamScores(context.Context) ([]pmg.SpamScore, error) {+ var v []pmg.SpamScore+ err := f.read("scores", `[{"level":"low","count":4}]`, &v)+ return v, err+}+func (f *pmgScopeFixture) GetQuarantineStatus(_ context.Context, category string) (*pmg.QuarantineStatus, error) {+ var v pmg.QuarantineStatus+ err := f.read("quarantine/"+category, `{"count":200}`, &v)+ return &v, err+}+func (f *pmgScopeFixture) ListRelayDomains(context.Context) ([]pmg.RelayDomainEntry, error) {+ var v []pmg.RelayDomainEntry+ err := f.read("domains", `[{"domain":"example.invalid"}]`, &v)+ return v, err+}+func (f *pmgScopeFixture) GetDomainStatistics(_ context.Context, start, end int64) ([]pmg.DomainStatisticsEntry, error) {+ if end-start != 86400 {+ return nil, errors.New("wrong domain window")+ }+ var v []pmg.DomainStatisticsEntry+ err := f.read("domain-stats", `[{"domain":"example.invalid","count":123}]`, &v)+ return v, err+}+func pmgScopeMonitor(cfg config.PMGInstance) *Monitor {+ cfg.Name = "gateway"+ return &Monitor{+ config: &config.Config{PMGInstances: []config.PMGInstance{cfg}},+ state: models.NewState(), authFailures: map[string]int{}, lastAuthAttempt: map[string]time.Time{},+ pollStatusMap: map[string]*pollStatus{}, circuitBreakers: map[string]*circuitBreaker{},+ }+}+func allPMGScope() config.PMGInstance {+ return config.PMGInstance{MonitoringConfigured: true, MonitorMailStats: true, MonitorQueues: true, MonitorQuarantine: true, MonitorDomainStats: true}+}+func TestPMGCollectionScope(t *testing.T) {+ for mask := 0; mask < 16; mask++ {+ t.Run(fmt.Sprintf("scope-%04b", mask), func(t *testing.T) {+ cfg := config.PMGInstance{MonitoringConfigured: true, MonitorMailStats: mask&1 != 0, MonitorQueues: mask&2 != 0, MonitorQuarantine: mask&4 != 0, MonitorDomainStats: mask&8 != 0}+ m := pmgScopeMonitor(cfg)+ f := &pmgScopeFixture{calls: map[string]int{}}+ m.pollPMGInstance(context.Background(), "gateway", f)+ want := map[string]int{"version": 1, "cluster": 1, "backup/one": 1, "backup/two": 1}+ if cfg.MonitorMailStats {+ want["mail"] = 1+ want["count"] = 1+ want["scores"] = 1+ }+ if cfg.MonitorQueues {+ want["queue/one"] = 1+ want["queue/two"] = 1+ }+ if cfg.MonitorQuarantine {+ want["quarantine/spam"] = 1+ want["quarantine/virus"] = 1+ }+ if cfg.MonitorDomainStats {+ want["domains"] = 1+ want["domain-stats"] = 1+ }+ if !reflect.DeepEqual(f.calls, want) {+ t.Fatalf("requests=%v want=%v", f.calls, want)+ }+ v := m.state.GetSnapshot().PMGInstances[0]+ if (v.MailStats != nil) != cfg.MonitorMailStats || (len(v.MailCount) > 0) != cfg.MonitorMailStats || (len(v.SpamDistribution) > 0) != cfg.MonitorMailStats {+ t.Fatalf("incorrect mail data: %+v", v)+ }+ if v.MailStats != nil && (v.MailStats.CountTotal != 123 || v.MailStats.AverageProcessTimeMs != 500) {+ t.Fatal("selected statistics lost values/units")+ }+ if (v.Quarantine != nil) != cfg.MonitorQuarantine {+ t.Fatalf("incorrect quarantine: %+v", v.Quarantine)+ }+ for _, n := range v.Nodes {+ if (n.QueueStatus != nil) != cfg.MonitorQueues {+ t.Fatalf("incorrect queue: %+v", n)+ }+ if n.QueueStatus != nil && n.QueueStatus.Total != 37 {+ t.Fatal("wrong queue total")+ }+ }+ if (len(v.DomainStats) > 0) != cfg.MonitorDomainStats || (len(v.RelayDomains) > 0) != cfg.MonitorDomainStats {+ t.Fatal("incorrect domain collection")+ }+ if v.Status != "online" || v.ConnectionHealth != "healthy" || m.pollStatusMap["pmg::gateway"].ConsecutiveFailures != 0 {+ t.Fatal("selected collection not recorded as successful")+ }+ })+ }+}+func TestPMGCollectionLegacyDefault(t *testing.T) {+ m := pmgScopeMonitor(config.PMGInstance{})+ f := &pmgScopeFixture{calls: map[string]int{}}+ m.pollPMGInstance(context.Background(), "gateway", f)+ want := map[string]int{"version": 1, "cluster": 1, "backup/one": 1, "backup/two": 1, "mail": 1, "count": 1, "scores": 1}+ if !reflect.DeepEqual(f.calls, want) {+ t.Fatalf("legacy requests=%v want=%v", f.calls, want)+ }+}+func TestPMGCollectionEditsPauseAndResume(t *testing.T) {+ m := pmgScopeMonitor(allPMGScope())+ f := &pmgScopeFixture{calls: map[string]int{}}+ m.pollPMGInstance(context.Background(), "gateway", f)+ config.Mu.Lock()+ m.config.PMGInstances[0] = config.PMGInstance{Name: "gateway", MonitoringConfigured: true}+ config.Mu.Unlock()+ f.calls = map[string]int{}+ m.pollPMGInstance(context.Background(), "gateway", f)+ if len(f.calls) != 4 {+ t.Fatalf("all-off still read datasets: %v", f.calls)+ }+ v := m.state.GetSnapshot().PMGInstances[0]+ if v.MailStats != nil || v.Quarantine != nil || v.Nodes[0].QueueStatus != nil || len(v.DomainStats) != 0 {+ t.Fatal("old dataset exposed as current after disable")+ }+ config.Mu.Lock()+ m.config.PMGInstances[0].Disabled = true+ config.Mu.Unlock()+ f.calls = map[string]int{}+ m.pollPMGInstance(context.Background(), "gateway", f)+ if len(f.calls) != 0 {+ t.Fatalf("paused requests=%v", f.calls)+ }+ if !reflect.DeepEqual(m.state.GetSnapshot().PMGInstances[0], v) {+ t.Fatal("pause overwrote last readings")+ }+ config.Mu.Lock()+ m.config.PMGInstances[0].Disabled = false+ m.config.PMGInstances[0].MonitorQueues = true+ config.Mu.Unlock()+ m.pollPMGInstance(context.Background(), "gateway", f)+ if f.calls["queue/one"] != 1 || f.calls["mail"] != 0 {+ t.Fatalf("resume scope=%v", f.calls)+ }+}+func TestPMGCollectionInFlightSnapshot(t *testing.T) {+ m := pmgScopeMonitor(allPMGScope())+ f := &pmgScopeFixture{calls: map[string]int{}}+ reached := make(chan struct{})+ resume := make(chan struct{})+ done := make(chan struct{})+ f.onVersion = func() { close(reached); <-resume }+ go func() { defer close(done); m.pollPMGInstance(context.Background(), "gateway", f) }()+ <-reached+ config.Mu.Lock()+ m.config.PMGInstances[0] = config.PMGInstance{Name: "gateway", MonitoringConfigured: true, Disabled: true}+ config.Mu.Unlock()+ close(resume)+ <-done+ if f.calls["mail"] != 1 || f.calls["queue/one"] != 1 || f.calls["domain-stats"] != 1 || f.calls["quarantine/spam"] != 1 {+ t.Fatal("in-flight snapshot changed during poll")+ }+ f.onVersion = nil+ f.calls = map[string]int{}+ m.pollPMGInstance(context.Background(), "gateway", f)+ if len(f.calls) != 0 {+ t.Fatalf("next paused poll requests=%v", f.calls)+ }+}+func TestPMGCollectionFailureEvidence(t *testing.T) {+ for _, op := range []string{"version", "cluster", "backup/one", "backup/two", "mail", "count", "scores", "queue/one", "queue/two", "quarantine/spam", "quarantine/virus", "domains", "domain-stats"} {+ t.Run(op, func(t *testing.T) {+ m := pmgScopeMonitor(allPMGScope())+ f := &pmgScopeFixture{calls: map[string]int{}}+ m.pollPMGInstance(context.Background(), "gateway", f)+ before := m.pollStatusMap["pmg::gateway"].LastSuccess+ f.fail = op+ m.pollPMGInstance(context.Background(), "gateway", f)+ status := m.pollStatusMap["pmg::gateway"]+ if status.ConsecutiveFailures != 1 || status.LastErrorMessage == "" || !status.LastSuccess.Equal(before) {+ t.Fatalf("failed read recorded as complete: %+v", status)+ }+ v := m.state.GetSnapshot().PMGInstances[0]+ if op == "version" {+ if v.Status != "offline" || v.ConnectionHealth != "unhealthy" {+ t.Fatal("failed connection not offline")+ }+ return+ }+ if v.Status != "online" || v.ConnectionHealth != "healthy" || !m.state.GetSnapshot().ConnectionHealth["pmg-gateway"] {+ t.Fatal("downstream failure mislabeled as version connection failure")+ }+ if (op == "quarantine/spam" || op == "quarantine/virus") && v.Quarantine != nil {+ t.Fatal("partial quarantine reported as zero/complete")+ }+ if op == "mail" && v.MailStats != nil {+ t.Fatal("failed stats published")+ }+ if op == "queue/one" && v.Nodes[0].QueueStatus != nil {+ t.Fatal("failed queue published")+ }+ f.fail = ""+ m.pollPMGInstance(context.Background(), "gateway", f)+ if status.ConsecutiveFailures != 0 || status.LastErrorMessage != "" {+ t.Fatal("next complete poll did not recover")+ }+ })+ }+}+func TestPMGCollectionCancelledAndUnknown(t *testing.T) {+ m := pmgScopeMonitor(allPMGScope())+ f := &pmgScopeFixture{calls: map[string]int{}}+ ctx, cancel := context.WithCancel(context.Background())+ cancel()+ m.pollPMGInstance(ctx, "gateway", f)+ m.pollPMGInstance(context.Background(), "unknown", f)+ if len(f.calls) != 0 {+ t.Fatalf("cancelled/unknown requests=%v", f.calls)+ }+}diff --git a/pkg/pmg/client.go b/pkg/pmg/client.goindex 1d69902ac9..3df1edd827 100644--- a/pkg/pmg/client.go+++ b/pkg/pmg/client.go@@ -485,21 +485,27 @@ func (c *Client) getJSON(ctx context.Context, path string, params url.Values, ou// GetVersion returns version information for the PMG instance.func (c *Client) GetVersion(ctx context.Context) (*VersionInfo, error) {- var resp apiResponse[VersionInfo]+ var resp apiResponse[*VersionInfo]if err := c.getJSON(ctx, "/version", nil, &resp); err != nil {return nil, err}- return &resp.Data, nil+ if resp.Data == nil {+ return nil, fmt.Errorf("PMG GetVersion response missing data")+ }+ return resp.Data, nil}func (c *Client) GetMailStatistics(ctx context.Context, timeframe string) (*MailStatistics, error) {// PMG API does not accept timeframe parameter - it returns current day statistics// The timeframe parameter is ignored to maintain API compatibility- var resp apiResponse[MailStatistics]+ var resp apiResponse[*MailStatistics]if err := c.getJSON(ctx, "/statistics/mail", nil, &resp); err != nil {return nil, err}- return &resp.Data, nil+ if resp.Data == nil {+ return nil, fmt.Errorf("PMG GetMailStatistics response missing data")+ }+ return resp.Data, nil}func (c *Client) GetMailCount(ctx context.Context, timespanSeconds int) ([]MailCountEntry, error) {@@ -537,20 +543,26 @@ func (c *Client) GetClusterStatus(ctx context.Context, listSingle bool) ([]Clustfunc (c *Client) GetQuarantineStatus(ctx context.Context, category string) (*QuarantineStatus, error) {path := fmt.Sprintf("/quarantine/%sstatus", category)- var resp apiResponse[QuarantineStatus]+ var resp apiResponse[*QuarantineStatus]if err := c.getJSON(ctx, path, nil, &resp); err != nil {return nil, err}- return &resp.Data, nil+ if resp.Data == nil {+ return nil, fmt.Errorf("PMG GetQuarantineStatus response missing data")+ }+ return resp.Data, nil}func (c *Client) GetQueueStatus(ctx context.Context, node string) (*QueueStatusEntry, error) {path := fmt.Sprintf("/nodes/%s/postfix/queue", node)- var resp apiResponse[QueueStatusEntry]+ var resp apiResponse[*QueueStatusEntry]if err := c.getJSON(ctx, path, nil, &resp); err != nil {return nil, err}- return &resp.Data, nil+ if resp.Data == nil {+ return nil, fmt.Errorf("PMG GetQueueStatus response missing data")+ }+ return resp.Data, nil}// ListBackups returns configuration backup archives available on a PMG node.diff --git a/pkg/pmg/client_test.go b/pkg/pmg/client_test.goindex 96420dfff8..391cb18e00 100644--- a/pkg/pmg/client_test.go+++ b/pkg/pmg/client_test.go@@ -797,3 +797,43 @@ func TestClientClusterStatusNoParam(t *testing.T) {t.Fatalf("GetClusterStatus failed: %v", err)}}++type pmgCollectionTransport func(*http.Request) (*http.Response, error)++func (f pmgCollectionTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }++func TestPMGCollectionMissingObjectData(t *testing.T) {+ for _, body := range []string{`{}`, `{"data":null}`, `{"data":0}`, `{"data":[]}`, `invalid`} {+ t.Run(body, func(t *testing.T) {+ client := &Client{baseURL: "https://example.invalid", auth: auth{tokenName: "synthetic", tokenValue: "synthetic", user: "fixture", realm: "pmg"}, httpClient: &http.Client{Transport: pmgCollectionTransport(func(r *http.Request) (*http.Response, error) {+ return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil+ })}}+ if v, err := client.GetVersion(context.Background()); err == nil || v != nil {+ t.Fatalf("version=%+v err=%v", v, err)+ }+ if v, err := client.GetMailStatistics(context.Background(), ""); err == nil || v != nil {+ t.Fatalf("mail=%+v err=%v", v, err)+ }+ if v, err := client.GetQueueStatus(context.Background(), "one"); err == nil || v != nil {+ t.Fatalf("queue=%+v err=%v", v, err)+ }+ if v, err := client.GetQuarantineStatus(context.Background(), "spam"); err == nil || v != nil {+ t.Fatalf("quarantine=%+v err=%v", v, err)+ }+ })+ }+}+func TestPMGCollectionObservedZeroData(t *testing.T) {+ client := &Client{baseURL: "https://example.invalid", auth: auth{tokenName: "synthetic", tokenValue: "synthetic", user: "fixture", realm: "pmg"}, httpClient: &http.Client{Transport: pmgCollectionTransport(func(r *http.Request) (*http.Response, error) {+ return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"data":{"count":0,"active":0,"deferred":0,"hold":0,"incoming":0}}`)), Request: r}, nil+ })}}+ if v, err := client.GetMailStatistics(context.Background(), ""); err != nil || v == nil || v.Count.Float64() != 0 {+ t.Fatalf("mail=%+v err=%v", v, err)+ }+ if v, err := client.GetQueueStatus(context.Background(), "one"); err != nil || v == nil || v.Active.Int64() != 0 {+ t.Fatalf("queue=%+v err=%v", v, err)+ }+ if v, err := client.GetQuarantineStatus(context.Background(), "spam"); err != nil || v == nil || v.Count.Int64() != 0 {+ t.Fatalf("quarantine=%+v err=%v", v, err)+ }+}