Compare commits

..

4 Commits

Author SHA1 Message Date
srikanthccv
8e6b780fc8 feat(alertmanager): say in the notification which template failed
A fallback that says nothing leaves the author with a notification that
is not the one they wrote, and no reason. Each notifier now adds one
line for each template that failed, with the expression and the reason.
The position that the template engine reports is left out: for a rule
template it counts a hidden preamble and does not point into the text
the author wrote.

Assisted-by: Claude Fable 5.2
2026-11-22 10:03:41 +05:30
srikanthccv
6ee6bee4ea fix(ruler): report a rule test that did not send
The rule test answered "notification sent" when a receiver refused the
alert; the failure went to the server log only. The test now returns it,
with one line for each receiver. It is an invalid input error and not an
internal one, because the receiver is the caller's to correct.

Assisted-by: Claude Fable 5.2
2026-11-22 09:44:01 +05:30
srikanthccv
c79d83aeb3 fix(ruler): check rule notification templates with the notifier engine
The rule API parsed the title and body templates with the ruler engine,
which has other variables and functions. It rejected templates the
notifier can execute and accepted ones it cannot parse. The check now
uses the notifier engine and rejects only a template that fails for
every alert: one that does not parse. A template that fails on some
alert data is accepted, because the send path falls back for it.

The patch path does not run the check, so a stored rule can always be
disabled.

Assisted-by: Claude Fable 5.2
2026-11-22 09:39:18 +05:30
srikanthccv
cbe4d94781 fix(alertmanager): send the notification when a title or body template fails
A rule template that the notifier could not execute stopped the
notification, and so did a channel template. Each half now falls back on
its own: rule template, then channel template, then the built-in template
of the channel kind. An empty template is not a failure and keeps its
current behaviour.

Assisted-by: Claude Fable 5.2
2026-11-22 09:34:36 +05:30
51 changed files with 1513 additions and 156 deletions

View File

@@ -28,7 +28,7 @@ You are operating within a constrained context window and strict system prompts.
- UI primitives come from `@signozhq/ui` (subpath imports) and icons from `@signozhq/icons`. No new `antd` component or direct icon library (`lucide-react`) where `@signozhq/ui` has an equivalent; `signoz/no-antd-components` enforces part of this list.
- Exception: a control added beside `antd` siblings of the same kind (a tab in an `antd` tab strip) matches them until that surface migrates. Say so in the PR.
- When `@signozhq/ui` or `@signozhq/icons` lacks what you need, say so in the PR before reaching for another library.
- Never override a `@signozhq/ui` component's styles: no `--<component>-*` CSS variables, no `:global` class or `data-*` selectors, no restyling through `className`/`style`. Use its props, and put layout on a wrapper you own. When it can't do what the design needs, file a UI suggestion in `SigNoz/uforge-pod` (`ui-suggestion.yml` template) and link it in the PR.
- Before styling a `@signozhq/ui` component, check its props in `node_modules/@signozhq/ui/dist/<component>/*.d.ts` for `className`/`style` support; some omit them. Avoid overriding the component's CSS vars unless explicitly needed.
- When writing code that could need authorization checks, read ./src/lib/authz/README.md
- A flow that gains a request also gates on that request's permission: a rename that now reads the view first needs `read` as well as `update`.
- Identity keys (legend groups, color groups, CSV headers, React keys) come from structured values, never from joined display text: `['us, east', 'prod']` and `['us', 'east, prod']` both join to `us, east, prod`.

View File

@@ -9,12 +9,12 @@
- [ ] No deep class nesting (max 3 class levels; pseudo-classes/elements and parent-reference selectors like `&.active`, `&#bar` are not counted)
- [ ] No hardcoded colors - use `--l1/l2/l3-*` semantic tokens (not `--bg-*` primitives)
- [ ] No magic numbers - use `--spacing-*` tokens
- [ ] Typography uses `--{variant}-{size}-{weight}-*` text style tokens (see Typography)
- [ ] No overrides of `@signozhq/ui` components (see below)
- [ ] Global escapes only for third-party overrides (`@signozhq/ui` is not third-party)
- [ ] Typography uses `--periscope-font-size-*` or `--font-size-*` tokens
- [ ] @signozhq/ui overrides use CSS variables, not direct class overrides
- [ ] Global escapes only for third-party overrides
- [ ] No ID selectors
- [ ] No bare element selectors
- [ ] Keyframes are declared in the module with plain `@keyframes name` (already local)
- [ ] Keyframes use `:local(@keyframes name)` to avoid global collisions
## Config (vite.config.ts)
@@ -77,7 +77,7 @@ css: {
// BAD: Nesting creates separate classes you might not expect
.button {
.icon { } // -> styles.icon, but the rule is `.button .icon`: it only matches inside .button
.icon { } // -> styles.icon (separate class, not scoped under .button)
}
// GOOD: Flat structure
@@ -289,32 +289,88 @@ Use L1/L2/L3 semantic tokens - they handle light/dark theme automatically.
- L2 = elevated surfaces (cards, panels)
- L3 = nested/inset elements
## @signozhq/ui Components
## Overriding @signozhq/ui Components
Don't override them. That covers setting a component's `--<component>-*` CSS variables, targeting its classes or `data-*` attributes through `:global(...)`, and restyling it with `className` or `style`. An override keeps working until the component changes, then breaks with no type error or lint warning, and the screen drifts from every other one using that component.
Components expose CSS variables for customization.
- Use the component's props (`variant`, `color`, `size`, ...) for how it looks.
- Put layout (position, margin, width inside a flex or grid parent) on a wrapper element you own.
- If the component can't do what the design needs, file a [UI suggestion](https://github.com/SigNoz/uforge-pod/issues/new?template=ui-suggestion.yml) in `SigNoz/uforge-pod` and ship with the component as it renders until the suggestion is decided. Link the issue in the PR.
You can ensure they exist by looking at ./node_modules/@signozhq/ui/dist.
Never write a override without confirm it exists.
Override via:
### Method 1: CSS Variables (Preferred)
Each component exposes `--<component>-<property>` variables:
```scss
// BAD: Restyling the component
.saveButton {
--button-primary-background-color: var(--success-background);
// Override Button
.customButton {
--button-background: var(--success-background);
--button-border-radius: var(--radius-2);
--button-padding: var(--spacing-4) var(--spacing-8);
--button-font-size: var(--label-base-400-font-size);
}
.toolbar :global([data-variant="outlined"]) {
--button-variant-outlined-border: 1px solid var(--accent-primary);
// Override Input
.customInput {
--input-height: 2.5rem;
--input-border-color: var(--l2-border);
--input-padding: var(--spacing-2) var(--spacing-6);
--input-placeholder-color: var(--l3-foreground);
}
// GOOD: Layout on your own wrapper, looks from props
.toolbarActions {
display: flex;
gap: var(--spacing-4);
margin-left: auto;
// Override nested parts
.customInput {
--input-prefix-padding: 0 var(--spacing-4) 0 var(--spacing-6);
--input-suffix-color: var(--accent-primary);
}
```
### Method 2: Data Attributes
Components use data attributes for variants/states. Target them for state-specific overrides:
```scss
// Target variant
.wrapper :global([data-variant="outlined"]) {
--button-border-color: var(--accent-primary);
}
// Target size
.wrapper :global([data-size="sm"]) {
--button-font-size: var(--label-small-400-font-size);
}
// Target color
.wrapper :global([data-color="destructive"]) {
--button-background: var(--danger-background);
}
// Target state (Radix patterns)
.popover :global([data-state="open"]) {
opacity: 1;
}
.tooltip :global([data-side="top"]) {
margin-bottom: var(--spacing-2);
}
```
### Common Component CSS Variables
**Button:**
- `--button-background`, `--button-border-radius`, `--button-padding`
- `--button-font-size`, `--button-height`, `--button-gap`
- `--button-hover-background`, `--button-disabled-opacity`
**Input:**
- `--input-height`, `--input-border-color`, `--input-background`
- `--input-padding`, `--input-font-size`, `--input-placeholder-color`
- `--input-focus-outline-color`, `--input-hover-border-color`
- `--input-prefix-*`, `--input-suffix-*` for adornments
**General pattern:** `--<component>-<property>` or `--<component>-<state>-<property>`
## Good Patterns
### Structure
@@ -378,21 +434,24 @@ Don't override them. That covers setting a component's `--<component>-*` CSS var
### Keyframes (Local Scoping)
CSS Modules scope `@keyframes` like classes: the build renames `fadeIn` to `_fadeIn_<hash>` and rewrites every `animation` in the same module that names it. Don't wrap it in `:local(...)`; Sass rejects `:local(@keyframes fadeIn)` with `expected selector`.
Without `:local()`, keyframe names are global and can clash across modules:
```scss
// GOOD: Local to this module
// BAD: Global keyframe - can conflict with other modules
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
// GOOD: Locally scoped keyframe
:local(@keyframes fadeIn) {
from { opacity: 0; }
to { opacity: 1; }
}
.modal {
animation: fadeIn 200ms ease;
}
// BAD: Doesn't compile
:local(@keyframes fadeIn) { }
```
## JS Import Patterns

View File

@@ -8,7 +8,7 @@
--input-focus-background: transparent;
--input-focus-outline-width: 0;
--input-box-shadow: none;
--input-font-size: var(--label-base-400-font-size);
--input-font-size: var(--periscope-font-size-base);
--input-line-height: 20px;
--input-placeholder-color: color-mix(
in srgb,

View File

@@ -12,8 +12,8 @@
}
.heading {
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-medium);
line-height: 1;
letter-spacing: 0.04em;
text-transform: uppercase;
@@ -34,9 +34,9 @@
--button-height: auto;
--button-padding: var(--spacing-4) var(--spacing-6);
--button-border-radius: var(--radius-3);
--button-font-size: var(--label-base-400-font-size);
--button-font-size: var(--periscope-font-size-base);
--button-size-line-height: var(--line-height-20);
--button-font-weight: var(--label-base-400-font-weight);
--button-font-weight: var(--font-weight-normal);
--button-variant-outlined-background-color: var(--l3-background-60);
--button-variant-outlined-border: none;
--button-variant-outlined-color: var(--l2-foreground);

View File

@@ -31,8 +31,8 @@
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-medium);
line-height: 18px;
letter-spacing: -0.005em;
}
@@ -54,7 +54,7 @@
.soloThought {
margin: 0;
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l2-foreground);
@@ -64,8 +64,8 @@
// While Noz works, the row names the step it's on.
.live .activitySummary {
font-size: var(--paragraph-base-400-font-size);
font-weight: var(--paragraph-base-400-font-weight);
font-size: var(--periscope-font-size-base);
font-weight: var(--font-weight-normal);
line-height: var(--line-height-20);
@include shimmer-text(var(--l3-foreground), var(--l1-foreground));
}

View File

@@ -59,7 +59,7 @@
border: none;
background: none;
font: inherit;
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l1-foreground);
@@ -90,7 +90,7 @@ button.title {
}
.detail {
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l2-foreground);

View File

@@ -42,7 +42,7 @@
}
.headerLabel {
font-size: var(--paragraph-base-400-font-size);
font-size: var(--font-size-sm);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l1-foreground);
@@ -61,7 +61,7 @@
.summary {
margin: 0;
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
line-height: var(--line-height-20);
color: var(--l2-foreground);
}

View File

@@ -134,8 +134,8 @@
--button-padding: 7px #{$padding-inline};
--button-border-radius: 0;
--button-justify-content: flex-start;
--button-font-size: var(--label-base-400-font-size);
--button-font-weight: var(--label-base-400-font-weight);
--button-font-size: var(--periscope-font-size-base);
--button-font-weight: var(--font-weight-normal);
--button-variant-ghost-color: var(--l2-foreground);
--button-variant-ghost-hover-color: var(--l1-foreground);
--button-variant-ghost-hover-background-color: var(--l3-background);
@@ -180,8 +180,8 @@
height: 44px;
padding: 0 var(--spacing-7);
border-bottom: 1px solid var(--l2-border);
font-size: var(--label-small-600-font-size);
font-weight: var(--label-small-600-font-weight);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-semibold);
line-height: 1;
letter-spacing: 0.04em;
text-transform: uppercase;

View File

@@ -8,8 +8,8 @@
border-radius: var(--radius-2);
background: var(--l3-background-60);
color: var(--l2-foreground);
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
font-size: var(--font-size-xs);
font-weight: var(--font-weight-medium);
line-height: 15px;
transition:
background-color 0.12s,

View File

@@ -40,7 +40,7 @@
}
.headerLabel {
font-size: var(--paragraph-base-400-font-size);
font-size: var(--font-size-sm);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l1-foreground);
@@ -48,7 +48,7 @@
.message {
margin: 0;
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
line-height: var(--line-height-20);
color: var(--l2-foreground);
}

View File

@@ -53,7 +53,7 @@
}
.title {
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
line-height: 20px;
letter-spacing: -0.005em;
color: var(--text-vanilla-400);
@@ -73,7 +73,7 @@
// Wide enough to hold the action buttons that replace it.
min-width: 16px;
text-align: right;
font-size: var(--paragraph-small-400-font-size);
font-size: var(--periscope-font-size-small);
line-height: 18px;
color: var(--l3-foreground);
opacity: calc(1 - var(--actions-opacity, 0));
@@ -87,7 +87,7 @@
width: 100%;
border-bottom: 1px solid var(--accent-primary);
--input-padding: 1px 0;
--input-font-size: var(--label-base-400-font-size);
--input-font-size: var(--periscope-font-size-base);
--input-hover-border-color: transparent;
}

View File

@@ -56,7 +56,7 @@
--button-border-radius: 3px;
--button-justify-content: flex-start;
--button-gap: var(--spacing-4);
--button-font-weight: var(--label-base-400-font-weight);
--button-font-weight: var(--font-weight-normal);
--button-variant-outlined-background-color: var(--l2-background);
--button-variant-outlined-border: 1px solid var(--l1-border);
--button-variant-outlined-color: var(--l2-foreground);
@@ -144,8 +144,8 @@
.groupLabel {
display: block;
padding: 0 0 7px;
font-size: var(--label-small-600-font-size);
font-weight: var(--label-small-600-font-weight);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-semibold);
line-height: 1;
text-transform: uppercase;
letter-spacing: 0.04em;

View File

@@ -14,8 +14,8 @@
}
.note {
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-medium);
line-height: 1;
font-feature-settings:
'tnum' on,

View File

@@ -71,7 +71,7 @@
align-items: flex-start;
background: var(--l2-background);
color: var(--l1-foreground);
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
border-bottom-left-radius: var(--radius-2);
}
@@ -274,7 +274,7 @@
width: max-content;
min-width: 100%;
border-collapse: collapse;
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
font-variant-numeric: tabular-nums;
word-break: normal;
@@ -286,8 +286,8 @@
th {
padding-block: 13px;
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-medium);
line-height: 1;
letter-spacing: 0.04em;
text-transform: uppercase;

View File

@@ -44,8 +44,8 @@
--button-height: 32px;
--button-padding: 0 var(--spacing-6);
--button-border-radius: var(--radius-round);
--button-font-size: var(--label-base-400-font-size);
--button-font-weight: var(--label-base-400-font-weight);
--button-font-size: var(--periscope-font-size-base);
--button-font-weight: var(--font-weight-normal);
--button-secondary-background-color: var(--l3-background);
--button-secondary-hover-background-color: var(--l3-background-hover);
--button-secondary-solid-foreground: var(--l1-foreground);

View File

@@ -29,7 +29,7 @@
align-items: center;
justify-content: space-between;
gap: var(--spacing-6);
font-size: var(--label-base-500-font-size);
font-size: var(--font-size-sm);
font-weight: 500;
}
@@ -37,7 +37,7 @@
.subtitle {
padding-left: calc(12px + var(--spacing-3));
font-family: var(--font-mono);
font-size: var(--paragraph-small-400-font-size);
font-size: var(--font-size-xs);
color: var(--muted-foreground);
}
@@ -58,7 +58,7 @@
.code {
flex-shrink: 0;
font-family: var(--font-mono);
font-size: var(--paragraph-small-400-font-size);
font-size: var(--font-size-xs);
color: var(--muted-foreground);
}
@@ -100,7 +100,7 @@
align-items: center;
gap: var(--spacing-2);
font-family: var(--font-mono);
font-size: var(--paragraph-small-400-font-size);
font-size: var(--font-size-xs);
letter-spacing: -0.01em;
font-variant-numeric: tabular-nums;
}

View File

@@ -36,7 +36,7 @@
.sizerValue {
font-size: 12px;
font-weight: var(--label-base-500-font-weight);
font-weight: var(--font-weight-medium);
font-variant-numeric: tabular-nums;
}

View File

@@ -46,7 +46,7 @@
}
.tooltipName {
font-weight: var(--label-base-500-font-weight);
font-weight: var(--font-weight-medium);
word-break: break-word;
}

View File

@@ -37,7 +37,7 @@
.value {
font-size: 12px;
line-height: 16px;
font-weight: var(--label-base-500-font-weight);
font-weight: var(--font-weight-medium);
color: var(--l1-foreground);
text-align: right;
white-space: nowrap;

View File

@@ -425,12 +425,15 @@ func (n *Email) prepareContent(ctx context.Context, alerts []*types.Alert) (stri
BodyTemplate: customBody,
DefaultTitleTemplate: n.conf.Headers["Subject"],
DefaultBodyTemplate: n.conf.HTML,
BuiltinTitleTemplate: config.DefaultEmailSubject,
BuiltinBodyTemplate: config.DefaultEmailConfig.HTML,
}, alerts)
if err != nil {
return "", "", err
}
subject := result.Title
notice := alertmanagertemplate.RenderFailureNotice(ctx, n.logger, result.Failures, markdownrenderer.RenderHTML)
if !result.IsDefaultBody {
// Custom-body path: render each expanded markdown body to HTML, then
@@ -447,6 +450,9 @@ func (n *Email) prepareContent(ctx context.Context, alerts []*types.Alert) (stri
result.Body[i] = rendered
}
appendRelatedLinkButtons(alerts, result.Body)
if notice != "" {
result.Body = append(result.Body, notice)
}
html, err := n.renderLayout(result)
if err != nil {
n.logger.WarnContext(ctx, "custom email template rendering failed, falling back to plain <div> wrap", errors.Attr(err))
@@ -455,7 +461,7 @@ func (n *Email) prepareContent(ctx context.Context, alerts []*types.Alert) (stri
return subject, html, nil
}
return subject, result.Body[0], nil
return subject, result.Body[0] + notice, nil
}
// renderLayout wraps result in the email.signoz.html HTML layout loaded

View File

@@ -1154,6 +1154,58 @@ func TestPrepareContent(t *testing.T) {
assert.Equal(t, "fixed from firing", subject)
assert.NotContains(t, subject, "subject")
})
t.Run("custom title template that fails; custom body template", func(t *testing.T) {
tmpl, err := template.FromGlobs([]string{})
require.NoError(t, err)
tmpl.ExternalURL, _ = url.Parse("http://am")
alerts := []*types.Alert{{
Alert: model.Alert{
Labels: model.LabelSet{"instance": "three"},
Annotations: model.LabelSet{
model.LabelName(ruletypes.AnnotationTitleTemplate): "Rule title: {{ .CommonLabels.alertname }}",
model.LabelName(ruletypes.AnnotationBodyTemplate): "line $labels.instance",
},
StartsAt: time.Now(),
EndsAt: time.Now().Add(time.Hour),
},
}}
cfg := &config.EmailConfig{Headers: map[string]string{"Subject": "channel subject"}}
n := New(cfg, tmpl, promslog.NewNopLogger(), testTemplater(tmpl))
subject, htmlBody, err := n.prepareContent(context.Background(), alerts)
require.NoError(t, err)
assert.Equal(t, "channel subject", subject)
assert.Equal(t, "<div><p>line three</p>\n</div><div><p>The rule title template failed: <code>.CommonLabels.alertname: nil pointer evaluating interface {}.alertname</code>. The channel title is shown.</p></div>", htmlBody)
})
t.Run("custom body template that fails; default body HTML template", func(t *testing.T) {
tmpl, err := template.FromGlobs([]string{})
require.NoError(t, err)
tmpl.ExternalURL, _ = url.Parse("http://am")
alerts := []*types.Alert{{
Alert: model.Alert{
Labels: model.LabelSet{"instance": "four"},
Annotations: model.LabelSet{
model.LabelName(ruletypes.AnnotationBodyTemplate): "{{ slice .labels.instance 0 40 }}",
},
StartsAt: time.Now(),
EndsAt: time.Now().Add(time.Hour),
},
}}
cfg := &config.EmailConfig{
Headers: map[string]string{"Subject": "the channel subject"},
HTML: "<p>Status: {{ .Status }}</p>",
}
n := New(cfg, tmpl, promslog.NewNopLogger(), testTemplater(tmpl))
subject, htmlBody, err := n.prepareContent(context.Background(), alerts)
require.NoError(t, err)
assert.Equal(t, "the channel subject", subject)
assert.Equal(t, "<p>Status: firing</p><p>The rule body template failed: <code>slice .labels.instance 0 40: error calling slice: index out of range: 40</code>. The channel body is shown.</p>", htmlBody)
})
}
func ptrTo(b bool) *bool {

View File

@@ -103,6 +103,9 @@ type openLink struct {
type content struct {
title string
bodies []string
// notice says which template failed. It is not one of bodies, which stay
// aligned with the alerts.
notice string
}
func New(conf *alertmanagertypes.GoogleChatReceiverConfig, t *template.Template, l *slog.Logger, templater alertmanagertypes.Templater) (*Notifier, error) {
@@ -164,7 +167,7 @@ func (n *Notifier) Notify(ctx context.Context, alerts ...*types.Alert) (bool, er
if len(alerts) > 0 {
footerAlert = alerts[0]
}
buf, err := encodeMessage(buildMessage(title, status, capAlerts, bodies, remaining, footerAlert))
buf, err := encodeMessage(buildMessage(title, status, capAlerts, bodies, remaining, c.notice, footerAlert))
if err != nil {
return false, err
}
@@ -180,7 +183,7 @@ func (n *Notifier) Notify(ctx context.Context, alerts ...*types.Alert) (bool, er
// templating makes that reachable.
break
}
if buf, err = encodeMessage(buildMessage(title, status, capAlerts, bodies, remaining, footerAlert)); err != nil {
if buf, err = encodeMessage(buildMessage(title, status, capAlerts, bodies, remaining, c.notice, footerAlert)); err != nil {
return false, err
}
}
@@ -208,6 +211,8 @@ func (n *Notifier) prepareContent(ctx context.Context, alerts []*types.Alert) (c
BodyTemplate: customBody,
DefaultTitleTemplate: n.conf.Title,
DefaultBodyTemplate: n.conf.Text,
BuiltinTitleTemplate: alertmanagertypes.DefaultGoogleChatReceiverConfig.Title,
BuiltinBodyTemplate: alertmanagertypes.DefaultGoogleChatReceiverConfig.Text,
}, alerts)
if err != nil {
return content{}, err
@@ -228,7 +233,9 @@ func (n *Notifier) prepareContent(ctx context.Context, alerts []*types.Alert) (c
bodies[i] = html
}
return content{title: result.Title, bodies: bodies}, nil
notice := alertmanagertemplate.RenderFailureNotice(ctx, n.logger, result.Failures, markdownrenderer.RenderHTML)
return content{title: result.Title, bodies: bodies, notice: notice}, nil
}
// statusLine returns a colored firing/resolved banner for the card body.
@@ -290,7 +297,7 @@ func capAlertSections(alerts []*types.Alert, bodies []string) ([]*types.Alert, [
// alerts and bodies slices are the already-capped, aligned render set; footerAlert
// is the original first alert, used for the per-rule footer button so it survives
// even when no body renders.
func buildMessage(title, statusHTML string, alerts []*types.Alert, bodies []string, remaining int, footerAlert *types.Alert) Message {
func buildMessage(title, statusHTML string, alerts []*types.Alert, bodies []string, remaining int, notice string, footerAlert *types.Alert) Message {
sections := []cardSection{{Widgets: []widget{{TextParagraph: &textParagraph{Text: statusHTML}}}}}
for i, body := range bodies {
@@ -311,6 +318,10 @@ func buildMessage(title, statusHTML string, alerts []*types.Alert, bodies []stri
sections = append(sections, cardSection{Widgets: []widget{{TextParagraph: &textParagraph{Text: note}}}})
}
if notice != "" {
sections = append(sections, cardSection{Widgets: []widget{{TextParagraph: &textParagraph{Text: notice}}}})
}
if footerAlert != nil {
if btn := sigNozButton(footerAlert); btn != nil {
sections = append(sections, cardSection{Widgets: []widget{{ButtonList: &buttonList{Buttons: []button{*btn}}}}})

View File

@@ -85,6 +85,8 @@ func (n *Notifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error)
BodyTemplate: customBody,
DefaultTitleTemplate: n.conf.Title,
DefaultBodyTemplate: n.conf.Description,
BuiltinTitleTemplate: alertmanagertypes.DefaultIncidentIOTitleTemplate,
BuiltinBodyTemplate: alertmanagertypes.DefaultIncidentIODescriptionTemplate,
}, as)
if err != nil {
return false, err
@@ -106,6 +108,9 @@ func (n *Notifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error)
parts = append(parts, body)
}
}
if notice := result.Failures.Notice(); notice != "" {
parts = append(parts, notice)
}
description := truncateRunes(strings.Join(parts, "\n\n---\n\n"), maxDescriptionLenRunes)
status := statusFiring

View File

@@ -77,6 +77,8 @@ func (n *Notifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error)
BodyTemplate: customBody,
DefaultTitleTemplate: n.conf.Summary,
DefaultBodyTemplate: n.conf.Description,
BuiltinTitleTemplate: alertmanagertypes.DefaultJiraSummaryTemplate,
BuiltinBodyTemplate: alertmanagertypes.DefaultJiraDescriptionTemplate,
}, as)
if err != nil {
return false, err
@@ -89,6 +91,9 @@ func (n *Notifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error)
parts = append(parts, body)
}
}
if notice := result.Failures.Notice(); notice != "" {
parts = append(parts, notice)
}
// custom body templates render per alert; join them under ADF rule dividers.
// The default body is a single combined part, so the join is a no-op there.
descText := truncateRunes(strings.Join(parts, "\n\n---\n\n"), maxDescriptionLenRunes)

View File

@@ -369,6 +369,28 @@ func TestNotifyCustomTemplateAnnotationsOverrideDefaults(t *testing.T) {
assert.NotContains(t, s, "Summary:") // default body template not used
}
// A rule title that the notifier cannot execute must not cost the issue. The
// channel summary takes its place and the description says why.
func TestNotifyRuleTitleFailureUsesTheChannelSummary(t *testing.T) {
m := newMockJira(t)
a := alert(true)
a.Annotations[ruletypes.AnnotationTitleTemplate] = "Rule title: {{ .CommonLabels.alertname }}"
_, err := newNotifier(t, m).Notify(ctx(), a)
require.NoError(t, err)
body := m.lastBody(t, "/issue")
fields, ok := body["fields"].(map[string]any)
require.True(t, ok)
assert.Equal(t, "[FIRING:1] HighCPU", fields["summary"])
js, err := json.Marshal(fields["description"])
require.NoError(t, err)
assert.Contains(t, string(js), "The rule title template failed: ")
assert.Contains(t, string(js), ".CommonLabels.alertname: nil pointer evaluating interface {}.alertname")
assert.Contains(t, string(js), ". The channel title is shown.")
}
// Jira replaces labels wholesale on PUT, so the update must union in the
// labels already on the issue or user-added ones get wiped.
func TestNotifyUpdatePreservesUserAddedLabels(t *testing.T) {

View File

@@ -210,6 +210,8 @@ func (n *Notifier) prepareContent(ctx context.Context, alerts []*types.Alert) ([
BodyTemplate: customBody,
DefaultTitleTemplate: n.conf.Title,
DefaultBodyTemplate: n.conf.Text,
BuiltinTitleTemplate: config.DefaultMSTeamsV2Config.Title,
BuiltinBodyTemplate: config.DefaultMSTeamsV2Config.Text,
}, alerts)
if err != nil {
return nil, err
@@ -245,7 +247,7 @@ func (n *Notifier) prepareContent(ctx context.Context, alerts []*types.Alert) ([
})
blocks = append(blocks, n.createLabelsAndAnnotationsBody(alert)...)
}
return blocks, nil
return appendFailureNotice(blocks, result.Failures), nil
}
// Custom body path: result.Body is positionally aligned with alerts;
@@ -266,7 +268,17 @@ func (n *Notifier) prepareContent(ctx context.Context, alerts []*types.Alert) ([
Color: perAlertColor,
})
}
return blocks, nil
return appendFailureNotice(blocks, result.Failures), nil
}
// appendFailureNotice adds a block that says which template failed.
func appendFailureNotice(blocks []Body, failures alertmanagertypes.TemplateFailures) []Body {
notice := failures.Notice()
if notice == "" {
return blocks
}
return append(blocks, Body{Type: "TextBlock", Text: notice, Wrap: true})
}
func (*Notifier) createLabelsAndAnnotationsBody(alert *types.Alert) []Body {

View File

@@ -145,12 +145,11 @@ func TestMSTeamsV2Templating(t *testing.T) {
titleLink: `{{ template "msteamsv2.default.titleLink" . }}`,
},
{
title: "title with templating errors",
title: "title with templating errors uses the builtin title",
cfg: &config.MSTeamsV2Config{
Title: "{{ ",
},
titleLink: `{{ template "msteamsv2.default.titleLink" . }}`,
errMsg: "template: :1: unclosed action",
},
{
title: "message with title link templating errors",

View File

@@ -54,6 +54,10 @@ type Notifier struct {
// immutable timeline. Off for plain OpsGenie. The alert-refresh-on-refire part
// rides on the upstream UpdateAlerts config flag, set alongside this.
advancedFeatures bool
// The compiled defaults of the channel kind this notifier serves: JSM Ops
// when advancedFeatures is set, OpsGenie otherwise.
builtinMessage string
builtinDescription string
}
// New returns a new OpsGenie notifier. advancedFeatures enables the JSM Ops
@@ -64,14 +68,20 @@ func New(c *config.OpsGenieConfig, t *template.Template, l *slog.Logger, templat
if err != nil {
return nil, err
}
builtinMessage, builtinDescription := config.DefaultOpsGenieConfig.Message, config.DefaultOpsGenieConfig.Description
if advancedFeatures {
builtinMessage, builtinDescription = alertmanagertypes.DefaultJSMOpsMessageTemplate, alertmanagertypes.DefaultJSMOpsDescriptionTemplate
}
return &Notifier{
conf: c,
tmpl: t,
logger: l,
client: client,
retrier: &notify.Retrier{RetryCodes: []int{http.StatusTooManyRequests}},
templater: templater,
advancedFeatures: advancedFeatures,
conf: c,
tmpl: t,
logger: l,
client: client,
retrier: &notify.Retrier{RetryCodes: []int{http.StatusTooManyRequests}},
templater: templater,
advancedFeatures: advancedFeatures,
builtinMessage: builtinMessage,
builtinDescription: builtinDescription,
}, nil
}
@@ -189,6 +199,8 @@ func (n *Notifier) prepareContent(ctx context.Context, alerts []*types.Alert) (s
BodyTemplate: customBody,
DefaultTitleTemplate: n.conf.Message,
DefaultBodyTemplate: n.conf.Description,
BuiltinTitleTemplate: n.builtinMessage,
BuiltinBodyTemplate: n.builtinDescription,
}, alerts)
if err != nil {
return "", "", err
@@ -197,11 +209,24 @@ func (n *Notifier) prepareContent(ctx context.Context, alerts []*types.Alert) (s
var description string
if result.IsDefaultBody && !n.advancedFeatures {
description = strings.Join(result.Body, "\n")
if notice := alertmanagertemplate.RenderFailureNotice(ctx, n.logger, result.Failures, markdownrenderer.RenderPlainText); notice != "" {
description += "\n\n" + notice
}
} else {
description, err = buildHTMLDescription(result.Body, maxDescriptionLenRunes)
// The notice takes its share of the budget first, so the alert parts
// are the ones that shrink.
notice := alertmanagertemplate.RenderFailureNotice(ctx, n.logger, result.Failures, markdownrenderer.RenderHTML)
if notice != "" {
notice = "<hr><div>" + notice + "</div>"
}
description, err = buildHTMLDescription(result.Body, maxDescriptionLenRunes-utf8.RuneCountInString(notice))
if err != nil {
return "", "", err
}
if description == "" {
notice = strings.TrimPrefix(notice, "<hr>")
}
description += notice
}
title, truncated := notify.TruncateInRunes(result.Title, maxMessageLenRunes)
@@ -315,6 +340,8 @@ func (n *Notifier) prepareNote(ctx context.Context, alerts []*types.Alert) (stri
BodyTemplate: customBody,
DefaultTitleTemplate: n.conf.Message,
DefaultBodyTemplate: n.conf.Description,
BuiltinTitleTemplate: n.builtinMessage,
BuiltinBodyTemplate: n.builtinDescription,
}, alerts)
if err != nil {
return "", err

View File

@@ -19,6 +19,7 @@ import (
"time"
"unicode/utf8"
signoztest "github.com/SigNoz/signoz/pkg/alertmanager/alertmanagernotify/alertmanagernotifytest"
"github.com/SigNoz/signoz/pkg/alertmanager/alertmanagertemplate"
"github.com/SigNoz/signoz/pkg/types/alertmanagertypes"
"github.com/SigNoz/signoz/pkg/types/ruletypes"
@@ -658,3 +659,57 @@ func readBody(t *testing.T, r *http.Request) string {
require.NoError(t, err)
return string(body)
}
// JSM Ops is served by this notifier, and its builtin title is not OpsGenie's.
func TestOpsGenieMessageFallsBackToTheBuiltinOfTheChannelKind(t *testing.T) {
testCases := []struct {
name string
advancedFeatures bool
wantMessage string
wantDescription string
}{
{
name: "OpsGenie",
wantMessage: "[FIRING:1] DiskFull (critical)",
wantDescription: "DiskFull\n\nThe channel title template failed: unclosed action. The built-in title is shown.",
},
{
name: "JSMOps",
advancedFeatures: true,
wantMessage: "[FIRING:1] DiskFull",
wantDescription: "<div><p>DiskFull</p>\n</div><hr><div><p>The channel title template failed: <code>unclosed action</code>. The built-in title is shown.</p></div>",
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
u, err := url.Parse("https://test-opsgenie-url")
require.NoError(t, err)
tmpl := signoztest.CreateTmpl(t)
notifier, err := New(&config.OpsGenieConfig{
Message: "{{ .Alerts.Firing | len",
Description: "{{ .CommonLabels.alertname }}",
APIKey: "k",
APIURL: &config.URL{URL: u},
HTTPConfig: &commoncfg.HTTPClientConfig{},
}, tmpl, promslog.NewNopLogger(), newTestTemplater(tmpl), testCase.advancedFeatures)
require.NoError(t, err)
ctx := notify.WithGroupKey(context.Background(), "1")
ctx = notify.WithGroupLabels(ctx, model.LabelSet{"alertname": "DiskFull"})
reqs, _, err := notifier.createRequests(ctx, &types.Alert{Alert: model.Alert{
StartsAt: time.Now(),
EndsAt: time.Now().Add(time.Hour),
Labels: model.LabelSet{"alertname": "DiskFull", "severity": "critical"},
}})
require.NoError(t, err)
require.NotEmpty(t, reqs)
var created opsGenieCreateMessage
require.NoError(t, json.Unmarshal([]byte(readBody(t, reqs[0])), &created))
assert.Equal(t, testCase.wantMessage, created.Message)
assert.Equal(t, testCase.wantDescription, created.Description)
})
}
}

View File

@@ -17,6 +17,7 @@ import (
"github.com/SigNoz/signoz/pkg/alertmanager/alertmanagertemplate"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/templating/markdownrenderer"
"github.com/SigNoz/signoz/pkg/types/alertmanagertypes"
"github.com/alecthomas/units"
commoncfg "github.com/prometheus/common/config"
@@ -303,16 +304,17 @@ func (n *Notifier) notifyV2(
// we care about — the description/summary field is what users see as the
// incident headline, so we feed the configured Description as the default
// title template and ignore any custom body_template entirely.
func (n *Notifier) prepareTitle(ctx context.Context, alerts []*types.Alert) (string, error) {
func (n *Notifier) prepareTitle(ctx context.Context, alerts []*types.Alert) (string, alertmanagertypes.TemplateFailures, error) {
customTitle, _ := alertmanagertemplate.ExtractTemplatesFromAnnotations(alerts)
result, err := n.templater.Expand(ctx, alertmanagertypes.ExpandRequest{
TitleTemplate: customTitle,
DefaultTitleTemplate: n.conf.Description,
BuiltinTitleTemplate: config.DefaultPagerdutyConfig.Description,
}, alerts)
if err != nil {
return "", err
return "", alertmanagertypes.TemplateFailures{}, err
}
return result.Title, nil
return result.Title, result.Failures, nil
}
// Notify implements the Notifier interface.
@@ -323,7 +325,7 @@ func (n *Notifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error)
}
logger := n.logger.With(slog.Any("group_key", key))
title, err := n.prepareTitle(ctx, as)
title, failures, err := n.prepareTitle(ctx, as)
if err != nil {
n.logger.ErrorContext(ctx, "failed to prepare notification content", errors.Attr(err))
return false, err
@@ -345,6 +347,10 @@ func (n *Notifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error)
if err != nil {
return false, errors.WrapInternalf(err, errors.CodeInternal, "failed to render details: %v", err)
}
// An event has no body, so the notice goes with the details.
if notice := alertmanagertemplate.RenderFailureNotice(ctx, logger, failures, markdownrenderer.RenderPlainText); notice != "" {
details["template_failure"] = notice
}
if n.conf.Timeout > 0 {
nfCtx, cancel := context.WithTimeoutCause(ctx, n.conf.Timeout, errors.NewInternalf(errors.CodeTimeout, "configured pagerduty timeout reached (%s)", n.conf.Timeout))

View File

@@ -945,7 +945,7 @@ func TestPrepareContent(t *testing.T) {
},
}
title, err := notifier.prepareTitle(ctx, alerts)
title, _, err := notifier.prepareTitle(ctx, alerts)
require.NoError(t, err)
assert.Equal(t, "HighCPU for Payment service (FIRING)", title)
})
@@ -981,7 +981,7 @@ func TestPrepareContent(t *testing.T) {
},
}
title, err := notifier.prepareTitle(ctx, alerts)
title, _, err := notifier.prepareTitle(ctx, alerts)
require.NoError(t, err)
assert.Equal(t, "HighCPU on api-server is in resolved state", title)
})

View File

@@ -0,0 +1,153 @@
package alertmanagernotify
import (
"context"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync"
"testing"
"time"
test "github.com/SigNoz/signoz/pkg/alertmanager/alertmanagernotify/alertmanagernotifytest"
"github.com/SigNoz/signoz/pkg/alertmanager/alertmanagernotify/googlechat"
"github.com/SigNoz/signoz/pkg/alertmanager/alertmanagernotify/incidentio"
"github.com/SigNoz/signoz/pkg/alertmanager/alertmanagernotify/msteamsv2"
"github.com/SigNoz/signoz/pkg/alertmanager/alertmanagernotify/opsgenie"
"github.com/SigNoz/signoz/pkg/alertmanager/alertmanagernotify/pagerduty"
"github.com/SigNoz/signoz/pkg/alertmanager/alertmanagernotify/slack"
"github.com/SigNoz/signoz/pkg/alertmanager/alertmanagernotify/telegram"
"github.com/SigNoz/signoz/pkg/alertmanager/alertmanagertemplate"
"github.com/SigNoz/signoz/pkg/types/alertmanagertypes"
"github.com/SigNoz/signoz/pkg/types/ruletypes"
"github.com/prometheus/alertmanager/config"
"github.com/prometheus/alertmanager/notify"
"github.com/prometheus/alertmanager/types"
commoncfg "github.com/prometheus/common/config"
"github.com/prometheus/common/model"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Jira, JSM Ops and email are not covered here: they need several endpoints,
// a fixed vendor URL and an SMTP server.
func TestReceiverIntegrationsNotifyWhenATemplateFails(t *testing.T) {
testCases := []struct {
name string
channelTitle string
channelBody string
annotations model.LabelSet
wantTitle string
wantNotice string
}{
{
// A title copied from a channel template reads fields that the
// rule data model does not have.
name: "RuleTitleFails_SendsTheChannelTitle",
channelTitle: "slow: {{ .CommonLabels.alertname }}",
channelBody: "{{ range .Alerts }}{{ .Annotations.summary }}{{ end }}",
annotations: model.LabelSet{ruletypes.AnnotationTitleTemplate: "Rule title: {{ .CommonLabels.alertname }}"},
wantTitle: "slow: PodMemoryHigh",
wantNotice: "The rule title template failed",
},
{
// slice fails on a pod name shorter than 40 characters.
name: "RuleBodyFails_SendsTheChannelBody",
channelTitle: "high: {{ .CommonLabels.alertname }}",
channelBody: "{{ range .Alerts }}{{ .Labels.pod }}{{ end }}",
annotations: model.LabelSet{ruletypes.AnnotationBodyTemplate: "{{ slice .labels.pod 0 40 }} is high"},
wantTitle: "high: PodMemoryHigh",
wantNotice: "The rule body template failed",
},
{
name: "ChannelTitleFails_SendsTheBuiltinTitle",
channelTitle: "{{ .Alerts.Firing | len",
channelBody: "{{ range .Alerts }}{{ .Labels.severity }}{{ end }}",
wantTitle: "[FIRING:1]",
wantNotice: "The channel title template failed",
},
{
// .Value is not a field of an alert in the channel data model.
name: "ChannelBodyFails_SendsTheBuiltinBody",
channelTitle: "hot: {{ .CommonLabels.alertname }}",
channelBody: "{{ range .Alerts }}{{ .Value }}{{ end }}",
wantTitle: "hot: PodMemoryHigh",
wantNotice: "The channel body template failed",
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
var mu sync.Mutex
posted := map[string]string{}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
mu.Lock()
posted[strings.Split(strings.TrimPrefix(r.URL.Path, "/"), "/")[0]] = string(body)
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"ok": true}`))
}))
defer srv.Close()
endpoint := func(path string) *url.URL {
parsed, err := url.Parse(srv.URL + "/" + path)
require.NoError(t, err)
return parsed
}
httpConfig := &commoncfg.HTTPClientConfig{}
title, body := testCase.channelTitle, testCase.channelBody
tmpl := test.CreateTmpl(t)
logger := slog.New(slog.DiscardHandler)
integrations, err := NewReceiverIntegrations(&alertmanagertypes.Receiver{
Receiver: &config.Receiver{
Name: "all-kinds",
SlackConfigs: []*config.SlackConfig{{HTTPConfig: httpConfig, APIURL: &config.SecretURL{URL: endpoint(slack.Integration)}, Channel: "#alerts", Title: title, Text: body}},
MSTeamsV2Configs: []*config.MSTeamsV2Config{{HTTPConfig: httpConfig, WebhookURL: &config.SecretURL{URL: endpoint(msteamsv2.Integration)}, Title: title, Text: body}},
OpsGenieConfigs: []*config.OpsGenieConfig{{HTTPConfig: httpConfig, APIKey: "key", APIURL: &config.URL{URL: endpoint(opsgenie.Integration + "/")}, Message: title, Description: body}},
PagerdutyConfigs: []*config.PagerdutyConfig{{HTTPConfig: httpConfig, RoutingKey: "key", URL: &config.URL{URL: endpoint(pagerduty.Integration)}, Description: title}},
},
GoogleChatConfigs: []*alertmanagertypes.GoogleChatReceiverConfig{{HTTPConfig: httpConfig, WebhookURL: &config.SecretURL{URL: endpoint(googlechat.Integration)}, Title: title, Text: body}},
IncidentIOConfigs: []*alertmanagertypes.IncidentIOReceiverConfig{{HTTPConfig: httpConfig, URL: endpoint(incidentio.Integration).String(), Token: "token", Title: title, Description: body}},
TelegramConfigs: []*alertmanagertypes.TelegramReceiverConfig{{HTTPConfig: httpConfig, APIUrl: &config.URL{URL: endpoint(telegram.Integration)}, BotToken: "123456:tok", ChatID: 42, ParseMode: "HTML", Title: title, Message: body}},
}, tmpl, logger, alertmanagertemplate.New(tmpl, logger))
require.NoError(t, err)
require.Len(t, integrations, 7)
annotations := model.LabelSet{"summary": "memory is above the limit"}
for name, value := range testCase.annotations {
annotations[name] = value
}
alert := &types.Alert{Alert: model.Alert{
Labels: model.LabelSet{"alertname": "PodMemoryHigh", "severity": "critical", "pod": "cart-5f6d7c8b9-q8w2z"},
Annotations: annotations,
StartsAt: time.Now(),
EndsAt: time.Now().Add(time.Hour),
}}
ctx := notify.WithGroupKey(context.Background(), "group")
ctx = notify.WithReceiverName(ctx, "all-kinds")
ctx = notify.WithGroupLabels(ctx, model.LabelSet{"alertname": "PodMemoryHigh"})
for _, integration := range integrations {
_, err := integration.Notify(ctx, alert)
assert.NoError(t, err, integration.Name())
}
mu.Lock()
defer mu.Unlock()
for _, integration := range integrations {
assert.Contains(t, posted[integration.Name()], testCase.wantTitle, integration.Name())
// A PagerDuty event has a title and no body template.
if integration.Name() == pagerduty.Integration && strings.Contains(testCase.wantNotice, "body") {
continue
}
assert.Contains(t, posted[integration.Name()], testCase.wantNotice, integration.Name())
}
})
}
}

View File

@@ -193,6 +193,8 @@ func (n *Notifier) prepareContent(ctx context.Context, alerts []*types.Alert, tm
BodyTemplate: customBody,
DefaultTitleTemplate: n.conf.Title,
DefaultBodyTemplate: n.conf.Text,
BuiltinTitleTemplate: config.DefaultSlackConfig.Title,
BuiltinBodyTemplate: config.DefaultSlackConfig.Text,
}, alerts)
if err != nil {
return nil, err
@@ -210,7 +212,7 @@ func (n *Notifier) prepareContent(ctx context.Context, alerts []*types.Alert, tm
} else {
markdownIn = n.conf.MrkdwnIn
}
return []attachment{
return n.appendFailureNotice(ctx, result.Failures, []attachment{
{
Title: title,
TitleLink: tmplText(n.conf.TitleLink),
@@ -224,7 +226,7 @@ func (n *Notifier) prepareContent(ctx context.Context, alerts []*types.Alert, tm
Color: tmplText(n.conf.Color),
MrkdwnIn: markdownIn,
},
}, nil
}), nil
}
// Custom template path: one title attachment + one attachment per
@@ -261,7 +263,17 @@ func (n *Notifier) prepareContent(ctx context.Context, alerts []*types.Alert, tm
})
}
return attachments, nil
return n.appendFailureNotice(ctx, result.Failures, attachments), nil
}
// appendFailureNotice adds an attachment that says which template failed.
func (n *Notifier) appendFailureNotice(ctx context.Context, failures alertmanagertypes.TemplateFailures, attachments []attachment) []attachment {
notice := alertmanagertemplate.RenderFailureNotice(ctx, n.logger, failures, markdownrenderer.RenderSlackMrkdwn)
if notice == "" {
return attachments
}
return append(attachments, attachment{Text: notice, MrkdwnIn: []string{"text"}})
}
// buildRelatedLinkActions returns the "View Related Logs/Traces" action

View File

@@ -17,6 +17,7 @@ import (
"os"
"strconv"
"strings"
"unicode/utf8"
"github.com/SigNoz/signoz/pkg/alertmanager/alertmanagertemplate"
"github.com/SigNoz/signoz/pkg/errors"
@@ -154,12 +155,15 @@ func (n *Notifier) encodeSendMessage(chatID int64, text string) (*bytes.Buffer,
}
// buildMessage sends the title in bold above the message. Each half comes from
// the rule's template when it has one and from the channel's otherwise; an
// empty title sends the message alone.
// the rule's template when it has one that executes and from the channel's
// otherwise; an empty title sends the message alone.
func (n *Notifier) buildMessage(ctx context.Context, logger *slog.Logger, as []*types.Alert) (string, error) {
customTitle, customBody := alertmanagertemplate.ExtractTemplatesFromAnnotations(as)
var result *alertmanagertypes.ExpandResult
var (
result *alertmanagertypes.ExpandResult
failures alertmanagertypes.TemplateFailures
)
if customTitle != "" || customBody != "" {
var err error
result, err = n.templater.Expand(ctx, alertmanagertypes.ExpandRequest{
@@ -169,6 +173,7 @@ func (n *Notifier) buildMessage(ctx context.Context, logger *slog.Logger, as []*
if err != nil {
return "", err
}
failures = result.Failures
if len(result.MissingVars) > 0 {
logger.WarnContext(ctx, "unresolved variables in rule template", slog.Any("template_missing_vars", result.MissingVars))
@@ -179,48 +184,65 @@ func (n *Notifier) buildMessage(ctx context.Context, logger *slog.Logger, as []*
title, body string
err error
)
if customTitle != "" {
if customTitle != "" && failures.RuleTitle == nil {
title, err = n.renderRuleTemplate(result.Title)
} else {
title, err = n.renderChannelTemplate(ctx, as, n.conf.Title)
title, failures.ChannelTitle, err = n.renderChannelTemplate(ctx, as, n.conf.Title, alertmanagertypes.DefaultTelegramTitleTemplate)
}
if err != nil {
return "", err
}
if customBody != "" {
if customBody != "" && failures.RuleBody == nil {
body, err = n.renderRuleTemplate(strings.Join(nonEmpty(result.Body), "\n\n"))
} else {
body, err = n.renderChannelTemplate(ctx, as, n.conf.Message)
body, failures.ChannelBody, err = n.renderChannelTemplate(ctx, as, n.conf.Message, alertmanagertypes.DefaultTelegramMessageTemplate)
}
if err != nil {
return "", err
}
if title == "" {
return body, nil
message := body
if title != "" {
message = "<b>" + title + "</b>\n\n" + body
}
// Past the limit the message is cut, and a cut inside the notice leaves
// markup that does not close, which Telegram rejects.
if notice := alertmanagertemplate.RenderFailureNotice(ctx, logger, failures, markdownrenderer.RenderTelegramHTML); notice != "" {
if utf8.RuneCountInString(message)+utf8.RuneCountInString(notice)+2 <= maxMessageLenRunes {
message += "\n\n" + notice
} else {
logger.WarnContext(ctx, "left the template failure notice out of a message at the length limit")
}
}
return strings.TrimSpace("<b>" + title + "</b>\n\n" + body), nil
return strings.TrimSpace(message), nil
}
// renderChannelTemplate reproduces upstream's rendering, including its choice
// of engine under parse_mode HTML: html/template escapes every interpolated
// value, so a channel template that does not pipe through html still sends.
func (n *Notifier) renderChannelTemplate(ctx context.Context, as []*types.Alert, text string) (string, error) {
// A channel template that fails gives way to the builtin one, and its error is
// the second result.
func (n *Notifier) renderChannelTemplate(ctx context.Context, as []*types.Alert, text string, builtin string) (string, error, error) {
if text == "" {
return "", nil
return "", nil, nil
}
var tmplErr error
var tmplErr, channelTemplateErr error
data := notify.GetTemplateData(ctx, n.tmpl, as, n.logger)
rendered := notify.TmplHTML(n.tmpl, data, &tmplErr)(text)
if tmplErr != nil && text != builtin {
n.logger.WarnContext(ctx, "telegram template failed, using the builtin template", errors.Attr(tmplErr))
channelTemplateErr, tmplErr = tmplErr, nil
rendered = notify.TmplHTML(n.tmpl, data, &tmplErr)(builtin)
}
if tmplErr != nil {
return "", errors.NewInvalidInputf(errors.CodeInvalidInput, "failed to execute telegram template: %s", tmplErr.Error())
return "", nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "failed to execute telegram template: %s", tmplErr.Error())
}
return strings.TrimSpace(rendered), nil
return strings.TrimSpace(rendered), channelTemplateErr, nil
}
// renderRuleTemplate converts the templater's output from markdown, which is

View File

@@ -8,9 +8,11 @@ import (
"net/http/httptest"
"net/url"
"strconv"
"strings"
"sync"
"testing"
"time"
"unicode/utf8"
test "github.com/SigNoz/signoz/pkg/alertmanager/alertmanagernotify/alertmanagernotifytest"
"github.com/SigNoz/signoz/pkg/alertmanager/alertmanagertemplate"
@@ -254,6 +256,124 @@ func TestNotifyBuildsTheMessage(t *testing.T) {
}
}
func TestNotifySendsWhenATemplateFails(t *testing.T) {
testCases := []struct {
name string
channelTitle string
channelMessage string
alerts []*types.Alert
wantText string
}{
{
// A title copied from a channel template reads fields that the
// rule data model does not have.
name: "RuleTitleFails_UsesChannelTitle",
channelTitle: alertmanagertypes.DefaultTelegramTitleTemplate,
channelMessage: alertmanagertypes.DefaultTelegramMessageTemplate,
alerts: []*types.Alert{newAlert("web-3", model.LabelSet{
ruletypes.AnnotationTitleTemplate: "Rule title: {{ .CommonLabels.alertname }}",
ruletypes.AnnotationBodyTemplate: "$alert.status for $rule.name",
})},
wantText: "<b>[FIRING:1] checkout-latency-high</b>\n\nfiring for checkout-latency-high\n\n" +
"The rule title template failed: <code>.CommonLabels.alertname: nil pointer evaluating interface {}.alertname</code>. The channel title is shown.",
},
{
// slice fails on a host name shorter than 40 characters.
name: "RuleBodyFails_UsesChannelMessage",
channelTitle: alertmanagertypes.DefaultTelegramTitleTemplate,
channelMessage: "{{ range .Alerts }}{{ .Labels.host }} is slow{{ end }}",
alerts: []*types.Alert{newAlert("web-4", model.LabelSet{
ruletypes.AnnotationTitleTemplate: "Incident on $labels.host",
ruletypes.AnnotationBodyTemplate: "{{ slice .labels.host 0 40 }} is slow",
})},
wantText: "<b>Incident on web-4</b>\n\nweb-4 is slow\n\n" +
"The rule body template failed: <code>slice .labels.host 0 40: error calling slice: index out of range: 40</code>. The channel body is shown.",
},
{
// An empty title is a choice the rule made, not a failure.
name: "RuleTitleExpandsToEmpty_SendsTheMessageAlone",
channelTitle: alertmanagertypes.DefaultTelegramTitleTemplate,
channelMessage: alertmanagertypes.DefaultTelegramMessageTemplate,
alerts: []*types.Alert{newAlert("web-5", model.LabelSet{
ruletypes.AnnotationTitleTemplate: `{{ if eq $alert.status "resolved" }}Recovered{{ end }}`,
ruletypes.AnnotationBodyTemplate: "$alert.status on $labels.host",
})},
wantText: "firing on web-5",
},
{
name: "ChannelTitleFails_UsesBuiltinTitle",
channelTitle: "{{ .Alerts.Firing | len",
channelMessage: "{{ range .Alerts }}{{ .Labels.host }} is degraded{{ end }}",
alerts: []*types.Alert{newAlert("web-6", nil)},
wantText: "<b>[FIRING:1] checkout-latency-high</b>\n\nweb-6 is degraded\n\n" +
"The channel title template failed: <code>unclosed action</code>. The built-in title is shown.",
},
{
// .Value is not a field of an alert in the channel data model.
name: "ChannelMessageFails_UsesBuiltinMessage",
channelTitle: "{{ .CommonLabels.host }}",
channelMessage: "{{ range .Alerts }}{{ .Value }}{{ end }}",
alerts: []*types.Alert{newAlert("web-7", nil)},
wantText: "<b>web-7</b>\n\n<b>Alert:</b> checkout-latency-high (warning)\n<b>Summary:</b> p99 is 612ms\n<a href=\"http://am/alerts/overview?ruleId=r1\">View in SigNoz</a>\n\n" +
"The channel body template failed: <code>.Value: can't evaluate field Value in type template.Alert</code>. The built-in body is shown.",
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
mock := newMockBotAPI(t)
tmpl := test.CreateTmpl(t)
apiURL, err := url.Parse(mock.srv.URL)
require.NoError(t, err)
logger := slog.New(slog.DiscardHandler)
notifier, err := New(&alertmanagertypes.TelegramReceiverConfig{
HTTPConfig: &commoncfg.HTTPClientConfig{},
APIUrl: &config.URL{URL: apiURL},
BotToken: "123456:tok",
ChatID: -1001234567890,
ParseMode: "HTML",
Title: testCase.channelTitle,
Message: testCase.channelMessage,
}, tmpl, logger, alertmanagertemplate.New(tmpl, logger))
require.NoError(t, err)
retry, err := notifier.Notify(notify.WithGroupKey(context.Background(), "1"), testCase.alerts...)
require.NoError(t, err)
assert.False(t, retry)
assert.Equal(t, testCase.wantText, mock.only(t)["text"])
})
}
}
// The message fits and the notice does not. The notice is the last part, so
// the cut at the limit would leave its markup open, which Telegram rejects.
func TestNotifyLeavesTheFailureNoticeOutOfAFullMessage(t *testing.T) {
mock := newMockBotAPI(t)
tmpl := test.CreateTmpl(t)
apiURL, err := url.Parse(mock.srv.URL)
require.NoError(t, err)
logger := slog.New(slog.DiscardHandler)
notifier, err := New(&alertmanagertypes.TelegramReceiverConfig{
HTTPConfig: &commoncfg.HTTPClientConfig{},
APIUrl: &config.URL{URL: apiURL},
BotToken: "123456:tok",
ChatID: -1001234567890,
ParseMode: "HTML",
Title: "{{ .Alerts.Firing | len",
Message: strings.Repeat("a long line of text. ", 190),
}, tmpl, logger, alertmanagertemplate.New(tmpl, logger))
require.NoError(t, err)
_, err = notifier.Notify(notify.WithGroupKey(context.Background(), "1"), newAlert("web-8", nil))
require.NoError(t, err)
text := mock.only(t)["text"]
assert.Equal(t, "<b>[FIRING:1] checkout-latency-high</b>\n\n"+strings.TrimSpace(strings.Repeat("a long line of text. ", 190)), text)
assert.Less(t, utf8.RuneCountInString(text), 4096)
}
// A v1-written receiver can carry a mode the v2 spec no longer offers. Nothing
// renders to those, so the send goes out as HTML without touching the receiver.
func TestNewForcesParseModeHTML(t *testing.T) {

View File

@@ -2,7 +2,9 @@ package alertmanagerserver
import (
"context"
"fmt"
"log/slog"
"slices"
"strings"
"sync"
"time"
@@ -418,7 +420,7 @@ func (server *Server) TestAlert(ctx context.Context, receiversMap map[*alertmana
}
var mu sync.Mutex
var errs []error
var failures []string
g, gCtx := errgroup.WithContext(ctx)
for _, group := range groupMap {
@@ -430,7 +432,7 @@ func (server *Server) TestAlert(ctx context.Context, receiversMap map[*alertmana
receiver, err := server.alertmanagerConfig.GetReceiver(receiverName)
if err != nil {
mu.Lock()
errs = append(errs, errors.WrapInternalf(err, errors.CodeInternal, "failed to get receiver %q", receiverName))
failures = append(failures, fmt.Sprintf("receiver %q: %s", receiverName, err.Error()))
mu.Unlock()
return nil // Return nil to continue processing other goroutines
}
@@ -448,7 +450,7 @@ func (server *Server) TestAlert(ctx context.Context, receiversMap map[*alertmana
)
if err != nil {
mu.Lock()
errs = append(errs, errors.WrapInternalf(err, errors.CodeInternal, "receiver %q test failed", receiverName))
failures = append(failures, fmt.Sprintf("receiver %q: %s", receiverName, err.Error()))
mu.Unlock()
}
return nil // Return nil to continue processing other goroutines
@@ -457,8 +459,11 @@ func (server *Server) TestAlert(ctx context.Context, receiversMap map[*alertmana
}
_ = g.Wait()
if len(errs) > 0 {
return errors.Join(errs...)
// A receiver that does not take the alert is the caller's to correct, so
// this is not an internal error.
if len(failures) > 0 {
slices.Sort(failures)
return errors.NewInvalidInputf(alertmanagertypes.ErrCodeAlertmanagerTestAlertFailed, "the test alert was not delivered to every receiver").WithAdditional(failures...)
}
return nil

View File

@@ -13,6 +13,7 @@ import (
"github.com/DATA-DOG/go-sqlmock"
"github.com/SigNoz/signoz/pkg/alertmanager/alertmanagerstore/sqlalertmanagerstore"
"github.com/SigNoz/signoz/pkg/alertmanager/nfmanager/nfmanagertest"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/factory/factorytest"
"github.com/SigNoz/signoz/pkg/sqlstore"
"github.com/SigNoz/signoz/pkg/sqlstore/sqlstoretest"
@@ -317,7 +318,11 @@ func TestServerTestAlertContinuesOnFailure(t *testing.T) {
}
err = server.TestAlert(context.Background(), receiversMap, config)
assert.Error(t, err)
require.Error(t, err)
assert.True(t, errors.Ast(err, errors.TypeInvalidInput))
failures := errors.AsJSON(err).Errors
require.Len(t, failures, 1)
assert.Contains(t, failures[0].Message, `receiver "failing-receiver": `)
time.Sleep(100 * time.Millisecond)

View File

@@ -33,15 +33,18 @@ func (at *templater) Expand(
) (*alertmanagertypes.ExpandResult, error) {
ntd := at.buildNotificationTemplateData(ctx, alerts)
missingVars := make(map[string]bool)
var failures alertmanagertypes.TemplateFailures
title, titleMissingVars, err := at.expandTitle(req.TitleTemplate, ntd)
if err != nil {
return nil, err
at.logger.WarnContext(ctx, "custom title template failed, using the default template", slog.String("rule.id", ntd.Rule.ID), errors.Attr(err))
failures.RuleTitle = err
}
// if title template results in empty string, use default template
// this happens for rules where custom title annotation was not set
// or failed
if title == "" && req.DefaultTitleTemplate != "" {
title, err = at.expandDefaultTemplate(ctx, req.DefaultTitleTemplate, alerts)
title, failures.ChannelTitle, err = at.expandDefaultTemplate(ctx, req.DefaultTitleTemplate, req.BuiltinTitleTemplate, alerts)
if err != nil {
return nil, err
}
@@ -52,13 +55,16 @@ func (at *templater) Expand(
isDefaultBody := false
body, bodyMissingVars, err := at.expandBody(req.BodyTemplate, ntd)
if err != nil {
return nil, err
at.logger.WarnContext(ctx, "custom body template failed, using the default template", slog.String("rule.id", ntd.Rule.ID), errors.Attr(err))
failures.RuleBody = err
}
// if body template results in nil, use default template
// this happens for rules where custom body annotation was not set
// or failed
if body == nil {
isDefaultBody = true
defaultBody, err := at.expandDefaultTemplate(ctx, req.DefaultBodyTemplate, alerts)
var defaultBody string
defaultBody, failures.ChannelBody, err = at.expandDefaultTemplate(ctx, req.DefaultBodyTemplate, req.BuiltinBodyTemplate, alerts)
if err != nil {
return nil, err
}
@@ -79,28 +85,42 @@ func (at *templater) Expand(
Body: body,
MissingVars: missingVarsList,
IsDefaultBody: isDefaultBody,
Failures: failures,
NotificationData: ntd,
}, nil
}
// expandDefaultTemplate uses go-template to expand the default template.
// expandDefaultTemplate uses go-template to expand the default template, and
// the builtin template when the default one fails. The second result is the
// error of the default template when the builtin one took its place.
func (at *templater) expandDefaultTemplate(
ctx context.Context,
tmplStr string,
builtinTmplStr string,
alerts []*types.Alert,
) (string, error) {
) (string, error, error) {
// if even the default template is empty, return empty string
// this is possible if user added channel with blank template
if tmplStr == "" {
at.logger.WarnContext(ctx, "default template is empty")
return "", nil
return "", nil, nil
}
data := notify.GetTemplateData(ctx, at.tmpl, alerts, at.logger)
result, err := at.tmpl.ExecuteTextString(tmplStr, data)
if err != nil {
return "", errors.NewInvalidInputf(errors.CodeInvalidInput, "failed to execute default template: %s", err.Error())
result, defaultTemplateErr := at.tmpl.ExecuteTextString(tmplStr, data)
if defaultTemplateErr == nil {
return result, nil, nil
}
return result, nil
if builtinTmplStr == "" || builtinTmplStr == tmplStr {
return "", nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "failed to execute default template: %s", defaultTemplateErr.Error())
}
receiver, _ := notify.ReceiverName(ctx)
at.logger.WarnContext(ctx, "default template failed, using the builtin template", slog.String("receiver", receiver), errors.Attr(defaultTemplateErr))
result, err := at.tmpl.ExecuteTextString(builtinTmplStr, data)
if err != nil {
return "", nil, errors.NewInternalf(errors.CodeInternal, "failed to execute builtin template: %s", err.Error())
}
return result, defaultTemplateErr, nil
}
// mergeMissingVars adds all keys from src into dst.

View File

@@ -11,6 +11,7 @@ import (
"github.com/SigNoz/signoz/pkg/types/alertmanagertypes"
"github.com/SigNoz/signoz/pkg/types/ruletypes"
"github.com/prometheus/common/model"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/prometheus/alertmanager/notify"
@@ -60,7 +61,6 @@ func TestExpandTemplates(t *testing.T) {
wantTitle string
wantBody []string
wantMissingVars []string
errorContains string
wantIsDefaultBody bool
}{
{
@@ -299,25 +299,11 @@ Description: Request rate exceeded 10k/s`},
wantBody: []string{"Runbook: https://runbook.example.com"},
wantIsDefaultBody: true,
},
{
name: "using non-existing function in template",
alerts: []*types.Alert{
createAlert(map[string]string{ruletypes.LabelAlertName: "HighCPU", ruletypes.LabelSeverityName: "critical"}, nil, true),
},
input: alertmanagertypes.ExpandRequest{
TitleTemplate: "$rule.name ({{$severity | toUpperAndTrim}}) for $alertname",
},
errorContains: "function \"toUpperAndTrim\" not defined",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got, err := at.Expand(ctx, tc.input, tc.alerts)
if tc.errorContains != "" {
require.ErrorContains(t, err, tc.errorContains)
return
}
require.NoError(t, err)
if tc.wantTitle != "" {
@@ -337,3 +323,203 @@ Description: Request rate exceeded 10k/s`},
})
}
}
func TestExpandTemplateFailures(t *testing.T) {
at, ctx := testSetup(t)
testCases := []struct {
name string
alerts []*types.Alert
input alertmanagertypes.ExpandRequest
wantTitle string
wantBody []string
wantIsDefaultBody bool
wantRuleTitleErr string
wantRuleBodyErr string
wantChannelTitleErr string
wantChannelBodyErr string
wantErr string
}{
{
// A title copied from a channel template reads fields that only
// the channel data model has.
name: "CustomTitleReadsChannelField_UsesDefaultTitle",
alerts: []*types.Alert{
createAlert(map[string]string{ruletypes.LabelAlertName: "HighCPU"}, nil, true),
},
input: alertmanagertypes.ExpandRequest{
TitleTemplate: "Rule title: {{ .CommonLabels.alertname }}",
BodyTemplate: "$rule.name is $alert.status",
DefaultTitleTemplate: "[{{ .Status | toUpper }}] {{ .CommonLabels.alertname }}",
DefaultBodyTemplate: "{{ range .Alerts }}{{ .Labels.alertname }}{{ end }}",
},
wantTitle: "[FIRING] HighCPU",
wantBody: []string{"HighCPU is firing"},
wantRuleTitleErr: "nil pointer evaluating interface {}.alertname",
},
{
name: "CustomTitleCallsUnknownFunction_UsesDefaultTitle",
alerts: []*types.Alert{
createAlert(map[string]string{ruletypes.LabelAlertName: "DiskFull", ruletypes.LabelSeverityName: "critical"}, nil, true),
},
input: alertmanagertypes.ExpandRequest{
TitleTemplate: "$rule.name ({{ $severity | toUpperAndTrim }})",
DefaultTitleTemplate: "{{ .CommonLabels.alertname }} is {{ .Status }}",
},
wantTitle: "DiskFull is firing",
wantBody: []string{""},
wantIsDefaultBody: true,
wantRuleTitleErr: `function "toUpperAndTrim" not defined`,
},
{
name: "CustomTitleDoesNotParse_UsesDefaultTitle",
alerts: []*types.Alert{
createAlert(map[string]string{ruletypes.LabelAlertName: "QueueLag"}, nil, true),
},
input: alertmanagertypes.ExpandRequest{
TitleTemplate: "Lag on {{ $labels.queue",
DefaultTitleTemplate: "{{ .CommonLabels.alertname }}",
},
wantTitle: "QueueLag",
wantBody: []string{""},
wantIsDefaultBody: true,
wantRuleTitleErr: "unclosed action",
},
{
// The custom title is empty for a firing group, so the default one
// is used. Nothing failed.
name: "CustomTitleExpandsToEmpty_UsesDefaultTitleWithoutAnError",
alerts: []*types.Alert{
createAlert(map[string]string{ruletypes.LabelAlertName: "CertExpiry"}, nil, true),
},
input: alertmanagertypes.ExpandRequest{
TitleTemplate: `{{ if eq $alert.status "resolved" }}Recovered{{ end }}`,
DefaultTitleTemplate: "{{ .CommonLabels.alertname }}",
},
wantTitle: "CertExpiry",
wantBody: []string{""},
wantIsDefaultBody: true,
},
{
// slice fails on the one pod name shorter than 30 characters, and
// the group shares one default body.
name: "CustomBodyFailsForOneAlert_UsesDefaultBodyForTheGroup",
alerts: []*types.Alert{
createAlert(map[string]string{ruletypes.LabelAlertName: "PodMemoryHigh", "pod": "checkout-7d9c8b5f4-x2k9p-canary-eu-west"}, nil, true),
createAlert(map[string]string{ruletypes.LabelAlertName: "PodMemoryHigh", "pod": "cart-5f6d7c8b9-q8w2z"}, nil, true),
createAlert(map[string]string{ruletypes.LabelAlertName: "PodMemoryHigh", "pod": "payments-6c5d7f9b8-h4j7m-canary-us-east"}, nil, true),
},
input: alertmanagertypes.ExpandRequest{
TitleTemplate: "$rule.name",
BodyTemplate: "Pod {{ slice .labels.pod 0 30 }} is high",
DefaultTitleTemplate: "{{ .CommonLabels.alertname }}",
DefaultBodyTemplate: "{{ range .Alerts }}{{ .Labels.pod }};{{ end }}",
},
wantTitle: "PodMemoryHigh",
wantBody: []string{"checkout-7d9c8b5f4-x2k9p-canary-eu-west;cart-5f6d7c8b9-q8w2z;payments-6c5d7f9b8-h4j7m-canary-us-east;"},
wantIsDefaultBody: true,
wantRuleBodyErr: "index out of range: 30",
},
{
name: "DefaultTitleFails_UsesBuiltinTitle",
alerts: []*types.Alert{
createAlert(map[string]string{ruletypes.LabelAlertName: "HighLatency"}, nil, true),
},
input: alertmanagertypes.ExpandRequest{
DefaultTitleTemplate: "{{ .Alerts.Firing | len",
DefaultBodyTemplate: "{{ range .Alerts }}{{ .Labels.alertname }}{{ end }}",
BuiltinTitleTemplate: "builtin: {{ .CommonLabels.alertname }}",
BuiltinBodyTemplate: "builtin body",
},
wantTitle: "builtin: HighLatency",
wantBody: []string{"HighLatency"},
wantIsDefaultBody: true,
wantChannelTitleErr: "unclosed action",
},
{
// .Value is not a field of an alert in the channel data model.
name: "DefaultBodyFails_UsesBuiltinBody",
alerts: []*types.Alert{
createAlert(map[string]string{ruletypes.LabelAlertName: "ErrorRateHigh"}, nil, true),
},
input: alertmanagertypes.ExpandRequest{
DefaultTitleTemplate: "{{ .CommonLabels.alertname }}",
DefaultBodyTemplate: "{{ range .Alerts }}{{ .Value }}{{ end }}",
BuiltinTitleTemplate: "builtin title",
BuiltinBodyTemplate: "builtin: {{ range .Alerts }}{{ .Labels.alertname }}{{ end }}",
},
wantTitle: "ErrorRateHigh",
wantBody: []string{"builtin: ErrorRateHigh"},
wantIsDefaultBody: true,
wantChannelBodyErr: "can't evaluate field Value in type template.Alert",
},
{
name: "CustomAndDefaultTitleFail_UsesBuiltinTitle",
alerts: []*types.Alert{
createAlert(map[string]string{ruletypes.LabelAlertName: "ReplicaLag"}, nil, true),
},
input: alertmanagertypes.ExpandRequest{
TitleTemplate: "{{ .GroupLabels.alertname }}",
DefaultTitleTemplate: "{{ .CommonLabels.alertname | toUpperAndTrim }}",
BuiltinTitleTemplate: "builtin: {{ .CommonLabels.alertname }}",
},
wantTitle: "builtin: ReplicaLag",
wantBody: []string{""},
wantIsDefaultBody: true,
wantRuleTitleErr: "nil pointer evaluating interface {}.alertname",
wantChannelTitleErr: `function "toUpperAndTrim" not defined`,
},
{
name: "EmptyDefaultTitle_IsNotAFailure",
alerts: []*types.Alert{
createAlert(map[string]string{ruletypes.LabelAlertName: "NodeDown"}, nil, true),
},
input: alertmanagertypes.ExpandRequest{
DefaultBodyTemplate: "{{ range .Alerts }}{{ .Labels.alertname }}{{ end }}",
BuiltinTitleTemplate: "builtin: {{ .CommonLabels.alertname }}",
},
wantBody: []string{"NodeDown"},
wantIsDefaultBody: true,
},
{
name: "DefaultTitleFails_NoBuiltin_ReturnsTheError",
alerts: []*types.Alert{
createAlert(map[string]string{ruletypes.LabelAlertName: "JobFailed"}, nil, true),
},
input: alertmanagertypes.ExpandRequest{
DefaultTitleTemplate: "{{ .CommonLabels.alertname | toUpperAndTrim }}",
},
wantErr: `failed to execute default template: template: :1: function "toUpperAndTrim" not defined`,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
got, err := at.Expand(ctx, testCase.input, testCase.alerts)
if testCase.wantErr != "" {
require.EqualError(t, err, testCase.wantErr)
return
}
require.NoError(t, err)
assert.Equal(t, testCase.wantTitle, got.Title)
assert.Equal(t, testCase.wantBody, got.Body)
assert.Equal(t, testCase.wantIsDefaultBody, got.IsDefaultBody)
for _, failure := range []struct {
got error
want string
}{
{got.Failures.RuleTitle, testCase.wantRuleTitleErr},
{got.Failures.RuleBody, testCase.wantRuleBodyErr},
{got.Failures.ChannelTitle, testCase.wantChannelTitleErr},
{got.Failures.ChannelBody, testCase.wantChannelBodyErr},
} {
if failure.want == "" {
assert.NoError(t, failure.got)
} else {
assert.ErrorContains(t, failure.got, failure.want)
}
}
})
}
}

View File

@@ -0,0 +1,29 @@
package alertmanagertemplate
import (
"context"
"log/slog"
"strings"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/types/alertmanagertypes"
)
// RenderFailureNotice returns the notice for the templates that failed, in the
// markup of one channel, and an empty string when none failed. A notice must
// never stop the notification, so one that does not render is logged and left
// out.
func RenderFailureNotice(ctx context.Context, logger *slog.Logger, failures alertmanagertypes.TemplateFailures, render func(markdown string) (string, error)) string {
notice := failures.Notice()
if notice == "" {
return ""
}
rendered, err := render(notice)
if err != nil {
logger.WarnContext(ctx, "failed to render the template failure notice", errors.Attr(err))
return ""
}
return strings.TrimSpace(rendered)
}

View File

@@ -0,0 +1,65 @@
package alertmanagertemplate
import (
"context"
"log/slog"
tmpltext "text/template"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/types/alertmanagertypes"
"github.com/prometheus/alertmanager/notify"
"github.com/prometheus/alertmanager/types"
"github.com/prometheus/common/model"
)
// ValidateRuleTemplates rejects a rule title or body template that fails for
// every alert: one that does not parse, or that calls a function that does not
// exist. A template that parses and then fails on the sample alert is accepted,
// because another alert can still execute it; Expand falls back to the default
// template for the alerts that cannot.
func ValidateRuleTemplates(ctx context.Context, titleTemplate, bodyTemplate string) error {
tmpl, err := alertmanagertypes.FromGlobs(nil)
if err != nil {
return err
}
at := &templater{tmpl: tmpl, logger: slog.New(slog.DiscardHandler)}
ctx = notify.WithReceiverName(ctx, "")
ctx = notify.WithGroupLabels(ctx, model.LabelSet{})
ntd := at.buildNotificationTemplateData(ctx, []*types.Alert{{}})
var messages []string
if err := at.parseError(titleTemplate, ntd); err != nil {
messages = append(messages, "title template: "+err.Error())
}
if err := at.parseError(bodyTemplate, &ntd.Alerts[0]); err != nil {
messages = append(messages, "body template: "+err.Error())
}
if len(messages) > 0 {
return errors.NewInvalidInputf(errors.CodeInvalidInput, "alert rule notification template is not valid").WithAdditional(messages...)
}
return nil
}
// parseError runs the template the way Expand does and returns only an error
// that comes before execution. The engine has no call that parses without
// executing.
func (at *templater) parseError(tmpl string, data any) error {
if tmpl == "" {
return nil
}
processRes, err := preProcessTemplateAndData(tmpl, data)
if err != nil {
return err
}
_, err = at.tmpl.ExecuteTextString(processRes.Template, processRes.Data)
var execErr tmpltext.ExecError
if errors.As(err, &execErr) {
return nil
}
return err
}

View File

@@ -0,0 +1,84 @@
package alertmanagertemplate
import (
"context"
"testing"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestValidateRuleTemplates(t *testing.T) {
testCases := []struct {
name string
titleTemplate string
bodyTemplate string
wantMessages []string
}{
{
name: "NoTemplates",
},
{
name: "DollarReferences",
titleTemplate: "$rule.name on $labels.host",
bodyTemplate: "$alert.status for $service.name",
},
{
name: "ActionBlockOnARuleVariable",
bodyTemplate: "{{ if $alert.is_firing }}up{{ end }} $rule.name",
},
{
name: "NotifierFunctions",
titleTemplate: "{{ .labels.pod | toUpper | trimSpace }}",
},
{
// .CommonLabels is a field of the channel data model, so this fails
// for every alert. Only execution can tell, and execution on a
// sample is not proof for every alert.
name: "ChannelField_FailsOnlyWhenExecuted",
titleTemplate: "Rule title: {{ .CommonLabels.alertname }}",
},
{
name: "SliceOutOfRange_FailsOnlyWhenExecuted",
bodyTemplate: "{{ slice .labels.pod 0 40 }} is high",
},
{
name: "UnclosedAction",
titleTemplate: "Lag on {{ $labels.queue",
wantMessages: []string{"title template: template: template:1: unclosed action"},
},
{
name: "UnknownFunction",
bodyTemplate: "{{ $severity | toUpperAndTrim }}",
wantMessages: []string{`body template: template: :1: function "toUpperAndTrim" not defined`},
},
{
name: "TitleAndBodyDoNotParse",
titleTemplate: "{{ if $alert.is_firing }}firing",
bodyTemplate: "{{ $labels.pod | humanizeBytes }}",
wantMessages: []string{
"title template: template: template:1: unexpected EOF",
`body template: template: :1: function "humanizeBytes" not defined`,
},
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
err := ValidateRuleTemplates(context.Background(), testCase.titleTemplate, testCase.bodyTemplate)
if len(testCase.wantMessages) == 0 {
require.NoError(t, err)
return
}
require.Error(t, err)
assert.True(t, errors.Ast(err, errors.TypeInvalidInput))
got := make([]string, 0, len(testCase.wantMessages))
for _, additional := range errors.AsJSON(err).Errors {
got = append(got, additional.Message)
}
assert.Equal(t, testCase.wantMessages, got)
})
}
}

View File

@@ -137,6 +137,9 @@ func (provider *provider) TestAlert(ctx context.Context, orgID string, ruleID st
receiversMap[alert] = match
}
}
if len(receiversMap) == 0 {
return errors.NewInvalidInputf(alertmanagertypes.ErrCodeAlertmanagerTestAlertFailed, "no notification policy matches the alerts of this rule")
}
}
return provider.service.TestAlert(ctx, orgID, receiversMap, config)
}

View File

@@ -16,6 +16,7 @@ import (
"github.com/go-openapi/strfmt"
"github.com/SigNoz/signoz/pkg/alertmanager"
"github.com/SigNoz/signoz/pkg/alertmanager/alertmanagertemplate"
"github.com/SigNoz/signoz/pkg/cache"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/modules/organization"
@@ -380,6 +381,9 @@ func (m *Manager) EditRule(ctx context.Context, ruleStr string, id valuer.UUID)
if err := m.validateChannels(ctx, claims.OrgID, &parsedRule); err != nil {
return err
}
if err := alertmanagertemplate.ValidateRuleTemplates(ctx, parsedRule.Annotations[ruletypes.AnnotationTitleTemplate], parsedRule.Annotations[ruletypes.AnnotationBodyTemplate]); err != nil {
return err
}
existingRule, err := m.ruleStore.GetStoredRule(ctx, orgID, id)
if err != nil {
return err
@@ -590,6 +594,9 @@ func (m *Manager) createRule(ctx context.Context, parsedRule ruletypes.PostableR
if err := m.validateChannels(ctx, claims.OrgID, &parsedRule); err != nil {
return nil, err
}
if err := alertmanagertemplate.ValidateRuleTemplates(ctx, parsedRule.Annotations[ruletypes.AnnotationTitleTemplate], parsedRule.Annotations[ruletypes.AnnotationBodyTemplate]); err != nil {
return nil, err
}
now := time.Now()
storedRule := &ruletypes.StorableRule{
Identifiable: types.Identifiable{
@@ -820,9 +827,9 @@ func (m *Manager) notifyFunc(ctx context.Context, orgID string, alerts ...*rulet
}
}
func (m *Manager) testNotifyFunc(ctx context.Context, orgID string, alerts ...*ruletypes.Alert) {
func (m *Manager) sendTestAlerts(ctx context.Context, orgID string, alerts ...*ruletypes.Alert) error {
if len(alerts) == 0 {
return
return nil
}
ruleID := alerts[0].Labels.Map()[ruletypes.AlertRuleIDLabel]
receiverMap := make(map[*alertmanagertypes.PostableAlert][]string)
@@ -845,10 +852,7 @@ func (m *Manager) testNotifyFunc(ctx context.Context, orgID string, alerts ...*r
}
receiverMap[a] = alert.Receivers
}
err := m.alertmanager.TestAlert(ctx, orgID, ruleID, receiverMap)
if err != nil {
m.logger.ErrorContext(ctx, "failed to send test notification", errors.Attr(err))
}
return m.alertmanager.TestAlert(ctx, orgID, ruleID, receiverMap)
}
func (m *Manager) ListActiveRules() ([]Rule, error) {
@@ -1121,6 +1125,9 @@ func (m *Manager) TestNotification(ctx context.Context, orgID valuer.UUID, ruleS
if err := m.validateChannels(ctx, orgID.StringValue(), &parsedRule); err != nil {
return 0, err
}
if err := alertmanagertemplate.ValidateRuleTemplates(ctx, parsedRule.Annotations[ruletypes.AnnotationTitleTemplate], parsedRule.Annotations[ruletypes.AnnotationBodyTemplate]); err != nil {
return 0, err
}
if !parsedRule.NotificationSettings.UsePolicy {
parsedRule.NotificationSettings.GroupBy = append(parsedRule.NotificationSettings.GroupBy, ruletypes.LabelThresholdName)
}
@@ -1130,6 +1137,7 @@ func (m *Manager) TestNotification(ctx context.Context, orgID valuer.UUID, ruleS
return 0, err
}
var sendErr error
alertCount, err := m.prepareTestRuleFunc(PrepareTestRuleOptions{
Rule: &parsedRule,
RuleStore: m.ruleStore,
@@ -1137,10 +1145,15 @@ func (m *Manager) TestNotification(ctx context.Context, orgID valuer.UUID, ruleS
Logger: m.opts.Logger,
Cache: m.cache,
ManagerOpts: m.opts,
NotifyFunc: m.testNotifyFunc,
SQLStore: m.sqlstore,
OrgID: orgID,
NotifyFunc: func(ctx context.Context, orgID string, alerts ...*ruletypes.Alert) {
sendErr = m.sendTestAlerts(ctx, orgID, alerts...)
},
SQLStore: m.sqlstore,
OrgID: orgID,
})
if err != nil {
return alertCount, err
}
return alertCount, err
return alertCount, sendErr
}

View File

@@ -11,6 +11,7 @@ import (
"github.com/SigNoz/signoz/pkg/alertmanager"
"github.com/SigNoz/signoz/pkg/alertmanager/alertmanagerserver"
alertmanagermock "github.com/SigNoz/signoz/pkg/alertmanager/alertmanagertest"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/instrumentation/instrumentationtest"
"github.com/SigNoz/signoz/pkg/prometheus"
"github.com/SigNoz/signoz/pkg/prometheus/prometheustest"
@@ -148,6 +149,56 @@ func TestManager_TestNotification_SendUnmatched_ThresholdRule(t *testing.T) {
}
}
// The caller pressed "test" to learn whether the notification arrives, so a
// receiver that does not take it is the result of the test.
func TestManager_TestNotification_ReturnsTheSendError(t *testing.T) {
target := 10.0
recovery := 5.0
rule := ThresholdRuleAtLeastOnceValueAbove(target, &recovery)
ruleBytes, err := json.Marshal(rule)
require.NoError(t, err)
orgID := valuer.GenerateUUID()
sendErr := errors.NewInvalidInputf(alertmanagertypes.ErrCodeAlertmanagerTestAlertFailed, "the test alert was not delivered to every receiver")
mgr := NewTestManager(t, &TestManagerOptions{
AlertmanagerHook: func(am alertmanager.Alertmanager) {
mockAM := am.(*alertmanagermock.MockAlertmanager)
mockAM.On("SetNotificationConfig", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil)
mockAM.On("Config").Return(alertmanagerserver.Config{ExternalURL: mustParseURL(t, "http://localhost:8080")})
mockAM.On("TestAlert", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(sendErr).Once()
},
SqlStoreHook: func(store sqlstore.SQLStore) {
mockStore := store.(*sqlstoretest.Provider)
orgRows := mockStore.Mock().NewRows([]string{"id"}).AddRow(orgID.StringValue())
mockStore.Mock().ExpectQuery("SELECT (.+) FROM (.+)organizations(.+) LIMIT (.+)").WillReturnRows(orgRows)
},
TelemetryStoreHook: func(store telemetrystore.TelemetryStore) {
mock := store.(*telemetrystoretest.Provider).Mock()
metadataCols := []cmock.ColumnType{
{Name: "metric_name", Type: "String"},
{Name: "temporality", Type: "String"},
{Name: "type", Type: "String"},
{Name: "is_monotonic", Type: "Bool"},
}
mock.ExpectQuery("*distributed_time_series_v4*").WithArgs(nil, nil, nil).WillReturnRows(cmock.NewRows(metadataCols, [][]any{
{"probe_success", metrictypes.Unspecified, metrictypes.GaugeType, false},
}))
mock.ExpectQuery("*meter*").WithArgs(nil).WillReturnRows(cmock.NewRows(metadataCols, [][]any{}))
queryArgs := GenerateMetricQueryCHArgs(time.Now().UTC(), 5*time.Minute, time.Duration(0), "probe_success", metrictypes.Unspecified)
mock.ExpectQuery("*WITH __temporal_aggregation_cte*").WithArgs(queryArgs...).WillReturnRows(cmock.NewRows(
[]cmock.ColumnType{{Name: "value", Type: "Float64"}, {Name: "attr", Type: "String"}, {Name: "ts", Type: "DateTime"}},
[][]any{{float64(12), "attr", time.Now()}},
))
},
})
count, err := mgr.TestNotification(context.Background(), orgID, string(ruleBytes))
require.ErrorIs(t, err, sendErr)
assert.Equal(t, 1, count)
}
func TestManager_TestNotification_SendUnmatched_PromRule(t *testing.T) {
target := 10.0

View File

@@ -0,0 +1,179 @@
package rules
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"time"
cmock "github.com/SigNoz/clickhouse-go-mock"
alertmanagernotifytest "github.com/SigNoz/signoz/pkg/alertmanager/alertmanagernotify/alertmanagernotifytest"
"github.com/SigNoz/signoz/pkg/alertmanager/alertmanagernotify/slack"
"github.com/SigNoz/signoz/pkg/alertmanager/alertmanagertemplate"
"github.com/SigNoz/signoz/pkg/instrumentation/instrumentationtest"
"github.com/SigNoz/signoz/pkg/telemetrystore"
"github.com/SigNoz/signoz/pkg/telemetrystore/telemetrystoretest"
"github.com/SigNoz/signoz/pkg/types/metrictypes"
qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
"github.com/SigNoz/signoz/pkg/types/ruletypes"
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
"github.com/SigNoz/signoz/pkg/valuer"
"github.com/prometheus/alertmanager/config"
"github.com/prometheus/alertmanager/notify"
"github.com/prometheus/alertmanager/types"
commoncfg "github.com/prometheus/common/config"
"github.com/prometheus/common/model"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// The ruler builds the alert and a notifier sends it. The title template of a
// rule is written for the notifier, so the ruler must hand it over as written,
// and a template the notifier cannot execute must not cost the notification.
func TestThresholdRuleTitleTemplateReachesTheNotifier(t *testing.T) {
testCases := []struct {
name string
titleTemplate string
wantTitle string
}{
{
name: "NoTitleTemplate_SendsTheChannelTitle",
wantTitle: "[FIRING:1] Checkout latency",
},
{
name: "TitleTemplateInTheRuleDataModel_IsExpandedByTheNotifier",
titleTemplate: "Fired: $rule.name",
wantTitle: "Fired: Checkout latency",
},
{
// .CommonLabels is a field of the channel data model.
name: "TitleTemplateThatFails_SendsTheChannelTitle",
titleTemplate: "Rule title: {{ .CommonLabels.alertname }}",
wantTitle: "[FIRING:1] Checkout latency",
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
target := float64(200)
postableRule := ruletypes.PostableRule{
AlertName: valuer.NewDisplayName("Checkout latency"),
AlertType: ruletypes.AlertTypeMetric,
RuleType: ruletypes.RuleTypeThreshold,
Evaluation: &ruletypes.EvaluationEnvelope{Kind: ruletypes.RollingEvaluation, Spec: ruletypes.RollingWindow{
EvalWindow: valuer.MustParseTextDuration("5m"),
Frequency: valuer.MustParseTextDuration("1m"),
}},
RuleCondition: &ruletypes.RuleCondition{
CompositeQuery: &ruletypes.AlertCompositeQuery{
QueryType: ruletypes.QueryTypeBuilder,
Unit: "ns",
Queries: []qbtypes.QueryEnvelope{
{
Type: qbtypes.QueryTypeBuilder,
Spec: qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]{
Name: "A",
StepInterval: qbtypes.Step{Duration: time.Minute},
Aggregations: []qbtypes.MetricAggregation{
{
MetricName: "signoz_calls_total",
Temporality: metrictypes.Cumulative,
TimeAggregation: metrictypes.TimeAggregationRate,
SpaceAggregation: metrictypes.SpaceAggregationSum,
},
},
Signal: telemetrytypes.SignalMetrics,
},
},
},
},
SelectedQuery: "A",
Thresholds: &ruletypes.RuleThresholdData{
Kind: ruletypes.BasicThresholdKind,
Spec: ruletypes.BasicRuleThresholds{
{
Name: "critical",
TargetValue: &target,
TargetUnit: "ms",
MatchType: ruletypes.AtleastOnce,
CompareOperator: ruletypes.ValueIsAbove,
},
},
},
},
Annotations: map[string]string{"summary": "observed {{$value}} against {{$threshold}}"},
}
if testCase.titleTemplate != "" {
postableRule.Annotations[ruletypes.AnnotationTitleTemplate] = testCase.titleTemplate
}
telemetryStore := telemetrystoretest.New(telemetrystore.Config{}, &queryMatcherAny{})
querier, mockMetadataStore := prepareQuerierForMetrics(t, telemetryStore)
mockMetadataStore.TypeMap["signoz_calls_total"] = metrictypes.SumType
telemetryStore.Mock().
ExpectQuery("SELECT any").
WithArgs(nil, nil, nil, nil, nil, nil, nil, nil).
WillReturnRows(cmock.NewRows(
[]cmock.ColumnType{{Name: "ts", Type: "DateTime"}, {Name: "value", Type: "Float64"}},
[][]any{{time.Now(), float64(572588400)}, {time.Now().Add(time.Second), float64(572386400)}},
))
rule, err := NewThresholdRule("69", valuer.GenerateUUID(), &postableRule, querier, instrumentationtest.New().Logger(), mustParseURL(t, "http://localhost:8000"))
require.NoError(t, err)
alertsFound, err := rule.Eval(context.Background(), time.Now())
require.NoError(t, err)
require.Equal(t, 1, alertsFound)
alerts := make([]*types.Alert, 0, len(rule.Active))
for _, active := range rule.Active {
labels := model.LabelSet{}
for name, value := range active.Labels.Map() {
labels[model.LabelName(name)] = model.LabelValue(value)
}
annotations := model.LabelSet{}
for name, value := range active.Annotations.Map() {
annotations[model.LabelName(name)] = model.LabelValue(value)
}
alerts = append(alerts, &types.Alert{Alert: model.Alert{Labels: labels, Annotations: annotations, StartsAt: time.Now(), EndsAt: time.Now().Add(time.Hour)}})
}
var posted struct {
Attachments []struct {
Title string `json:"title"`
} `json:"attachments"`
}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.NoError(t, json.NewDecoder(r.Body).Decode(&posted))
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"ok": true}`))
}))
defer srv.Close()
webhookURL, err := url.Parse(srv.URL)
require.NoError(t, err)
tmpl := alertmanagernotifytest.CreateTmpl(t)
logger := slog.New(slog.DiscardHandler)
notifier, err := slack.New(&config.SlackConfig{
APIURL: &config.SecretURL{URL: webhookURL},
Channel: "#alerts",
Title: `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }}`,
Text: `{{ range .Alerts }}{{ .Annotations.summary }}{{ end }}`,
HTTPConfig: &commoncfg.HTTPClientConfig{},
}, tmpl, logger, alertmanagertemplate.New(tmpl, logger))
require.NoError(t, err)
ctx := notify.WithGroupKey(context.Background(), "group")
ctx = notify.WithReceiverName(ctx, "slack")
ctx = notify.WithGroupLabels(ctx, model.LabelSet{"ruleId": "69"})
_, err = notifier.Notify(ctx, alerts...)
require.NoError(t, err)
require.NotEmpty(t, posted.Attachments)
assert.Equal(t, testCase.wantTitle, posted.Attachments[0].Title)
})
}
}

View File

@@ -45,6 +45,8 @@ const (
NoDataLabel = model.LabelName("nodata")
)
var ErrCodeAlertmanagerTestAlertFailed = errors.MustNewCode("alertmanager_test_alert_failed")
type DeprecatedGettableAlert struct {
*model.Alert
Status types.AlertStatus `json:"status" description:"The alert state and the silences and inhibitions suppressing it."`

View File

@@ -1,6 +1,8 @@
package alertmanagertypes
import (
"fmt"
"regexp"
"strings"
"time"
@@ -14,6 +16,18 @@ import (
// recipient; the alertmanager reads them off the raw alert before stripping.
const privateAnnotationPrefix = "_"
var (
// templateErrorPosition matches what the template engine puts in front of
// the reason, such as `template: :1:431: executing "" `. The position
// counts a preamble that Expand adds to a rule template, so it does not
// point into the text the author wrote.
templateErrorPosition = regexp.MustCompile(`^.*?template: [^:]*:\d+(?::\d+)?: (?:executing "[^"]*" )?`)
// templateErrorExpression matches how the engine names the expression that
// failed: `at <.Value>: `. The angle brackets are markup in more than one
// channel.
templateErrorExpression = regexp.MustCompile(`^at <(.*)>: `)
)
// IsPrivateAnnotation reports whether an annotation key is considered
// private — i.e. internal to alertmanager and should not be rendered in
// notifications.
@@ -37,12 +51,16 @@ func FilterPublicAnnotations(kv template.KV) template.KV {
// ExpandRequest carries the title/body templates and their defaults handed to
// Templater.Expand. Default templates are used when the custom templates
// expand to empty strings.
// expand to empty strings or fail. Builtin templates are the channel kind's
// compiled defaults, used when a default template fails; a default template
// that is empty or expands to an empty string is not a failure.
type ExpandRequest struct {
TitleTemplate string
BodyTemplate string
DefaultTitleTemplate string
DefaultBodyTemplate string
BuiltinTitleTemplate string
BuiltinBodyTemplate string
}
// ExpandResult is the rendered output of Templater.Expand.
@@ -53,8 +71,12 @@ type ExpandResult struct {
// body template is applied per-alert and concatenated by the caller.
Body []string
// IsDefaultBody is true when Body came from the default template (no
// user-authored body was supplied), false when a custom template was used.
// user-authored body was supplied, or it failed), false when a custom
// template was used.
IsDefaultBody bool
// Failures names each template that failed and was replaced. A template
// that expands to an empty string is not in it.
Failures TemplateFailures
// MissingVars is the union of $-references in the title and body templates
// that did not resolve to any known field. Surfaced for preview warnings;
// at runtime these render as "<no value>".
@@ -65,6 +87,38 @@ type ExpandResult struct {
NotificationData *NotificationTemplateData
}
// TemplateFailures holds the error of each title or body template that failed
// and was replaced: the rule's by the channel's, and the channel's by the
// builtin one.
type TemplateFailures struct {
RuleTitle error
RuleBody error
ChannelTitle error
ChannelBody error
}
// Notice returns markdown for the reader of the notification, one line for
// each template that failed, and an empty string when none failed.
func (f TemplateFailures) Notice() string {
var lines []string
for _, failure := range []struct {
template string
replacement string
err error
}{
{"rule title", "channel title", f.RuleTitle},
{"rule body", "channel body", f.RuleBody},
{"channel title", "built-in title", f.ChannelTitle},
{"channel body", "built-in body", f.ChannelBody},
} {
if failure.err != nil {
lines = append(lines, fmt.Sprintf("The %s template failed: `%s`. The %s is shown.", failure.template, templateFailureReason(failure.err), failure.replacement))
}
}
return strings.Join(lines, "\n\n")
}
// AlertData holds per-alert data used when expanding body templates.
//
// Field paths follow OpenTelemetry-style dotted namespaces (via mapstructure
@@ -142,3 +196,13 @@ type NotificationAlert struct {
TotalFiring int `json:"totalFiring" mapstructure:"total_firing"`
TotalResolved int `json:"totalResolved" mapstructure:"total_resolved"`
}
// templateFailureReason returns the error as one line that is safe inside a
// markdown code span.
func templateFailureReason(err error) string {
reason := strings.Join(strings.Fields(err.Error()), " ")
reason = templateErrorPosition.ReplaceAllString(reason, "")
reason = templateErrorExpression.ReplaceAllString(reason, "$1: ")
return strings.ReplaceAll(reason, "`", "'")
}

View File

@@ -0,0 +1,75 @@
package alertmanagertypes
import (
"testing"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/stretchr/testify/assert"
)
func TestTemplateFailuresNotice(t *testing.T) {
engineError := func(message string) error {
return errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, message)
}
testCases := []struct {
name string
failures TemplateFailures
want string
}{
{
name: "NoFailure",
},
{
// The position counts the preamble of a rule template, and the
// angle brackets are markup in some channels.
name: "RuleTitle_ExecutionError_KeepsTheExpressionAndTheReason",
failures: TemplateFailures{RuleTitle: engineError(`failed to execute custom title template: template: :1:431: executing "" at <.CommonLabels.alertname>: nil pointer evaluating interface {}.alertname`)},
want: "The rule title template failed: `.CommonLabels.alertname: nil pointer evaluating interface {}.alertname`. The channel title is shown.",
},
{
name: "RuleBody_ParseError",
failures: TemplateFailures{RuleBody: engineError("template: template:1: unclosed action")},
want: "The rule body template failed: `unclosed action`. The channel body is shown.",
},
{
name: "ChannelTitle_UnknownFunction",
failures: TemplateFailures{ChannelTitle: engineError(`template: :1: function "toUpperAndTrim" not defined`)},
want: "The channel title template failed: `function \"toUpperAndTrim\" not defined`. The built-in title is shown.",
},
{
name: "ChannelBody_ExecutionError",
failures: TemplateFailures{ChannelBody: engineError(`failed to execute default template: template: :3:22: executing "" at <.Value>: can't evaluate field Value in type template.Alert`)},
want: "The channel body template failed: `.Value: can't evaluate field Value in type template.Alert`. The built-in body is shown.",
},
{
name: "BackticksAndLineBreaks_StayInOneCodeSpan",
failures: TemplateFailures{RuleBody: engineError("template: :2:5: executing \"\" at <printf `%d`\n .labels.pod>: wrong type")},
want: "The rule body template failed: `printf '%d' .labels.pod: wrong type`. The channel body is shown.",
},
{
name: "NotAnEngineError_IsShownAsItIs",
failures: TemplateFailures{RuleTitle: engineError("failed to build template data map")},
want: "The rule title template failed: `failed to build template data map`. The channel title is shown.",
},
{
name: "EveryTemplateFailed_OneLineEach",
failures: TemplateFailures{
RuleTitle: engineError("template: template:1: unexpected EOF"),
RuleBody: engineError("template: template:4: unclosed action"),
ChannelTitle: engineError(`template: :1: function "upper" not defined`),
ChannelBody: engineError(`template: :1: function "lower" not defined`),
},
want: "The rule title template failed: `unexpected EOF`. The channel title is shown.\n\n" +
"The rule body template failed: `unclosed action`. The channel body is shown.\n\n" +
"The channel title template failed: `function \"upper\" not defined`. The built-in title is shown.\n\n" +
"The channel body template failed: `function \"lower\" not defined`. The built-in body is shown.",
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
assert.Equal(t, testCase.want, testCase.failures.Notice())
})
}
}

View File

@@ -547,8 +547,12 @@ func testTemplateParsing(rl *PostableRule) (errs []error) {
}
}
// Parsing Annotations.
for _, val := range rl.Annotations {
// Parsing Annotations. Private ones carry templates for the notifier,
// which has its own engine; the rule manager validates those.
for name, val := range rl.Annotations {
if alertmanagertypes.IsPrivateAnnotation(name) {
continue
}
err := parseTest(val)
if err != nil {
errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput, "template parsing error: %s", err.Error()))

View File

@@ -387,6 +387,12 @@ func TestValidate_PostableRule_Common(t *testing.T) {
name: "valid template in label",
json: patchJSON(validV2Alpha1Builder(), `{"labels": {"severity": "{{$labels.host}}"}}`),
},
{
// $alert is a variable of the notifier engine, which expands the
// private annotations; it is not one of the ruler engine.
name: "notifier template in private annotation",
json: patchJSON(validV2Alpha1Builder(), `{"annotations": {"_body_template": "{{ if $alert.is_firing }}up{{ end }} $rule.name"}}`),
},
// anomaly seasonality
{