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.

Repair email identity and compose silent-source History

pulse-triage[bot]50173e6a5921
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 75ed90b670..14a9c787a1 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -812,6 +812,15 @@ performance report and the reporting runtime snapshot leave it out of their
disk tables. The performance report colours a collected reading by the
tenant's alert disk temperature thresholds for the disk type, not a fixed line.
+The same lease bounds the host row's other readings in that API: once the
+host reads `offline`, an empty `agent` range returns no live CPU, memory, disk
+or sensor temperature point from the host row the expiry kept. An agent linked
+to a Proxmox node answers from that node row instead, under the node row's own
+checks. A Docker host that `evaluateDockerAgents` marks offline likewise stops
+answering with live points for itself and its containers, except that a Docker
+row merged with a reporting host agent shows the agent's status until its
+Docker sighting goes stale. The retained values stay last-known context.
+
An enabled availability target assigned to a host agent creates an
agent-lifecycle lease for that exact target/agent pairing. First assignment
and reassignment start a fresh reporting grace window; a result from the
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 26e33f5054..110f5bb2b0 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -6449,6 +6449,37 @@ from the clear value and red from the trigger, as the Physical Disks Temp
column does, and leaves it plain when disk temperature alerting is off. It no
longer uses a fixed 50/60C. Proof:
`TestContract_ReportsCarryDiskTemperatureAlertThresholds`.
+
+The live fallback for the other row types withholds the point when the
+snapshot row's source has stopped reporting. A host agent row gets none once
+`HostsSnapshot` reports it `offline` (the reporting lease
+`State.ExpireHostTelemetry` enforces); an agent linked to a Proxmox node then
+answers from the node row its `LinkedNodeID` names, under the node rule, and
+gets none when no node row has that ID. A Proxmox node row, also reached
+through the `agent` type, gets none when its projected status is `offline` or
+`unknown`. A VM, system container, node, or integration host row without an
+agent sighting gets none once the registry has marked stale every sighting it
+records from Proxmox, an agent, Docker, vSphere or TrueNAS; a `warning` status
+alone is not a lapse, since a linked agent's storage risk sets it on a row that
+still reports. A Docker host, and an app container through its host, gets none
+once its projected status is `offline` or its Docker sighting is stale. Power
+state and health are not a lapse: a stopped VM keeps its zero CPU point and a
+degraded Docker host that still reports keeps its point. Inside the PVE offline
+grace a node keeps its carried readings and its live point, as on other
+surfaces.
+These checks read row status and sightings, not the source each merged metric
+came from, so rows merged across sources keep the registry's merge decisions.
+A Docker row merged with a reporting host agent shows the agent's status until
+its Docker sighting goes stale. A node merged with a silent linked agent
+projects `online` while its Proxmox sighting is current, even after the poller
+reports the node offline. A hypervisor-managed guest merged with another
+source keeps its platform CPU after the platform stops reporting.
+With the metrics store available a withheld range stays empty; without a
+store, a request with no other fallback still answers 503, as one for a
+resource with no data does.
+`TestContract_MetricsHistoryLivePointOnlyWhileSourceReports` drives each lapse
+from the state transition that records it, and
+`TestContract_MetricsHistoryLiveReadingSightingsLapsed` pins the sighting rule.
That same metrics-history contract also owns Kubernetes pod identity
normalization. `/api/metrics-store/history` must accept legacy bare pod IDs
such as `cluster-1:pod:pod-1`, canonicalize them onto the unified pod metrics
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index d9df74de16..99d5d56fee 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -2949,6 +2949,20 @@ rather than the PVE poll time, applying their own heartbeat cutoff.
`TestSilentLinkedAgentStopsFeedingNodeDisk` drives the disk and projection
path through `evaluateHostAgents` and the registry-backed store refresh.
+The metrics-history API's live fallback relies on the same projection: it
+treats a host row reading `offline` as past its lease, and an agent linked to
+a Proxmox node then answers from the node row. For node rows it takes a
+projected `offline` or `unknown` as the lapse and otherwise reads the
+registry's sightings (`NodeView.SourceStatus`), because a projected `warning`
+is ambiguous: the stale pass shows an unreachable node that way, and so does a
+reporting linked agent's storage risk. The projection does not always carry
+the poller's verdict: a node merged with a silent linked agent projects
+`online` while its Proxmox sighting is current, even after the poller reports
+it offline. Docker host rows likewise lose the `offline` that
+`evaluateDockerAgents` set, to the stale pass's `warning` or to a merged
+agent's status, so that consumer also reads the Docker source's own sighting
+from `DockerHostView.SourceStatus(SourceDocker)`.
+
Unified Agent host reports now make module readiness and updater/config
lifecycle evidence monitoring-owned observed state. Monitoring preserves the
last successful one-shot update transition across subsequent reports, forwards
diff --git a/docs/release-control/v6/internal/subsystems/notifications.md b/docs/release-control/v6/internal/subsystems/notifications.md
index 421117c0e5..212efbade3 100644
--- a/docs/release-control/v6/internal/subsystems/notifications.md
+++ b/docs/release-control/v6/internal/subsystems/notifications.md
@@ -1301,3 +1301,30 @@ the queued close through the normal entry points for ntfy, and renders Discord,
both Teams cards, Mattermost, PagerDuty, a grouped Slack list, a grouped ntfy
batch and email/Apprise content, plus the unchanged ordinary recovery wording
and visuals.
+
+### Default email subjects retain bounded resource and host identity
+
+Single firing subjects retain severity/type and name the resource and its host.
+Digest subjects retain every severity count and include up to three distinct
+resource/host labels, sorted and deduplicated before shortening, with `+N more`
+for omitted labels (not omitted alerts). A host display name retains its raw
+host alongside it when they differ; absent node identity is `unknown host`,
+never an inferred connection/instance. An empty resource name falls back to its
+resource ID, then `Unknown resource`. Each supplied label/type is bounded to
+48 UTF-8 bytes, with visible truncation; controls/whitespace become spaces.
+Full body identities remain unchanged. Subjects are hints, not globally unique
+resource keys or proof of current host identity.
+
+Email-only recovery subjects carry the same bounded identity while preserving
+single resolved/moved and batch resolved wording. Occurrence threading,
+recovery receipt admission, routing, queue policy and other destination titles
+are unchanged. Both ordinary and attachment MIME construction encode Unicode
+subjects with RFC 2047 and fold at spaces/encoded-word boundaries; they still
+sanitize header line breaks. `email_subject_identity_test.go` checks the
+three-host collision, display/raw/missing identities, severity, deterministic
+bounds/overflow, full bodies, MIME decode/injection safety and normal
+single/grouped/recovery construction through an in-memory transport. This is
+source acceptance, not SMTP/Gmail delivery or an installed reporter retest.
+Literal ASCII encoded-word syntax in supplied names is itself MIME-encoded,
+so decoding the subject once preserves the name rather than interpreting it as
+another identity. The literal-encoded-word control covers both MIME builders.
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index 46d9f58a96..e264ee7c74 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -3112,3 +3112,11 @@ the mock-mode synthetic series derived from that reading, when the temperature
was not collected by the current observation. This only withholds a value the
caller was already authorized to read; the route, its authentication and scope
checks, tenant resolution and response shape are unchanged.
+
+The same endpoint also withholds the live point for host agent, Proxmox node,
+guest, integration host, Docker host and app container rows it judges to have
+stopped reporting, and answers a lapsed agent linked to a Proxmox node from
+that node's row in the same monitor. This only withholds or substitutes values
+the caller could already read; the new `NodeView` and `DockerHostView`
+`SourceStatus` accessors expose no field beyond the delivery state the registry
+already records on the resource.
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 0f04d0b1d6..b2820b90c5 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -6879,3 +6879,9 @@ migration or recovery authority is added or moved.
The performance report and reporting runtime snapshot handlers apply the same
test before tabulating a disk temperature. That changes only which held value a
report shows, not any storage or recovery path.
+
+The handler likewise withholds the live point for host agent, Proxmox node,
+guest, integration host, Docker host and app container rows it judges to have
+stopped reporting, or answers a lapsed linked agent from its node row. It reads
+only snapshot status and the registry's per-source sightings, and writes
+nothing.
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index 9815a49b8b..3055eca259 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -520,6 +520,18 @@ here instead of the row's `LastSeen`. The accessor returns a copy of the recorde
status and adds no freshness policy of its own.
`TestView_HostViewSourceStatusSeparatesAgentFromMergedRow` pins the merged-row
split.
+`NodeView.SourceStatus(source)` and `DockerHostView.SourceStatus(source)` do
+the same for node and Docker host rows. A merged node row takes its linked
+agent's status when the sources merge, and once any sighting goes stale the
+stale pass recomputes the status from the sightings: `online` while one is
+current, `warning` when every one is stale. `warning` is also a status a row
+that still reports can carry (a degraded Docker host, a node whose linked agent
+reports storage risk). The metrics-history live
+fallback therefore reads these sightings alongside the row's `offline` and
+`unknown` status to decide whether a row's readings are current. The accessors
+return a copy of the recorded status and add no freshness policy.
+`TestView_NodeViewSourceStatusSeparatesMergedSources` and
+`TestView_DockerHostViewSourceStatusSeparatesSilentFromDegraded` pin them.
### Bounded incident-history selection
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index fa09df5ea3..191757de6b 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -12843,6 +12843,220 @@ func TestContract_MetricsHistoryCanonicalizesLegacyKubernetesPodIDs(t *testing.T
}
}
+// A live point claims a reading taken now, while snapshot rows keep a silent
+// source's last readings as context. An empty range therefore answers with a
+// live point only while the source behind the row still reports: an agent
+// inside its lease, a node the poller sees online, a guest or Docker host
+// whose registry sighting is current. Power state and health are not a lapse:
+// a stopped guest and a degraded Docker host keep their live point.
+func TestContract_MetricsHistoryLivePointOnlyWhileSourceReports(t *testing.T) {
+ // Complete store setup before capturing current-report times. Slow setup
+ // must not age a live fixture past the existing reporting lease.
+ store, err := metrics.NewStore(metrics.DefaultConfig(t.TempDir()))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = store.Close() })
+
+ now := time.Now()
+ lapsed := now.Add(-time.Hour)
+ state := models.NewState()
+
+ state.UpsertHost(models.Host{
+ ID: "agent-silent", Hostname: "silent", Status: "online", IntervalSeconds: 30, LastSeen: lapsed,
+ CPUUsage: 55, Memory: models.Memory{Total: 100, Used: 40, Usage: 40},
+ Disks: []models.Disk{{Mountpoint: "/", Total: 100, Used: 70, Usage: 70}},
+ Sensors: models.HostSensorSummary{TemperatureCelsius: map[string]float64{"cpu_package": 61}},
+ })
+ if expired, changed := state.ExpireHostTelemetry("agent-silent", lapsed); !changed || expired.Status != "offline" {
+ t.Fatalf("lease expiry did not mark the silent agent offline: %+v", expired)
+ }
+ if hosts := state.GetHosts(); len(hosts) != 1 || hosts[0].CPUUsage != 55 {
+ t.Fatalf("lease expiry should keep the last telemetry as context, got %+v", hosts)
+ }
+ state.UpsertHost(models.Host{
+ ID: "agent-reporting", Hostname: "reporting", Status: "online", IntervalSeconds: 30, LastSeen: now,
+ CPUUsage: 12, Sensors: models.HostSensorSummary{TemperatureCelsius: map[string]float64{"cpu_package": 48}},
+ })
+
+ nodeMemory := models.Memory{Total: 100, Used: 45, Usage: 45}
+ state.UpdateNodesForInstance("pve", []models.Node{
+ // The PVE grace policy keeps an unreachable node's memory and disk.
+ {ID: "pve-unreachable", Name: "unreachable", Instance: "pve", Type: "node", Status: "offline", ConnectionHealth: "error", Memory: nodeMemory, LastSeen: lapsed},
+ // The cluster reports this member offline on a fresh poll.
+ {ID: "pve-down", Name: "down", Instance: "pve", Type: "node", Status: "offline", ConnectionHealth: "error", Memory: nodeMemory, LastSeen: now},
+ // A member the cluster lists online that this poll did not observe.
+ {ID: "pve-unobserved", Name: "unobserved", Instance: "pve", Type: "node", Status: "unknown", ConnectionHealth: "degraded", Memory: nodeMemory, LastSeen: now},
+ {ID: "pve-online", Name: "online", Instance: "pve", Type: "node", Status: "online", ConnectionHealth: "healthy", CPU: 0.2, Memory: nodeMemory, LastSeen: now},
+ // Nodes merged with a linked host agent: one agent past its lease,
+ // one reporting a degraded array.
+ {ID: "pve-merged", Name: "merged", Instance: "pve", Type: "node", Status: "online", ConnectionHealth: "healthy", CPU: 0.35, Memory: nodeMemory, LastSeen: now, LinkedAgentID: "agent-merged"},
+ {ID: "pve-raid", Name: "raid", Instance: "pve", Type: "node", Status: "online", ConnectionHealth: "healthy", CPU: 0.45, Memory: nodeMemory, LastSeen: now, LinkedAgentID: "agent-raid"},
+ })
+ state.UpsertHost(models.Host{
+ ID: "agent-merged", Hostname: "merged", Status: "online", IntervalSeconds: 30, LastSeen: lapsed, LinkedNodeID: "pve-merged",
+ CPUUsage: 77, Sensors: models.HostSensorSummary{TemperatureCelsius: map[string]float64{"cpu_package": 66}},
+ })
+ if _, changed := state.ExpireHostTelemetry("agent-merged", lapsed); !changed {
+ t.Fatal("lease expiry did not mark the linked agent offline")
+ }
+ state.UpsertHost(models.Host{
+ ID: "agent-raid", Hostname: "raid", Status: "online", IntervalSeconds: 30, LastSeen: now, LinkedNodeID: "pve-raid", CPUUsage: 45,
+ RAID: []models.HostRAIDArray{{Device: "/dev/md2", Level: "raid1", State: "degraded", TotalDevices: 2, ActiveDevices: 1, WorkingDevices: 1, FailedDevices: 1}},
+ })
+ state.UpdateVMsForInstance("pve", []models.VM{
+ {ID: "pve:unreachable:101", VMID: 101, Name: "kept", Node: "unreachable", Instance: "pve", Type: "qemu", Status: "running", CPU: 0.3, LastSeen: lapsed},
+ {ID: "pve:online:102", VMID: 102, Name: "running", Node: "online", Instance: "pve", Type: "qemu", Status: "running", CPU: 0.4, LastSeen: now},
+ {ID: "pve:online:103", VMID: 103, Name: "stopped", Node: "online", Instance: "pve", Type: "qemu", Status: "stopped", LastSeen: now},
+ })
+ state.UpdateContainersForInstance("pve", []models.Container{
+ {ID: "pve:unreachable:201", VMID: 201, Name: "kept-ct", Node: "unreachable", Instance: "pve", Type: "lxc", Status: "running", CPU: 0.25, LastSeen: lapsed},
+ {ID: "pve:online:202", VMID: 202, Name: "running-ct", Node: "online", Instance: "pve", Type: "lxc", Status: "running", CPU: 0.15, LastSeen: now},
+ })
+
+ dockerHost := func(id string, status string, interval int, lastSeen time.Time, cpu float64, containerMemory float64) models.DockerHost {
+ return models.DockerHost{
+ ID: id, AgentID: id + "-agent", Hostname: id, Status: status, IntervalSeconds: interval, LastSeen: lastSeen, CPUs: 4, CPUUsage: cpu,
+ Containers: []models.DockerContainer{{ID: id + "-app", Name: id + "-app", State: "running", Status: "Up", MemoryPercent: containerMemory}},
+ }
+ }
+ // evaluateDockerAgents marks a host offline once its report is overdue.
+ // The silent host is past the registry's stale window too; the overdue
+ // one is past its own lease but not yet stale.
+ state.UpsertDockerHost(dockerHost("docker-silent", "online", 30, lapsed, 20, 6))
+ state.UpsertDockerHost(dockerHost("docker-overdue", "online", 10, now.Add(-time.Minute), 22, 7))
+ for _, id := range []string{"docker-silent", "docker-overdue"} {
+ if !state.SetDockerHostStatus(id, "offline") {
+ t.Fatalf("%s: offline transition not applied", id)
+ }
+ }
+ state.UpsertDockerHost(dockerHost("docker-degraded", "degraded", 30, now, 33, 9))
+ state.UpsertDockerHost(dockerHost("docker-reporting", "online", 30, now, 21, 8))
+
+ monitor := &monitoring.Monitor{}
+ setUnexportedField(t, monitor, "state", state)
+ setUnexportedField(t, monitor, "metricsHistory", monitoring.NewMetricsHistory(10, time.Hour))
+ setUnexportedField(t, monitor, "metricsStore", store)
+ router := &Router{monitor: monitor}
+
+ // Row status alone cannot tell a lapse from a warning: the stale pass
+ // shows the unreachable node as warning, and the reporting agent's
+ // degraded array gives its merged node the same status.
+ nodeStatus := make(map[string]string)
+ for _, node := range monitor.NodesSnapshot() {
+ nodeStatus[node.ID] = node.Status
+ }
+ if nodeStatus["pve-unreachable"] != "warning" || nodeStatus["pve-raid"] != "warning" || nodeStatus["pve-merged"] != "online" {
+ t.Fatalf("node statuses = %v, want the unreachable and degraded-array nodes as warning and the merged node online", nodeStatus)
+ }
+
+ history := func(query string) (metricsHistoryResponse, map[string]json.RawMessage) {
+ t.Helper()
+ rec := httptest.NewRecorder()
+ router.handleMetricsHistory(rec, httptest.NewRequest(http.MethodGet, "/api/metrics-store/history?range=5m&"+query, nil))
+ if rec.Code != http.StatusOK {
+ t.Fatalf("%s: status = %d, body=%s", query, rec.Code, rec.Body.String())
+ }
+ var single metricsHistoryResponse
+ var all struct {
+ Metrics map[string]json.RawMessage `json:"metrics"`
+ }
+ if err := json.Unmarshal(rec.Body.Bytes(), &single); err != nil {
+ t.Fatalf("%s: decode: %v", query, err)
+ }
+ if err := json.Unmarshal(rec.Body.Bytes(), &all); err != nil {
+ t.Fatalf("%s: decode metrics: %v", query, err)
+ }
+ return single, all.Metrics
+ }
+
+ for _, tc := range []struct{ resourceType, resourceID, metric string }{
+ {"agent", "agent-silent", "cpu"},
+ {"agent", "agent-silent", "temperature"},
+ {"node", "pve-unreachable", "memory"},
+ {"node", "pve-down", "memory"},
+ {"node", "pve-unobserved", "memory"},
+ {"agent", "pve-unreachable", "memory"},
+ {"vm", "pve:unreachable:101", "cpu"},
+ {"system-container", "pve:unreachable:201", "cpu"},
+ {"docker-host", "docker-silent", "cpu"},
+ {"docker-host", "docker-overdue", "cpu"},
+ {"app-container", "docker-silent-app", "memory"},
+ {"app-container", "docker-overdue-app", "memory"},
+ } {
+ target := "resourceType=" + tc.resourceType + "&resourceId=" + tc.resourceID
+ if resp, _ := history(target + "&metric=" + tc.metric); resp.Source == "live" || len(resp.Points) != 0 {
+ t.Fatalf("%s %s: retained %s served as current: source=%q points=%+v", tc.resourceType, tc.resourceID, tc.metric, resp.Source, resp.Points)
+ }
+ if _, all := history(target); len(all) != 0 {
+ t.Fatalf("%s %s: retained readings served as current: %v", tc.resourceType, tc.resourceID, all)
+ }
+ }
+
+ // The linked agent's retained sensor reading is not served; its node has
+ // no temperature of its own to stand in.
+ if resp, _ := history("resourceType=agent&resourceId=agent-merged&metric=temperature"); resp.Source == "live" || len(resp.Points) != 0 {
+ t.Fatalf("linked agent's retained temperature served as current: source=%q points=%+v", resp.Source, resp.Points)
+ }
+ if _, all := history("resourceType=agent&resourceId=agent-merged"); all["temperature"] != nil || all["cpu"] == nil {
+ t.Fatalf("linked agent all-metrics live points = %v, want the node's readings without the agent's temperature", all)
+ }
+
+ for _, tc := range []struct {
+ resourceType, resourceID, metric string
+ want float64
+ }{
+ {"agent", "agent-reporting", "cpu", 12},
+ // The poll keeps the linked node's readings current after the agent
+ // falls silent.
+ {"agent", "agent-merged", "cpu", 35},
+ {"node", "pve-raid", "cpu", 45},
+ {"agent", "agent-raid", "cpu", 45},
+ {"agent", "agent-reporting", "temperature", 48},
+ {"node", "pve-online", "cpu", 20},
+ {"vm", "pve:online:102", "cpu", 40},
+ {"vm", "pve:online:103", "cpu", 0},
+ {"system-container", "pve:online:202", "cpu", 15},
+ {"docker-host", "docker-reporting", "cpu", 21},
+ {"docker-host", "docker-degraded", "cpu", 33},
+ {"app-container", "docker-reporting-app", "memory", 8},
+ {"app-container", "docker-degraded-app", "memory", 9},
+ } {
+ resp, _ := history("resourceType=" + tc.resourceType + "&resourceId=" + tc.resourceID + "&metric=" + tc.metric)
+ if resp.Source != "live" || len(resp.Points) != 1 || math.Abs(resp.Points[0].Value-tc.want) > 0.001 {
+ t.Fatalf("%s %s: current %s not served as a live point: source=%q points=%+v", tc.resourceType, tc.resourceID, tc.metric, resp.Source, resp.Points)
+ }
+ }
+}
+
+// A row lapses only when it records a reading source and every one it records
+// is stale; one current reading source keeps it reporting. A sighting never
+// delivered (unknown) is no evidence of a lapse, and availability probes and
+// PBS sightings supply no readings either way.
+func TestContract_MetricsHistoryLiveReadingSightingsLapsed(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ sightings map[unifiedresources.DataSource]string
+ want bool
+ }{
+ {"no sightings", nil, false},
+ {"availability probe only", map[unifiedresources.DataSource]string{unifiedresources.SourceAvailability: "stale"}, false},
+ {"current PBS sighting supplies no readings", map[unifiedresources.DataSource]string{unifiedresources.SourceProxmox: "stale", unifiedresources.SourcePBS: "online"}, true},
+ {"provider stale", map[unifiedresources.DataSource]string{unifiedresources.SourceVMware: "stale"}, true},
+ {"every source stale", map[unifiedresources.DataSource]string{unifiedresources.SourceProxmox: "stale", unifiedresources.SourceAgent: "stale"}, true},
+ {"one source current", map[unifiedresources.DataSource]string{unifiedresources.SourceProxmox: "stale", unifiedresources.SourceAgent: "online"}, false},
+ {"never delivered", map[unifiedresources.DataSource]string{unifiedresources.SourceTrueNAS: "unknown"}, false},
+ } {
+ got := readingSightingsLapsed(func(source unifiedresources.DataSource) (unifiedresources.SourceStatus, bool) {
+ status, ok := tc.sightings[source]
+ return unifiedresources.SourceStatus{Status: status}, ok
+ })
+ if got != tc.want {
+ t.Fatalf("%s: lapsed = %v, want %v", tc.name, got, tc.want)
+ }
+ }
+}
+
func TestContract_MetricsHistoryPhysicalDiskIOLiveWindowUsesCanonicalDiskTarget(t *testing.T) {
mh := monitoring.NewMetricsHistory(1000, time.Hour)
now := time.Now().UTC().Truncate(time.Second)
diff --git a/internal/api/router.go b/internal/api/router.go
index 616f425769..12152c6313 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -6334,6 +6334,9 @@ func (r *Router) handleMetricsHistory(w http.ResponseWriter, req *http.Request)
storageFallbackOnce sync.Once
unifiedStorage []storageMetricFallback
+
+ sightingFallbackOnce sync.Once
+ lapsedRows map[string]struct{}
)
loadFallbackState := func() {
@@ -6528,17 +6531,113 @@ func (r *Router) handleMetricsHistory(w http.ResponseWriter, req *http.Request)
return nil
}
- findDockerContainer := func(id string) (*models.DockerContainer, int) {
+ findDockerContainer := func(id string) (*models.DockerContainer, *models.DockerHost) {
loadFallbackState()
for i := range dockerHosts {
host := &dockerHosts[i]
for j := range host.Containers {
if host.Containers[j].ID == id {
- return &host.Containers[j], host.CPUs
+ return &host.Containers[j], host
}
}
}
- return nil, 0
+ return nil, nil
+ }
+
+ // The snapshot rows above keep a silent source's last readings as
+ // context: ExpireHostTelemetry keeps an expired agent's telemetry, the
+ // PVE node grace policy keeps an unreachable node's memory and disk, and
+ // guests and Docker hosts keep their last report after the registry marks
+ // that source stale. A live point claims a reading taken now, so it is
+ // built only while a source behind the row is still reporting.
+ loadLapsedSightings := func() {
+ sightingFallbackOnce.Do(func() {
+ lapsedRows = make(map[string]struct{})
+ readState := monitor.GetUnifiedReadStateOrSnapshot()
+ if readState == nil {
+ return
+ }
+ // Index under both IDs a snapshot row can carry.
+ record := func(kind string, lapsed bool, ids ...string) {
+ if !lapsed {
+ return
+ }
+ for _, id := range ids {
+ if id = strings.TrimSpace(id); id != "" {
+ lapsedRows[kind+"\x00"+id] = struct{}{}
+ }
+ }
+ }
+ for _, vm := range readState.VMs() {
+ if vm != nil {
+ record("guest", readingSightingsLapsed(vm.SourceStatus), vm.SourceID(), vm.ID())
+ }
+ }
+ for _, ct := range readState.Containers() {
+ if ct != nil {
+ record("guest", readingSightingsLapsed(ct.SourceStatus), ct.SourceID(), ct.ID())
+ }
+ }
+ for _, node := range readState.Nodes() {
+ if node != nil {
+ record("node", readingSightingsLapsed(node.SourceStatus), node.SourceID(), node.ID())
+ }
+ }
+ // An agent row's own lease decides its status in HostsSnapshot;
+ // integration rows without an agent sighting fall back to their
+ // provider's sightings.
+ for _, host := range readState.Hosts() {
+ if host == nil {
+ continue
+ }
+ if agent, ok := host.SourceStatus(unifiedresources.SourceAgent); ok && !agent.LastSeen.IsZero() {
+ continue
+ }
+ record("host", readingSightingsLapsed(host.SourceStatus), host.AgentID(), host.ID())
+ }
+ // A Docker row's own readings and its containers arrive in the
+ // Docker report, so its Docker sighting decides.
+ for _, host := range readState.DockerHosts() {
+ if host != nil {
+ record("docker", readingSightingsLapsed(func(source unifiedresources.DataSource) (unifiedresources.SourceStatus, bool) {
+ if source != unifiedresources.SourceDocker {
+ return unifiedresources.SourceStatus{}, false
+ }
+ return host.SourceStatus(source)
+ }), host.HostSourceID(), host.ID())
+ }
+ }
+ })
+ }
+ rowLapsed := func(kind, id string) bool {
+ loadLapsedSightings()
+ _, lapsed := lapsedRows[kind+"\x00"+id]
+ return lapsed
+ }
+ // HostsSnapshot reports an agent row past its reporting lease as offline.
+ hostReporting := func(host *models.Host) bool {
+ return !strings.EqualFold(strings.TrimSpace(host.Status), "offline") && !rowLapsed("host", host.ID)
+ }
+ // The poller marks a node it cannot reach, or one the cluster lists but
+ // this poll did not observe, offline or unknown and keeps earlier
+ // readings. A warning status alone is not a lapse: a linked agent's
+ // storage risk can set it on a row that is still reporting.
+ nodeReporting := func(node *models.Node) bool {
+ switch strings.ToLower(strings.TrimSpace(node.Status)) {
+ case "offline", "unknown":
+ return false
+ }
+ return !rowLapsed("node", node.ID)
+ }
+ guestReporting := func(id string) bool {
+ return !rowLapsed("guest", id)
+ }
+ // evaluateDockerAgents marks a host offline once its report is overdue.
+ // The registry's stale pass can later show that host as warning, and a
+ // merged agent row keeps the agent's status, so the Docker sighting
+ // decides as well.
+ dockerHostReporting := func(host *models.DockerHost) bool {
+ return !strings.EqualFold(strings.TrimSpace(host.Status), "offline") && !rowLapsed("docker", host.ID)
}
findDisk := func(id string) *unifiedresources.Resource {
@@ -6596,7 +6695,7 @@ func (r *Router) handleMetricsHistory(w http.ResponseWriter, req *http.Request)
switch resourceType {
case "vm":
vm := findVM(resourceID)
- if vm == nil {
+ if vm == nil || !guestReporting(vm.ID) {
return points
}
points["cpu"] = monitoring.MetricPoint{Timestamp: now, Value: chartapi.ProxmoxModelCPURatioPercent(vm.CPU)}
@@ -6610,7 +6709,7 @@ func (r *Router) handleMetricsHistory(w http.ResponseWriter, req *http.Request)
points["netout"] = monitoring.MetricPoint{Timestamp: now, Value: float64(vm.NetworkOut)}
case "system-container", "oci-container":
ct := findContainer(resourceID)
- if ct == nil {
+ if ct == nil || !guestReporting(ct.ID) {
return points
}
points["cpu"] = monitoring.MetricPoint{Timestamp: now, Value: chartapi.ProxmoxModelCPURatioPercent(ct.CPU)}
@@ -6624,7 +6723,7 @@ func (r *Router) handleMetricsHistory(w http.ResponseWriter, req *http.Request)
points["netout"] = monitoring.MetricPoint{Timestamp: now, Value: float64(ct.NetworkOut)}
case "node":
node := findNode(resourceID)
- if node == nil {
+ if node == nil || !nodeReporting(node) {
return points
}
points["cpu"] = monitoring.MetricPoint{Timestamp: now, Value: chartapi.ProxmoxModelCPURatioPercent(node.CPU)}
@@ -6664,7 +6763,7 @@ func (r *Router) handleMetricsHistory(w http.ResponseWriter, req *http.Request)
}
case "docker-host":
host := findDockerHost(resourceID)
- if host == nil {
+ if host == nil || !dockerHostReporting(host) {
return points
}
points["cpu"] = monitoring.MetricPoint{Timestamp: now, Value: host.CPUUsage}
@@ -6675,7 +6774,17 @@ func (r *Router) handleMetricsHistory(w http.ResponseWriter, req *http.Request)
}
points["disk"] = monitoring.MetricPoint{Timestamp: now, Value: diskPercent}
case "agent":
+ nodeID := resourceID
host := findHost(resourceID)
+ if host != nil && !hostReporting(host) {
+ // A host agent linked to a Proxmox node describes the same
+ // machine; once the agent's lease lapses, the node's poll
+ // still supplies its current readings.
+ if strings.TrimSpace(host.LinkedNodeID) == "" {
+ return points
+ }
+ nodeID, host = host.LinkedNodeID, nil
+ }
if host != nil {
points["cpu"] = monitoring.MetricPoint{Timestamp: now, Value: host.CPUUsage}
points["memory"] = monitoring.MetricPoint{Timestamp: now, Value: host.Memory.Usage}
@@ -6693,8 +6802,8 @@ func (r *Router) handleMetricsHistory(w http.ResponseWriter, req *http.Request)
// Showing cumulative bytes as if they were rates would be misleading (showing GB instead of KB/s).
return points
}
- node := findNode(resourceID)
- if node == nil {
+ node := findNode(nodeID)
+ if node == nil || !nodeReporting(node) {
return points
}
points["cpu"] = monitoring.MetricPoint{Timestamp: now, Value: chartapi.ProxmoxModelCPURatioPercent(node.CPU)}
@@ -6704,11 +6813,12 @@ func (r *Router) handleMetricsHistory(w http.ResponseWriter, req *http.Request)
points["temperature"] = monitoring.MetricPoint{Timestamp: now, Value: *temperature}
}
case "app-container":
- container, hostCPUs := findDockerContainer(resourceID)
- if container == nil {
+ // A container's readings arrive in its Docker host's report.
+ container, host := findDockerContainer(resourceID)
+ if container == nil || !dockerHostReporting(host) {
return points
}
- points["cpu"] = monitoring.MetricPoint{Timestamp: now, Value: models.DockerContainerCPUCapacityPercent(*container, hostCPUs)}
+ points["cpu"] = monitoring.MetricPoint{Timestamp: now, Value: models.DockerContainerCPUCapacityPercent(*container, host.CPUs)}
points["memory"] = monitoring.MetricPoint{Timestamp: now, Value: container.MemoryPercent}
if container.RootFilesystemBytes > 0 && container.WritableLayerBytes > 0 {
diskPercent := float64(container.WritableLayerBytes) / float64(container.RootFilesystemBytes) * 100
@@ -7408,6 +7518,36 @@ func canonicalizeMetricsHistoryResourceID(runtimeResourceType, resourceID string
return trimmed
}
+// liveReadingSources are the sources that supply the readings of the rows
+// liveMetricPoints reads, so their sightings decide whether those readings are
+// current. A PBS sighting can join a host row without supplying its metrics,
+// and availability probes report reachability, not readings.
+var liveReadingSources = []unifiedresources.DataSource{
+ unifiedresources.SourceProxmox,
+ unifiedresources.SourceAgent,
+ unifiedresources.SourceDocker,
+ unifiedresources.SourceVMware,
+ unifiedresources.SourceTrueNAS,
+}
+
+// readingSightingsLapsed reports whether a row records at least one reading
+// source and the registry has marked every one of them stale. A sighting that
+// was never delivered (unknown) is not evidence of a lapse.
+func readingSightingsLapsed(sourceStatus func(unifiedresources.DataSource) (unifiedresources.SourceStatus, bool)) bool {
+ recorded := false
+ for _, source := range liveReadingSources {
+ status, ok := sourceStatus(source)
+ if !ok {
+ continue
+ }
+ if !strings.EqualFold(strings.TrimSpace(status.Status), "stale") {
+ return false
+ }
+ recorded = true
+ }
+ return recorded
+}
+
func primaryHostSensorTemperatureCelsius(sensors models.HostSensorSummary) *float64 {
if len(sensors.TemperatureCelsius) == 0 {
return nil
diff --git a/internal/notifications/email_enhanced.go b/internal/notifications/email_enhanced.go
index 63c411fe7a..4c26697a00 100644
--- a/internal/notifications/email_enhanced.go
+++ b/internal/notifications/email_enhanced.go
@@ -8,6 +8,7 @@ import (
"encoding/hex"
"fmt"
"io"
+ "mime"
"mime/multipart"
"mime/quotedprintable"
"net"
@@ -86,6 +87,46 @@ func sanitizeEmailHeaderValue(value string) string {
return strings.TrimSpace(clean)
}
+// RFC 2047 encoding keeps non-ASCII host/resource names readable without
+// requiring SMTPUTF8. Fold only at spaces (including between encoded words),
+// never inside a character or encoded word. Short ASCII subjects are unchanged.
+func emailSubjectHeader(subject string) string {
+ clean := sanitizeEmailHeaderValue(subject)
+ encoded := mime.QEncoding.Encode("UTF-8", clean)
+ if encoded == clean && strings.Contains(clean, "=?") {
+ // The standard encoder leaves printable ASCII unchanged. A literal
+ // encoded-word in a supplied name would then be decoded as syntax by
+ // mail clients, changing the identity. Wrap it once, in <=75-byte
+ // encoded words. This branch is ASCII-only, so byte cuts are safe.
+ var words []string
+ for len(clean) > 0 {
+ end := min(45, len(clean))
+ words = append(words, "=?UTF-8?b?"+base64.StdEncoding.EncodeToString([]byte(clean[:end]))+"?=")
+ clean = clean[end:]
+ }
+ encoded = strings.Join(words, " ")
+ }
+ var header strings.Builder
+ column := len("Subject: ")
+ for i, word := range strings.Split(encoded, " ") {
+ space := ""
+ if i > 0 {
+ space = " "
+ }
+ if column+len(space)+len(word) > 78 {
+ space = "\r\n "
+ column = 1
+ }
+ header.WriteString(space)
+ header.WriteString(word)
+ column += len(word)
+ if space == " " {
+ column++
+ }
+ }
+ return header.String()
+}
+
type resolvedEmailAddresses struct {
from *mail.Address
to []*mail.Address
@@ -232,7 +273,7 @@ func buildMultipartEmailMessage(addresses resolvedEmailAddresses, subject, htmlB
return nil, fmt.Errorf("write reply-to header: %w", err)
}
}
- if _, err := fmt.Fprintf(&message, "Subject: %s\r\n", sanitizeEmailHeaderValue(subject)); err != nil {
+ if _, err := fmt.Fprintf(&message, "Subject: %s\r\n", emailSubjectHeader(subject)); err != nil {
return nil, fmt.Errorf("write subject header: %w", err)
}
if _, err := fmt.Fprintf(&message, "Date: %s\r\n", now.Format(time.RFC1123Z)); err != nil {
@@ -291,7 +332,7 @@ func buildMultipartEmailMessageWithAttachments(addresses resolvedEmailAddresses,
return nil, fmt.Errorf("write reply-to header: %w", err)
}
}
- if _, err := fmt.Fprintf(&message, "Subject: %s\r\n", sanitizeEmailHeaderValue(subject)); err != nil {
+ if _, err := fmt.Fprintf(&message, "Subject: %s\r\n", emailSubjectHeader(subject)); err != nil {
return nil, fmt.Errorf("write subject header: %w", err)
}
if _, err := fmt.Fprintf(&message, "Date: %s\r\n", now.Format(time.RFC1123Z)); err != nil {
diff --git a/internal/notifications/email_subject.go b/internal/notifications/email_subject.go
new file mode 100644
index 0000000000..eb301d002c
--- /dev/null
+++ b/internal/notifications/email_subject.go
@@ -0,0 +1,134 @@
+package notifications
+
+import (
+ "fmt"
+ "sort"
+ "strings"
+ "unicode"
+ "unicode/utf8"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts"
+)
+
+const (
+ emailSubjectComponentBytes = 48
+ emailSubjectIdentityLimit = 3
+)
+
+// Subject labels are hints, not replacements for the full identity in the body.
+// Keep their byte budget independent of character width and do not let supplied
+// names introduce header controls. Truncation never splits a UTF-8 character.
+func emailSubjectLabel(value string) string {
+ return strings.Join(strings.Fields(strings.Map(func(r rune) rune {
+ if unicode.IsControl(r) || unicode.IsSpace(r) {
+ return ' '
+ }
+ return r
+ }, value)), " ")
+}
+
+func boundEmailSubjectLabel(value string) string {
+ if len(value) <= emailSubjectComponentBytes {
+ return value
+ }
+ end := emailSubjectComponentBytes - len("…")
+ for !utf8.RuneStart(value[end]) {
+ end--
+ }
+ return value[:end] + "…"
+}
+
+type emailSubjectIdentity struct {
+ resource, node, display string
+}
+
+func subjectIdentity(alert *alerts.Alert) emailSubjectIdentity {
+ resource := emailSubjectLabel(alert.ResourceName)
+ if resource == "" {
+ resource = emailSubjectLabel(alert.ResourceID)
+ }
+ if resource == "" {
+ resource = "Unknown resource"
+ }
+ node, display := emailSubjectLabel(alert.Node), emailSubjectLabel(alert.NodeDisplayName)
+ if display == "" || display == node {
+ display = node
+ }
+ return emailSubjectIdentity{resource, node, display}
+}
+
+func (identity emailSubjectIdentity) label() string {
+ node := boundEmailSubjectLabel(identity.node)
+ display := boundEmailSubjectLabel(identity.display)
+ host := display
+ if host == "" {
+ host = "unknown host"
+ } else if node != "" && identity.display != identity.node {
+ // Keep the raw host alongside a renamed host: display names need not be
+ // unique, and an alias must not hide the three-host case in #2635.
+ host += " [" + node + "]"
+ }
+ return boundEmailSubjectLabel(identity.resource) + " (" + host + ")"
+}
+
+func emailSubjectIdentities(alertList []*alerts.Alert) string {
+ // Deduplicate and sort full labels BEFORE bounding. Different long labels
+ // must not disappear just because their shortened hints look alike.
+ seen := make(map[emailSubjectIdentity]struct{}, len(alertList))
+ identities := make([]emailSubjectIdentity, 0, len(alertList))
+ for _, alert := range alertList {
+ if alert == nil {
+ continue
+ }
+ identity := subjectIdentity(alert)
+ if _, exists := seen[identity]; exists {
+ continue
+ }
+ seen[identity] = struct{}{}
+ identities = append(identities, identity)
+ }
+ sort.Slice(identities, func(i, j int) bool {
+ a, b := identities[i], identities[j]
+ if a.resource != b.resource {
+ return a.resource < b.resource
+ }
+ if a.node != b.node {
+ return a.node < b.node
+ }
+ return a.display < b.display
+ })
+ labels := make([]string, 0, emailSubjectIdentityLimit+1)
+ for i, identity := range identities {
+ if i == emailSubjectIdentityLimit {
+ labels = append(labels, fmt.Sprintf("+%d more", len(identities)-i))
+ break
+ }
+ labels = append(labels, identity.label())
+ }
+ return strings.Join(labels, ", ")
+}
+
+// This is email-only. Other destinations keep their own resolution titles and
+// all destinations keep the existing occurrence-qualified recovery admission.
+func resolvedEmailSubject(alertList []*alerts.Alert) string {
+ var primary *alerts.Alert
+ count := 0
+ for _, alert := range alertList {
+ if alert != nil {
+ if primary == nil {
+ primary = alert
+ }
+ count++
+ }
+ }
+ if count == 0 {
+ return ""
+ }
+ prefix := "Pulse alert resolved"
+ if count > 1 {
+ prefix = fmt.Sprintf("Pulse alerts resolved (%d)", count)
+ } else if primary.Resolution.Outcome() != "" {
+ prefix = "Pulse alert moved"
+ }
+ return prefix + ": " + emailSubjectIdentities(alertList)
+}
diff --git a/internal/notifications/email_subject_identity_test.go b/internal/notifications/email_subject_identity_test.go
new file mode 100644
index 0000000000..32dc50d838
--- /dev/null
+++ b/internal/notifications/email_subject_identity_test.go
@@ -0,0 +1,393 @@
+package notifications
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "mime"
+ "mime/multipart"
+ "net"
+ "net/mail"
+ "net/textproto"
+ "reflect"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+ "unicode"
+ "unicode/utf8"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts"
+)
+
+func subjectIdentityAlert(node string, level alerts.AlertLevel) *alerts.Alert {
+ return &alerts.Alert{ID: "docker-" + node + "-nginx-cpu", ResourceID: "docker/" + node + "/nginx",
+ ResourceName: "nginx", Node: node, Type: "cpu", Level: level,
+ Message: "CPU above threshold", StartTime: time.Date(2026, 10, 7, 2, 0, 0, 123, time.UTC)}
+}
+
+// These controls use existing entry points only so identical final test bytes
+// can reject the exact parent, rather than test a hand-built replacement subject.
+func TestEmailSubjectIdentitySingle(t *testing.T) {
+ for _, tc := range []struct {
+ name, node, display, resource, resourceID, want string
+ level alerts.AlertLevel
+ }{
+ {"raw", "docker-one", "", "nginx", "id", "[Pulse Alert] Critical: CPU on nginx (docker-one)", alerts.AlertLevelCritical},
+ {"display and raw", "docker-two", "Kitchen", "nginx", "id", "[Pulse Alert] Warning: CPU on nginx (Kitchen [docker-two])", alerts.AlertLevelWarning},
+ {"display only", "", "Kitchen", "nginx", "id", "[Pulse Alert] Info: CPU on nginx (Kitchen)", alerts.AlertLevelInfo},
+ {"same display", "docker-three", "docker-three", "nginx", "id", "[Pulse Alert] Warning: CPU on nginx (docker-three)", alerts.AlertLevelWarning},
+ {"no host", "", "", "nginx", "id", "[Pulse Alert] Warning: CPU on nginx (unknown host)", alerts.AlertLevelWarning},
+ {"resource ID fallback", "docker-one", "", " \t", "container-123", "[Pulse Alert] Warning: CPU on container-123 (docker-one)", alerts.AlertLevelWarning},
+ {"unknown identity and severity", "", "", "", "", "[Pulse Alert] Warning: CPU on Unknown resource (unknown host)", alerts.AlertLevel("unknown")},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ a := subjectIdentityAlert(tc.node, tc.level)
+ a.NodeDisplayName, a.ResourceName, a.ResourceID = tc.display, tc.resource, tc.resourceID
+ a.Instance = "connection-is-not-a-host"
+ before := a.Clone()
+ subject, html, text := EmailTemplate([]*alerts.Alert{a}, true)
+ if subject != tc.want {
+ t.Fatalf("subject = %q, want %q", subject, tc.want)
+ }
+ if !strings.Contains(text, "- Node: "+alertNodeDisplay(a)) || !strings.Contains(html, "CPU") {
+ t.Fatal("identity repair lost the full original body")
+ }
+ if !reflect.DeepEqual(a, before) {
+ t.Fatal("subject construction mutated the incident")
+ }
+ })
+ }
+}
+
+func TestEmailSubjectIdentityDigest(t *testing.T) {
+ batch := []*alerts.Alert{subjectIdentityAlert("docker-three", alerts.AlertLevelInfo),
+ subjectIdentityAlert("docker-one", alerts.AlertLevelCritical), subjectIdentityAlert("docker-two", alerts.AlertLevelWarning)}
+ for _, a := range batch {
+ a.NodeDisplayName = "Kitchen"
+ }
+ want := "[Pulse Alert] 1 Critical, 1 Warning, 1 Info alerts: nginx (Kitchen [docker-one]), nginx (Kitchen [docker-three]), nginx (Kitchen [docker-two])"
+ subject, html, text := EmailTemplate(batch, false)
+ if subject != want {
+ t.Fatalf("subject = %q, want %q", subject, want)
+ }
+ for _, a := range batch {
+ if !strings.Contains(text, a.ResourceName) || !strings.Contains(html, a.ResourceName) {
+ t.Fatal("digest lost resource body")
+ }
+ }
+ reversed := []*alerts.Alert{batch[2], batch[1], batch[0]}
+ reordered, _, _ := EmailTemplate(reversed, false)
+ if reordered != subject {
+ t.Fatalf("same identities changed subject on reorder: %q", reordered)
+ }
+ one, _, _ := EmailTemplate(batch[:1], false)
+ if one != "[Pulse Alert] 1 Info alert: nginx (Kitchen [docker-three])" {
+ t.Fatalf("one-alert digest = %q", one)
+ }
+}
+
+func TestEmailSubjectIdentityBounds(t *testing.T) {
+ batch := make([]*alerts.Alert, 0, 22)
+ for i := 19; i >= 0; i-- {
+ a := subjectIdentityAlert(fmt.Sprintf("host-%02d", i), alerts.AlertLevelWarning)
+ a.ResourceName = "nœud-東京-🚨-" + strings.Repeat("界", 200)
+ a.NodeDisplayName = strings.Repeat("🚨", 200)
+ batch = append(batch, a)
+ }
+ // Different metrics for the same resource/host label count in severity,
+ // not twice in the subject's identity list.
+ batch = append(batch, batch[0].Clone(), batch[0].Clone())
+ subject, html, text := EmailTemplate(batch, false)
+ if !strings.HasPrefix(subject, "[Pulse Alert] 22 Warning alerts:") || !strings.HasSuffix(subject, "+17 more") {
+ t.Fatalf("incorrect alert count or full-label overflow: %q", subject)
+ }
+ if len(subject) > 600 || !utf8.ValidString(subject) {
+ t.Fatalf("unbounded/invalid UTF-8 subject (%d bytes)", len(subject))
+ }
+ for _, host := range []string{"host-00", "host-01", "host-02"} {
+ if !strings.Contains(subject, host) {
+ t.Fatalf("deterministic leading identity %s omitted", host)
+ }
+ }
+ if strings.Contains(subject, "host-03") || !strings.Contains(subject, "…") {
+ t.Fatal("identity/byte bounds not applied")
+ }
+ if !strings.Contains(html, batch[0].ResourceName) || !strings.Contains(text, batch[0].NodeDisplayName) {
+ t.Fatal("bounding removed full body labels")
+ }
+ // Four distinct full labels with the same truncated hint must still report
+ // an omitted label, not silently collapse into one.
+ for i := range batch[:4] {
+ batch[i].Node, batch[i].NodeDisplayName = strings.Repeat("x", 100)+fmt.Sprint(i), ""
+ }
+ collision, _, _ := EmailTemplate(batch[:4], false)
+ if !strings.HasSuffix(collision, "+1 more") {
+ t.Fatalf("truncated hints collapsed full identities: %q", collision)
+ }
+ empty, _, _ := EmailTemplate(nil, false)
+ if strings.Contains(empty, "unknown host") || strings.Contains(empty, ": ") {
+ t.Fatalf("empty digest invented identity: %q", empty)
+ }
+}
+
+func readIdentityEmail(t *testing.T, raw []byte) (*mail.Message, string) {
+ t.Helper()
+ message, err := mail.ReadMessage(bytes.NewReader(raw))
+ if err != nil {
+ t.Fatal(err)
+ }
+ subject, err := new(mime.WordDecoder).DecodeHeader(message.Header.Get("Subject"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if message.Header.Get("Bcc") != "" || message.Header.Get("X-Injected") != "" {
+ t.Fatal("identity injected an email header")
+ }
+ if !utf8.ValidString(subject) {
+ t.Fatal("invalid decoded UTF-8")
+ }
+ for _, r := range subject {
+ if unicode.IsControl(r) {
+ t.Fatalf("subject retained control %U", r)
+ }
+ }
+ return message, subject
+}
+
+func TestEmailSubjectIdentityLiteralEncodedWord(t *testing.T) {
+ a := subjectIdentityAlert("=?UTF-8?q?different_host?=", alerts.AlertLevelWarning)
+ a.ResourceName = "=?UTF-8?q?different_resource?="
+ subject, html, text := EmailTemplate([]*alerts.Alert{a}, true)
+ manager := newEmailDeliveryManager(EmailConfig{From: "[email protected]"}, []string{"[email protected]"})
+ addresses, err := manager.resolveEmailAddresses()
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, attachments := range [][]EmailAttachment{nil, {{Filename: "report.txt", Data: []byte("safe")}}} {
+ raw, err := buildMultipartEmailMessageWithAttachments(addresses, subject, html, text, attachments, "", a.StartTime)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, decoded := readIdentityEmail(t, raw)
+ if decoded != subject {
+ t.Fatalf("literal name interpreted as MIME syntax: %q, want %q", decoded, subject)
+ }
+ }
+}
+
+func TestEmailSubjectIdentityMIME(t *testing.T) {
+ a := subjectIdentityAlert("docker-東京\r\nBcc: [email protected]", alerts.AlertLevelCritical)
+ a.ResourceName = "café-🚨\x00\t\r\nX-Injected: no"
+ a.NodeDisplayName = "Kitchen\nHouse"
+ a.Type = strings.Repeat("界", 100)
+ b := a.Clone()
+ b.Node = strings.Repeat("🚨", 100)
+ c := a.Clone()
+ c.Node = strings.Repeat("界", 100)
+ subject, html, text := EmailTemplate([]*alerts.Alert{a, b, c}, false)
+ for _, single := range []bool{false, true} {
+ if single {
+ subject, html, text = EmailTemplate([]*alerts.Alert{a}, true)
+ }
+ for _, attachments := range [][]EmailAttachment{nil, {{Filename: "report.txt", ContentType: "text/plain", Data: []byte("safe attachment")}}} {
+ manager := newEmailDeliveryManager(EmailConfig{From: "[email protected]"}, []string{"[email protected]"})
+ addresses, err := manager.resolveEmailAddresses()
+ if err != nil {
+ t.Fatal(err)
+ }
+ raw, err := buildMultipartEmailMessageWithAttachments(addresses, subject, html, text, attachments, alertListThreadID([]*alerts.Alert{a}), a.StartTime)
+ if err != nil {
+ t.Fatal(err)
+ }
+ parsed, decoded := readIdentityEmail(t, raw)
+ if decoded != subject {
+ t.Fatalf("MIME round trip = %q, want %q", decoded, subject)
+ }
+ header := strings.SplitN(string(raw), "\r\n\r\n", 2)[0]
+ if !strings.Contains(header, "=?UTF-8?q?") {
+ t.Fatal("Unicode identity not RFC 2047 encoded")
+ }
+ inSubject := false
+ for _, line := range strings.Split(header, "\r\n") {
+ if strings.HasPrefix(line, "Subject:") {
+ inSubject = true
+ } else if !strings.HasPrefix(line, " ") {
+ inSubject = false
+ }
+ if inSubject && len(line) > 78 {
+ t.Fatalf("unfolded subject line exceeds 78 bytes: %d", len(line))
+ }
+ }
+ media, params, err := mime.ParseMediaType(parsed.Header.Get("Content-Type"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if media != "multipart/alternative" && media != "multipart/mixed" {
+ t.Fatalf("incorrect MIME type %q", media)
+ }
+ reader := multipart.NewReader(parsed.Body, params["boundary"])
+ part, err := reader.NextPart()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(attachments) != 0 {
+ _, nested, err := mime.ParseMediaType(part.Header.Get("Content-Type"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ part, err = multipart.NewReader(part, nested["boundary"]).NextPart()
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ body, err := io.ReadAll(part)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(body) != normalizeEmailBodyLineEndings(text) {
+ t.Fatal("MIME identity repair changed full text body")
+ }
+ }
+ }
+}
+
+// Only in-memory net.Pipe connections: no listeners, provider, credentials,
+// induced alert or real SMTP. Capture the actual MIME send from the existing
+// normal single/grouped/resolved methods and their incident threading boundary.
+func captureSubjectEmails(t *testing.T) <-chan []byte {
+ t.Helper()
+ messages := make(chan []byte, 32)
+ var servers sync.WaitGroup
+ original := smtpDialTimeout
+ t.Cleanup(func() { smtpDialTimeout = original; servers.Wait() })
+ smtpDialTimeout = func(network, address string, timeout time.Duration) (net.Conn, error) {
+ if address != "smtp.example.test:25" {
+ t.Fatalf("unexpected transport address %q", address)
+ }
+ client, server := net.Pipe()
+ servers.Add(1)
+ go func() {
+ defer servers.Done()
+ defer server.Close()
+ _ = server.SetDeadline(time.Now().Add(5 * time.Second))
+ conn := textproto.NewConn(server)
+ if err := conn.PrintfLine("220 fixture ESMTP"); err != nil {
+ t.Error(err)
+ return
+ }
+ for {
+ line, err := conn.ReadLine()
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ fields := strings.Fields(line)
+ if len(fields) == 0 {
+ t.Error("empty SMTP command")
+ return
+ }
+ switch fields[0] {
+ case "EHLO", "HELO", "MAIL", "RCPT":
+ err = conn.PrintfLine("250 OK")
+ case "DATA":
+ if err = conn.PrintfLine("354 Send message"); err != nil {
+ t.Error(err)
+ return
+ }
+ raw, readErr := conn.ReadDotBytes()
+ if readErr != nil {
+ t.Error(readErr)
+ return
+ }
+ messages <- raw
+ err = conn.PrintfLine("250 Accepted by fixture")
+ case "QUIT":
+ _ = conn.PrintfLine("221 Bye")
+ return
+ default:
+ t.Errorf("unexpected command %q", fields[0])
+ return
+ }
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ }
+ }()
+ return client, nil
+ }
+ return messages
+}
+
+func TestEmailSubjectIdentityNormalSend(t *testing.T) {
+ messages := captureSubjectEmails(t)
+ config := EmailConfig{SMTPHost: "smtp.example.test", SMTPPort: 25, From: "[email protected]", To: []string{"[email protected]"}, RateLimit: 1000}
+ manager := &NotificationManager{}
+ batch := []*alerts.Alert{subjectIdentityAlert("docker-one", alerts.AlertLevelCritical),
+ subjectIdentityAlert("docker-two", alerts.AlertLevelWarning), subjectIdentityAlert("docker-three", alerts.AlertLevelInfo)}
+ check := func(want, thread string) {
+ t.Helper()
+ select {
+ case raw := <-messages:
+ parsed, subject := readIdentityEmail(t, raw)
+ if subject != want {
+ t.Fatalf("normal sent subject = %q, want %q", subject, want)
+ }
+ if parsed.Header.Get("References") != thread || parsed.Header.Get("In-Reply-To") != thread {
+ t.Fatal("identity changed occurrence threading")
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("normal send produced no MIME message")
+ }
+ }
+ for _, a := range batch {
+ if err := manager.sendSingleEmailWithError(a, config); err != nil {
+ t.Fatal(err)
+ }
+ check(fmt.Sprintf("[Pulse Alert] %s: CPU on nginx (%s)", titleCase(string(a.Level)), a.Node), alertThreadMessageID(a.ID, a.StartTime))
+ }
+ if err := manager.sendGroupedEmail(config, batch); err != nil {
+ t.Fatal(err)
+ }
+ check("[Pulse Alert] 1 Critical, 1 Warning, 1 Info alerts: nginx (docker-one), nginx (docker-three), nginx (docker-two)", "")
+ if err := manager.sendGroupedEmail(config, batch[:1]); err != nil {
+ t.Fatal(err)
+ }
+ thread := alertThreadMessageID(batch[0].ID, batch[0].StartTime)
+ check("[Pulse Alert] 1 Critical alert: nginx (docker-one)", thread)
+ if err := manager.sendResolvedEmail(config, batch[:1], time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ check("Pulse alert resolved: nginx (docker-one)", thread)
+ if err := manager.sendResolvedEmail(config, batch, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ check("Pulse alerts resolved (3): nginx (docker-one), nginx (docker-three), nginx (docker-two)", "")
+ moved := movedNodeMemoryAlert()
+ if err := manager.sendResolvedEmail(config, []*alerts.Alert{moved}, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ check("Pulse alert moved: pve1 (pve1)", alertThreadMessageID(moved.ID, moved.StartTime))
+ next := batch[0].Clone()
+ next.StartTime = next.StartTime.Add(time.Nanosecond)
+ if err := manager.sendSingleEmailWithError(next, config); err != nil {
+ t.Fatal(err)
+ }
+ nextThread := alertThreadMessageID(next.ID, next.StartTime)
+ if nextThread == thread {
+ t.Fatal("adjacent occurrence reused incident thread")
+ }
+ check("[Pulse Alert] Critical: CPU on nginx (docker-one)", nextThread)
+ if err := manager.sendResolvedEmail(config, nil, time.Now()); err == nil {
+ t.Fatal("empty resolution admitted")
+ }
+ if err := manager.sendResolvedEmail(config, []*alerts.Alert{nil}, time.Now()); err == nil {
+ t.Fatal("nil-only resolution admitted")
+ }
+ select {
+ case <-messages:
+ t.Fatal("unexpected extra message")
+ default:
+ }
+}
diff --git a/internal/notifications/email_template.go b/internal/notifications/email_template.go
index c7cadeb97d..4df623da25 100644
--- a/internal/notifications/email_template.go
+++ b/internal/notifications/email_template.go
@@ -90,7 +90,7 @@ func singleAlertTemplate(alert *alerts.Alert) (subject, htmlBody, textBody strin
alertType := alertTypeDisplay(alert.Type)
subject = fmt.Sprintf("[Pulse Alert] %s: %s on %s",
- titleCase(string(level)), alertType, alert.ResourceName)
+ titleCase(string(level)), boundEmailSubjectLabel(emailSubjectLabel(alertType)), emailSubjectIdentities([]*alerts.Alert{alert}))
escapedLevel := html.EscapeString(string(level))
escapedResourceName := html.EscapeString(alert.ResourceName)
@@ -316,6 +316,9 @@ func groupedAlertTemplate(alertList []*alerts.Alert) (subject, htmlBody, textBod
severityParts = append(severityParts, fmt.Sprintf("%d Info", info))
}
subject = fmt.Sprintf("[Pulse Alert] %s alert%s", strings.Join(severityParts, ", "), pluralize(len(alertList)))
+ if identities := emailSubjectIdentities(alertList); identities != "" {
+ subject += ": " + identities
+ }
// Build alert rows
var alertRows strings.Builder
diff --git a/internal/notifications/notifications.go b/internal/notifications/notifications.go
index 71f467b967..cf75adfa22 100644
--- a/internal/notifications/notifications.go
+++ b/internal/notifications/notifications.go
@@ -2199,6 +2199,7 @@ func (n *NotificationManager) sendResolvedEmail(config EmailConfig, alertList []
if subject == "" && textBody == "" {
return fmt.Errorf("failed to build resolved email content")
}
+ subject = resolvedEmailSubject(alertList)
return n.sendThreadedHTMLEmailWithError(subject, htmlBody, textBody, alertListThreadID(alertList), config)
}
diff --git a/internal/unifiedresources/views.go b/internal/unifiedresources/views.go
index ac2fe90a23..c3dc8112fc 100644
--- a/internal/unifiedresources/views.go
+++ b/internal/unifiedresources/views.go
@@ -773,6 +773,18 @@ func (v NodeView) Status() ResourceStatus {
return v.r.Status
}
+// SourceStatus returns the canonical delivery freshness recorded for one
+// source. A node row keeps an unreachable node's last readings, and a merged
+// row's status follows its highest-priority source, so consumers presenting
+// the row's readings as current must check the sightings here.
+func (v NodeView) SourceStatus(source DataSource) (SourceStatus, bool) {
+ if v.r == nil {
+ return SourceStatus{}, false
+ }
+ status, ok := v.r.SourceStatus[source]
+ return status, ok
+}
+
func (v NodeView) NodeName() string {
if v.r == nil || v.r.Proxmox == nil {
return ""
@@ -1876,6 +1888,18 @@ func (v DockerHostView) LastSeen() time.Time {
return v.r.LastSeen
}
+// SourceStatus returns the canonical delivery freshness recorded for one
+// source. The registry marks a Docker host's source stale once its report is
+// overdue while the row keeps the last report, so consumers presenting the
+// row's readings or its containers' as current must check the source here.
+func (v DockerHostView) SourceStatus(source DataSource) (SourceStatus, bool) {
+ if v.r == nil {
+ return SourceStatus{}, false
+ }
+ status, ok := v.r.SourceStatus[source]
+ return status, ok
+}
+
func (v DockerHostView) CPUPercent() float64 {
if v.r == nil {
return 0
diff --git a/internal/unifiedresources/views_test.go b/internal/unifiedresources/views_test.go
index 8c8bcc98cc..725c0308ce 100644
--- a/internal/unifiedresources/views_test.go
+++ b/internal/unifiedresources/views_test.go
@@ -972,6 +972,91 @@ func TestView_HostViewSourceStatusSeparatesAgentFromMergedRow(t *testing.T) {
}
}
+// A node merged with a linked host agent takes the agent's status, so a
+// consumer judging whether the node's readings are current needs each
+// source's own sighting.
+func TestView_NodeViewSourceStatusSeparatesMergedSources(t *testing.T) {
+ now := time.Now().UTC()
+ agentLastReport := now.Add(-30 * time.Minute)
+ registry := NewRegistry(nil)
+ registry.IngestSnapshot(models.StateSnapshot{
+ Nodes: []models.Node{{
+ ID: "pve1-node1", Name: "node1", Instance: "pve1", Status: "online",
+ LastSeen: now, LinkedAgentID: "agent-1",
+ }},
+ Hosts: []models.Host{{
+ ID: "agent-1", Hostname: "node1", Status: "offline", LinkedNodeID: "pve1-node1",
+ IntervalSeconds: 30, LastSeen: agentLastReport,
+ }},
+ })
+
+ nodes := registry.Nodes()
+ if len(nodes) != 1 {
+ t.Fatalf("expected the agent and node to merge into one node row, got %d", len(nodes))
+ }
+ node := nodes[0]
+ if sighting, ok := node.SourceStatus(SourceProxmox); !ok || sighting.Status != "online" || !sighting.LastSeen.Equal(now) {
+ t.Fatalf("Proxmox sighting = %+v (ok=%v), want online at %v", sighting, ok, now)
+ }
+ if sighting, ok := node.SourceStatus(SourceAgent); !ok || sighting.Status != "stale" || !sighting.LastSeen.Equal(agentLastReport) {
+ t.Fatalf("agent sighting = %+v (ok=%v), want stale at %v", sighting, ok, agentLastReport)
+ }
+ if _, ok := node.SourceStatus(SourceDocker); ok {
+ t.Fatal("a source that never reported must not have a status")
+ }
+
+ var nilView NodeView
+ if _, ok := nilView.SourceStatus(SourceProxmox); ok {
+ t.Fatal("nil-backed view must report no source status")
+ }
+}
+
+// A Docker host past its reporting lease stays offline even after its source
+// sighting goes stale; a degraded host that still reports remains warning.
+// Preserve both the current row policy and each source's original receipt time.
+func TestView_DockerHostViewSourceStatusSeparatesSilentFromDegraded(t *testing.T) {
+ now := time.Now().UTC()
+ registry := NewRegistry(nil)
+ registry.IngestSnapshot(models.StateSnapshot{
+ DockerHosts: []models.DockerHost{
+ {ID: "docker-silent", AgentID: "agent-silent", Hostname: "silent", Status: "offline", IntervalSeconds: 30, LastSeen: now.Add(-time.Hour), CPUUsage: 20},
+ {ID: "docker-degraded", AgentID: "agent-degraded", Hostname: "degraded", Status: "degraded", IntervalSeconds: 30, LastSeen: now, CPUUsage: 33},
+ },
+ })
+
+ views := make(map[string]*DockerHostView)
+ for _, view := range registry.DockerHosts() {
+ views[view.HostSourceID()] = view
+ }
+ for id, want := range map[string]struct {
+ row ResourceStatus
+ source string
+ seen time.Time
+ }{
+ "docker-silent": {StatusOffline, "stale", now.Add(-time.Hour)},
+ "docker-degraded": {StatusWarning, "online", now},
+ } {
+ view := views[id]
+ if view == nil {
+ t.Fatalf("missing Docker host view %s", id)
+ }
+ if view.Status() != want.row {
+ t.Fatalf("%s status = %q, want %q", id, view.Status(), want.row)
+ }
+ if sighting, ok := view.SourceStatus(SourceDocker); !ok || sighting.Status != want.source || !sighting.LastSeen.Equal(want.seen) {
+ t.Fatalf("%s Docker sighting = %+v (ok=%v), want %s at %s", id, sighting, ok, want.source, want.seen)
+ }
+ }
+ if _, ok := views["docker-degraded"].SourceStatus(SourceProxmox); ok {
+ t.Fatal("a source that never reported must not have a status")
+ }
+
+ var nilView DockerHostView
+ if _, ok := nilView.SourceStatus(SourceDocker); ok {
+ t.Fatal("nil-backed view must report no source status")
+ }
+}
+
func TestView_HostViewMetricsTargetAccessor(t *testing.T) {
r := &Resource{
ID: "host-metrics",