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.

feat(notifications): route alerts by resource tags

[email protected]51d4b1241513
diff --git a/docs/API.md b/docs/API.md
index 2cd8614246..4f9701c289 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -536,6 +536,12 @@ Triggers a test alert to all configured channels.
- `GET /api/notifications/webhook-templates` (admin)
- `GET /api/notifications/webhook-history` (admin)
- `GET /api/notifications/email-providers` (admin)
+
+Email and webhook configurations accept optional `tagFilter` (an array of
+resource-tag strings) and `tagFilterMode` (`"all"` or `"any"`). An omitted
+field is preserved on update; an empty `tagFilter` clears routing and restores
+delivery for all resources.
+
- `GET /api/notifications/health` (admin)
- Queue health is `degraded` whenever any retained `failed` or `dlq`
delivery exists, and `unavailable` when queue state cannot be read.
diff --git a/docs/WEBHOOKS.md b/docs/WEBHOOKS.md
index 449d5c1f00..6dcc6a1fd2 100644
--- a/docs/WEBHOOKS.md
+++ b/docs/WEBHOOKS.md
@@ -73,6 +73,8 @@ These fields and behaviors are stable; ticket-routing integrations can rely on t
**Tenant identity.** In multi-tenant organizations and MSP client runtimes, `{{.TenantID}}` and `{{.TenantName}}` identify which tenant fired the alert. Client runtimes get identity from the `PULSE_TENANT_ID` / `PULSE_TENANT_NAME` environment; shared-process organizations stamp the org ID and display name automatically.
+**Resource tag routing.** Email and each alert webhook can be limited to resources with selected tags in **Alerts → Notifications**. An empty filter receives every alert. With multiple tags, choose **Match all tags** or **Match any tag**. Matching ignores case. Proxmox tags are matched as shown; Docker container and service labels are exposed as `key:value` tags (or `key` when the label value is empty). Recovery notifications follow the destinations that received the firing alert, even if a resource's tags change before recovery.
+
**Retries.** Failed deliveries retry with exponential backoff. The persistent notification queue makes up to 3 delivery attempts per notification; webhooks configured with transport-level retry add up to 3 more HTTP retries per attempt (1s doubling to a 30s cap, honoring `Retry-After` on HTTP 429). A receiver may therefore see the same logical event more than once.
**Idempotency.** Every alert delivery carries an `X-Pulse-Event-ID` header of the form `<alertID>:<event>` (e.g. `a1b2c3:alert`, `a1b2c3:resolved`). It is identical across all retries of the same logical event — deduplicate on it.
diff --git a/frontend-modern/src/api/__tests__/notifications.test.ts b/frontend-modern/src/api/__tests__/notifications.test.ts
index bf6ccc3dd2..a6d333306b 100644
--- a/frontend-modern/src/api/__tests__/notifications.test.ts
+++ b/frontend-modern/src/api/__tests__/notifications.test.ts
@@ -79,6 +79,53 @@ describe('NotificationsAPI', () => {
});
});
+ it('maps email tag routing and sends explicit routing updates', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({
+ enabled: true,
+ provider: 'smtp',
+ server: 'smtp.internal',
+ port: 587,
+ username: 'ops',
+ password: '',
+ from: 'pulse@internal',
+ to: ['alerts@internal'],
+ tls: false,
+ startTLS: true,
+ tagFilter: ['customer:alpha', 'critical'],
+ tagFilterMode: 'any',
+ });
+
+ const config = await NotificationsAPI.getEmailConfig();
+
+ expect(config).toEqual(
+ expect.objectContaining({
+ tagFilter: ['customer:alpha', 'critical'],
+ tagFilterMode: 'any',
+ }),
+ );
+
+ apiFetchJSONMock.mockResolvedValueOnce({ success: true });
+ await NotificationsAPI.updateEmailConfig({
+ ...config,
+ tagFilter: [],
+ tagFilterMode: 'all',
+ });
+
+ expect(apiFetchJSONMock).toHaveBeenLastCalledWith(
+ '/api/notifications/email',
+ expect.objectContaining({
+ method: 'PUT',
+ body: expect.stringContaining('"tagFilter":[]'),
+ }),
+ );
+ expect(JSON.parse(apiFetchJSONMock.mock.calls.at(-1)?.[1]?.body as string)).toEqual(
+ expect.objectContaining({
+ tagFilter: [],
+ tagFilterMode: 'all',
+ }),
+ );
+ });
+
it('normalizes malformed webhook collections to empty arrays', async () => {
apiFetchJSONMock.mockResolvedValueOnce({ webhooks: [] } as any);
diff --git a/frontend-modern/src/api/notifications.ts b/frontend-modern/src/api/notifications.ts
index 299e07861f..5705ef4950 100644
--- a/frontend-modern/src/api/notifications.ts
+++ b/frontend-modern/src/api/notifications.ts
@@ -54,6 +54,8 @@ export interface EmailConfig {
tls: boolean;
startTLS: boolean;
rateLimit?: number;
+ tagFilter?: string[];
+ tagFilterMode?: 'all' | 'any';
}
export interface Webhook {
@@ -67,6 +69,8 @@ export interface Webhook {
service?: string; // Added to support Discord, Slack, etc.
customFields?: Record<string, string>;
mention?: string; // Platform-specific mention (e.g., @everyone, @channel, <@USER_ID>)
+ tagFilter?: string[];
+ tagFilterMode?: 'all' | 'any';
}
export interface AppriseConfig {
@@ -269,7 +273,7 @@ export class NotificationsAPI {
const port = finiteNumberOrUndefined(backendConfig.port);
// Backend already returns fields with correct names (server, port)
- return {
+ const config: EmailConfig = {
enabled: strictBoolean(backendConfig.enabled),
provider: strictString(backendConfig.provider),
server: strictString(backendConfig.server),
@@ -282,6 +286,13 @@ export class NotificationsAPI {
startTLS: strictBoolean(backendConfig.startTLS),
rateLimit: finiteNumberOrUndefined(backendConfig.rateLimit),
};
+ if (Array.isArray(backendConfig.tagFilter)) {
+ config.tagFilter = stringArray(backendConfig.tagFilter);
+ }
+ if (typeof backendConfig.tagFilterMode === 'string') {
+ config.tagFilterMode = backendConfig.tagFilterMode === 'any' ? 'any' : 'all';
+ }
+ return config;
}
static async updateEmailConfig(config: EmailConfig): Promise<{ success: boolean }> {
@@ -303,6 +314,12 @@ export class NotificationsAPI {
if (config.rateLimit !== undefined) {
backendConfig.rateLimit = config.rateLimit;
}
+ if (config.tagFilter !== undefined) {
+ backendConfig.tagFilter = config.tagFilter;
+ }
+ if (config.tagFilterMode !== undefined) {
+ backendConfig.tagFilterMode = config.tagFilterMode === 'any' ? 'any' : 'all';
+ }
return apiFetchJSON(`${this.baseUrl}/email`, {
method: 'PUT',
diff --git a/frontend-modern/src/components/Alerts/EmailProviderSelect.test.tsx b/frontend-modern/src/components/Alerts/EmailProviderSelect.test.tsx
index 9fe2fd1d64..040a525195 100644
--- a/frontend-modern/src/components/Alerts/EmailProviderSelect.test.tsx
+++ b/frontend-modern/src/components/Alerts/EmailProviderSelect.test.tsx
@@ -124,6 +124,34 @@ describe('EmailProviderSelect', () => {
expect(emailProviderSelectSource).not.toContain('<textarea');
});
+ it('edits resource tag routing and its all-or-any matching mode', () => {
+ render(() => (
+ <EmailProviderSelect
+ config={makeConfig({
+ tagFilter: ['customer:alpha', 'critical'],
+ tagFilterMode: 'all',
+ })}
+ onChange={onChangeMock}
+ onTest={onTestMock}
+ />
+ ));
+
+ expect(screen.getByText('Resource tag routing')).toBeInTheDocument();
+ expect(screen.getByText('customer:alpha')).toBeInTheDocument();
+ expect(screen.getByText('critical')).toBeInTheDocument();
+
+ fireEvent.change(screen.getByRole('combobox', { name: 'Tag matching' }), {
+ target: { value: 'any' },
+ });
+
+ expect(onChangeMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ tagFilter: ['customer:alpha', 'critical'],
+ tagFilterMode: 'any',
+ }),
+ );
+ });
+
it('exposes canonical labels for provider and security selects', () => {
render(() => (
<EmailProviderSelect config={makeConfig()} onChange={onChangeMock} onTest={onTestMock} />
diff --git a/frontend-modern/src/components/Alerts/EmailProviderSelect.tsx b/frontend-modern/src/components/Alerts/EmailProviderSelect.tsx
index 9181c3f0df..2197785026 100644
--- a/frontend-modern/src/components/Alerts/EmailProviderSelect.tsx
+++ b/frontend-modern/src/components/Alerts/EmailProviderSelect.tsx
@@ -38,6 +38,7 @@ import {
} from './useEmailProviderSelectState';
import { FormSelect } from '@/components/shared/FormSelect';
import { FormTextarea } from '@/components/shared/FormTextarea';
+import { TagInput } from '@/components/shared/TagInput';
interface EmailProviderSelectProps extends EmailProviderSelectStateProps {
config: UIEmailConfig;
@@ -59,6 +60,7 @@ export function EmailProviderSelect(props: EmailProviderSelectProps) {
rateLimit: `${fieldIdPrefix}-rate-limit`,
maxRetries: `${fieldIdPrefix}-max-retries`,
retryDelay: `${fieldIdPrefix}-retry-delay`,
+ tagMode: `${fieldIdPrefix}-tag-mode`,
};
const instructionBoxClass =
'mt-2 rounded border border-blue-200 bg-blue-50 px-3 py-2 text-xs leading-relaxed text-blue-900 dark:border-blue-700 dark:bg-blue-900 dark:text-blue-200';
@@ -236,6 +238,38 @@ export function EmailProviderSelect(props: EmailProviderSelectProps) {
placeholder={getAlertEmailRecipientsPlaceholder(props.config.from)}
/>
+ <div class="space-y-2 border-t border-border pt-3">
+ <div>
+ <div class={labelClass()}>Resource tag routing</div>
+ <p class={formHelpText + ' mt-1'}>
+ Leave empty to receive all alerts. Add tags to deliver only alerts from matching
+ resources.
+ </p>
+ </div>
+ <TagInput
+ tags={props.config.tagFilter ?? []}
+ onChange={(tagFilter) => props.onChange({ ...props.config, tagFilter })}
+ placeholder="Add a resource tag"
+ />
+ <Show when={(props.config.tagFilter?.length ?? 0) > 1}>
+ <FormSelect
+ id={fieldIds.tagMode}
+ label="Tag matching"
+ value={props.config.tagFilterMode === 'any' ? 'any' : 'all'}
+ onChange={(event) =>
+ props.onChange({
+ ...props.config,
+ tagFilterMode: event.currentTarget.value === 'any' ? 'any' : 'all',
+ })
+ }
+ selectBaseClass={controlClass('px-2 py-1.5')}
+ >
+ <option value="all">Match all tags</option>
+ <option value="any">Match any tag</option>
+ </FormSelect>
+ </Show>
+ </div>
+
<div class="border-t border-border pt-3">
<button
type="button"
diff --git a/frontend-modern/src/components/Alerts/WebhookConfig.test.tsx b/frontend-modern/src/components/Alerts/WebhookConfig.test.tsx
index 160894c278..0b176b7e53 100644
--- a/frontend-modern/src/components/Alerts/WebhookConfig.test.tsx
+++ b/frontend-modern/src/components/Alerts/WebhookConfig.test.tsx
@@ -193,6 +193,40 @@ describe('WebhookConfig', () => {
expect(screen.getByText('https://hooks.slack.com/services/abc')).toBeInTheDocument();
});
+ it('renders and preserves webhook resource tag routing while editing', () => {
+ const webhook = makeWebhook({
+ id: 'wh-routed',
+ tagFilter: ['customer:alpha', 'critical'],
+ tagFilterMode: 'any',
+ });
+
+ render(() => (
+ <WebhookConfig
+ webhooks={[webhook]}
+ onAdd={onAddMock}
+ onUpdate={onUpdateMock}
+ onDelete={onDeleteMock}
+ onTest={onTestMock}
+ />
+ ));
+
+ expect(screen.getByText('customer:alpha')).toBeInTheDocument();
+ expect(screen.getByText('critical')).toBeInTheDocument();
+ expect(screen.getByText('Match any')).toBeInTheDocument();
+
+ fireEvent.click(screen.getByText('Edit'));
+ expect(screen.getByRole('combobox', { name: 'Tag matching' })).toHaveValue('any');
+ fireEvent.click(screen.getByText('Update Webhook'));
+
+ expect(onUpdateMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: 'wh-routed',
+ tagFilter: ['customer:alpha', 'critical'],
+ tagFilterMode: 'any',
+ }),
+ );
+ });
+
it('shows enabled count summary', () => {
const webhooks = [
makeWebhook({ id: 'wh-1', enabled: true }),
diff --git a/frontend-modern/src/components/Alerts/WebhookConfigForm.tsx b/frontend-modern/src/components/Alerts/WebhookConfigForm.tsx
index 2825305de4..231f78820b 100644
--- a/frontend-modern/src/components/Alerts/WebhookConfigForm.tsx
+++ b/frontend-modern/src/components/Alerts/WebhookConfigForm.tsx
@@ -45,6 +45,7 @@ import {
} from '@/components/shared/Form';
import { FormSelect } from '@/components/shared/FormSelect';
import { FormTextarea } from '@/components/shared/FormTextarea';
+import { TagInput } from '@/components/shared/TagInput';
import type { CustomFieldInput, HeaderInput, WebhookConfigFormData } from './useWebhookConfigState';
@@ -167,6 +168,38 @@ export function WebhookConfigForm(props: WebhookConfigFormProps) {
</p>
</div>
+ <div class="space-y-2 border-t border-border pt-3">
+ <div>
+ <div class={labelClass()}>Resource tag routing</div>
+ <p class={formHelpText + ' mt-1'}>
+ Leave empty to receive all alerts. Add tags to route only alerts from matching resources
+ to this webhook.
+ </p>
+ </div>
+ <TagInput
+ tags={props.formData().tagFilter ?? []}
+ onChange={(tagFilter) => props.setFormData((prev) => ({ ...prev, tagFilter }))}
+ placeholder="Add a resource tag"
+ />
+ <Show when={(props.formData().tagFilter?.length ?? 0) > 1}>
+ <FormSelect
+ id="alert-webhook-tag-mode"
+ label="Tag matching"
+ value={props.formData().tagFilterMode === 'any' ? 'any' : 'all'}
+ onChange={(event) =>
+ props.setFormData((prev) => ({
+ ...prev,
+ tagFilterMode: event.currentTarget.value === 'any' ? 'any' : 'all',
+ }))
+ }
+ selectBaseClass={controlClass('px-2 py-1.5')}
+ >
+ <option value="all">Match all tags</option>
+ <option value="any">Match any tag</option>
+ </FormSelect>
+ </Show>
+ </div>
+
<Show
when={hasAlertWebhookMentionSupportFromTemplates(
props.formData().service,
diff --git a/frontend-modern/src/components/Alerts/WebhookConfigList.tsx b/frontend-modern/src/components/Alerts/WebhookConfigList.tsx
index f0a15fa952..1e1699c0a4 100644
--- a/frontend-modern/src/components/Alerts/WebhookConfigList.tsx
+++ b/frontend-modern/src/components/Alerts/WebhookConfigList.tsx
@@ -1,4 +1,4 @@
-import { For } from 'solid-js';
+import { For, Show } from 'solid-js';
import type { Accessor } from 'solid-js';
import type { Webhook, WebhookTemplate } from '@/api/notifications';
@@ -75,6 +75,18 @@ export function WebhookConfigList(props: WebhookConfigListProps) {
<span class="rounded bg-surface-alt px-2 py-0.5 text-base-content">
{webhook.method}
</span>
+ <For each={webhook.tagFilter ?? []}>
+ {(tag) => (
+ <span class="rounded bg-sky-50 px-2 py-0.5 text-sky-700 dark:bg-sky-900 dark:text-sky-300">
+ {tag}
+ </span>
+ )}
+ </For>
+ <Show when={(webhook.tagFilter?.length ?? 0) > 1}>
+ <span class="rounded bg-surface-alt px-2 py-0.5 text-muted">
+ Match {webhook.tagFilterMode === 'any' ? 'any' : 'all'}
+ </span>
+ </Show>
</div>
<p class="mt-2 break-all text-[11px] font-mono text-muted sm:text-xs">{webhook.url}</p>
<div class="mt-3 flex flex-wrap gap-2 border-t border-border-subtle pt-2 sm:justify-end w-full">
diff --git a/frontend-modern/src/components/Alerts/useWebhookConfigState.ts b/frontend-modern/src/components/Alerts/useWebhookConfigState.ts
index 94f9316ff3..d0f22132e0 100644
--- a/frontend-modern/src/components/Alerts/useWebhookConfigState.ts
+++ b/frontend-modern/src/components/Alerts/useWebhookConfigState.ts
@@ -39,6 +39,8 @@ const createDefaultFormData = (): WebhookConfigFormData => ({
payloadTemplate: '',
customFields: {},
mention: '',
+ tagFilter: [],
+ tagFilterMode: 'all',
});
const buildMapFromInputs = (
@@ -180,6 +182,8 @@ export function useWebhookConfigState(props: WebhookConfigProps): WebhookConfigS
webhook.customFields || {},
),
mention: webhook.mention || '',
+ tagFilter: webhook.tagFilter ?? [],
+ tagFilterMode: webhook.tagFilterMode === 'any' ? 'any' : 'all',
});
const headers = webhook.headers || {};
@@ -263,6 +267,8 @@ export function useWebhookConfigState(props: WebhookConfigProps): WebhookConfigS
template: data.payloadTemplate,
customFields: normalizedCustomFields,
mention: data.mention,
+ tagFilter: data.tagFilter ?? [],
+ tagFilterMode: data.tagFilterMode === 'any' ? 'any' : 'all',
});
resetForm();
};
diff --git a/frontend-modern/src/features/alerts/__tests__/alertDestinationsModel.test.ts b/frontend-modern/src/features/alerts/__tests__/alertDestinationsModel.test.ts
index 5bf1a31ba7..d3bc4e8d7c 100644
--- a/frontend-modern/src/features/alerts/__tests__/alertDestinationsModel.test.ts
+++ b/frontend-modern/src/features/alerts/__tests__/alertDestinationsModel.test.ts
@@ -50,6 +50,34 @@ describe('alertDestinationsModel', () => {
});
+ it('includes explicit email tag routing, including an empty filter used to clear routing', () => {
+ expect(
+ buildEmailConfigPayload({
+ enabled: true,
+ provider: 'smtp',
+ server: 'smtp.internal',
+ port: 587,
+ username: '[email protected]',
+ password: '',
+ tls: true,
+ startTLS: true,
+ replyTo: '',
+ maxRetries: 3,
+ retryDelay: 60,
+ rateLimit: 0,
+ tagFilter: [],
+ tagFilterMode: 'any',
+ }),
+ ).toEqual(
+ expect.objectContaining({
+ tagFilter: [],
+ tagFilterMode: 'any',
+ }),
+ );
+ });
+
it('builds outbound email and apprise payloads from UI state', () => {
expect(
buildEmailConfigPayload({
diff --git a/frontend-modern/src/features/alerts/alertDestinationsModel.ts b/frontend-modern/src/features/alerts/alertDestinationsModel.ts
index 8c9c748043..8d6fe89ca1 100644
--- a/frontend-modern/src/features/alerts/alertDestinationsModel.ts
+++ b/frontend-modern/src/features/alerts/alertDestinationsModel.ts
@@ -24,7 +24,7 @@ export function normalizeAppriseConfig(
}
export function buildEmailConfigPayload(config: UIEmailConfig): EmailConfig {
- return {
+ const payload: EmailConfig = {
enabled: config.enabled,
provider: config.provider,
server: config.server,
@@ -35,7 +35,14 @@ export function buildEmailConfigPayload(config: UIEmailConfig): EmailConfig {
to: config.to.map((entry) => entry.trim()).filter((entry) => entry.length > 0),
tls: config.tls,
startTLS: config.startTLS,
- } as EmailConfig;
+ };
+ if (config.tagFilter !== undefined) {
+ payload.tagFilter = config.tagFilter;
+ }
+ if (config.tagFilterMode !== undefined) {
+ payload.tagFilterMode = config.tagFilterMode === 'any' ? 'any' : 'all';
+ }
+ return payload;
}
export function buildAppriseConfigPayload(config: UIAppriseConfig): AppriseConfig {
diff --git a/frontend-modern/src/features/alerts/helpers.ts b/frontend-modern/src/features/alerts/helpers.ts
index 26cb2981c6..a67b042d0a 100644
--- a/frontend-modern/src/features/alerts/helpers.ts
+++ b/frontend-modern/src/features/alerts/helpers.ts
@@ -102,6 +102,8 @@ export const createDefaultEmailConfig = (): UIEmailConfig => ({
maxRetries: 3,
retryDelay: 5,
rateLimit: 60,
+ tagFilter: [],
+ tagFilterMode: 'all',
});
export const readStringValue = (value: unknown, fallback = ''): string =>
@@ -134,6 +136,8 @@ export const normalizeEmailConfigFromAPI = (
tls: readBooleanValue(value?.tls, defaults.tls),
startTLS: readBooleanValue(value?.startTLS, defaults.startTLS),
rateLimit: readNumberValue(value?.rateLimit, defaults.rateLimit),
+ tagFilter: readStringArrayValue(value?.tagFilter),
+ tagFilterMode: value?.tagFilterMode === 'any' ? 'any' : 'all',
};
};
diff --git a/frontend-modern/src/features/alerts/types.ts b/frontend-modern/src/features/alerts/types.ts
index c4cd9af6aa..ddf8812946 100644
--- a/frontend-modern/src/features/alerts/types.ts
+++ b/frontend-modern/src/features/alerts/types.ts
@@ -149,6 +149,8 @@ export interface UIEmailConfig {
maxRetries: number;
retryDelay: number;
rateLimit: number;
+ tagFilter?: string[];
+ tagFilterMode?: 'all' | 'any';
}
export interface UIAppriseConfig {
diff --git a/internal/alerts/docker.go b/internal/alerts/docker.go
index be28ada6b8..16e6cf7783 100644
--- a/internal/alerts/docker.go
+++ b/internal/alerts/docker.go
@@ -2,6 +2,7 @@ package alerts
import (
"fmt"
+ "sort"
"strings"
"time"
@@ -259,6 +260,7 @@ func (m *Manager) evaluateDockerContainer(host models.DockerHost, container mode
nodeName := strings.TrimSpace(host.Hostname)
instanceName := dockerInstanceName(host)
resourceType := "app-container"
+ containerTags := dockerLabelTags(container.Labels)
m.mu.RLock()
overrideConfig, hasOverride := m.config.Overrides[resourceID]
@@ -313,6 +315,7 @@ func (m *Manager) evaluateDockerContainer(host models.DockerHost, container mode
"cpuCapacityPercent": cpuCapacityPercent,
"cpuRawPercent": container.CPUPercent,
"cpuCapacityCores": host.CPUs,
+ "tags": containerTags,
}
spec, err := buildCanonicalMetricSpec(resourceID, containerName, unifiedresources.ResourceTypeAppContainer, "cpu", thresholds.CPU)
if err != nil {
@@ -341,6 +344,7 @@ func (m *Manager) evaluateDockerContainer(host models.DockerHost, container mode
"metric": "memory",
"memoryPercent": container.MemoryPercent,
"memoryUsageBytes": container.MemoryUsage,
+ "tags": containerTags,
}
if container.MemoryLimit > 0 {
memMetadata["memoryLimitBytes"] = container.MemoryLimit
@@ -378,6 +382,7 @@ func (m *Manager) evaluateDockerContainer(host models.DockerHost, container mode
"writableLayerBytes": usedBytes,
"rootFilesystemBytes": totalBytes,
"mountCount": len(container.Mounts),
+ "tags": containerTags,
}
if container.BlockIO != nil {
diskMetadata["blockIoReadBytes"] = container.BlockIO.ReadBytes
@@ -461,6 +466,7 @@ func (m *Manager) evaluateDockerService(host models.DockerHost, service models.D
"completedTasks": service.CompletedTasks,
"missingTasks": missing,
"percentMissing": percentMissing,
+ "tags": dockerLabelTags(service.Labels),
}
alertID := fmt.Sprintf("docker-service-health-%s", resourceID)
@@ -770,26 +776,16 @@ func (m *Manager) checkDockerContainerState(host models.DockerHost, container mo
Observed: observedState,
},
},
- Tracking: m.dockerStateConfirm,
- TrackingKey: stateKey,
- AlertID: alertID,
- AlertType: "docker-container-state",
- ResourceID: resourceID,
- ResourceName: containerName,
- Node: nodeName,
- Instance: instanceName,
- Message: fmt.Sprintf("Docker container '%s' is %s", containerName, strings.TrimSpace(container.Status)),
- Metadata: map[string]interface{}{
- "resourceType": "app-container",
- "hostId": host.ID,
- "hostName": host.DisplayName,
- "hostHostname": host.Hostname,
- "containerId": container.ID,
- "containerName": containerName,
- "image": container.Image,
- "state": container.State,
- "status": container.Status,
- },
+ Tracking: m.dockerStateConfirm,
+ TrackingKey: stateKey,
+ AlertID: alertID,
+ AlertType: "docker-container-state",
+ ResourceID: resourceID,
+ ResourceName: containerName,
+ Node: nodeName,
+ Instance: instanceName,
+ Message: fmt.Sprintf("Docker container '%s' is %s", containerName, strings.TrimSpace(container.Status)),
+ Metadata: dockerContainerAlertMetadata(host, container, containerName),
AddToRecent: true,
AddToHistory: true,
DispatchAsync: true,
@@ -814,7 +810,30 @@ func dockerContainerAlertMetadata(host models.DockerHost, container models.Docke
"image": container.Image,
"state": container.State,
"status": container.Status,
+ "tags": dockerLabelTags(container.Labels),
+ }
+}
+
+func dockerLabelTags(labels map[string]string) []string {
+ if len(labels) == 0 {
+ return nil
+ }
+
+ tags := make([]string, 0, len(labels))
+ for rawKey, rawValue := range labels {
+ key := strings.TrimSpace(rawKey)
+ if key == "" {
+ continue
+ }
+ value := strings.TrimSpace(rawValue)
+ if value == "" {
+ tags = append(tags, key)
+ continue
+ }
+ tags = append(tags, key+":"+value)
}
+ sort.Strings(tags)
+ return tags
}
func (m *Manager) checkDockerContainerHealth(host models.DockerHost, container models.DockerContainer, resourceID, containerName, instanceName, nodeName string) {
diff --git a/internal/alerts/guest.go b/internal/alerts/guest.go
index 46b22f50bc..4316406afb 100644
--- a/internal/alerts/guest.go
+++ b/internal/alerts/guest.go
@@ -201,7 +201,7 @@ func (m *Manager) CheckGuest(guest any, instanceName string) {
}
}
}
- m.checkGuestPoweredOffWithThresholdsAndIntent(guestID, name, node, instanceName, guestType, thresholds, monitorOnly, backupContext)
+ m.checkGuestPoweredOffWithThresholdsAndIntentAndTags(guestID, name, node, instanceName, guestType, thresholds, monitorOnly, backupContext, snapshot.Tags)
}
} else {
// For paused/suspended, clear powered-off alert
@@ -312,6 +312,7 @@ func (m *Manager) CheckGuest(guest any, instanceName string) {
Name: name,
Node: node,
Instance: instanceName,
+ Tags: snapshot.Tags,
CPU: &UnifiedResourceMetric{Percent: cpu},
Memory: memoryMetric,
Disk: diskMetric,
@@ -375,6 +376,7 @@ func (m *Manager) CheckGuest(guest any, instanceName string) {
"freeBytes": disk.Free,
"diskIndex": idx,
"label": label,
+ "tags": append([]string(nil), snapshot.Tags...),
}
resourceType, ok := unifiedMetricResourceType(snapshot.resourceType())
if !ok {
@@ -464,6 +466,10 @@ func (m *Manager) checkGuestPoweredOffWithThresholds(guestID, name, node, instan
}
func (m *Manager) checkGuestPoweredOffWithThresholdsAndIntent(guestID, name, node, instanceName, guestType string, thresholds ThresholdConfig, monitorOnly bool, backupContext BackupIntentContext) {
+ m.checkGuestPoweredOffWithThresholdsAndIntentAndTags(guestID, name, node, instanceName, guestType, thresholds, monitorOnly, backupContext, nil)
+}
+
+func (m *Manager) checkGuestPoweredOffWithThresholdsAndIntentAndTags(guestID, name, node, instanceName, guestType string, thresholds ThresholdConfig, monitorOnly bool, backupContext BackupIntentContext, tags []string) {
alertID := fmt.Sprintf("guest-powered-off-%s", guestID)
severity := NormalizePoweredOffSeverity(thresholds.PoweredOffSeverity)
resourceType := unifiedresources.ResourceTypeVM
@@ -494,6 +500,14 @@ func (m *Manager) checkGuestPoweredOffWithThresholdsAndIntent(guestID, name, nod
return
}
+ metadata := map[string]interface{}{
+ "monitorOnly": monitorOnly,
+ "resourceType": strings.ToLower(guestType),
+ }
+ if len(tags) > 0 {
+ metadata["tags"] = append([]string(nil), tags...)
+ }
+
m.evaluateCanonicalLifecycleAlert(canonicalLifecycleAlertParams{
Spec: spec,
Evidence: alertspecs.AlertEvidence{
@@ -503,19 +517,16 @@ func (m *Manager) checkGuestPoweredOffWithThresholdsAndIntent(guestID, name, nod
Observed: alertspecs.PowerStateOff,
},
},
- Tracking: tracking,
- TrackingKey: guestID,
- AlertID: alertID,
- AlertType: "powered-off",
- ResourceID: guestID,
- ResourceName: name,
- Node: node,
- Instance: instanceName,
- Message: fmt.Sprintf("%s '%s' is powered off", guestType, name),
- Metadata: map[string]interface{}{
- "monitorOnly": monitorOnly,
- "resourceType": strings.ToLower(guestType),
- },
+ Tracking: tracking,
+ TrackingKey: guestID,
+ AlertID: alertID,
+ AlertType: "powered-off",
+ ResourceID: guestID,
+ ResourceName: name,
+ Node: node,
+ Instance: instanceName,
+ Message: fmt.Sprintf("%s '%s' is powered off", guestType, name),
+ Metadata: metadata,
AddToRecent: true,
AddToHistory: true,
DispatchAsync: false,
diff --git a/internal/alerts/guest_tags_test.go b/internal/alerts/guest_tags_test.go
index 781deadf9b..f7da837195 100644
--- a/internal/alerts/guest_tags_test.go
+++ b/internal/alerts/guest_tags_test.go
@@ -6,6 +6,71 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/models"
)
+func TestGuestAlertIncludesTagsForNotificationRouting(t *testing.T) {
+ m := newTestManager(t)
+ m.ClearActiveAlerts()
+
+ m.mu.Lock()
+ m.config.GuestDefaults = ThresholdConfig{
+ CPU: &HysteresisThreshold{Trigger: 80, Clear: 70},
+ }
+ m.config.TimeThresholds = map[string]int{}
+ m.mu.Unlock()
+
+ guest := models.VM{
+ ID: "qemu/route-100",
+ Name: "customer-alpha",
+ Status: "running",
+ CPU: 0.95,
+ Tags: []string{"customer:alpha", "critical"},
+ }
+ m.CheckGuest(guest, "pve-prod")
+
+ m.mu.RLock()
+ alert := testRequireActiveAlert(t, m, canonicalMetricStateID(guest.ID, "cpu"))
+ m.mu.RUnlock()
+ tags, ok := alert.Metadata["tags"].([]string)
+ if !ok || len(tags) != 2 || tags[0] != "customer:alpha" || tags[1] != "critical" {
+ t.Fatalf("guest routing tags = %#v", alert.Metadata["tags"])
+ }
+}
+
+func TestGuestPoweredOffAlertIncludesTagsForNotificationRouting(t *testing.T) {
+ m := newTestManager(t)
+ tags := []string{"customer:alpha", "critical"}
+
+ m.checkGuestPoweredOffWithThresholdsAndIntentAndTags(
+ "qemu/route-offline",
+ "customer-alpha-offline",
+ "pve-prod",
+ "pve-prod",
+ "VM",
+ m.config.GuestDefaults,
+ false,
+ BackupIntentContext{},
+ tags,
+ )
+ m.checkGuestPoweredOffWithThresholdsAndIntentAndTags(
+ "qemu/route-offline",
+ "customer-alpha-offline",
+ "pve-prod",
+ "pve-prod",
+ "VM",
+ m.config.GuestDefaults,
+ false,
+ BackupIntentContext{},
+ tags,
+ )
+
+ m.mu.RLock()
+ alert := testRequireActiveAlert(t, m, "guest-powered-off-qemu/route-offline")
+ m.mu.RUnlock()
+ got, ok := alert.Metadata["tags"].([]string)
+ if !ok || len(got) != 2 || got[0] != "customer:alpha" || got[1] != "critical" {
+ t.Fatalf("powered-off routing tags = %#v", alert.Metadata["tags"])
+ }
+}
+
func TestIgnoredGuestPrefixesSkipsAlerts(t *testing.T) {
m := newTestManager(t)
m.ClearActiveAlerts()
diff --git a/internal/alerts/unified_eval.go b/internal/alerts/unified_eval.go
index 9c7bf0fd5c..63e0a8ecf4 100644
--- a/internal/alerts/unified_eval.go
+++ b/internal/alerts/unified_eval.go
@@ -44,6 +44,7 @@ type UnifiedResourceInput struct {
Name string
Node string
Instance string
+ Tags []string
CPU *UnifiedResourceMetric
Memory *UnifiedResourceMetric
Disk *UnifiedResourceMetric
@@ -236,11 +237,30 @@ func (m *Manager) evaluateUnifiedMetrics(input *UnifiedResourceInput, thresholds
return
}
+ opts = metricOptionsWithTags(opts, input.Tags)
for _, candidate := range buildUnifiedMetricCandidates(input, thresholds) {
m.checkMetricWithCanonicalSpec(candidate.Spec, input.Name, input.Node, input.Instance, unifiedAlertType(input.Type), candidate.Value, candidate.Threshold, opts)
}
}
+func metricOptionsWithTags(opts *metricOptions, tags []string) *metricOptions {
+ if len(tags) == 0 {
+ return opts
+ }
+
+ merged := metricOptions{}
+ if opts != nil {
+ merged = *opts
+ }
+ metadata := make(map[string]interface{}, len(merged.Metadata)+1)
+ for key, value := range merged.Metadata {
+ metadata[key] = value
+ }
+ metadata["tags"] = append([]string(nil), tags...)
+ merged.Metadata = metadata
+ return &merged
+}
+
func buildUnifiedMetricCandidates(input *UnifiedResourceInput, thresholds ThresholdConfig) []unifiedMetricCandidate {
if input == nil {
return nil
@@ -449,6 +469,7 @@ func UnifiedResourceInputFromResource(resource unifiedresources.Resource) (*Unif
Name: unifiedResourceAlertName(resource),
Node: unifiedResourceAlertNode(resource),
Instance: unifiedResourceAlertInstance(resource, typeKey),
+ Tags: append([]string(nil), resource.Tags...),
}
if metrics := resource.Metrics; metrics != nil {
diff --git a/internal/alerts/unified_eval_test.go b/internal/alerts/unified_eval_test.go
index 23bf6f07df..58d041485a 100644
--- a/internal/alerts/unified_eval_test.go
+++ b/internal/alerts/unified_eval_test.go
@@ -483,6 +483,7 @@ func TestUnifiedResourceInputFromKubernetesTrueNASAndVMwareResources(t *testing.
Type: unifiedresources.ResourceTypePod,
Name: "api-7d9f",
ParentName: "worker-1",
+ Tags: []string{"customer:alpha", "critical"},
Sources: []unifiedresources.DataSource{unifiedresources.SourceK8s},
Kubernetes: &unifiedresources.K8sData{
ClusterName: "prod",
@@ -504,6 +505,9 @@ func TestUnifiedResourceInputFromKubernetesTrueNASAndVMwareResources(t *testing.
if podInput.CPU == nil || podInput.CPU.Percent != 82 {
t.Fatalf("unexpected pod CPU metric: %+v", podInput.CPU)
}
+ if len(podInput.Tags) != 2 || podInput.Tags[0] != "customer:alpha" || podInput.Tags[1] != "critical" {
+ t.Fatalf("unexpected pod routing tags: %+v", podInput.Tags)
+ }
pool := unifiedresources.Resource{
ID: "storage:truenas-main/pool:tank",
@@ -1245,6 +1249,7 @@ func TestCheckDockerContainerStateAnnotatesCanonicalSpecMetadata(t *testing.T) {
Name: "web",
State: "exited",
Status: "Exited (1) seconds ago",
+ Labels: map[string]string{"customer": "alpha", "critical": ""},
},
},
}
@@ -1260,6 +1265,10 @@ func TestCheckDockerContainerStateAnnotatesCanonicalSpecMetadata(t *testing.T) {
if got := alert.Metadata["canonicalSpecID"]; got != resourceID+"-runtime-state" {
t.Fatalf("canonicalSpecID = %v, want %s", got, resourceID+"-runtime-state")
}
+ tags, ok := alert.Metadata["tags"].([]string)
+ if !ok || len(tags) != 2 || tags[0] != "critical" || tags[1] != "customer:alpha" {
+ t.Fatalf("container routing tags = %#v", alert.Metadata["tags"])
+ }
}
func TestCheckDockerServiceAnnotatesCanonicalSpecMetadata(t *testing.T) {
@@ -1277,6 +1286,7 @@ func TestCheckDockerServiceAnnotatesCanonicalSpecMetadata(t *testing.T) {
DesiredTasks: 4,
RunningTasks: 2,
Mode: "replicated",
+ Labels: map[string]string{"customer": "alpha", "critical": ""},
},
},
}
@@ -1291,6 +1301,10 @@ func TestCheckDockerServiceAnnotatesCanonicalSpecMetadata(t *testing.T) {
if got := alert.Metadata["canonicalSpecID"]; got != resourceID+"-service-gap" {
t.Fatalf("canonicalSpecID = %v, want %s", got, resourceID+"-service-gap")
}
+ tags, ok := alert.Metadata["tags"].([]string)
+ if !ok || len(tags) != 2 || tags[0] != "critical" || tags[1] != "customer:alpha" {
+ t.Fatalf("service routing tags = %#v", alert.Metadata["tags"])
+ }
}
func TestCheckDockerServiceUpdateStateAnnotatesCanonicalSpecMetadata(t *testing.T) {
diff --git a/internal/api/notifications.go b/internal/api/notifications.go
index 2504b05040..e525e4a0a2 100644
--- a/internal/api/notifications.go
+++ b/internal/api/notifications.go
@@ -183,7 +183,9 @@ func (h *NotificationHandlers) UpdateEmailConfig(w http.ResponseWriter, r *http.
// Parse strict subset to check for presence of fields
var presenceCheck struct {
- RateLimit *int `json:"rateLimit"`
+ RateLimit *int `json:"rateLimit"`
+ TagFilter *[]string `json:"tagFilter"`
+ TagMode *string `json:"tagFilterMode"`
}
if err := json.Unmarshal(body, &presenceCheck); err != nil {
// Non-fatal, just means we can't do presence check
@@ -207,6 +209,12 @@ func (h *NotificationHandlers) UpdateEmailConfig(w http.ResponseWriter, r *http.
if presenceCheck.RateLimit == nil {
config.RateLimit = existingConfig.RateLimit
}
+ if presenceCheck.TagFilter == nil {
+ config.TagFilter = existingConfig.TagFilter
+ }
+ if presenceCheck.TagMode == nil {
+ config.TagMode = existingConfig.TagMode
+ }
log.Info().
Bool("enabled", config.Enabled).
@@ -327,6 +335,11 @@ func (h *NotificationHandlers) GetWebhooks(w http.ResponseWriter, r *http.Reques
whMap["mention"] = webhook.Mention
}
+ if len(webhook.TagFilter) > 0 {
+ whMap["tagFilter"] = append([]string(nil), webhook.TagFilter...)
+ whMap["tagFilterMode"] = webhook.TagMode
+ }
+
// Signal that a signing secret is configured without revealing it
if webhook.SigningSecret != "" {
whMap["signingSecret"] = "***REDACTED***"
@@ -385,6 +398,8 @@ func (h *NotificationHandlers) CreateWebhook(w http.ResponseWriter, r *http.Requ
}
responseData["id"] = webhook.ID
responseData["customFields"] = webhook.CustomFields
+ responseData["tagFilter"] = webhook.TagFilter
+ responseData["tagFilterMode"] = webhook.TagMode
if err := utils.WriteJSONResponse(w, responseData); err != nil {
log.Error().Err(err).Msg("Failed to write webhook creation response")
@@ -418,6 +433,11 @@ func (h *NotificationHandlers) UpdateWebhook(w http.ResponseWriter, r *http.Requ
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
+ var routingPresence struct {
+ TagFilter *[]string `json:"tagFilter"`
+ TagMode *string `json:"tagFilterMode"`
+ }
+ _ = json.Unmarshal(bodyBytes, &routingPresence)
webhook = notifications.NormalizeWebhookConfig(webhook)
// Preserve original headers/customFields if the incoming values are redacted
@@ -425,6 +445,12 @@ func (h *NotificationHandlers) UpdateWebhook(w http.ResponseWriter, r *http.Requ
existingWebhooks := h.getMonitor(r.Context()).GetNotificationManager().GetWebhooks()
for _, existing := range existingWebhooks {
if existing.ID == webhookID {
+ if routingPresence.TagFilter == nil {
+ webhook.TagFilter = existing.TagFilter
+ }
+ if routingPresence.TagMode == nil {
+ webhook.TagMode = existing.TagMode
+ }
// Preserve headers if incoming contains redacted values
if len(webhook.Headers) > 0 && len(existing.Headers) > 0 {
hasRedacted := false
@@ -485,6 +511,8 @@ func (h *NotificationHandlers) UpdateWebhook(w http.ResponseWriter, r *http.Requ
}
responseData["id"] = webhookID
responseData["customFields"] = webhook.CustomFields
+ responseData["tagFilter"] = webhook.TagFilter
+ responseData["tagFilterMode"] = webhook.TagMode
if err := utils.WriteJSONResponse(w, responseData); err != nil {
log.Error().Err(err).Str("webhookID", webhookID).Msg("Failed to write webhook update response")
diff --git a/internal/api/notifications_test.go b/internal/api/notifications_test.go
index 0ca6835960..ba7886200d 100644
--- a/internal/api/notifications_test.go
+++ b/internal/api/notifications_test.go
@@ -336,6 +336,60 @@ func TestNotificationHandlers(t *testing.T) {
mockPersistence.AssertExpectations(t)
})
+ t.Run("UpdateEmailConfig_PreservesOmittedTagRouting", func(t *testing.T) {
+ existing := notifications.EmailConfig{
+ TagFilter: []string{"customer:alpha", "critical"},
+ TagMode: "any",
+ }
+ mockManager.On("GetEmailConfig").Return(existing).Once()
+ mockManager.On("SetEmailConfig", mock.MatchedBy(func(cfg notifications.EmailConfig) bool {
+ return assert.ObjectsAreEqual(
+ []string{"customer:alpha", "critical"},
+ cfg.TagFilter,
+ ) && cfg.TagMode == "any"
+ })).Return().Once()
+ mockPersistence.On("SaveEmailConfig", mock.MatchedBy(func(cfg notifications.EmailConfig) bool {
+ return assert.ObjectsAreEqual(
+ []string{"customer:alpha", "critical"},
+ cfg.TagFilter,
+ ) && cfg.TagMode == "any"
+ })).Return(nil).Once()
+
+ req := httptest.NewRequest(
+ "PUT",
+ "/api/notifications/email",
+ bytes.NewBufferString(`{"enabled":true}`),
+ )
+ w := httptest.NewRecorder()
+ h.UpdateEmailConfig(w, req)
+
+ assert.Equal(t, http.StatusOK, w.Code)
+ })
+
+ t.Run("UpdateEmailConfig_ClearsTagRoutingExplicitly", func(t *testing.T) {
+ existing := notifications.EmailConfig{
+ TagFilter: []string{"customer:alpha"},
+ TagMode: "any",
+ }
+ mockManager.On("GetEmailConfig").Return(existing).Once()
+ mockManager.On("SetEmailConfig", mock.MatchedBy(func(cfg notifications.EmailConfig) bool {
+ return len(cfg.TagFilter) == 0 && cfg.TagMode == "all"
+ })).Return().Once()
+ mockPersistence.On("SaveEmailConfig", mock.MatchedBy(func(cfg notifications.EmailConfig) bool {
+ return len(cfg.TagFilter) == 0 && cfg.TagMode == "all"
+ })).Return(nil).Once()
+
+ req := httptest.NewRequest(
+ "PUT",
+ "/api/notifications/email",
+ bytes.NewBufferString(`{"enabled":true,"tagFilter":[],"tagFilterMode":"all"}`),
+ )
+ w := httptest.NewRecorder()
+ h.UpdateEmailConfig(w, req)
+
+ assert.Equal(t, http.StatusOK, w.Code)
+ })
+
t.Run("UpdateEmailConfig_InvalidJSON", func(t *testing.T) {
req := httptest.NewRequest("PUT", "/api/notifications/email", bytes.NewReader([]byte("{invalid}")))
w := httptest.NewRecorder()
@@ -359,11 +413,13 @@ func TestNotificationHandlers(t *testing.T) {
t.Run("GetWebhooks", func(t *testing.T) {
webhooks := []notifications.WebhookConfig{
{
- ID: "wh1",
- Name: "Test Webhook",
- URL: "https://example.com",
- Headers: map[string]string{"Authorization": "Bearer token"},
- Mention: "@everyone",
+ ID: "wh1",
+ Name: "Test Webhook",
+ URL: "https://example.com",
+ Headers: map[string]string{"Authorization": "Bearer token"},
+ Mention: "@everyone",
+ TagFilter: []string{"customer:alpha", "critical"},
+ TagMode: "any",
},
}
mockManager.On("GetWebhooks").Return(webhooks).Once()
@@ -378,6 +434,8 @@ func TestNotificationHandlers(t *testing.T) {
assert.Equal(t, 1, len(resp))
assert.Equal(t, "wh1", resp[0]["id"])
assert.Equal(t, "@everyone", resp[0]["mention"])
+ assert.Equal(t, []interface{}{"customer:alpha", "critical"}, resp[0]["tagFilter"])
+ assert.Equal(t, "any", resp[0]["tagFilterMode"])
headers := resp[0]["headers"].(map[string]interface{})
assert.Equal(t, "***REDACTED***", headers["Authorization"])
})
@@ -480,6 +538,43 @@ func TestNotificationHandlers(t *testing.T) {
assert.Equal(t, 200, w.Code)
})
+ t.Run("UpdateWebhook_PreservesOmittedTagRouting", func(t *testing.T) {
+ existing := notifications.WebhookConfig{
+ ID: "wh1",
+ URL: "https://example.com/hook",
+ TagFilter: []string{"customer:alpha", "critical"},
+ TagMode: "any",
+ }
+ mockManager.On("GetWebhooks").Return([]notifications.WebhookConfig{existing}).Once()
+ mockManager.On("ValidateWebhookURL", existing.URL).Return(nil).Once()
+ mockManager.On(
+ "UpdateWebhook",
+ "wh1",
+ mock.MatchedBy(func(cfg notifications.WebhookConfig) bool {
+ return assert.ObjectsAreEqual(
+ []string{"customer:alpha", "critical"},
+ cfg.TagFilter,
+ ) && cfg.TagMode == "any"
+ }),
+ ).Return(nil).Once()
+ mockManager.On("GetWebhooks").Return([]notifications.WebhookConfig{existing}).Once()
+ mockPersistence.On("SaveWebhooks", mock.Anything).Return(nil).Once()
+
+ req := httptest.NewRequest(
+ "PUT",
+ "/api/notifications/webhooks/wh1",
+ bytes.NewBufferString(`{"name":"Updated","url":"https://example.com/hook"}`),
+ )
+ w := httptest.NewRecorder()
+ h.UpdateWebhook(w, req)
+
+ assert.Equal(t, http.StatusOK, w.Code)
+ var response map[string]interface{}
+ assert.NoError(t, json.Unmarshal(w.Body.Bytes(), &response))
+ assert.Equal(t, []interface{}{"customer:alpha", "critical"}, response["tagFilter"])
+ assert.Equal(t, "any", response["tagFilterMode"])
+ })
+
t.Run("DeleteWebhook", func(t *testing.T) {
mockManager.On("DeleteWebhook", "wh1").Return(nil).Once()
mockManager.On("GetWebhooks").Return([]notifications.WebhookConfig{}).Once()
diff --git a/internal/notifications/notifications.go b/internal/notifications/notifications.go
index 039f21ff5a..6713d2e45e 100644
--- a/internal/notifications/notifications.go
+++ b/internal/notifications/notifications.go
@@ -289,6 +289,9 @@ func copyEmailConfig(cfg EmailConfig) EmailConfig {
if len(cfg.To) > 0 {
copy.To = append([]string(nil), cfg.To...)
}
+ if len(cfg.TagFilter) > 0 {
+ copy.TagFilter = append([]string(nil), cfg.TagFilter...)
+ }
return copy
}
@@ -315,6 +318,9 @@ func copyWebhookConfigs(webhooks []WebhookConfig) []WebhookConfig {
}
clone.CustomFields = custom
}
+ if len(clone.TagFilter) > 0 {
+ clone.TagFilter = append([]string(nil), clone.TagFilter...)
+ }
copies = append(copies, clone)
}
@@ -334,6 +340,12 @@ func copyWebhookConfig(webhook WebhookConfig) WebhookConfig {
// carry canonical webhook state and must not rely on legacy alias migration here.
func NormalizeWebhookConfig(webhook WebhookConfig) WebhookConfig {
normalized := webhook
+ normalized.TagFilter = normalizeNotificationTagFilter(normalized.TagFilter)
+ if len(normalized.TagFilter) == 0 {
+ normalized.TagMode = ""
+ } else {
+ normalized.TagMode = normalizeNotificationTagMode(normalized.TagMode)
+ }
if strings.EqualFold(strings.TrimSpace(normalized.Service), "pushover") {
normalized.CustomFields = normalizePushoverWebhookCustomFields(normalized.CustomFields)
}
@@ -560,6 +572,8 @@ type EmailConfig struct {
TLS bool `json:"tls"`
StartTLS bool `json:"startTLS"` // STARTTLS support
RateLimit int `json:"rateLimit"` // Max emails per minute (0 = default 60)
+ TagFilter []string `json:"tagFilter,omitempty"`
+ TagMode string `json:"tagFilterMode,omitempty"` // "all" (default) or "any"
}
// WebhookConfig holds webhook settings
@@ -574,6 +588,8 @@ type WebhookConfig struct {
Template string `json:"template"` // Custom payload template
CustomFields map[string]string `json:"customFields,omitempty"`
Mention string `json:"mention,omitempty"` // Platform-specific mention (e.g., @everyone, @channel, <@USER_ID>)
+ TagFilter []string `json:"tagFilter,omitempty"`
+ TagMode string `json:"tagFilterMode,omitempty"` // "all" (default) or "any"
// SigningSecret enables HMAC-SHA256 signing of outbound deliveries.
// When set, requests carry X-Pulse-Timestamp and X-Pulse-Signature
// (v1=hex(hmac_sha256(secret, timestamp + "." + body))) so receivers
@@ -614,6 +630,12 @@ func normalizeEmailConfig(cfg EmailConfig) EmailConfig {
normalized.SMTPHost = strings.TrimSpace(normalized.SMTPHost)
normalized.Username = strings.TrimSpace(normalized.Username)
normalized.From = strings.TrimSpace(normalized.From)
+ normalized.TagFilter = normalizeNotificationTagFilter(normalized.TagFilter)
+ if len(normalized.TagFilter) == 0 {
+ normalized.TagMode = ""
+ } else {
+ normalized.TagMode = normalizeNotificationTagMode(normalized.TagMode)
+ }
if normalized.SMTPPort <= 0 || normalized.SMTPPort > 65535 {
log.Warn().
@@ -892,7 +914,7 @@ func (n *NotificationManager) SetGroupingOptions(byNode, byGuest bool) {
func (n *NotificationManager) AddWebhook(webhook WebhookConfig) {
n.mu.Lock()
defer n.mu.Unlock()
- n.webhooks = append(n.webhooks, copyWebhookConfig(webhook))
+ n.webhooks = append(n.webhooks, copyWebhookConfig(NormalizeWebhookConfig(webhook)))
}
// UpdateWebhook updates an existing webhook
@@ -902,7 +924,7 @@ func (n *NotificationManager) UpdateWebhook(webhookID string, webhook WebhookCon
for i, w := range n.webhooks {
if w.ID == webhookID {
- n.webhooks[i] = copyWebhookConfig(webhook)
+ n.webhooks[i] = copyWebhookConfig(NormalizeWebhookConfig(webhook))
return nil
}
}
@@ -1462,28 +1484,34 @@ func buildNotificationDeliveryJobsForTarget(
jobs := make([]notificationDeliveryJob, 0, 2+len(webhooks))
if emailConfig.Enabled && (target == notificationDeliveryTargetAll || target == notificationDeliveryTargetEmail) {
- emailCopy := emailConfig
- jobs = append(jobs, notificationDeliveryJob{
- Type: "email",
- Event: event,
- Alerts: alertsToSend,
- ResolvedAt: resolvedAt,
- EmailConfig: &emailCopy,
- })
+ routedAlerts := routeNotificationAlerts(alertsToSend, emailConfig.TagFilter, emailConfig.TagMode, event)
+ if len(routedAlerts) > 0 {
+ emailCopy := emailConfig
+ jobs = append(jobs, notificationDeliveryJob{
+ Type: "email",
+ Event: event,
+ Alerts: routedAlerts,
+ ResolvedAt: resolvedAt,
+ EmailConfig: &emailCopy,
+ })
+ }
}
if target == notificationDeliveryTargetAll || target == notificationDeliveryTargetWebhook {
for _, webhook := range webhooks {
if !webhook.Enabled {
continue
}
- webhookCopy := webhook
- jobs = append(jobs, notificationDeliveryJob{
- Type: "webhook",
- Event: event,
- Alerts: alertsToSend,
- ResolvedAt: resolvedAt,
- WebhookConfig: &webhookCopy,
- })
+ routedAlerts := routeNotificationAlerts(alertsToSend, webhook.TagFilter, webhook.TagMode, event)
+ if len(routedAlerts) > 0 {
+ webhookCopy := webhook
+ jobs = append(jobs, notificationDeliveryJob{
+ Type: "webhook",
+ Event: event,
+ Alerts: routedAlerts,
+ ResolvedAt: resolvedAt,
+ WebhookConfig: &webhookCopy,
+ })
+ }
}
}
if appriseConfig.Enabled && (target == notificationDeliveryTargetAll || target == notificationDeliveryTargetApprise) {
diff --git a/internal/notifications/tag_routing.go b/internal/notifications/tag_routing.go
new file mode 100644
index 0000000000..bd256b1e3b
--- /dev/null
+++ b/internal/notifications/tag_routing.go
@@ -0,0 +1,131 @@
+package notifications
+
+import (
+ "strings"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts"
+)
+
+const (
+ notificationTagModeAll = "all"
+ notificationTagModeAny = "any"
+)
+
+func normalizeNotificationTagMode(raw string) string {
+ if strings.EqualFold(strings.TrimSpace(raw), notificationTagModeAny) {
+ return notificationTagModeAny
+ }
+ return notificationTagModeAll
+}
+
+func normalizeNotificationTagFilter(values []string) []string {
+ if len(values) == 0 {
+ return nil
+ }
+
+ normalized := make([]string, 0, len(values))
+ seen := make(map[string]struct{}, len(values))
+ for _, raw := range values {
+ value := strings.TrimSpace(raw)
+ key := strings.ToLower(value)
+ if value == "" {
+ continue
+ }
+ if _, exists := seen[key]; exists {
+ continue
+ }
+ seen[key] = struct{}{}
+ normalized = append(normalized, value)
+ }
+ if len(normalized) == 0 {
+ return nil
+ }
+ return normalized
+}
+
+func notificationAlertTags(alert *alerts.Alert) []string {
+ if alert == nil || alert.Metadata == nil {
+ return nil
+ }
+
+ values := make([]string, 0)
+ for _, key := range []string{"tags", "resourceTags", "hostTags", "serviceTags"} {
+ values = appendNotificationTagValues(values, alert.Metadata[key])
+ }
+ return normalizeNotificationTagFilter(values)
+}
+
+func appendNotificationTagValues(target []string, raw interface{}) []string {
+ switch value := raw.(type) {
+ case string:
+ for _, part := range strings.FieldsFunc(value, func(r rune) bool {
+ return r == ',' || r == ';'
+ }) {
+ target = append(target, part)
+ }
+ case []string:
+ target = append(target, value...)
+ case []interface{}:
+ for _, item := range value {
+ if text, ok := item.(string); ok {
+ target = append(target, text)
+ }
+ }
+ }
+ return target
+}
+
+func notificationAlertMatchesTags(alert *alerts.Alert, filter []string, mode string) bool {
+ filter = normalizeNotificationTagFilter(filter)
+ if len(filter) == 0 {
+ return true
+ }
+
+ alertTags := notificationAlertTags(alert)
+ if len(alertTags) == 0 {
+ return false
+ }
+
+ tagSet := make(map[string]struct{}, len(alertTags))
+ for _, tag := range alertTags {
+ tagSet[strings.ToLower(tag)] = struct{}{}
+ }
+
+ if normalizeNotificationTagMode(mode) == notificationTagModeAny {
+ for _, required := range filter {
+ if _, exists := tagSet[strings.ToLower(required)]; exists {
+ return true
+ }
+ }
+ return false
+ }
+
+ for _, required := range filter {
+ if _, exists := tagSet[strings.ToLower(required)]; !exists {
+ return false
+ }
+ }
+ return true
+}
+
+func routeNotificationAlerts(
+ alertList []*alerts.Alert,
+ filter []string,
+ mode string,
+ event notificationEvent,
+) []*alerts.Alert {
+ // Resolutions are routed by delivery receipts later in the pipeline.
+ // Reapplying a mutable tag filter here could suppress the clear after tags
+ // changed between firing and recovery.
+ if event == eventResolved || len(normalizeNotificationTagFilter(filter)) == 0 {
+ return alertList
+ }
+
+ routed := make([]*alerts.Alert, 0, len(alertList))
+ for _, alert := range alertList {
+ if notificationAlertMatchesTags(alert, filter, mode) {
+ routed = append(routed, alert)
+ }
+ }
+ return routed
+}
diff --git a/internal/notifications/tag_routing_test.go b/internal/notifications/tag_routing_test.go
new file mode 100644
index 0000000000..c1420f4c2d
--- /dev/null
+++ b/internal/notifications/tag_routing_test.go
@@ -0,0 +1,137 @@
+package notifications
+
+import (
+ "reflect"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts"
+)
+
+func taggedRoutingAlert(id string, tags interface{}) *alerts.Alert {
+ return &alerts.Alert{
+ ID: id,
+ StartTime: time.Unix(1_700_000_000, 0),
+ Metadata: map[string]interface{}{"tags": tags},
+ }
+}
+
+func TestBuildNotificationDeliveryJobsRoutesAlertsByDestinationTags(t *testing.T) {
+ alpha := taggedRoutingAlert("alpha", []string{"customer:alpha", "critical"})
+ beta := taggedRoutingAlert("beta", []interface{}{"customer:beta", "critical"})
+ untagged := &alerts.Alert{ID: "untagged", StartTime: time.Unix(1_700_000_000, 0)}
+
+ jobs := buildNotificationDeliveryJobs(
+ EmailConfig{
+ Enabled: true,
+ TagFilter: []string{"customer:alpha", "critical"},
+ TagMode: notificationTagModeAll,
+ },
+ []WebhookConfig{
+ {ID: "alpha", Enabled: true, TagFilter: []string{"customer:alpha"}},
+ {ID: "critical", Enabled: true, TagFilter: []string{"critical"}, TagMode: notificationTagModeAny},
+ {ID: "global", Enabled: true},
+ {ID: "missing", Enabled: true, TagFilter: []string{"does-not-exist"}},
+ },
+ AppriseConfig{},
+ []*alerts.Alert{alpha, beta, untagged},
+ eventAlert,
+ time.Time{},
+ )
+
+ if len(jobs) != 4 {
+ t.Fatalf("jobs = %d, want email plus three matching webhooks", len(jobs))
+ }
+ if got := alertIDs(jobs[0].Alerts); !reflect.DeepEqual(got, []string{"alpha"}) {
+ t.Fatalf("email alerts = %v, want [alpha]", got)
+ }
+ if got := alertIDs(jobs[1].Alerts); !reflect.DeepEqual(got, []string{"alpha"}) {
+ t.Fatalf("alpha webhook alerts = %v, want [alpha]", got)
+ }
+ if got := alertIDs(jobs[2].Alerts); !reflect.DeepEqual(got, []string{"alpha", "beta"}) {
+ t.Fatalf("critical webhook alerts = %v, want [alpha beta]", got)
+ }
+ if got := alertIDs(jobs[3].Alerts); !reflect.DeepEqual(got, []string{"alpha", "beta", "untagged"}) {
+ t.Fatalf("global webhook alerts = %v, want all alerts", got)
+ }
+}
+
+func TestTagRoutingNormalizesCaseSourcesAndModes(t *testing.T) {
+ alert := &alerts.Alert{
+ ID: "mixed",
+ Metadata: map[string]interface{}{
+ "tags": " Customer:Alpha ; production ",
+ "resourceTags": []string{"Critical"},
+ "hostTags": []interface{}{"eu-west", 7},
+ },
+ }
+
+ if !notificationAlertMatchesTags(alert, []string{"customer:alpha", "CRITICAL"}, "all") {
+ t.Fatal("expected case-insensitive all-tag match across metadata sources")
+ }
+ if !notificationAlertMatchesTags(alert, []string{"missing", "EU-WEST"}, "ANY") {
+ t.Fatal("expected case-insensitive any-tag match")
+ }
+ if notificationAlertMatchesTags(alert, []string{"missing"}, "any") {
+ t.Fatal("unexpected match for absent tag")
+ }
+ if !notificationAlertMatchesTags(alert, nil, "all") {
+ t.Fatal("empty filter must preserve global delivery")
+ }
+}
+
+func TestResolvedTagRoutingDefersToDeliveryReceipts(t *testing.T) {
+ alert := taggedRoutingAlert("changed-tags", []string{"customer:beta"})
+ routed := routeNotificationAlerts(
+ []*alerts.Alert{alert},
+ []string{"customer:alpha"},
+ notificationTagModeAll,
+ eventResolved,
+ )
+ if len(routed) != 1 {
+ t.Fatal("resolution must reach the receipt filter even after tags change")
+ }
+}
+
+func TestNotificationTagConfigNormalizationAndCopies(t *testing.T) {
+ email := normalizeEmailConfig(EmailConfig{
+ TagFilter: []string{" Customer:Alpha ", "customer:alpha", "", "Critical"},
+ TagMode: "unexpected",
+ })
+ if !reflect.DeepEqual(email.TagFilter, []string{"Customer:Alpha", "Critical"}) {
+ t.Fatalf("normalized email filter = %v", email.TagFilter)
+ }
+ if email.TagMode != notificationTagModeAll {
+ t.Fatalf("normalized email mode = %q, want all", email.TagMode)
+ }
+
+ webhook := NormalizeWebhookConfig(WebhookConfig{
+ TagFilter: []string{" prod ", "PROD", "customer:beta"},
+ TagMode: "ANY",
+ })
+ if !reflect.DeepEqual(webhook.TagFilter, []string{"prod", "customer:beta"}) {
+ t.Fatalf("normalized webhook filter = %v", webhook.TagFilter)
+ }
+ if webhook.TagMode != notificationTagModeAny {
+ t.Fatalf("normalized webhook mode = %q, want any", webhook.TagMode)
+ }
+ if got := NormalizeWebhookConfig(WebhookConfig{TagMode: notificationTagModeAny}); got.TagMode != "" {
+ t.Fatalf("unfiltered webhook mode = %q, want empty for legacy compatibility", got.TagMode)
+ }
+
+ emailCopy := copyEmailConfig(email)
+ webhookCopy := copyWebhookConfig(webhook)
+ emailCopy.TagFilter[0] = "mutated"
+ webhookCopy.TagFilter[0] = "mutated"
+ if email.TagFilter[0] == "mutated" || webhook.TagFilter[0] == "mutated" {
+ t.Fatal("notification config copies must isolate tag-filter slices")
+ }
+}
+
+func alertIDs(alertList []*alerts.Alert) []string {
+ ids := make([]string, 0, len(alertList))
+ for _, alert := range alertList {
+ ids = append(ids, alert.ID)
+ }
+ return ids
+}