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.

Link alert notifications to the alert in Pulse

rcourtmanc40051c8095c
diff --git a/docs/WEBHOOKS.md b/docs/WEBHOOKS.md
index 0356b8e132..318158d2bd 100644
--- a/docs/WEBHOOKS.md
+++ b/docs/WEBHOOKS.md
@@ -39,6 +39,7 @@ For generic webhooks, use Go templates to format the JSON payload.
- `{{.ResourceName}}`, `{{.ResourceID}}`, `{{.ResourceType}}`, `{{.Node}}`, `{{.NodeDisplayName}}`
- `{{.Message}}`, `{{.Value}}`, `{{.Threshold}}`, `{{.Duration}}`, `{{.Timestamp}}`
- `{{.Instance}}` (Pulse public URL if configured)
+- `{{.AlertURL}}` (opens the alert in Pulse's Alert History, or the Alerts page for a grouped notification; falls back to `{{.Instance}}` when no public URL is configured)
- `{{.TenantID}}`, `{{.TenantName}}` (tenant identity in multi-tenant orgs and MSP client runtimes; empty on plain single-tenant installs)
- `{{.CustomFields.<name>}}` (user-defined fields in the UI)
- `{{.Metadata}}` (alert metadata map)
diff --git a/docs/release-control/v6/internal/subsystems/notifications.md b/docs/release-control/v6/internal/subsystems/notifications.md
index 24e0f774a0..4c30ccd353 100644
--- a/docs/release-control/v6/internal/subsystems/notifications.md
+++ b/docs/release-control/v6/internal/subsystems/notifications.md
@@ -1424,6 +1424,28 @@ 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.
+### Notifications link to the alert they report
+
+With a public URL configured, a notification links to the alert itself rather
+than to Pulse's front page: `alertHistoryURL` builds
+`/alerts/history?alert=<id>`, the address the frontend opens one alert at
+(`buildAlertHistoryAlertPath`); a Patrol finding, which reaches notifications
+as a synthetic alert History never stores, links to the Patrol page
+(`alertLinkURL`), as does a batch made only of findings; and `alertsPageURL`
+links any other grouped
+notification to the Alerts overview while its alerts fire and to Alert
+History once they resolve. Single emails end with "View this alert in
+Pulse"; grouped emails link each alert's name and point their footer at the
+overview. Apprise and resolved text add a "View in Pulse" line per alert next
+to the existing Dashboard line. Webhook templates get `{{.AlertURL}}` (the
+alert link, the grouped page link, or the existing `{{.Instance}}` fallback
+without a public URL); the built-in Telegram, Slack, Teams, PagerDuty, Teams
+Adaptive Card, Gotify, ntfy and Mattermost templates link it and say "View in
+Pulse" where they said "View in Proxmox", and the default JSON payloads add
+`alertUrl`. `{{.Instance}}` keeps its meaning, so custom templates are
+unchanged. The link carries only the alert id already present in every
+payload (`alert_links_test.go`).
+
### SMTP editor settings follow the public configuration
The existing Email notification form offers only settings accepted by its
diff --git a/frontend-modern/public/docs/WEBHOOKS.md b/frontend-modern/public/docs/WEBHOOKS.md
index 0356b8e132..318158d2bd 100644
--- a/frontend-modern/public/docs/WEBHOOKS.md
+++ b/frontend-modern/public/docs/WEBHOOKS.md
@@ -39,6 +39,7 @@ For generic webhooks, use Go templates to format the JSON payload.
- `{{.ResourceName}}`, `{{.ResourceID}}`, `{{.ResourceType}}`, `{{.Node}}`, `{{.NodeDisplayName}}`
- `{{.Message}}`, `{{.Value}}`, `{{.Threshold}}`, `{{.Duration}}`, `{{.Timestamp}}`
- `{{.Instance}}` (Pulse public URL if configured)
+- `{{.AlertURL}}` (opens the alert in Pulse's Alert History, or the Alerts page for a grouped notification; falls back to `{{.Instance}}` when no public URL is configured)
- `{{.TenantID}}`, `{{.TenantName}}` (tenant identity in multi-tenant orgs and MSP client runtimes; empty on plain single-tenant installs)
- `{{.CustomFields.<name>}}` (user-defined fields in the UI)
- `{{.Metadata}}` (alert metadata map)
diff --git a/internal/notifications/alert_links.go b/internal/notifications/alert_links.go
new file mode 100644
index 0000000000..c4d4a16523
--- /dev/null
+++ b/internal/notifications/alert_links.go
@@ -0,0 +1,96 @@
+package notifications
+
+import (
+ "net/url"
+ "strings"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts"
+)
+
+// The Pulse routes notifications link to. The frontend owns the same
+// addresses (ALERT_HISTORY_PATH and buildAlertHistoryAlertPath in
+// frontend-modern/src/routing/resourceLinks.ts): the `alert` parameter opens
+// Alert History narrowed to that alert with its latest timeline open.
+const (
+ alertHistoryPath = "/alerts/history"
+ alertHistoryAlertKey = "alert"
+ alertsOverviewPath = "/alerts/overview"
+ // Patrol findings reach notifications as synthetic alerts that Alert
+ // History never stores, so they link to the Patrol page instead.
+ patrolPath = "/patrol"
+)
+
+func trimmedPublicURL(publicURL string) string {
+ return strings.TrimRight(strings.TrimSpace(publicURL), "/")
+}
+
+// alertHistoryURL is the Pulse address that opens one alert in Alert
+// History. It is empty when no public URL is configured or the alert has no
+// identifier, so callers keep their existing fallback.
+func alertHistoryURL(publicURL, alertID string) string {
+ base := trimmedPublicURL(publicURL)
+ id := strings.TrimSpace(alertID)
+ if base == "" || id == "" {
+ return ""
+ }
+ return base + alertHistoryPath + "?" + url.Values{alertHistoryAlertKey: {id}}.Encode()
+}
+
+// alertLinkURL is the Pulse address for one notified alert: its Alert
+// History entry, or the Patrol page for a Patrol finding.
+func alertLinkURL(publicURL string, alert *alerts.Alert) string {
+ if alert == nil {
+ return ""
+ }
+ if isPatrolFindingAlert(alert) {
+ if base := trimmedPublicURL(publicURL); base != "" {
+ return base + patrolPath
+ }
+ return ""
+ }
+ return alertHistoryURL(publicURL, alert.ID)
+}
+
+// alertsPageURL is where a notification about these alerts links: one alert
+// opens in Alert History; several open the page that lists them, the
+// overview while they fire and History once they have resolved.
+func alertsPageURL(publicURL string, alertList []*alerts.Alert, resolved bool) string {
+ base := trimmedPublicURL(publicURL)
+ if base == "" {
+ return ""
+ }
+ var only *alerts.Alert
+ count, findings := 0, 0
+ for _, alert := range alertList {
+ if alert == nil {
+ continue
+ }
+ count++
+ if isPatrolFindingAlert(alert) {
+ findings++
+ }
+ only = alert
+ }
+ if count == 1 {
+ if link := alertLinkURL(base, only); link != "" {
+ return link
+ }
+ }
+ // A batch of Patrol findings alone lists nowhere under Alerts.
+ if count > 0 && findings == count {
+ return base + patrolPath
+ }
+ if resolved {
+ return base + alertHistoryPath
+ }
+ return base + alertsOverviewPath
+}
+
+func firstNonEmpty(values ...string) string {
+ for _, value := range values {
+ if value != "" {
+ return value
+ }
+ }
+ return ""
+}
diff --git a/internal/notifications/alert_links_test.go b/internal/notifications/alert_links_test.go
new file mode 100644
index 0000000000..5e413bd88c
--- /dev/null
+++ b/internal/notifications/alert_links_test.go
@@ -0,0 +1,197 @@
+package notifications
+
+import (
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts"
+)
+
+// Notifications link into Pulse with the address the frontend opens one alert
+// at (buildAlertHistoryAlertPath in frontend-modern/src/routing/resourceLinks.ts).
+func TestAlertHistoryURLMatchesTheFrontendAddress(t *testing.T) {
+ got := alertHistoryURL("https://pulse.example/ ", "docker:host/web app::health")
+ want := "https://pulse.example/alerts/history?alert=docker%3Ahost%2Fweb+app%3A%3Ahealth"
+ if got != want {
+ t.Fatalf("alertHistoryURL = %q, want %q", got, want)
+ }
+ if alertHistoryURL("", "a-1") != "" || alertHistoryURL("https://pulse.example", " ") != "" {
+ t.Fatal("alertHistoryURL must be empty without a public URL or an alert id")
+ }
+}
+
+func TestAlertsPageURLLinksOneAlertOrTheListingPage(t *testing.T) {
+ one := []*alerts.Alert{{ID: "a-1"}}
+ two := []*alerts.Alert{{ID: "a-1"}, nil, {ID: "a-2"}}
+ base := "https://pulse.example"
+ if got := alertsPageURL(base, one, false); got != base+"/alerts/history?alert=a-1" {
+ t.Fatalf("single alert link = %q", got)
+ }
+ if got := alertsPageURL(base, two, false); got != base+"/alerts/overview" {
+ t.Fatalf("grouped firing link = %q", got)
+ }
+ if got := alertsPageURL(base, two, true); got != base+"/alerts/history" {
+ t.Fatalf("grouped resolved link = %q", got)
+ }
+ if got := alertsPageURL("", one, false); got != "" {
+ t.Fatalf("link without a public URL = %q", got)
+ }
+}
+
+func linkTestAlert(id, resource string) *alerts.Alert {
+ return &alerts.Alert{
+ ID: id,
+ Type: "cpu",
+ Level: alerts.AlertLevelWarning,
+ ResourceID: resource,
+ ResourceName: resource,
+ Node: "pve1",
+ Message: "CPU above threshold",
+ Value: 91,
+ Threshold: 80,
+ StartTime: time.Now().Add(-5 * time.Minute),
+ }
+}
+
+func TestAlertEmailsLinkEachAlertIntoPulse(t *testing.T) {
+ base := "https://pulse.example"
+ alert := linkTestAlert("vm-101-cpu", "web-01")
+ link := base + "/alerts/history?alert=vm-101-cpu"
+
+ _, htmlBody, textBody := EmailTemplate([]*alerts.Alert{alert}, true, base)
+ if !strings.Contains(htmlBody, `<a href="`+link+`">View this alert in Pulse</a>`) {
+ t.Fatalf("single email HTML lacks the alert link:\n%s", htmlBody)
+ }
+ if !strings.Contains(textBody, "View this alert in Pulse: "+link) {
+ t.Fatalf("single email text lacks the alert link:\n%s", textBody)
+ }
+
+ second := linkTestAlert("vm-102-cpu", "web-02")
+ _, htmlBody, textBody = EmailTemplate([]*alerts.Alert{alert, second}, false, base)
+ for _, want := range []string{
+ `<a href="` + link + `" style="color: #1a1a1a;">web-01</a>`,
+ `<a href="` + base + `/alerts/history?alert=vm-102-cpu" style="color: #1a1a1a;">web-02</a>`,
+ `<a href="` + base + `/alerts/overview">Open these alerts in Pulse</a>`,
+ } {
+ if !strings.Contains(htmlBody, want) {
+ t.Fatalf("grouped email HTML lacks %q", want)
+ }
+ }
+ if !strings.Contains(textBody, " View in Pulse: "+link) ||
+ !strings.Contains(textBody, "Open these alerts in Pulse: "+base+"/alerts/overview") {
+ t.Fatalf("grouped email text lacks its links:\n%s", textBody)
+ }
+
+ // Without a public URL the emails keep their old pointer and no links.
+ _, htmlBody, textBody = EmailTemplate([]*alerts.Alert{alert}, true, "")
+ if strings.Contains(htmlBody, "/alerts/history") ||
+ !strings.Contains(textBody, "View alerts and configure settings in your Pulse dashboard.") {
+ t.Fatal("email without a public URL changed its footer")
+ }
+}
+
+func TestWebhookPayloadsCarryTheAlertLink(t *testing.T) {
+ n := NewNotificationManager("https://pulse.example")
+ defer n.Stop()
+ alert := linkTestAlert("vm-101-cpu", "web-01")
+ data := n.prepareWebhookData(alert, nil)
+ if data.AlertURL != "https://pulse.example/alerts/history?alert=vm-101-cpu" {
+ t.Fatalf("AlertURL = %q", data.AlertURL)
+ }
+
+ bare := NewNotificationManager("")
+ defer bare.Stop()
+ alert.Instance = "https://pve.example:8006"
+ if got := bare.prepareWebhookData(alert, nil).AlertURL; got != alert.Instance {
+ t.Fatalf("AlertURL without a public URL = %q, want the Instance fallback", got)
+ }
+
+ // Every built-in template that links back to Pulse links to the alert.
+ linked := 0
+ data.AlertURL = "https://pulse.example/alerts/history?alert=LINK"
+ for _, tmpl := range GetWebhookTemplates() {
+ for _, source := range []string{tmpl.PayloadTemplate, tmpl.ResolvedPayloadTemplate} {
+ if strings.Contains(source, "View in Proxmox") {
+ t.Fatalf("template %q still labels its Pulse link as Proxmox", tmpl.Service)
+ }
+ if !strings.Contains(source, ".AlertURL") {
+ continue
+ }
+ payload, err := n.generatePayloadFromTemplateWithService(source, data, tmpl.Service)
+ if err != nil {
+ t.Fatalf("template %q: %v", tmpl.Service, err)
+ }
+ linked++
+ if !strings.Contains(string(payload), "alerts/history?alert=LINK") {
+ t.Fatalf("template %q does not link to the alert:\n%s", tmpl.Service, payload)
+ }
+ }
+ }
+ if linked < 8 {
+ t.Fatalf("only %d built-in templates link to the alert, want at least 8", linked)
+ }
+}
+
+func TestTextNotificationsLinkEachAlert(t *testing.T) {
+ base := "https://pulse.example"
+ alert := linkTestAlert("vm-101-cpu", "web-01")
+ link := "View in Pulse: " + base + "/alerts/history?alert=vm-101-cpu"
+
+ _, body, _ := buildApprisePayload([]*alerts.Alert{alert}, base)
+ if !strings.Contains(body, link) {
+ t.Fatalf("Apprise body lacks the alert link:\n%s", body)
+ }
+ _, _, textBody := buildResolvedNotificationContent([]*alerts.Alert{alert}, time.Now(), base)
+ if !strings.Contains(textBody, link) {
+ t.Fatalf("resolved body lacks the alert link:\n%s", textBody)
+ }
+}
+
+// Patrol findings reach notifications as synthetic alerts Alert History never
+// stores; a link to History would open its "no longer in history" state.
+func TestPatrolFindingNotificationsLinkToPatrol(t *testing.T) {
+ base := "https://pulse.example"
+ finding := linkTestAlert("patrol-finding-f-1", "db-01")
+ finding.Type = "patrol_finding"
+
+ if got := alertLinkURL(base, finding); got != base+"/patrol" {
+ t.Fatalf("finding link = %q, want the Patrol page", got)
+ }
+ if got := alertsPageURL(base, []*alerts.Alert{finding}, false); got != base+"/patrol" {
+ t.Fatalf("single finding page link = %q", got)
+ }
+
+ n := NewNotificationManager(base)
+ defer n.Stop()
+ if got := n.prepareWebhookData(finding, nil).AlertURL; got != base+"/patrol" {
+ t.Fatalf("finding webhook AlertURL = %q", got)
+ }
+ _, htmlBody, _ := EmailTemplate([]*alerts.Alert{finding}, true, base)
+ if strings.Contains(htmlBody, "/alerts/history") || !strings.Contains(htmlBody, `href="`+base+`/patrol"`) {
+ t.Fatalf("finding email does not link to Patrol:\n%s", htmlBody)
+ }
+ _, body, _ := buildApprisePayload([]*alerts.Alert{finding}, base)
+ if strings.Contains(body, "/alerts/history") {
+ t.Fatalf("finding Apprise body links to Alert History:\n%s", body)
+ }
+
+ // Two findings grouped together still belong to Patrol; a batch that
+ // also holds a real alert links to the Alerts page that lists it.
+ other := linkTestAlert("patrol-finding-f-2", "db-02")
+ other.Type = "patrol_finding"
+ pair := []*alerts.Alert{finding, other}
+ for _, resolved := range []bool{false, true} {
+ if got := alertsPageURL(base, pair, resolved); got != base+"/patrol" {
+ t.Fatalf("grouped findings page link (resolved=%v) = %q", resolved, got)
+ }
+ }
+ _, htmlBody, _ = EmailTemplate(pair, false, base)
+ if !strings.Contains(htmlBody, `<a href="`+base+`/patrol">Open these alerts in Pulse</a>`) {
+ t.Fatalf("grouped findings email footer does not link to Patrol:\n%s", htmlBody)
+ }
+ mixed := []*alerts.Alert{finding, linkTestAlert("vm-101-cpu", "web-01")}
+ if got := alertsPageURL(base, mixed, false); got != base+"/alerts/overview" {
+ t.Fatalf("mixed batch page link = %q", got)
+ }
+}
diff --git a/internal/notifications/email_subject_identity_test.go b/internal/notifications/email_subject_identity_test.go
index 32dc50d838..5b1c3501ab 100644
--- a/internal/notifications/email_subject_identity_test.go
+++ b/internal/notifications/email_subject_identity_test.go
@@ -46,7 +46,7 @@ func TestEmailSubjectIdentitySingle(t *testing.T) {
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)
+ subject, html, text := EmailTemplate([]*alerts.Alert{a}, true, "")
if subject != tc.want {
t.Fatalf("subject = %q, want %q", subject, tc.want)
}
@@ -67,7 +67,7 @@ func TestEmailSubjectIdentityDigest(t *testing.T) {
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)
+ subject, html, text := EmailTemplate(batch, false, "")
if subject != want {
t.Fatalf("subject = %q, want %q", subject, want)
}
@@ -77,11 +77,11 @@ func TestEmailSubjectIdentityDigest(t *testing.T) {
}
}
reversed := []*alerts.Alert{batch[2], batch[1], batch[0]}
- reordered, _, _ := EmailTemplate(reversed, false)
+ reordered, _, _ := EmailTemplate(reversed, false, "")
if reordered != subject {
t.Fatalf("same identities changed subject on reorder: %q", reordered)
}
- one, _, _ := EmailTemplate(batch[:1], false)
+ one, _, _ := EmailTemplate(batch[:1], false, "")
if one != "[Pulse Alert] 1 Info alert: nginx (Kitchen [docker-three])" {
t.Fatalf("one-alert digest = %q", one)
}
@@ -98,7 +98,7 @@ func TestEmailSubjectIdentityBounds(t *testing.T) {
// 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)
+ 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)
}
@@ -121,11 +121,11 @@ func TestEmailSubjectIdentityBounds(t *testing.T) {
for i := range batch[:4] {
batch[i].Node, batch[i].NodeDisplayName = strings.Repeat("x", 100)+fmt.Sprint(i), ""
}
- collision, _, _ := EmailTemplate(batch[:4], false)
+ collision, _, _ := EmailTemplate(batch[:4], false, "")
if !strings.HasSuffix(collision, "+1 more") {
t.Fatalf("truncated hints collapsed full identities: %q", collision)
}
- empty, _, _ := EmailTemplate(nil, false)
+ empty, _, _ := EmailTemplate(nil, false, "")
if strings.Contains(empty, "unknown host") || strings.Contains(empty, ": ") {
t.Fatalf("empty digest invented identity: %q", empty)
}
@@ -158,7 +158,7 @@ func readIdentityEmail(t *testing.T, raw []byte) (*mail.Message, string) {
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)
+ subject, html, text := EmailTemplate([]*alerts.Alert{a}, true, "")
manager := newEmailDeliveryManager(EmailConfig{From: "[email protected]"}, []string{"[email protected]"})
addresses, err := manager.resolveEmailAddresses()
if err != nil {
@@ -185,10 +185,10 @@ func TestEmailSubjectIdentityMIME(t *testing.T) {
b.Node = strings.Repeat("🚨", 100)
c := a.Clone()
c.Node = strings.Repeat("η•Œ", 100)
- subject, html, text := EmailTemplate([]*alerts.Alert{a, b, c}, false)
+ 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)
+ 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]"})
diff --git a/internal/notifications/email_template.go b/internal/notifications/email_template.go
index 4df623da25..b354f461ce 100644
--- a/internal/notifications/email_template.go
+++ b/internal/notifications/email_template.go
@@ -66,15 +66,28 @@ func patrolFindingCategory(alert *alerts.Alert) string {
return titleCase(strings.TrimSpace(category))
}
-// EmailTemplate generates a professional HTML email template for alerts
-func EmailTemplate(alertList []*alerts.Alert, isSingle bool) (subject, htmlBody, textBody string) {
+// EmailTemplate generates a professional HTML email template for alerts.
+// With a public URL, each alert links to its page in Pulse.
+func EmailTemplate(alertList []*alerts.Alert, isSingle bool, publicURL string) (subject, htmlBody, textBody string) {
if isSingle && len(alertList) == 1 {
- return singleAlertTemplate(alertList[0])
+ return singleAlertTemplate(alertList[0], publicURL)
}
- return groupedAlertTemplate(alertList)
+ return groupedAlertTemplate(alertList, publicURL)
}
-func singleAlertTemplate(alert *alerts.Alert) (subject, htmlBody, textBody string) {
+// emailFooterLinks is the closing line of an alert email: a link into Pulse
+// when a public URL is configured, the old pointer to the dashboard without.
+func emailFooterLinks(link, label string) (footerHTML, footerText string) {
+ if link == "" {
+ return "<p>View alerts and configure settings in your Pulse dashboard</p>",
+ "View alerts and configure settings in your Pulse dashboard."
+ }
+ return fmt.Sprintf(`<p><a href="%s">%s</a></p>`, html.EscapeString(link), html.EscapeString(label)),
+ label + ": " + link
+}
+
+func singleAlertTemplate(alert *alerts.Alert, publicURL string) (subject, htmlBody, textBody string) {
+ footerHTML, footerText := emailFooterLinks(alertLinkURL(publicURL, alert), "View this alert in Pulse")
level := alerts.NormalizeAlertLevel(alert.Level)
levelColor := "#3b82f6"
levelBg := "#eff6ff"
@@ -200,7 +213,7 @@ func singleAlertTemplate(alert *alerts.Alert) (subject, htmlBody, textBody strin
</div>
<div class="footer">
<p>This is an automated notification from Pulse Monitoring</p>
- <p>View alerts and configure settings in your Pulse dashboard</p>
+ %s
</div>
</div>
</body>
@@ -216,6 +229,7 @@ func singleAlertTemplate(alert *alerts.Alert) (subject, htmlBody, textBody strin
escapedInstance,
escapedStarted,
escapedDuration,
+ footerHTML,
)
if isPatrolFindingAlert(alert) {
@@ -234,7 +248,7 @@ Details:
- Duration: %s
This is an automated notification from Pulse Monitoring.
-View alerts and configure settings in your Pulse dashboard.`,
+%s`,
strings.ToUpper(string(level)),
alert.ResourceName,
alert.ResourceName,
@@ -245,6 +259,7 @@ View alerts and configure settings in your Pulse dashboard.`,
alert.Instance,
formatAlertStartTime(alert.StartTime),
formatDuration(time.Since(alert.StartTime)),
+ footerText,
)
return subject, htmlBody, textBody
}
@@ -265,7 +280,7 @@ Details:
- Duration: %s
This is an automated notification from Pulse Monitoring.
-View alerts and configure settings in your Pulse dashboard.`,
+%s`,
strings.ToUpper(string(level)),
alert.ResourceName,
alert.ResourceName,
@@ -278,12 +293,14 @@ View alerts and configure settings in your Pulse dashboard.`,
alert.Instance,
formatAlertStartTime(alert.StartTime),
formatDuration(time.Since(alert.StartTime)),
+ footerText,
)
return subject, htmlBody, textBody
}
-func groupedAlertTemplate(alertList []*alerts.Alert) (subject, htmlBody, textBody string) {
+func groupedAlertTemplate(alertList []*alerts.Alert, publicURL string) (subject, htmlBody, textBody string) {
+ footerHTML, footerText := emailFooterLinks(alertsPageURL(publicURL, alertList, false), "Open these alerts in Pulse")
critical := 0
warning := 0
info := 0
@@ -333,6 +350,10 @@ func groupedAlertTemplate(alertList []*alerts.Alert) (subject, htmlBody, textBod
}
escapedResourceName := html.EscapeString(alert.ResourceName)
+ nameHTML := escapedResourceName
+ if link := alertLinkURL(publicURL, alert); link != "" {
+ nameHTML = fmt.Sprintf(`<a href="%s" style="color: #1a1a1a;">%s</a>`, html.EscapeString(link), escapedResourceName)
+ }
escapedType := html.EscapeString(alert.Type)
escapedNode := html.EscapeString(alertNodeDisplay(alert))
escapedLevel := html.EscapeString(string(level))
@@ -374,7 +395,7 @@ func groupedAlertTemplate(alertList []*alerts.Alert) (subject, htmlBody, textBod
</td>
</tr>`,
levelColor,
- escapedResourceName,
+ nameHTML,
escapedDetail,
levelColor, escapedLevel,
value,
@@ -477,11 +498,11 @@ func groupedAlertTemplate(alertList []*alerts.Alert) (subject, htmlBody, textBod
</div>
<div class="footer">
<p>This is an automated notification from Pulse Monitoring</p>
- <p>View alerts and configure settings in your Pulse dashboard</p>
+ %s
</div>
</div>
</body>
-</html>`, valueHeading, alertRows.String())
+</html>`, valueHeading, alertRows.String(), footerHTML)
// Plain text version
var textBuilder strings.Builder
@@ -508,11 +529,14 @@ func groupedAlertTemplate(alertList []*alerts.Alert) (subject, htmlBody, textBod
}
textBuilder.WriteString(fmt.Sprintf(" Node: %s | Started: %s ago\n", alertNodeDisplay(alert), formatDuration(time.Since(alert.StartTime))))
textBuilder.WriteString(fmt.Sprintf(" Message: %s\n", alert.Message))
+ if link := alertLinkURL(publicURL, alert); link != "" {
+ textBuilder.WriteString(" View in Pulse: " + link + "\n")
+ }
}
textBuilder.WriteString("\n─────────────────────────────────────────────────────────────\n")
textBuilder.WriteString("This is an automated notification from Pulse Monitoring.\n")
- textBuilder.WriteString("Configure alert settings in the Pulse dashboard.")
+ textBuilder.WriteString(footerText)
textBody = textBuilder.String()
return subject, htmlBody, textBody
diff --git a/internal/notifications/email_template_test.go b/internal/notifications/email_template_test.go
index a4d0c27c9f..5cd3bf0aa7 100644
--- a/internal/notifications/email_template_test.go
+++ b/internal/notifications/email_template_test.go
@@ -687,7 +687,7 @@ func TestEmailTemplate(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
- subject, htmlBody, textBody := EmailTemplate(tt.alerts, tt.isSingle)
+ subject, htmlBody, textBody := EmailTemplate(tt.alerts, tt.isSingle, "")
// Check subject contains expected content
if !strings.Contains(subject, tt.subjectContains) {
@@ -727,7 +727,7 @@ func TestGroupedEmailTemplatePreservesInformationalSeverity(t *testing.T) {
{ID: "info", Level: alerts.AlertLevelInfo, ResourceName: "host", Type: "system_update", StartTime: time.Now()},
{ID: "warning", Level: alerts.AlertLevelWarning, ResourceName: "vm", Type: "cpu", StartTime: time.Now()},
}
- subject, htmlBody, textBody := EmailTemplate(alertList, false)
+ subject, htmlBody, textBody := EmailTemplate(alertList, false, "")
if !strings.Contains(subject, "1 Warning, 1 Info alerts") {
t.Fatalf("subject = %q, want both represented severities", subject)
@@ -741,7 +741,7 @@ func TestEmailTemplateFailsUnknownSeveritySafeToWarning(t *testing.T) {
t.Parallel()
alert := &alerts.Alert{ID: "unknown", Level: "unexpected", ResourceName: "host", Type: "system", StartTime: time.Now()}
- subject, htmlBody, textBody := EmailTemplate([]*alerts.Alert{alert}, true)
+ subject, htmlBody, textBody := EmailTemplate([]*alerts.Alert{alert}, true, "")
if !strings.Contains(subject, "Warning") || !strings.Contains(htmlBody, "warning Alert") || !strings.Contains(textBody, "WARNING ALERT") {
t.Fatalf("unknown severity did not fail safe to warning: subject=%q text=%q", subject, textBody)
@@ -765,7 +765,7 @@ func TestEmailTemplateEscapesHTMLContent(t *testing.T) {
StartTime: time.Now().Add(-5 * time.Minute),
}
- _, htmlBody, textBody := EmailTemplate([]*alerts.Alert{alert}, true)
+ _, htmlBody, textBody := EmailTemplate([]*alerts.Alert{alert}, true, "")
if strings.Contains(htmlBody, "<script>") {
t.Fatalf("html body should escape script tags, got %q", htmlBody)
@@ -798,7 +798,7 @@ func TestEmailTemplatePatrolFindingShowsFindingInsteadOfMetrics(t *testing.T) {
}
t.Run("grouped", func(t *testing.T) {
- _, htmlBody, textBody := EmailTemplate([]*alerts.Alert{alert}, false)
+ _, htmlBody, textBody := EmailTemplate([]*alerts.Alert{alert}, false, "")
if !strings.Contains(htmlBody, alert.Message) {
t.Fatalf("grouped HTML omitted finding title: %q", htmlBody)
@@ -818,7 +818,7 @@ func TestEmailTemplatePatrolFindingShowsFindingInsteadOfMetrics(t *testing.T) {
})
t.Run("single", func(t *testing.T) {
- subject, htmlBody, textBody := EmailTemplate([]*alerts.Alert{alert}, true)
+ subject, htmlBody, textBody := EmailTemplate([]*alerts.Alert{alert}, true, "")
if !strings.Contains(subject, "Patrol Finding") {
t.Fatalf("single subject = %q, want Patrol Finding", subject)
@@ -847,7 +847,7 @@ func TestEmailTemplateGroupedPatrolFindingEscapesFindingContent(t *testing.T) {
Metadata: map[string]interface{}{"category": `<script>alert("category")</script>`},
}
- _, htmlBody, _ := EmailTemplate([]*alerts.Alert{alert}, false)
+ _, htmlBody, _ := EmailTemplate([]*alerts.Alert{alert}, false, "")
if strings.Contains(htmlBody, "<script>") || strings.Contains(htmlBody, `<img src=x onerror="alert(1)">`) {
t.Fatalf("grouped Patrol HTML did not escape finding content: %q", htmlBody)
}
diff --git a/internal/notifications/grouped_rendering_contract_test.go b/internal/notifications/grouped_rendering_contract_test.go
index 70df6d96ed..373764691a 100644
--- a/internal/notifications/grouped_rendering_contract_test.go
+++ b/internal/notifications/grouped_rendering_contract_test.go
@@ -67,7 +67,7 @@ func assertEveryAlertNamed(t *testing.T, surface, rendered string, batch []*aler
func TestContractGroupedEmailRendersEveryAlert(t *testing.T) {
batch := contractGroupedAlerts()
- subject, htmlBody, textBody := groupedAlertTemplate(batch)
+ subject, htmlBody, textBody := groupedAlertTemplate(batch, "")
if subject == "" {
t.Fatal("grouped email rendered an empty subject")
}
diff --git a/internal/notifications/notifications.go b/internal/notifications/notifications.go
index 1262364a06..b4c3e9df82 100644
--- a/internal/notifications/notifications.go
+++ b/internal/notifications/notifications.go
@@ -2195,7 +2195,7 @@ func (n *NotificationManager) sendGroupedEmail(config EmailConfig, alertList []*
// by using the From address as the recipient
// Generate email using template
- subject, htmlBody, textBody := EmailTemplate(alertList, false)
+ subject, htmlBody, textBody := EmailTemplate(alertList, false, n.publicURL)
// Send using HTML-aware method
return n.sendThreadedHTMLEmailWithError(subject, htmlBody, textBody, alertListThreadID(alertList), config)
@@ -2287,6 +2287,9 @@ func buildApprisePayload(alertList []*alerts.Alert, publicURL string) (string, s
if alert.Instance != "" && alert.Instance != alert.Node {
bodyBuilder.WriteString(fmt.Sprintf("Instance: %s\n", alert.Instance))
}
+ if link := alertLinkURL(publicURL, alert); link != "" {
+ bodyBuilder.WriteString("View in Pulse: " + link + "\n")
+ }
bodyBuilder.WriteString("\n")
}
@@ -2363,6 +2366,11 @@ func buildResolvedNotificationContent(alertList []*alerts.Alert, resolvedAt time
if alert.Threshold != 0 || alert.Value != 0 {
bodyBuilder.WriteString(fmt.Sprintf("Last value %.2f (threshold %.2f)\n", alert.Value, alert.Threshold))
}
+ if link := alertLinkURL(publicURL, alert); link != "" {
+ bodyBuilder.WriteString("View in Pulse: ")
+ bodyBuilder.WriteString(link)
+ bodyBuilder.WriteString("\n")
+ }
bodyBuilder.WriteString("\n")
}
@@ -2580,7 +2588,7 @@ func (n *NotificationManager) sendResolvedApprise(config AppriseConfig, alertLis
// sendEmail sends an email notification
func (n *NotificationManager) sendSingleEmailWithError(alert *alerts.Alert, config EmailConfig) error {
- subject, htmlBody, textBody := EmailTemplate([]*alerts.Alert{alert}, true)
+ subject, htmlBody, textBody := EmailTemplate([]*alerts.Alert{alert}, true, n.publicURL)
return n.sendThreadedHTMLEmailWithError(subject, htmlBody, textBody, alertListThreadID([]*alerts.Alert{alert}), config)
}
@@ -2967,6 +2975,7 @@ func (n *NotificationManager) sendGroupedWebhook(webhook WebhookConfig, alertLis
data := n.prepareWebhookData(primaryAlert, customFields)
data.AlertCount = len(alertList)
data.Alerts = alertList
+ data.AlertURL = firstNonEmpty(alertsPageURL(n.publicURL, alertList, false), data.Instance)
data.Mention = webhook.Mention
if webhook.Service == "ntfy" {
webhook = withNtfyAlertHeaders(webhook, alertList)
@@ -2986,6 +2995,9 @@ func (n *NotificationManager) sendGroupedWebhook(webhook WebhookConfig, alertLis
"source": "pulse-monitoring",
"grouped": true,
}
+ if link := alertsPageURL(n.publicURL, alertList, false); link != "" {
+ payload["alertUrl"] = link
+ }
return json.Marshal(payload)
})
if err != nil {
@@ -3044,6 +3056,7 @@ func (n *NotificationManager) sendResolvedWebhook(webhook WebhookConfig, alertLi
data.NotRecovered = resolvedAlertsIncludeNotRecovered(alertList)
data.AlertCount = len(alertList)
data.Alerts = alertList
+ data.AlertURL = firstNonEmpty(alertsPageURL(n.publicURL, alertList, true), data.Instance)
if len(alertList) > 1 {
names := make([]string, 0, len(alertList))
for _, a := range alertList {
@@ -3077,6 +3090,9 @@ func (n *NotificationManager) sendResolvedWebhook(webhook WebhookConfig, alertLi
if len(alertList) == 1 {
payload["alertIdentifier"] = alert.ID
}
+ if link := alertsPageURL(n.publicURL, alertList, true); link != "" {
+ payload["alertUrl"] = link
+ }
return json.Marshal(payload)
})
if err != nil {
@@ -3512,6 +3528,7 @@ func (n *NotificationManager) prepareWebhookData(alert *alerts.Alert, customFiel
Node: alert.Node,
NodeDisplayName: alertNodeDisplay(alert),
Instance: instance,
+ AlertURL: firstNonEmpty(alertLinkURL(n.publicURL, alert), instance),
Message: alert.Message,
Value: roundedValue,
Threshold: roundedThreshold,
diff --git a/internal/notifications/webhook_enhanced.go b/internal/notifications/webhook_enhanced.go
index 7f65c6ac74..e597798e32 100644
--- a/internal/notifications/webhook_enhanced.go
+++ b/internal/notifications/webhook_enhanced.go
@@ -40,15 +40,19 @@ type WebhookFilterRules struct {
// WebhookPayloadData contains all data available for templates
type WebhookPayloadData struct {
// Alert fields
- ID string
- MessageKey string
- Level string
- Type string
- ResourceName string
- ResourceID string
- Node string
- NodeDisplayName string
- Instance string
+ ID string
+ MessageKey string
+ Level string
+ Type string
+ ResourceName string
+ ResourceID string
+ Node string
+ NodeDisplayName string
+ Instance string
+ // AlertURL opens this alert in Pulse's Alert History, or the Alerts page
+ // for a grouped notification; it falls back to Instance when no public
+ // URL is configured.
+ AlertURL string
Message string
Value float64
Threshold float64
diff --git a/internal/notifications/webhook_templates.go b/internal/notifications/webhook_templates.go
index 5e4b2bf152..ae58a8b59b 100644
--- a/internal/notifications/webhook_templates.go
+++ b/internal/notifications/webhook_templates.go
@@ -82,7 +82,7 @@ func GetWebhookTemplates() []WebhookTemplate {
Headers: map[string]string{"Content-Type": "application/json"},
PayloadTemplate: `{
"chat_id": "{{.ChatID | jsonString}}",
- "text": "*Pulse Alert: {{.Level | title | jsonString}}*\n\n{{.Message | jsonString}}\n\n*Details:*\nβ€’ Resource: {{.ResourceName | jsonString}}\nβ€’ Node: {{.Node | jsonString}}\nβ€’ Type: {{.Type | title | jsonString}}\nβ€’ Value: {{if or (eq .Type "diskRead") (eq .Type "diskWrite")}}{{printf "%.1f" .Value}} MB/s{{else}}{{printf "%.1f" .Value}}%{{end}}\nβ€’ Threshold: {{if or (eq .Type "diskRead") (eq .Type "diskWrite")}}{{printf "%.0f" .Threshold}} MB/s{{else}}{{printf "%.0f" .Threshold}}%{{end}}\nβ€’ Duration: {{.Duration | jsonString}}\n\n[View in Pulse]({{.Instance | jsonString}})",
+ "text": "*Pulse Alert: {{.Level | title | jsonString}}*\n\n{{.Message | jsonString}}\n\n*Details:*\nβ€’ Resource: {{.ResourceName | jsonString}}\nβ€’ Node: {{.Node | jsonString}}\nβ€’ Type: {{.Type | title | jsonString}}\nβ€’ Value: {{if or (eq .Type "diskRead") (eq .Type "diskWrite")}}{{printf "%.1f" .Value}} MB/s{{else}}{{printf "%.1f" .Value}}%{{end}}\nβ€’ Threshold: {{if or (eq .Type "diskRead") (eq .Type "diskWrite")}}{{printf "%.0f" .Threshold}} MB/s{{else}}{{printf "%.0f" .Threshold}}%{{end}}\nβ€’ Duration: {{.Duration | jsonString}}\n\n[View in Pulse]({{.AlertURL | jsonString}})",
"parse_mode": "Markdown",
"disable_web_page_preview": true
}`,
@@ -145,7 +145,7 @@ func GetWebhookTemplates() []WebhookTemplate {
"elements": [
{
"type": "mrkdwn",
- "text": "View in <{{.Instance | jsonString}}|Proxmox> | Alert Identifier: {{.ID | jsonString}}"
+ "text": "View in <{{.AlertURL | jsonString}}|Pulse> | Alert Identifier: {{.ID | jsonString}}"
}
]
}
@@ -231,10 +231,10 @@ func GetWebhookTemplates() []WebhookTemplate {
}],
"potentialAction": [{
"@type": "OpenUri",
- "name": "View in Proxmox",
+ "name": "View in Pulse",
"targets": [{
"os": "default",
- "uri": "{{.Instance | jsonString}}"
+ "uri": "{{.AlertURL | jsonString}}"
}]
}]
}`,
@@ -292,10 +292,10 @@ func GetWebhookTemplates() []WebhookTemplate {
}
},
"client": "Pulse Monitoring",
- "client_url": "{{.Instance | jsonString}}",
+ "client_url": "{{.AlertURL | jsonString}}",
"links": [{
- "href": "{{.Instance | jsonString}}",
- "text": "View in Proxmox"
+ "href": "{{.AlertURL | jsonString}}",
+ "text": "View in Pulse"
}]
}`,
ResolvedPayloadTemplate: `{
@@ -352,8 +352,8 @@ func GetWebhookTemplates() []WebhookTemplate {
],
"actions": [{
"type": "Action.OpenUrl",
- "title": "View in Proxmox",
- "url": "{{.Instance | jsonString}}"
+ "title": "View in Pulse",
+ "url": "{{.AlertURL | jsonString}}"
}]
}
}]
@@ -435,7 +435,7 @@ func GetWebhookTemplates() []WebhookTemplate {
Method: "POST",
Headers: map[string]string{"Content-Type": "application/json"},
PayloadTemplate: `{
- "message": "**{{if eq .Level "critical"}}CRITICAL{{else if eq .Level "warning"}}WARNING{{else}}INFO{{end}}**: **{{.ResourceName | jsonString}}** on **{{.Node | jsonString}}**\n\n{{.Message | jsonString}}\n\n**Alert Details:**\n- **Resource:** {{.ResourceName | jsonString}}\n- **Node:** {{.Node | jsonString}}\n- **Type:** {{.Type | title | jsonString}}\n- **Current:** {{if or (eq .Type "diskRead") (eq .Type "diskWrite")}}{{printf "%.1f" .Value}} MB/s{{else}}{{printf "%.1f" .Value}}%{{end}}\n- **Threshold:** {{if or (eq .Type "diskRead") (eq .Type "diskWrite")}}{{printf "%.0f" .Threshold}} MB/s{{else}}{{printf "%.0f" .Threshold}}%{{end}}\n- **Duration:** {{.Duration | jsonString}}\n- **Alert Identifier:** {{.ID | jsonString}}\n\n[View in Pulse]({{.Instance | jsonString}})",
+ "message": "**{{if eq .Level "critical"}}CRITICAL{{else if eq .Level "warning"}}WARNING{{else}}INFO{{end}}**: **{{.ResourceName | jsonString}}** on **{{.Node | jsonString}}**\n\n{{.Message | jsonString}}\n\n**Alert Details:**\n- **Resource:** {{.ResourceName | jsonString}}\n- **Node:** {{.Node | jsonString}}\n- **Type:** {{.Type | title | jsonString}}\n- **Current:** {{if or (eq .Type "diskRead") (eq .Type "diskWrite")}}{{printf "%.1f" .Value}} MB/s{{else}}{{printf "%.1f" .Value}}%{{end}}\n- **Threshold:** {{if or (eq .Type "diskRead") (eq .Type "diskWrite")}}{{printf "%.0f" .Threshold}} MB/s{{else}}{{printf "%.0f" .Threshold}}%{{end}}\n- **Duration:** {{.Duration | jsonString}}\n- **Alert Identifier:** {{.ID | jsonString}}\n\n[View in Pulse]({{.AlertURL | jsonString}})",
"title": "{{.ResourceName | jsonString}} - {{.Type | title | jsonString}} {{.Level | upper | jsonString}} Alert",
"priority": {{if eq .Level "critical"}}10{{else if eq .Level "warning"}}5{{else}}2{{end}},
"extras": {
@@ -500,7 +500,7 @@ Alert Details:
- Duration: {{.Duration}}
- Alert Identifier: {{.ID}}
-View in Pulse: {{.Instance}}`,
+View in Pulse: {{.AlertURL}}`,
Instructions: "1. Choose a topic name (e.g., 'my-pulse-alerts')\n2. URL format: https://ntfy.sh/YOUR_TOPIC\n Or for self-hosted: https://your-ntfy-server/YOUR_TOPIC\n3. For authentication, add a custom header:\n β€’ Header Name: Authorization\n β€’ Header Value: Bearer YOUR_TOKEN (or Basic base64_encoded_credentials)\n4. Subscribe to the topic in your ntfy app using the same topic name",
},
{
@@ -516,7 +516,7 @@ View in Pulse: {{.Instance}}`,
PayloadTemplate: `{
"username": "Pulse Monitoring",
"icon_url": "https://raw.githubusercontent.com/rcourtman/Pulse/main/frontend-modern/public/android-chrome-192x192.png",
- "text": "{{if eq .Level "critical"}}:rotating_light: **CRITICAL ALERT**{{else if eq .Level "warning"}}:warning: **WARNING ALERT**{{else}}:information_source: **INFO**{{end}}\n\n**{{.ResourceName | jsonString}}** on **{{.Node | jsonString}}**\n\n{{.Message | jsonString}}\n\n| Detail | Value |\n|:-------|:------|\n| Resource | {{.ResourceName | jsonString}} |\n| Node | {{.Node | jsonString}} |\n| Type | {{.Type | title | jsonString}} |\n| Current | {{if or (eq .Type "diskRead") (eq .Type "diskWrite")}}{{printf "%.1f" .Value}} MB/s{{else}}{{printf "%.1f" .Value}}%{{end}} |\n| Threshold | {{if or (eq .Type "diskRead") (eq .Type "diskWrite")}}{{printf "%.0f" .Threshold}} MB/s{{else}}{{printf "%.0f" .Threshold}}%{{end}} |\n| Duration | {{.Duration | jsonString}} |\n| Alert Identifier | {{.ID | jsonString}} |\n\n[View in Pulse]({{.Instance | jsonString}})"
+ "text": "{{if eq .Level "critical"}}:rotating_light: **CRITICAL ALERT**{{else if eq .Level "warning"}}:warning: **WARNING ALERT**{{else}}:information_source: **INFO**{{end}}\n\n**{{.ResourceName | jsonString}}** on **{{.Node | jsonString}}**\n\n{{.Message | jsonString}}\n\n| Detail | Value |\n|:-------|:------|\n| Resource | {{.ResourceName | jsonString}} |\n| Node | {{.Node | jsonString}} |\n| Type | {{.Type | title | jsonString}} |\n| Current | {{if or (eq .Type "diskRead") (eq .Type "diskWrite")}}{{printf "%.1f" .Value}} MB/s{{else}}{{printf "%.1f" .Value}}%{{end}} |\n| Threshold | {{if or (eq .Type "diskRead") (eq .Type "diskWrite")}}{{printf "%.0f" .Threshold}} MB/s{{else}}{{printf "%.0f" .Threshold}}%{{end}} |\n| Duration | {{.Duration | jsonString}} |\n| Alert Identifier | {{.ID | jsonString}} |\n\n[View in Pulse]({{.AlertURL | jsonString}})"
}`,
ResolvedPayloadTemplate: `{
"username": "Pulse Monitoring",