Compare commits

...

24 Commits

Author SHA1 Message Date
nikhilmantri0902
3d76db44c3 fix(sqlmigration): swap the msteams related links template for any call spelling 2026-11-26 19:21:42 +05:30
nikhilmantri0902
b6468391d8 fix(alertmanager): trim msteams text by its encoded size 2026-11-26 19:21:41 +05:30
Nikhil Mantri
85f2906356 Merge branch 'main' into fix/msteams_dont_drop_description 2026-11-26 18:26:29 +05:30
nikhilmantri0902
4973767852 fix(alertmanager): copy msteams alerts with a struct literal 2026-11-26 18:11:59 +05:30
nikhilmantri0902
515bc4b131 fix(sqlmigration): save msteams receivers when a later notifier is rewritten 2026-11-26 18:01:20 +05:30
nikhilmantri0902
ee23f660ed fix(alertmanager): escape backticks and paired tildes in msteams label values 2026-11-26 17:46:37 +05:30
Nikhil Mantri
c84e192974 Merge branch 'main' into fix/msteams_dont_drop_description 2026-11-26 16:11:19 +05:30
Nikhil Mantri
7a4ac47825 Merge branch 'main' into fix/msteams_dont_drop_description 2026-11-25 12:52:49 +05:30
nikhilmantri0902
8c1982746d fix(alertmanager): drop emptied msteams alert blocks when trimming to the size limit 2026-11-24 17:21:48 +05:30
nikhilmantri0902
53885a633b Merge branch 'fix/msteams_dont_drop_description' of github.com:SigNoz/signoz into fix/msteams_dont_drop_description 2026-11-23 21:45:29 +05:30
nikhilmantri0902
5d50703d95 fix(sqlmigration): leave msteams text holding placeholder characters untouched 2026-11-23 21:45:15 +05:30
Nikhil Mantri
ebe657ec94 Merge branch 'main' into fix/msteams_dont_drop_description 2026-11-23 19:37:29 +05:30
nikhilmantri0902
1fea333afa fix(alertmanager): escape msteams group labels and backslashes, log trim once 2026-11-23 18:50:47 +05:30
nikhilmantri0902
aa9146d62f test(frontend): use current test ids in the msteams prefill test 2026-11-23 18:50:40 +05:30
nikhilmantri0902
4519b746de Merge branch 'fix/msteams_dont_drop_description' of github.com:SigNoz/signoz into fix/msteams_dont_drop_description 2026-11-23 17:33:12 +05:30
nikhilmantri0902
7b77d4cfc1 fix(alertmanager): resolve lint findings in the msteams migration 2026-11-23 17:32:41 +05:30
Nikhil Mantri
79874c3390 Merge branch 'main' into fix/msteams_dont_drop_description 2026-11-23 17:27:34 +05:30
nikhilmantri0902
eac35e303a fix(alertmanager): show msteams label values as written
Teams reads card text as markdown, so a label value such as a*b*c or [x](y) lost
characters. The notifier now escapes label values before templates run.
2026-11-23 17:08:49 +05:30
nikhilmantri0902
0a7676fcd6 refactor(alertmanager): write formatted text with fprintf in the msteams migration 2026-11-20 15:07:00 +05:30
nikhilmantri0902
c930801318 test(alertmanager): cover a rule body template on the msteams channel 2026-11-20 15:06:09 +05:30
nikhilmantri0902
e5af805513 chore(alertmanager): regenerate openapi spec for the msteams defaults 2026-11-20 14:56:03 +05:30
nikhilmantri0902
0f5579d3a4 fix(alertmanager): prefill the msteams form with the teams defaults
Also shortens the migration factory name, which was over the 31 character limit and
stopped the server from starting.
2026-11-20 14:55:59 +05:30
nikhilmantri0902
277d869394 fix(alertmanager): migrate stored msteams templates to the teams defaults
Untouched slack seeds become the new defaults, edited seeds have their slack formatting
converted in place, and text written from scratch is left as is.
2026-11-20 14:31:21 +05:30
nikhilmantri0902
43df8c917b fix(alertmanager): render the msteams channel description on the card
The Teams defaults redefine upstream's msteamsv2.default.* templates, so channels
that already store the marker pick up the new default without a data change.
2026-11-20 14:12:40 +05:30
15 changed files with 1686 additions and 173 deletions

View File

@@ -674,11 +674,11 @@ components:
nullable: true
type: boolean
text:
description: Alertmanager template for the card body; defaults to the Alertmanager
Teams default.
description: Alertmanager template for the card body, rendered as Teams
markdown; defaults to the SigNoz Teams default.
type: string
title:
description: Alertmanager template for the card title; defaults to the Alertmanager
description: Alertmanager template for the card title; defaults to the SigNoz
Teams default.
type: string
webhookUrl:

View File

@@ -751,12 +751,12 @@ export interface AlertmanagertypesChannelMSTeamsConfigDTO {
sendResolved?: boolean | null;
/**
* @type string
* @description Alertmanager template for the card body; defaults to the Alertmanager Teams default.
* @description Alertmanager template for the card body, rendered as Teams markdown; defaults to the SigNoz Teams default.
*/
text?: string;
/**
* @type string
* @description Alertmanager template for the card title; defaults to the Alertmanager Teams default.
* @description Alertmanager template for the card title; defaults to the SigNoz Teams default.
*/
title?: string;
/**

View File

@@ -4,6 +4,7 @@ import {
AlertmanagertypesChannelIncidentIOConfigDTO,
AlertmanagertypesChannelJiraConfigDTO,
AlertmanagertypesChannelJSMOpsConfigDTO,
AlertmanagertypesChannelMSTeamsConfigDTO,
AlertmanagertypesChannelOpsgenieConfigDTO,
AlertmanagertypesChannelPagerdutyConfigDTO,
AlertmanagertypesChannelSlackConfigDTO,
@@ -12,7 +13,6 @@ import {
import { ChannelKind, ChannelSpecFormValues, JiraDeployment } from './types';
// shared by slack and ms teams, both render the same title / description boxes
export const SlackInitialConfig: Partial<AlertmanagertypesChannelSlackConfigDTO> =
{
text: `{{ range .Alerts -}}
@@ -39,6 +39,26 @@ export const SlackInitialConfig: Partial<AlertmanagertypesChannelSlackConfigDTO>
{{- end }}`,
};
// mirrors DefaultMSTeamsTitleTemplate / DefaultMSTeamsTextTemplate in
// pkg/types/alertmanagertypes/channel_msteams.go, which the backend applies
// when title / text are left empty
export const MsTeamsInitialConfig: Partial<AlertmanagertypesChannelMSTeamsConfigDTO> =
{
title: `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }}`,
text: `{{ range .Alerts -}}
**Alert:** {{ .Labels.alertname }}{{ if .Labels.severity }} ({{ .Labels.severity }}){{ end }} - {{ .Status }}
{{ if .Annotations.summary }}**Summary:** {{ .Annotations.summary }}
{{ end }}{{ if .Annotations.description }}**Description:** {{ .Annotations.description }}
{{ end }}{{ template "signoz.relatedLinks.markdown" . }}{{ with (.Labels.Remove (stringSlice "alertname" "severity" "ruleId" "ruleSource")).SortedPairs }}**Details:**
{{ range . }}- **{{ .Name }}:** {{ .Value }}
{{ end }}
{{ end }}{{ end }}`,
};
// mirrors DefaultGoogleChatReceiverConfig in pkg/types/alertmanagertypes/googlechat.go,
// which the backend applies when title / text are left empty
export const GoogleChatInitialConfig: Partial<AlertmanagertypesChannelGoogleChatConfigDTO> =
@@ -577,7 +597,7 @@ export const DEFAULT_CHANNEL_KIND = ChannelKind.slack;
export const ChannelInitialConfig: Record<ChannelKind, ChannelSpecFormValues> =
{
[ChannelKind.slack]: SlackInitialConfig,
[ChannelKind.msteams]: SlackInitialConfig,
[ChannelKind.msteams]: MsTeamsInitialConfig,
[ChannelKind.googlechat]: GoogleChatInitialConfig,
[ChannelKind.jira]: JiraInitialConfig,
[ChannelKind.jsmops]: JsmOpsInitialConfig,

View File

@@ -700,6 +700,71 @@ describe('ChannelForm save', () => {
TEST_TIMEOUT,
);
it(
'prefills microsoft teams with its own templates instead of the slack ones',
async () => {
let body: Record<string, unknown> | undefined;
server.use(
rest.post(
'http://localhost/api/v2/notification_channels',
async (req, res, ctx) => {
body = await req.json();
return res(ctx.status(201), ctx.json({ status: 'success', data: {} }));
},
),
);
render(<ChannelForm onDone={jest.fn()} />);
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
await pickChannelType(user, ChannelKind.msteams);
const teamsTitle =
'[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }}';
expect(screen.getByTestId('title-textarea')).toHaveValue(teamsTitle);
const description = screen.getByTestId(
'description-textarea',
) as HTMLTextAreaElement;
expect(description.value).toContain(
'**Alert:** {{ .Labels.alertname }}{{ if .Labels.severity }} ({{ .Labels.severity }}){{ end }} - {{ .Status }}',
);
expect(description.value).toContain(
'{{ template "signoz.relatedLinks.markdown" . }}',
);
expect(description.value).not.toContain('*Alert:* ');
expect(description.value).not.toContain('signoz.relatedLinks.slack');
await user.type(
screen.getByTestId('channel-name-textbox-field'),
'teams alerts',
);
await user.type(
screen.getByTestId('webhook-url-textbox-field'),
'https://teams.example.com/workflows/hook',
);
const save = screen.getByTestId('save-channel-button');
await waitFor(
() => expect(save).toHaveAttribute('aria-disabled', 'false'),
FIND,
);
await user.click(save);
await waitFor(() => expect(body).toBeDefined(), FIND);
expect(body).toMatchObject({
config: {
kind: 'msteams',
spec: {
webhookUrl: 'https://teams.example.com/workflows/hook',
title: teamsTitle,
text: description.value,
},
},
});
},
TEST_TIMEOUT,
);
it(
'leaves the pagerduty client url empty so the backend links to this instance',
async () => {

View File

@@ -14,10 +14,12 @@ import (
"os"
"slices"
"strings"
"unicode"
"github.com/SigNoz/signoz/pkg/alertmanager/alertmanagertemplate"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/types/alertmanagertypes"
"github.com/SigNoz/signoz/pkg/types/ruletypes"
commoncfg "github.com/prometheus/common/config"
"github.com/prometheus/common/model"
@@ -35,6 +37,10 @@ const (
const (
Integration = "msteamsv2"
// Teams rejects messages over 28 KB; the margin covers the workflow's own envelope.
// https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/add-incoming-webhook
maxMessageBytes = 25 * 1024
)
type Notifier struct {
@@ -67,7 +73,6 @@ type Body struct {
Wrap bool `json:"wrap,omitempty"`
Style string `json:"style,omitempty"`
Color string `json:"color,omitempty"`
Facts []Fact `json:"facts,omitempty"`
}
type Action struct {
@@ -76,11 +81,6 @@ type Action struct {
URL string `json:"url"`
}
type Fact struct {
Title string `json:"title"`
Value string `json:"value"`
}
type Msteams struct {
Width string `json:"width"`
}
@@ -154,8 +154,177 @@ func (n *Notifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error)
return false, err
}
// A message as referenced in https://learn.microsoft.com/en-us/connectors/teams/?tabs=text1%2Cdotnet#request-body-schema
t := teamsMessage{
payload, err := encodeMessage(bodyBlocks, titleLink)
if err != nil {
return false, err
}
originalBytes := payload.Len()
for payload.Len() > maxMessageBytes {
longest := indexLongestText(bodyBlocks)
if longest < 0 {
break
}
text := truncateToEncodedBytes(bodyBlocks[longest].Text, payload.Len()-maxMessageBytes)
if text == "" && longest > 0 {
bodyBlocks = slices.Delete(bodyBlocks, longest, longest+1)
} else {
bodyBlocks[longest].Text = text
}
if payload, err = encodeMessage(bodyBlocks, titleLink); err != nil {
return false, err
}
}
if payload.Len() < originalBytes {
n.logger.WarnContext(ctx, "truncated message text to fit the size limit", slog.Int("original_bytes", originalBytes), slog.Int("final_bytes", payload.Len()), slog.Int("max_bytes", maxMessageBytes))
}
resp, err := n.postJSONFunc(ctx, n.client, url, payload) //nolint:bodyclose
if err != nil {
return true, notify.RedactURL(err)
}
defer notify.Drain(resp) //drain is used to close the body of the response hence the nolint directive
// https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/connectors-using?tabs=cURL#rate-limiting-for-connectors
shouldRetry, err := n.retrier.Check(resp.StatusCode, resp.Body)
if err != nil {
return shouldRetry, notify.NewErrorWithReason(notify.GetFailureReasonFromStatusCode(resp.StatusCode), err)
}
return shouldRetry, err
}
// prepareContent builds the Adaptive Card body blocks for the notification.
// The first block is always the title; the remainder is the channel text, or
// one block per alert when the alerts carried a custom body template.
func (n *Notifier) prepareContent(ctx context.Context, alerts []*types.Alert) ([]Body, error) {
if groupLabels, ok := notify.GroupLabels(ctx); ok {
ctx = notify.WithGroupLabels(ctx, escapeLabels(groupLabels))
}
customTitle, customBody := alertmanagertemplate.ExtractTemplatesFromAnnotations(alerts)
result, err := n.templater.Expand(ctx, alertmanagertypes.ExpandRequest{
TitleTemplate: customTitle,
BodyTemplate: customBody,
DefaultTitleTemplate: n.conf.Title,
DefaultBodyTemplate: n.conf.Text,
}, escapeLabelValues(alerts))
if err != nil {
return nil, err
}
color := colorGrey
switch types.Alerts(alerts...).Status() {
case model.AlertFiring:
color = colorRed
case model.AlertResolved:
color = colorGreen
}
blocks := []Body{{
Type: "TextBlock",
Text: result.Title,
Weight: "Bolder",
Size: "Medium",
Wrap: true,
Style: "heading",
Color: color,
}}
if result.IsDefaultBody {
for _, body := range result.Body {
if body = strings.TrimSpace(body); body != "" {
blocks = append(blocks, Body{Type: "TextBlock", Text: body, Wrap: true})
}
}
return blocks, nil
}
// Custom body path: result.Body is positionally aligned with alerts;
// entries for alerts whose template rendered empty are kept as "" so we
// can skip them here without shifting the per-alert color index.
for i, body := range result.Body {
if body == "" || i >= len(alerts) {
continue
}
perAlertColor := colorRed
if alerts[i].Resolved() {
perAlertColor = colorGreen
}
blocks = append(blocks, Body{
Type: "TextBlock",
Text: body,
Wrap: true,
Color: perAlertColor,
})
}
return blocks, nil
}
// escapeLabelValues copies the alerts so a label value shows on the card as written instead of being read as markdown.
func escapeLabelValues(alerts []*types.Alert) []*types.Alert {
escaped := make([]*types.Alert, 0, len(alerts))
for _, alert := range alerts {
escaped = append(escaped, &types.Alert{
Alert: model.Alert{
Labels: escapeLabels(alert.Labels),
Annotations: alert.Annotations.Clone(),
StartsAt: alert.StartsAt,
EndsAt: alert.EndsAt,
GeneratorURL: alert.GeneratorURL,
},
UpdatedAt: alert.UpdatedAt,
Timeout: alert.Timeout,
})
}
return escaped
}
func escapeLabels(labels model.LabelSet) model.LabelSet {
escaped := make(model.LabelSet, len(labels))
for name, value := range labels {
if name == ruletypes.LabelRuleSource {
escaped[name] = value
continue
}
escaped[name] = model.LabelValue(escapeMarkdown(string(value)))
}
return escaped
}
// escapeMarkdown leaves an underscore inside a word and a lone tilde alone, since Teams reads neither as markup.
func escapeMarkdown(value string) string {
runes := []rune(value)
pairedTildes := strings.Count(value, "~") > 1
var escaped strings.Builder
for i, r := range runes {
switch r {
case '\\', '*', '[', ']', '`':
escaped.WriteRune('\\')
case '~':
if pairedTildes {
escaped.WriteRune('\\')
}
case '_':
if i == 0 || i == len(runes)-1 || !isWordRune(runes[i-1]) || !isWordRune(runes[i+1]) {
escaped.WriteRune('\\')
}
}
escaped.WriteRune(r)
}
return escaped.String()
}
func isWordRune(r rune) bool {
return unicode.IsLetter(r) || unicode.IsDigit(r)
}
// A message as referenced in https://learn.microsoft.com/en-us/connectors/teams/?tabs=text1%2Cdotnet#request-body-schema
func encodeMessage(bodyBlocks []Body, titleLink string) (*bytes.Buffer, error) {
message := teamsMessage{
Type: "message",
Attachments: []Attachment{
{
@@ -182,134 +351,49 @@ func (n *Notifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error)
}
var payload bytes.Buffer
if err = json.NewEncoder(&payload).Encode(t); err != nil {
return false, err
}
resp, err := n.postJSONFunc(ctx, n.client, url, &payload) //nolint:bodyclose
if err != nil {
return true, notify.RedactURL(err)
}
defer notify.Drain(resp) //drain is used to close the body of the response hence the nolint directive
// https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/connectors-using?tabs=cURL#rate-limiting-for-connectors
shouldRetry, err := n.retrier.Check(resp.StatusCode, resp.Body)
if err != nil {
return shouldRetry, notify.NewErrorWithReason(notify.GetFailureReasonFromStatusCode(resp.StatusCode), err)
}
return shouldRetry, err
}
// prepareContent builds the Adaptive Card body blocks for the notification.
// The first block is always the title; the remainder depends on whether the
// alerts carried a custom body template.
func (n *Notifier) prepareContent(ctx context.Context, alerts []*types.Alert) ([]Body, error) {
customTitle, customBody := alertmanagertemplate.ExtractTemplatesFromAnnotations(alerts)
result, err := n.templater.Expand(ctx, alertmanagertypes.ExpandRequest{
TitleTemplate: customTitle,
BodyTemplate: customBody,
DefaultTitleTemplate: n.conf.Title,
DefaultBodyTemplate: n.conf.Text,
}, alerts)
if err != nil {
if err := json.NewEncoder(&payload).Encode(message); err != nil {
return nil, err
}
color := colorGrey
switch types.Alerts(alerts...).Status() {
case model.AlertFiring:
color = colorRed
case model.AlertResolved:
color = colorGreen
}
blocks := []Body{{
Type: "TextBlock",
Text: result.Title,
Weight: "Bolder",
Size: "Medium",
Wrap: true,
Style: "heading",
Color: color,
}}
if result.IsDefaultBody {
for _, alert := range alerts {
blocks = append(blocks, Body{
Type: "TextBlock",
Text: "Alerts",
Weight: "Bolder",
Size: "Medium",
Wrap: true,
Color: color,
})
blocks = append(blocks, n.createLabelsAndAnnotationsBody(alert)...)
}
return blocks, nil
}
// Custom body path: result.Body is positionally aligned with alerts;
// entries for alerts whose template rendered empty are kept as "" so we
// can skip them here without shifting the per-alert color index.
for i, body := range result.Body {
if body == "" || i >= len(alerts) {
continue
}
perAlertColor := colorRed
if alerts[i].Resolved() {
perAlertColor = colorGreen
}
blocks = append(blocks, Body{
Type: "TextBlock",
Text: body,
Wrap: true,
Color: perAlertColor,
})
}
return blocks, nil
return &payload, nil
}
func (*Notifier) createLabelsAndAnnotationsBody(alert *types.Alert) []Body {
bodies := []Body{}
bodies = append(bodies, Body{
Type: "TextBlock",
Text: "Labels",
Weight: "Bolder",
Size: "Medium",
})
// truncateToEncodedBytes cuts text until its JSON encoding is overflow bytes shorter, since escaping makes some characters longer than their raw bytes.
func truncateToEncodedBytes(text string, overflow int) string {
budget := encodedLen(text) - overflow
facts := []Fact{}
for k, v := range alert.Labels {
if slices.Contains([]string{"alertname", "severity", "ruleId", "ruleSource"}, string(k)) {
continue
low, high := 0, len(text)
for low < high {
mid := (low + high + 1) / 2
truncated, _ := notify.TruncateInBytes(text, mid)
if encodedLen(truncated) <= budget {
low = mid
} else {
high = mid - 1
}
facts = append(facts, Fact{Title: string(k), Value: string(v)})
}
bodies = append(bodies, Body{
Type: "FactSet",
Facts: facts,
})
truncated, _ := notify.TruncateInBytes(text, low)
bodies = append(bodies, Body{
Type: "TextBlock",
Text: "Annotations",
Weight: "Bolder",
Size: "Medium",
})
annotationsFacts := []Fact{}
for k, v := range alert.Annotations {
if slices.Contains([]string{"summary", "related_logs", "related_traces"}, string(k)) ||
alertmanagertypes.IsPrivateAnnotation(string(k)) {
continue
}
annotationsFacts = append(annotationsFacts, Fact{Title: string(k), Value: string(v)})
}
bodies = append(bodies, Body{
Type: "FactSet",
Facts: annotationsFacts,
})
return bodies
return truncated
}
func encodedLen(text string) int {
encoded, _ := json.Marshal(text)
return len(encoded)
}
// indexLongestText returns -1 once no block has text left to trim; the title at index 0 goes last.
func indexLongestText(blocks []Body) int {
longest := -1
for i := 1; i < len(blocks); i++ {
if len(blocks[i].Text) > 0 && (longest < 0 || len(blocks[i].Text) > len(blocks[longest].Text)) {
longest = i
}
}
if longest < 0 && len(blocks) > 0 && len(blocks[0].Text) > 0 {
return 0
}
return longest
}

View File

@@ -5,6 +5,7 @@
package msteamsv2
import (
"bytes"
"context"
"encoding/json"
"io"
@@ -13,6 +14,7 @@ import (
"net/http/httptest"
"net/url"
"os"
"strings"
"testing"
"time"
@@ -340,3 +342,399 @@ func TestMSTeamsV2ReadingURLFromFile(t *testing.T) {
test.AssertNotifyLeaksNoSecret(ctx, t, notifier, u.String())
}
func TestPrepareContentChannelText(t *testing.T) {
testCases := []struct {
name string
title string
text string
annotations model.LabelSet
expectedTitle string
expectedBody []Body
}{
{
name: "CustomChannelText_Rendered",
title: "Team alert: {{ .CommonLabels.alertname }}",
text: "Service {{ range .Alerts }}{{ .Labels.service }}{{ end }} needs attention",
expectedTitle: "Team alert: checkout errors",
expectedBody: []Body{{Type: "TextBlock", Text: "Service checkout needs attention", Wrap: true}},
},
{
name: "DefaultMarkers_RenderTeamsDefault",
title: `{{ template "msteamsv2.default.title" . }}`,
text: `{{ template "msteamsv2.default.text" . }}`,
annotations: model.LabelSet{"description": "error rate crossed 5%"},
expectedTitle: "[FIRING:1] checkout errors",
expectedBody: []Body{{
Type: "TextBlock",
Text: "**Alert:** checkout errors (critical) - firing\n\n**Description:** error rate crossed 5%\n\n**Details:**\n\n- **service:** checkout",
Wrap: true,
}},
},
{
name: "RuleBodyTemplate_OverridesChannelText",
title: "Rule wins: {{ .CommonLabels.alertname }}",
text: "channel text that must not appear",
annotations: model.LabelSet{ruletypes.AnnotationBodyTemplate: "rule body for $alertname"},
expectedTitle: "Rule wins: checkout errors",
expectedBody: []Body{{Type: "TextBlock", Text: "rule body for checkout errors", Wrap: true, Color: colorRed}},
},
{
name: "EmptyText_TitleOnly",
title: "Only a title",
text: "",
expectedTitle: "Only a title",
expectedBody: []Body{},
},
{
name: "WhitespaceText_TitleOnly",
title: "Still only a title",
text: "{{ if false }}never{{ end }}\n ",
expectedTitle: "Still only a title",
expectedBody: []Body{},
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
tmpl, err := alertmanagertypes.FromGlobs([]string{})
require.NoError(t, err)
tmpl.ExternalURL = &url.URL{Scheme: "http", Host: "signoz.test"}
notifier, err := New(
&config.MSTeamsV2Config{
WebhookURL: &config.SecretURL{URL: testWebhookURL},
HTTPConfig: &commoncfg.HTTPClientConfig{},
Title: testCase.title,
Text: testCase.text,
},
tmpl,
`{{ template "msteamsv2.default.titleLink" . }}`,
promslog.NewNopLogger(),
newTestTemplater(tmpl),
)
require.NoError(t, err)
alerts := []*types.Alert{{
Alert: model.Alert{
Labels: model.LabelSet{"alertname": "checkout errors", "severity": "critical", "service": "checkout", "ruleId": "0199051c-f374-71f7-a340-ec79ad81e70f"},
Annotations: testCase.annotations,
StartsAt: time.Now(),
EndsAt: time.Now().Add(time.Hour),
},
}}
blocks, err := notifier.prepareContent(notify.WithGroupKey(context.Background(), "1"), alerts)
require.NoError(t, err)
require.NotEmpty(t, blocks)
assert.Equal(t, testCase.expectedTitle, blocks[0].Text)
assert.Equal(t, colorRed, blocks[0].Color)
assert.Equal(t, testCase.expectedBody, blocks[1:])
})
}
}
func TestNotifyMessageSize(t *testing.T) {
testCases := []struct {
name string
text string
ruleBody string
alertCount int
expectedTruncated bool
expectedWarnLogs int
}{
{
name: "UnderLimit_TextUntouched",
text: strings.Repeat("short body ", 100),
expectedTruncated: false,
expectedWarnLogs: 0,
},
{
name: "OverLimit_TextTrimmedToFit",
text: strings.Repeat("a very long body line\n\n", 4000),
expectedTruncated: true,
expectedWarnLogs: 1,
},
{
name: "OverLimit_EscapedCharacters_StillFits",
text: strings.Repeat("request to \"checkout\" failed with a timeout after several retries\n", 4000),
expectedTruncated: true,
expectedWarnLogs: 1,
},
{
name: "OverLimit_HTMLCharacters_KeepsFittingPrefix",
text: strings.Repeat("&", 6000),
expectedTruncated: true,
expectedWarnLogs: 1,
},
{
name: "OverLimit_Backslashes_KeepsFittingPrefix",
text: strings.Repeat(`C:\\Users\\x `, 4000),
expectedTruncated: true,
expectedWarnLogs: 1,
},
{
name: "OverLimit_ManyRuleBodies_BlocksDropped",
text: "unused channel text",
ruleBody: "rule body for $alertname",
alertCount: 600,
expectedTruncated: true,
expectedWarnLogs: 1,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
var received []byte
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
received, _ = io.ReadAll(r.Body)
}))
defer srv.Close()
u, err := url.Parse(srv.URL)
require.NoError(t, err)
var logs bytes.Buffer
tmpl := test.CreateTmpl(t)
notifier, err := New(
&config.MSTeamsV2Config{
WebhookURL: &config.SecretURL{URL: u},
HTTPConfig: &commoncfg.HTTPClientConfig{},
Title: "size check",
Text: testCase.text,
},
tmpl,
`{{ template "msteamsv2.default.titleLink" . }}`,
slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelWarn})),
newTestTemplater(tmpl),
)
require.NoError(t, err)
alerts := make([]*types.Alert, 0, max(testCase.alertCount, 1))
for range max(testCase.alertCount, 1) {
alert := &types.Alert{Alert: model.Alert{Labels: model.LabelSet{"alertname": "size"}, StartsAt: time.Now(), EndsAt: time.Now().Add(time.Hour)}}
if testCase.ruleBody != "" {
alert.Annotations = model.LabelSet{ruletypes.AnnotationBodyTemplate: model.LabelValue(testCase.ruleBody)}
}
alerts = append(alerts, alert)
}
_, err = notifier.Notify(notify.WithGroupKey(context.Background(), "1"), alerts...)
require.NoError(t, err)
require.NotEmpty(t, received)
assert.LessOrEqual(t, len(received), maxMessageBytes)
assert.Equal(t, testCase.expectedWarnLogs, strings.Count(logs.String(), "level=WARN"))
var message teamsMessage
require.NoError(t, json.Unmarshal(received, &message))
require.Len(t, message.Attachments, 1)
body := message.Attachments[0].Content.Body
require.NotEmpty(t, body)
assert.Equal(t, "size check", body[0].Text)
if testCase.alertCount > 1 {
assert.Greater(t, len(body), 1)
assert.Less(t, len(body), testCase.alertCount+1)
for _, block := range body {
assert.NotEmpty(t, block.Text)
}
return
}
require.Len(t, body, 2)
assert.NotEmpty(t, body[1].Text)
assert.Equal(t, testCase.expectedTruncated, len(body[1].Text) < len(strings.TrimSpace(testCase.text)))
if testCase.expectedTruncated {
assert.Greater(t, len(received), maxMessageBytes-32)
}
})
}
}
func TestEscapeMarkdown(t *testing.T) {
testCases := []struct {
name string
value string
expected string
}{
{name: "AsteriskPair_Escaped", value: "a*b*c", expected: `a\*b\*c`},
{name: "LinkSyntax_BracketsEscaped", value: "[runbook](https://wiki.test)", expected: `\[runbook\](https://wiki.test)`},
{name: "UnderscoreAtWordEdges_Escaped", value: "_internal_ value", expected: `\_internal\_ value`},
{name: "DoubleUnderscore_AllEscaped", value: "__init__", expected: `\_\_init\_\_`},
{name: "UnderscoreInsideWord_Untouched", value: "k8s_namespace_name", expected: "k8s_namespace_name"},
{name: "UnderscoreAfterSymbol_Escaped", value: "/api/v1/*_bulk", expected: `/api/v1/\*\_bulk`},
{name: "TrailingUnderscore_Escaped", value: "tmp_", expected: `tmp\_`},
{name: "NonASCIIWord_UnderscoreUntouched", value: "größe_wert", expected: "größe_wert"},
{name: "WindowsPath_BackslashesEscaped", value: `C:\Users\x`, expected: `C:\\Users\\x`},
{name: "UNCPath_BackslashesEscaped", value: `\\server\share`, expected: `\\\\server\\share`},
{name: "EscapedAsterisk_BackslashAndAsteriskEscaped", value: `x\*y*`, expected: `x\\\*y\*`},
{name: "BacktickPair_Escaped", value: "run `cmd` now", expected: "run \\`cmd\\` now"},
{name: "TildePair_Escaped", value: "a~b~c", expected: `a\~b\~c`},
{name: "DoubleTildePair_Escaped", value: "a~~b~~c", expected: `a\~\~b\~\~c`},
{name: "LoneTilde_Untouched", value: "https://host.test/~user/logs", expected: "https://host.test/~user/logs"},
{name: "HTMLAndHash_Untouched", value: "<b>tag</b> # not a heading", expected: "<b>tag</b> # not a heading"},
{name: "Empty_Untouched", value: "", expected: ""},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
assert.Equal(t, testCase.expected, escapeMarkdown(testCase.value))
})
}
}
func TestEscapeLabelValues(t *testing.T) {
startsAt := time.Unix(1700000000, 0)
testCases := []struct {
name string
alert *types.Alert
expectedLabels model.LabelSet
expectedAnnotations model.LabelSet
}{
{
name: "MarkdownInLabels_CopyEscaped_OriginalUntouched",
alert: &types.Alert{
Alert: model.Alert{
Labels: model.LabelSet{"alertname": "a*b*c"},
Annotations: model.LabelSet{"summary": "**bold**"},
StartsAt: startsAt,
EndsAt: startsAt.Add(time.Minute),
GeneratorURL: "https://signoz.test/alerts",
},
UpdatedAt: startsAt,
Timeout: true,
},
expectedLabels: model.LabelSet{"alertname": `a\*b\*c`},
expectedAnnotations: model.LabelSet{"summary": "**bold**"},
},
{
name: "PlainLabels_CopyUnchanged_OriginalUntouched",
alert: &types.Alert{Alert: model.Alert{Labels: model.LabelSet{"service": "checkout"}, Annotations: model.LabelSet{}, StartsAt: startsAt}},
expectedLabels: model.LabelSet{"service": "checkout"},
expectedAnnotations: model.LabelSet{},
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
originalLabels := testCase.alert.Labels.Clone()
originalAnnotations := testCase.alert.Annotations.Clone()
escaped := escapeLabelValues([]*types.Alert{testCase.alert})
require.Len(t, escaped, 1)
assert.Equal(t, testCase.expectedLabels, escaped[0].Labels)
assert.Equal(t, testCase.expectedAnnotations, escaped[0].Annotations)
assert.Equal(t, testCase.alert.StartsAt, escaped[0].StartsAt)
assert.Equal(t, testCase.alert.EndsAt, escaped[0].EndsAt)
assert.Equal(t, testCase.alert.GeneratorURL, escaped[0].GeneratorURL)
assert.Equal(t, testCase.alert.UpdatedAt, escaped[0].UpdatedAt)
assert.Equal(t, testCase.alert.Timeout, escaped[0].Timeout)
escaped[0].Annotations["added"] = "x"
escaped[0].Labels["added"] = "x"
assert.Equal(t, originalLabels, testCase.alert.Labels)
assert.Equal(t, originalAnnotations, testCase.alert.Annotations)
})
}
}
func TestPrepareContentEscapesLabelValues(t *testing.T) {
testCases := []struct {
name string
title string
text string
annotations model.LabelSet
expectedTitle string
expectedBody string
}{
{
name: "DefaultTemplates_AlertNameAndDetailsEscaped",
title: `{{ template "msteamsv2.default.title" . }}`,
text: `{{ template "msteamsv2.default.text" . }}`,
expectedTitle: `[FIRING:1] CPU \*high\* \[prod\]`,
expectedBody: "**Alert:** CPU \\*high\\* \\[prod\\] (critical) - firing\n\n**Details:**\n\n- **expr:** rate(a\\[5m\\]) \\* 2\n- **k8s_pod_name:** api_server_1",
},
{
name: "CustomChannelTemplates_LabelValuesEscaped",
title: "Custom: {{ .CommonLabels.alertname }}",
text: "{{ range .Alerts }}expr={{ .Labels.expr }} pod={{ .Labels.k8s_pod_name }}{{ end }}",
expectedTitle: `Custom: CPU \*high\* \[prod\]`,
expectedBody: `expr=rate(a\[5m\]) \* 2 pod=api_server_1`,
},
{
name: "CustomChannelTemplates_GroupLabelValuesEscaped",
title: "Group: {{ .GroupLabels.alertname }}",
text: "{{ .GroupLabels.alertname }} from {{ .GroupLabels.ruleSource }}",
expectedTitle: `Group: CPU \*high\* \[prod\]`,
expectedBody: `CPU \*high\* \[prod\] from https://signoz.test/alerts/overview?ruleId=[x]_`,
},
{
name: "RuleBodyTemplate_LabelValuesEscaped",
title: "Rule: {{ .CommonLabels.alertname }}",
text: "unused channel text",
annotations: model.LabelSet{ruletypes.AnnotationBodyTemplate: "expr is $expr"},
expectedTitle: `Rule: CPU \*high\* \[prod\]`,
expectedBody: `expr is rate(a\[5m\]) \* 2`,
},
{
name: "AnnotationValues_LeftAsWritten",
title: "Annotations: {{ .CommonLabels.severity }}",
text: "{{ range .Alerts }}{{ .Annotations.summary }}{{ end }}",
annotations: model.LabelSet{"summary": "see **the** [runbook](https://wiki.test) for a*b"},
expectedTitle: "Annotations: critical",
expectedBody: "see **the** [runbook](https://wiki.test) for a*b",
},
{
name: "RuleSourceLabel_LeftAsWritten",
title: "Source: {{ .CommonLabels.severity }}",
text: "{{ range .Alerts }}[open]({{ .Labels.ruleSource }}){{ end }}",
expectedTitle: "Source: critical",
expectedBody: "[open](https://signoz.test/alerts/overview?ruleId=[x]_)",
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
tmpl, err := alertmanagertypes.FromGlobs([]string{})
require.NoError(t, err)
tmpl.ExternalURL = &url.URL{Scheme: "http", Host: "signoz.test"}
notifier, err := New(
&config.MSTeamsV2Config{
WebhookURL: &config.SecretURL{URL: testWebhookURL},
HTTPConfig: &commoncfg.HTTPClientConfig{},
Title: testCase.title,
Text: testCase.text,
},
tmpl,
`{{ template "msteamsv2.default.titleLink" . }}`,
promslog.NewNopLogger(),
newTestTemplater(tmpl),
)
require.NoError(t, err)
alerts := []*types.Alert{{
Alert: model.Alert{
Labels: model.LabelSet{
"alertname": "CPU *high* [prod]", "severity": "critical", "expr": "rate(a[5m]) * 2", "k8s_pod_name": "api_server_1",
"ruleSource": "https://signoz.test/alerts/overview?ruleId=[x]_",
},
Annotations: testCase.annotations,
StartsAt: time.Now(),
EndsAt: time.Now().Add(time.Hour),
},
}}
groupLabels := model.LabelSet{"alertname": "CPU *high* [prod]", "ruleSource": "https://signoz.test/alerts/overview?ruleId=[x]_"}
ctx := notify.WithGroupLabels(notify.WithGroupKey(context.Background(), "1"), groupLabels)
blocks, err := notifier.prepareContent(ctx, alerts)
require.NoError(t, err)
require.Len(t, blocks, 2)
assert.Equal(t, testCase.expectedTitle, blocks[0].Text)
assert.Equal(t, testCase.expectedBody, blocks[1].Text)
assert.Equal(t, model.LabelValue("CPU *high* [prod]"), groupLabels["alertname"])
assert.Equal(t, model.LabelValue("CPU *high* [prod]"), alerts[0].Labels["alertname"])
assert.Equal(t, model.LabelValue("rate(a[5m]) * 2"), alerts[0].Labels["expr"])
})
}
}

View File

@@ -278,6 +278,7 @@ func NewSQLMigrationProviderFactories(
sqlmigration.NewMigrateRelatedLinksTemplateFactory(),
sqlmigration.NewAddOrganizationTuplesFactory(sqlstore),
sqlmigration.NewAddOrgPreferenceTuplesFactory(sqlstore),
sqlmigration.NewMigrateMSTeamsDefaultTemplatesFactory(),
)
}

View File

@@ -0,0 +1,698 @@
package sqlmigration
import (
"context"
"crypto/md5"
"encoding/json"
"fmt"
"log/slog"
"regexp"
"slices"
"strings"
"text/template/parse"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/factory"
"github.com/uptrace/bun"
"github.com/uptrace/bun/migrate"
)
const (
msteamsConfigsKey = "msteamsv2_configs"
msteamsTitleField = "title"
msteamsTextField = "text"
msteamsDefaultTitle = `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }}`
msteamsDefaultText = `{{ range .Alerts -}}
**Alert:** {{ .Labels.alertname }}{{ if .Labels.severity }} ({{ .Labels.severity }}){{ end }} - {{ .Status }}
{{ if .Annotations.summary }}**Summary:** {{ .Annotations.summary }}
{{ end }}{{ if .Annotations.description }}**Description:** {{ .Annotations.description }}
{{ end }}{{ template "signoz.relatedLinks.markdown" . }}{{ with (.Labels.Remove (stringSlice "alertname" "severity" "ruleId" "ruleSource")).SortedPairs }}**Details:**
{{ range . }}- **{{ .Name }}:** {{ .Value }}
{{ end }}
{{ end }}{{ end }}`
msteamsSlackSeedTitle = `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }} for {{ .CommonLabels.job }}
{{- if gt (len .CommonLabels) (len .GroupLabels) -}}
{{" "}}(
{{- with .CommonLabels.Remove .GroupLabels.Names }}
{{- range $index, $label := .SortedPairs -}}
{{ if $index }}, {{ end }}
{{- $label.Name }}="{{ $label.Value -}}"
{{- end }}
{{- end -}}
)
{{- end }}`
msteamsSlackRelatedLinksName = `"signoz.relatedLinks.slack"`
msteamsMarkdownRelatedLinksName = `"signoz.relatedLinks.markdown"`
msteamsMaskOpen = ""
msteamsMaskClose = ""
// A description counts as derived from the Slack seed once it still bolds this many of the seed's labels the Slack way.
msteamsSlackSeedLabelThreshold = 2
)
const (
msteamsTemplateUnchanged msteamsTemplateOutcome = iota
msteamsTemplateReplaced
msteamsTemplateConverted
msteamsTemplateCustom
)
var (
// Every description the channel form prefilled for Microsoft Teams; they differ only in the related links lines.
msteamsSlackSeedTexts = []string{
`{{ range .Alerts -}}
*Alert:* {{ .Labels.alertname }}{{ if .Labels.severity }} - {{ .Labels.severity }}{{ end }}
*Summary:* {{ .Annotations.summary }}
*Description:* {{ .Annotations.description }}
*Details:*
{{ range .Labels.SortedPairs }} • *{{ .Name }}:* {{ .Value }}
{{ end }}
{{ end }}`,
`{{ range .Alerts -}}
*Alert:* {{ .Labels.alertname }}{{ if .Labels.severity }} - {{ .Labels.severity }}{{ end }}
*Summary:* {{ .Annotations.summary }}
*Description:* {{ .Annotations.description }}
*RelatedLogs:* {{ .Annotations.related_logs }}
*RelatedTraces:* {{ .Annotations.related_traces }}
*Details:*
{{ range .Labels.SortedPairs }} • *{{ .Name }}:* {{ .Value }}
{{ end }}
{{ end }}`,
`{{ range .Alerts -}}
*Alert:* {{ .Labels.alertname }}{{ if .Labels.severity }} - {{ .Labels.severity }}{{ end }}
*Summary:* {{ .Annotations.summary }}
*Description:* {{ .Annotations.description }}
*RelatedLogs:* {{ if gt (len .Annotations.related_logs) 0 -}} View in <{{ .Annotations.related_logs }}|logs explorer> {{- end}}
*RelatedTraces:* {{ if gt (len .Annotations.related_traces) 0 -}} View in <{{ .Annotations.related_traces }}|traces explorer> {{- end}}
*Details:*
{{ range .Labels.SortedPairs }} • *{{ .Name }}:* {{ .Value }}
{{ end }}
{{ end }}`,
`{{ range .Alerts -}}
*Alert:* {{ .Labels.alertname }}{{ if .Labels.severity }} - {{ .Labels.severity }}{{ end }}
*Summary:* {{ .Annotations.summary }}
*Description:* {{ .Annotations.description }}
{{ template "signoz.relatedLinks.slack" . }}
*Details:*
{{ range .Labels.SortedPairs }} • *{{ .Name }}:* {{ .Value }}
{{ end }}
{{ end }}`,
}
msteamsSlackSeedLabels = []string{"Alert:", "Summary:", "Description:", "Details:"}
msteamsControlKeywords = []string{"if", "else", "end", "range", "with", "define", "block", "break", "continue"}
msteamsActionPattern = regexp.MustCompile(`(?s)\{\{.*?\}\}`)
msteamsMaskPattern = regexp.MustCompile(msteamsMaskOpen + `(\d+)` + msteamsMaskClose)
msteamsSlackBoldPattern = regexp.MustCompile(`\*([^\s*][^*\n]*)\*`)
msteamsSlackLinkPattern = regexp.MustCompile(`<([^<>|\s]+)\|([^<>\n]+)>`)
msteamsSlackBulletPattern = regexp.MustCompile(`[ \t]*•[ \t]*`)
msteamsIndentPattern = regexp.MustCompile(`(?m)^[ \t]+`)
)
type msteamsTemplateOutcome int
type migrateMSTeamsDefaultTemplates struct {
logger *slog.Logger
}
type msteamsConfigRow struct {
bun.BaseModel `bun:"table:alertmanager_config"`
ID string `bun:"id"`
OrgID string `bun:"org_id"`
Config string `bun:"config"`
}
type msteamsChannelRow struct {
bun.BaseModel `bun:"table:notification_channel"`
ID string `bun:"id"`
OrgID string `bun:"org_id"`
Data string `bun:"data"`
Spec string `bun:"spec,nullzero"`
}
type msteamsMigrationCounts struct {
replaced int
converted int
custom int
failed int
}
func NewMigrateMSTeamsDefaultTemplatesFactory() factory.ProviderFactory[SQLMigration, Config] {
return factory.NewProviderFactory(
factory.MustNewName("migrate_msteams_templates"),
func(ctx context.Context, ps factory.ProviderSettings, c Config) (SQLMigration, error) {
return &migrateMSTeamsDefaultTemplates{logger: ps.Logger}, nil
},
)
}
func (migration *migrateMSTeamsDefaultTemplates) Register(migrations *migrate.Migrations) error {
return migrations.Register(migration.Up, migration.Down)
}
func (migration *migrateMSTeamsDefaultTemplates) Up(ctx context.Context, db *bun.DB) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer func() {
_ = tx.Rollback()
}()
if err := migration.migrateConfigs(ctx, tx); err != nil {
return err
}
if err := migration.migrateChannels(ctx, tx); err != nil {
return err
}
return tx.Commit()
}
func (migration *migrateMSTeamsDefaultTemplates) Down(context.Context, *bun.DB) error {
return nil
}
func (migration *migrateMSTeamsDefaultTemplates) migrateConfigs(ctx context.Context, tx bun.Tx) error {
rows := make([]*msteamsConfigRow, 0)
if err := tx.NewSelect().Model(&rows).Scan(ctx); err != nil {
return err
}
counts := msteamsMigrationCounts{}
for _, row := range rows {
cfg := make(map[string]json.RawMessage)
if err := json.Unmarshal([]byte(row.Config), &cfg); err != nil {
migration.logger.WarnContext(ctx, "skipping alertmanager config with unreadable config", slog.String("config_id", row.ID), errors.Attr(err))
counts.failed++
continue
}
receiversRaw, ok := cfg["receivers"]
if !ok || string(receiversRaw) == "null" {
continue
}
receivers := make([]map[string]json.RawMessage, 0)
if err := json.Unmarshal(receiversRaw, &receivers); err != nil {
migration.logger.WarnContext(ctx, "skipping alertmanager config with unreadable receivers", slog.String("config_id", row.ID), errors.Attr(err))
counts.failed++
continue
}
changed := false
for _, receiver := range receivers {
var receiverName string
_ = json.Unmarshal(receiver["name"], &receiverName)
outcomes, receiverChanged, err := migrateMSTeamsReceiver(receiver)
if err != nil {
migration.logger.WarnContext(ctx, "leaving msteams receiver templates as is", slog.String("config_id", row.ID), slog.String("org_id", row.OrgID), slog.String("receiver", receiverName), errors.Attr(err))
counts.failed++
continue
}
for field, outcome := range outcomes {
if counts.add(outcome) {
migration.logger.InfoContext(ctx, "migrated msteams receiver template", slog.String("config_id", row.ID), slog.String("org_id", row.OrgID), slog.String("receiver", receiverName), slog.String("field", field), slog.String("outcome", outcome.String()))
}
}
changed = changed || receiverChanged
}
if !changed {
continue
}
newReceivers, err := json.Marshal(receivers)
if err != nil {
return err
}
cfg["receivers"] = newReceivers
newConfig, err := json.Marshal(cfg)
if err != nil {
return err
}
if _, err := tx.NewUpdate().
Model((*msteamsConfigRow)(nil)).
Set("config = ?", string(newConfig)).
Set("hash = ?", fmt.Sprintf("%x", md5.Sum(newConfig))).
Where("id = ?", row.ID).
Exec(ctx); err != nil {
return err
}
}
migration.logger.InfoContext(ctx, "migrated msteams templates on alertmanager configs", slog.Int("total", len(rows)), slog.Int("replaced", counts.replaced), slog.Int("converted", counts.converted), slog.Int("custom", counts.custom), slog.Int("failed", counts.failed))
return nil
}
func (migration *migrateMSTeamsDefaultTemplates) migrateChannels(ctx context.Context, tx bun.Tx) error {
rows := make([]*msteamsChannelRow, 0)
if err := tx.NewSelect().Model(&rows).Where("type = ?", "msteams").Scan(ctx); err != nil {
return err
}
counts := msteamsMigrationCounts{}
for _, row := range rows {
query := tx.NewUpdate().Model((*msteamsChannelRow)(nil)).Where("id = ?", row.ID)
receiver := make(map[string]json.RawMessage)
if err := json.Unmarshal([]byte(row.Data), &receiver); err != nil {
migration.logger.WarnContext(ctx, "skipping notification channel with unreadable data", slog.String("org_id", row.OrgID), slog.String("channel_id", row.ID), errors.Attr(err))
counts.failed++
continue
}
outcomes, changed, err := migrateMSTeamsReceiver(receiver)
if err != nil {
migration.logger.WarnContext(ctx, "leaving notification channel templates as is", slog.String("org_id", row.OrgID), slog.String("channel_id", row.ID), errors.Attr(err))
counts.failed++
continue
}
for field, outcome := range outcomes {
if counts.add(outcome) {
migration.logger.InfoContext(ctx, "migrated msteams notification channel template", slog.String("org_id", row.OrgID), slog.String("channel_id", row.ID), slog.String("field", field), slog.String("outcome", outcome.String()))
}
}
if changed {
newData, err := json.Marshal(receiver)
if err != nil {
return err
}
query = query.Set("data = ?", string(newData))
}
if row.Spec != "" {
spec := make(map[string]json.RawMessage)
if err := json.Unmarshal([]byte(row.Spec), &spec); err != nil {
migration.logger.WarnContext(ctx, "skipping notification channel spec with unreadable json", slog.String("org_id", row.OrgID), slog.String("channel_id", row.ID), errors.Attr(err))
} else {
specOutcomes, err := migrateMSTeamsFields(spec)
if err != nil {
migration.logger.WarnContext(ctx, "leaving notification channel spec templates as is", slog.String("org_id", row.OrgID), slog.String("channel_id", row.ID), errors.Attr(err))
}
specChanged := false
for _, outcome := range specOutcomes {
specChanged = specChanged || outcome.rewrites()
}
if err == nil && specChanged {
newSpec, err := json.Marshal(spec)
if err != nil {
return err
}
query = query.Set("spec = ?", string(newSpec))
changed = true
}
}
}
if !changed {
continue
}
if _, err := query.Exec(ctx); err != nil {
return err
}
}
migration.logger.InfoContext(ctx, "migrated msteams templates on notification channels", slog.Int("total", len(rows)), slog.Int("replaced", counts.replaced), slog.Int("converted", counts.converted), slog.Int("custom", counts.custom), slog.Int("failed", counts.failed))
return nil
}
func (outcome msteamsTemplateOutcome) String() string {
switch outcome {
case msteamsTemplateReplaced:
return "replaced"
case msteamsTemplateConverted:
return "converted"
case msteamsTemplateCustom:
return "custom"
default:
return "unchanged"
}
}
func (outcome msteamsTemplateOutcome) rewrites() bool {
return outcome == msteamsTemplateReplaced || outcome == msteamsTemplateConverted
}
// add reports whether the outcome is worth a log line of its own.
func (counts *msteamsMigrationCounts) add(outcome msteamsTemplateOutcome) bool {
switch outcome {
case msteamsTemplateReplaced:
counts.replaced++
case msteamsTemplateConverted:
counts.converted++
case msteamsTemplateCustom:
counts.custom++
default:
return false
}
return true
}
// migrateMSTeamsReceiver reports the outcome of the receiver's first msteams notifier, the only one a channel carries, and whether any notifier was rewritten.
func migrateMSTeamsReceiver(receiver map[string]json.RawMessage) (map[string]msteamsTemplateOutcome, bool, error) {
configsRaw, ok := receiver[msteamsConfigsKey]
outcomes := make(map[string]msteamsTemplateOutcome)
if !ok || string(configsRaw) == "null" {
return outcomes, false, nil
}
configs := make([]map[string]json.RawMessage, 0)
if err := json.Unmarshal(configsRaw, &configs); err != nil {
return nil, false, err
}
changed := false
for i, config := range configs {
configOutcomes, err := migrateMSTeamsFields(config)
if err != nil {
return nil, false, err
}
if i == 0 {
outcomes = configOutcomes
}
for _, outcome := range configOutcomes {
changed = changed || outcome.rewrites()
}
}
if !changed {
return outcomes, false, nil
}
newConfigs, err := json.Marshal(configs)
if err != nil {
return nil, false, err
}
receiver[msteamsConfigsKey] = newConfigs
return outcomes, true, nil
}
func migrateMSTeamsFields(object map[string]json.RawMessage) (map[string]msteamsTemplateOutcome, error) {
outcomes := make(map[string]msteamsTemplateOutcome, 2)
for _, field := range []string{msteamsTitleField, msteamsTextField} {
raw, ok := object[field]
if !ok || string(raw) == "null" {
continue
}
var tmpl string
if err := json.Unmarshal(raw, &tmpl); err != nil {
return nil, err
}
var (
migrated string
outcome msteamsTemplateOutcome
err error
)
if field == msteamsTitleField {
migrated, outcome, err = migrateMSTeamsTitle(tmpl)
} else {
migrated, outcome, err = migrateMSTeamsText(tmpl)
}
if err != nil {
return nil, err
}
outcomes[field] = outcome
if !outcome.rewrites() {
continue
}
newRaw, err := json.Marshal(migrated)
if err != nil {
return nil, err
}
object[field] = newRaw
}
return outcomes, nil
}
func migrateMSTeamsTitle(title string) (string, msteamsTemplateOutcome, error) {
if isMSTeamsDefaultOrEmpty(title, msteamsDefaultTitle) {
return title, msteamsTemplateUnchanged, nil
}
matches, err := matchesAnyMSTeamsTemplate(title, []string{msteamsSlackSeedTitle})
if err != nil {
return title, msteamsTemplateUnchanged, err
}
if matches {
return msteamsDefaultTitle, msteamsTemplateReplaced, nil
}
return title, msteamsTemplateCustom, nil
}
func migrateMSTeamsText(text string) (string, msteamsTemplateOutcome, error) {
if isMSTeamsDefaultOrEmpty(text, msteamsDefaultText) {
return text, msteamsTemplateUnchanged, nil
}
matches, err := matchesAnyMSTeamsTemplate(text, msteamsSlackSeedTexts)
if err != nil {
return text, msteamsTemplateUnchanged, err
}
if matches {
return msteamsDefaultText, msteamsTemplateReplaced, nil
}
// Text already holding a placeholder character cannot be masked safely.
if strings.Contains(text, msteamsMaskOpen) || strings.Contains(text, msteamsMaskClose) || !isMSTeamsSlackSeedDerived(text) {
return text, msteamsTemplateCustom, nil
}
converted := convertMSTeamsSlackSeed(text)
if _, err := normalizeMSTeamsTemplate(converted); err != nil {
return text, msteamsTemplateUnchanged, err
}
return converted, msteamsTemplateConverted, nil
}
// isMSTeamsDefaultOrEmpty covers what needs no migration: nothing stored, an upstream marker or the new default itself.
func isMSTeamsDefaultOrEmpty(tmpl string, newDefault string) bool {
trimmed := strings.TrimSpace(tmpl)
return trimmed == "" || trimmed == newDefault || strings.HasPrefix(trimmed, `{{ template "msteamsv2.default.`) || strings.HasPrefix(trimmed, `{{ template "msteams.default.`)
}
func matchesAnyMSTeamsTemplate(tmpl string, shipped []string) (bool, error) {
normalized, err := normalizeMSTeamsTemplate(tmpl)
if err != nil {
return false, err
}
for _, candidate := range shipped {
normalizedCandidate, err := normalizeMSTeamsTemplate(candidate)
if err != nil {
return false, err
}
if normalized == normalizedCandidate {
return true, nil
}
}
return false, nil
}
func isMSTeamsSlackSeedDerived(text string) bool {
masked, _ := maskMSTeamsActions(text)
found := 0
for _, match := range findMSTeamsSlackBold(masked) {
if slices.Contains(msteamsSlackSeedLabels, masked[match[2]:match[3]]) {
found++
}
}
return found >= msteamsSlackSeedLabelThreshold
}
// convertMSTeamsSlackSeed rewrites Slack mrkdwn into the markdown a Teams card renders, leaving every {{ }} action as written.
func convertMSTeamsSlackSeed(text string) string {
text = strings.ReplaceAll(text, msteamsSlackRelatedLinksName, msteamsMarkdownRelatedLinksName)
text = strings.ReplaceAll(text, "\r\n", "\n")
masked, actions := maskMSTeamsActions(text)
var bolded strings.Builder
last := 0
for _, match := range findMSTeamsSlackBold(masked) {
bolded.WriteString(masked[last:match[0]])
fmt.Fprintf(&bolded, "**%s**", masked[match[2]:match[3]])
last = match[1]
}
bolded.WriteString(masked[last:])
masked = bolded.String()
masked = msteamsSlackLinkPattern.ReplaceAllString(masked, "[$2]($1)")
masked = msteamsSlackBulletPattern.ReplaceAllString(masked, "- ")
masked = msteamsIndentPattern.ReplaceAllString(masked, "")
masked = separateMSTeamsParagraphs(masked, actions)
return msteamsMaskPattern.ReplaceAllStringFunc(masked, func(mask string) string {
var index int
_, _ = fmt.Sscanf(strings.TrimSuffix(strings.TrimPrefix(mask, msteamsMaskOpen), msteamsMaskClose), "%d", &index)
return actions[index]
})
}
// maskMSTeamsActions swaps each {{ }} action for a placeholder so text rules can span them, as in *{{ .Name }}:*.
func maskMSTeamsActions(text string) (string, []string) {
actions := make([]string, 0)
masked := msteamsActionPattern.ReplaceAllStringFunc(text, func(action string) string {
actions = append(actions, action)
return fmt.Sprintf("%s%d%s", msteamsMaskOpen, len(actions)-1, msteamsMaskClose)
})
return masked, actions
}
// findMSTeamsSlackBold returns the *bold* spans that are not already part of a **bold** one.
func findMSTeamsSlackBold(masked string) [][]int {
matches := make([][]int, 0)
for _, match := range msteamsSlackBoldPattern.FindAllStringSubmatchIndex(masked, -1) {
if match[0] > 0 && masked[match[0]-1] == '*' {
continue
}
if match[1] < len(masked) && masked[match[1]] == '*' {
continue
}
if strings.TrimRight(masked[match[2]:match[3]], " \t") != masked[match[2]:match[3]] {
continue
}
matches = append(matches, match)
}
return matches
}
// separateMSTeamsParagraphs puts a blank line between adjacent lines of content, which Teams needs outside a list.
func separateMSTeamsParagraphs(masked string, actions []string) string {
lines := strings.Split(masked, "\n")
separated := make([]string, 0, len(lines))
for i, line := range lines {
separated = append(separated, line)
if i == len(lines)-1 {
continue
}
content, list := classifyMSTeamsLine(line, actions)
nextContent, nextList := classifyMSTeamsLine(lines[i+1], actions)
if content && nextContent && (!list || !nextList) {
separated = append(separated, "")
}
}
return strings.Join(separated, "\n")
}
// classifyMSTeamsLine reports whether a line renders any text and whether that text is a list item.
func classifyMSTeamsLine(line string, actions []string) (bool, bool) {
rendered := msteamsMaskPattern.ReplaceAllStringFunc(line, func(mask string) string {
var index int
_, _ = fmt.Sscanf(strings.TrimSuffix(strings.TrimPrefix(mask, msteamsMaskOpen), msteamsMaskClose), "%d", &index)
if isMSTeamsControlAction(actions[index]) {
return ""
}
return mask
})
rendered = strings.TrimSpace(rendered)
return rendered != "", strings.HasPrefix(rendered, "- ")
}
func isMSTeamsControlAction(action string) bool {
inner := strings.TrimSpace(strings.Trim(strings.TrimSuffix(strings.TrimPrefix(action, "{{"), "}}"), "-"))
if strings.HasPrefix(inner, "/*") {
return true
}
keyword, _, _ := strings.Cut(inner, " ")
return slices.Contains(msteamsControlKeywords, keyword)
}
// normalizeMSTeamsTemplate re-emits a parsed template with whitespace collapsed, so two templates that differ only in spacing compare equal.
func normalizeMSTeamsTemplate(tmpl string) (string, error) {
tree := parse.New("msteams")
tree.Mode = parse.SkipFuncCheck
parsed, err := tree.Parse(tmpl, "{{", "}}", map[string]*parse.Tree{})
if err != nil {
return "", err
}
var builder strings.Builder
writeNormalizedMSTeamsNode(&builder, parsed.Root)
return builder.String(), nil
}
func writeNormalizedMSTeamsNode(builder *strings.Builder, node parse.Node) {
switch node := node.(type) {
case *parse.ListNode:
if node == nil {
return
}
for _, child := range node.Nodes {
writeNormalizedMSTeamsNode(builder, child)
}
case *parse.TextNode:
builder.WriteString(strings.Join(strings.Fields(string(node.Text)), " "))
builder.WriteString("|")
case *parse.IfNode:
writeNormalizedMSTeamsBranch(builder, "if", &node.BranchNode)
case *parse.RangeNode:
writeNormalizedMSTeamsBranch(builder, "range", &node.BranchNode)
case *parse.WithNode:
writeNormalizedMSTeamsBranch(builder, "with", &node.BranchNode)
default:
builder.WriteString(node.String())
}
}
func writeNormalizedMSTeamsBranch(builder *strings.Builder, keyword string, branch *parse.BranchNode) {
fmt.Fprintf(builder, "{{%s %s}}", keyword, branch.Pipe.String())
writeNormalizedMSTeamsNode(builder, branch.List)
if branch.ElseList != nil {
builder.WriteString("{{else}}")
writeNormalizedMSTeamsNode(builder, branch.ElseList)
}
builder.WriteString("{{end}}")
}

View File

@@ -6,11 +6,29 @@ import (
"github.com/prometheus/alertmanager/config"
)
// The text is markdown, which a Teams Adaptive Card TextBlock renders as is.
const (
DefaultMSTeamsTitleTemplate = `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }}`
DefaultMSTeamsTextTemplate = `{{ range .Alerts -}}
**Alert:** {{ .Labels.alertname }}{{ if .Labels.severity }} ({{ .Labels.severity }}){{ end }} - {{ .Status }}
{{ if .Annotations.summary }}**Summary:** {{ .Annotations.summary }}
{{ end }}{{ if .Annotations.description }}**Description:** {{ .Annotations.description }}
{{ end }}{{ template "signoz.relatedLinks.markdown" . }}{{ with (.Labels.Remove (stringSlice "alertname" "severity" "ruleId" "ruleSource")).SortedPairs }}**Details:**
{{ range . }}- **{{ .Name }}:** {{ .Value }}
{{ end }}
{{ end }}{{ end }}`
)
type ChannelMSTeamsConfig struct {
SendResolved *bool `json:"sendResolved,omitempty" description:"Also notify when the alert resolves. Defaults to true."`
WebhookURL string `json:"webhookUrl" required:"true" format:"password" description:"The Teams incoming webhook URL. A secret; returned by create, update and fetch by ID, never by list."`
Title valuer.UnsetOrNonEmptyString `json:"title,omitzero" description:"Alertmanager template for the card title; defaults to the Alertmanager Teams default."`
Text valuer.UnsetOrNonEmptyString `json:"text,omitzero" description:"Alertmanager template for the card body; defaults to the Alertmanager Teams default."`
Title valuer.UnsetOrNonEmptyString `json:"title,omitzero" description:"Alertmanager template for the card title; defaults to the SigNoz Teams default."`
Text valuer.UnsetOrNonEmptyString `json:"text,omitzero" description:"Alertmanager template for the card body, rendered as Teams markdown; defaults to the SigNoz Teams default."`
}
func (c *ChannelMSTeamsConfig) UnmarshalJSON(data []byte) error {

View File

@@ -2,6 +2,7 @@ package alertmanagertypes
import (
"bytes"
"fmt"
"net/url"
tmplhtml "html/template"
@@ -42,17 +43,19 @@ func FromGlobs(paths []string) (*alertmanagertemplate.Template, error) {
return nil, err
}
if err := t.Parse(bytes.NewReader([]byte(`
if err := t.Parse(bytes.NewReader([]byte(fmt.Sprintf(`
{{ define "__ruleIdPath" }}{{- $isTestAlert := "" -}}{{- range .CommonLabels.SortedPairs -}}{{- if eq .Name "testalert" -}}{{- if eq .Value "true" -}}{{- $isTestAlert = "true" -}}{{- end -}}{{- end -}}{{- end -}}{{- range .CommonLabels.SortedPairs -}}{{- if eq .Name "ruleId" -}}{{- if ne .Value "" -}}/edit?ruleId={{ .Value | urlescape }}{{- if $isTestAlert -}}&isTestAlert=true{{- end -}}{{- end -}}{{- end -}}{{- end -}}{{- end }}
{{ define "__alertmanagerURL" }}{{ .ExternalURL }}/alerts{{ template "__ruleIdPath" . }}{{ end }}
{{ define "msteamsv2.default.titleLink" }}{{ template "__alertmanagerURL" . }}{{ end }}
{{ define "msteamsv2.default.title" }}%s{{ end }}
{{ define "msteamsv2.default.text" }}%s{{ end }}
{{ define "signoz.relatedLinks.slack" }}{{ range $i, $link := relatedLinks . }}{{ if $i }} · {{ end }}<{{ $link.URL }}|{{ $link.Label }}>{{ end }}{{ end }}
{{ define "signoz.relatedLinks.markdown" }}{{ range relatedLinks . }}[{{ .Label }}]({{ .URL }})
{{ end }}{{ end }}
{{ define "signoz.relatedLinks.html" }}{{ range relatedLinks . }}<a href="{{ .URL | html }}">{{ .Label | html }}</a>
{{ end }}{{ end }}
`))); err != nil {
`, DefaultMSTeamsTitleTemplate, DefaultMSTeamsTextTemplate)))); err != nil {
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error parsing alertmanager templates")
}

View File

@@ -314,3 +314,84 @@ func TestFromGlobsRelatedLinksHTML(t *testing.T) {
}
}
}
func TestFromGlobsMSTeamsDefaults(t *testing.T) {
tmpl, err := FromGlobs([]string{})
require.NoError(t, err)
tmpl.ExternalURL = &url.URL{Scheme: "http", Host: "localhost:8080"}
firing := time.Now().Add(time.Hour)
resolved := time.Now().Add(-time.Minute)
testCases := []struct {
name string
template string
alerts []*types.Alert
expected string
}{
{
name: "Title_Firing_CountAndAlertName",
template: `{{ template "msteamsv2.default.title" . }}`,
alerts: []*types.Alert{
{Alert: model.Alert{Labels: model.LabelSet{"alertname": "High CPU"}, EndsAt: firing}},
},
expected: "[FIRING:1] High CPU",
},
{
name: "Title_Resolved_NoCount",
template: `{{ template "msteamsv2.default.title" . }}`,
alerts: []*types.Alert{
{Alert: model.Alert{Labels: model.LabelSet{"alertname": "Disk Full"}, EndsAt: resolved}},
},
expected: "[RESOLVED] Disk Full",
},
{
name: "Text_AllFields_HidesRuleLabels",
template: `{{ template "msteamsv2.default.text" . }}`,
alerts: []*types.Alert{
{Alert: model.Alert{
Labels: model.LabelSet{
"alertname": "Error Rate", "severity": "critical", "ruleId": "0199051c-f374-71f7-a340-ec79ad81e70f",
"ruleSource": "http://localhost:8080/alerts/overview?ruleId=0199051c", "service.name": "checkout",
},
Annotations: model.LabelSet{
"summary": "errors are up", "description": "error rate crossed 5%",
"related_logs": "https://signoz.io/logs/logs-explorer?f=6", "related_traces": "https://signoz.io/traces-explorer?f=6",
},
EndsAt: firing,
}},
},
expected: "**Alert:** Error Rate (critical) - firing\n\n**Summary:** errors are up\n\n**Description:** error rate crossed 5%\n\n" +
"[View Related Logs](https://signoz.io/logs/logs-explorer?f=6)\n\n[View Related Traces](https://signoz.io/traces-explorer?f=6)\n\n" +
"**Details:**\n\n- **service.name:** checkout\n\n",
},
{
name: "Text_NoAnnotationsNoExtraLabels_AlertLineOnly",
template: `{{ template "msteamsv2.default.text" . }}`,
alerts: []*types.Alert{
{Alert: model.Alert{Labels: model.LabelSet{"alertname": "Queue Lag", "ruleId": "01a10b3d-e55d-75e3-aa44-8d73f1d969d7"}, EndsAt: resolved}},
},
expected: "**Alert:** Queue Lag - resolved\n\n",
},
{
name: "Text_TwoAlerts_OneBlockEach",
template: `{{ template "msteamsv2.default.text" . }}`,
alerts: []*types.Alert{
{Alert: model.Alert{Labels: model.LabelSet{"alertname": "Pod Restarts", "pod": "api-1"}, EndsAt: firing}},
{Alert: model.Alert{Labels: model.LabelSet{"alertname": "Pod Restarts", "pod": "api-2"}, EndsAt: resolved}},
},
expected: "**Alert:** Pod Restarts - firing\n\n**Details:**\n\n- **pod:** api-1\n\n" +
"**Alert:** Pod Restarts - resolved\n\n**Details:**\n\n- **pod:** api-2\n\n",
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
data := tmpl.Data("__receiver", model.LabelSet{}, testCase.alerts...)
got, err := tmpl.ExecuteTextString(testCase.template, data)
require.NoError(t, err)
assert.Equal(t, testCase.expected, got)
})
}
}

View File

@@ -110,8 +110,16 @@ msteams_default_config = {
"msteamsv2_configs": [
{
"webhook_url": "msteams/webhook_url", # base_url configured on runtime
"title": '[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }} for {{ .CommonLabels.job }}\n {{- if gt (len .CommonLabels) (len .GroupLabels) -}}\n {{" "}}(\n {{- with .CommonLabels.Remove .GroupLabels.Names }}\n {{- range $index, $label := .SortedPairs -}}\n {{ if $index }}, {{ end }}\n {{- $label.Name }}="{{ $label.Value -}}"\n {{- end }}\n {{- end -}}\n )\n {{- end }}',
"text": '{{ range .Alerts -}}\r\n *Alert:* {{ .Labels.alertname }}{{ if .Labels.severity }} - {{ .Labels.severity }}{{ end }}\r\n\r\n *Summary:* {{ .Annotations.summary }}\r\n *Description:* {{ .Annotations.description }}\r\n {{ template "signoz.relatedLinks.slack" . }}\r\n\r\n *Details:*\r\n {{ range .Labels.SortedPairs -}}\r\n {{- if ne .Name "ruleId" -}}\r\n \u2022 *{{ .Name }}:* {{ .Value }}\r\n {{ end -}}\r\n {{ end -}}\r\n{{ end }}',
}
],
}
msteams_custom_text_config = {
"msteamsv2_configs": [
{
"webhook_url": "msteams/custom_text_webhook_url", # base_url configured on runtime
"title": "Teams custom title: {{ .CommonLabels.alertname }}",
"text": "Teams custom description for {{ range .Alerts }}{{ .Labels.alertname }} ({{ .Labels.severity }}){{ end }}",
}
],
}

View File

@@ -0,0 +1,58 @@
{
"alert": "rule_body_template",
"ruleType": "threshold_rule",
"alertType": "METRIC_BASED_ALERT",
"condition": {
"thresholds": {
"kind": "basic",
"spec": [
{
"name": "critical",
"target": 10,
"matchType": "at_least_once",
"op": "above",
"channels": [
"test channel"
]
}
]
},
"compositeQuery": {
"queryType": "clickhouse_sql",
"panelType": "graph",
"queries": [
{
"type": "clickhouse_sql",
"spec": {
"name": "A",
"query": "WITH __temporal_aggregation_cte AS (\n SELECT \n fingerprint, \n toStartOfInterval(toDateTime(intDiv(unix_milli, 1000)), toIntervalSecond(60)) AS ts, \n avg(value) AS per_series_value \n FROM signoz_metrics.distributed_samples_v4 AS points \n INNER JOIN (\n SELECT fingerprint \n FROM signoz_metrics.time_series_v4 \n WHERE metric_name IN ('request_total_threshold_above_at_least_once') \n AND LOWER(temporality) LIKE LOWER('cumulative') \n GROUP BY fingerprint\n ) AS filtered_time_series ON points.fingerprint = filtered_time_series.fingerprint \n WHERE metric_name IN ('request_total_threshold_above_at_least_once') \n AND unix_milli >= $start_timestamp_ms \n AND unix_milli < $end_timestamp_ms \n GROUP BY fingerprint, ts \n ORDER BY fingerprint, ts\n), \n__spatial_aggregation_cte AS (\n SELECT \n ts, \n sum(per_series_value) AS value \n FROM __temporal_aggregation_cte \n WHERE isNaN(per_series_value) = 0 \n GROUP BY ts\n) \nSELECT * FROM __spatial_aggregation_cte \nORDER BY ts"
}
}
]
},
"selectedQueryName": "A"
},
"evaluation": {
"kind": "rolling",
"spec": {
"evalWindow": "5m0s",
"frequency": "15s"
}
},
"labels": {},
"annotations": {
"description": "This alert is fired when the defined metric (current value: {{$value}}) crosses the threshold ({{$threshold}})",
"summary": "This alert is fired when the defined metric (current value: {{$value}}) crosses the threshold ({{$threshold}})",
"_body_template": "Rule body for $alertname at severity $severity"
},
"notificationSettings": {
"groupBy": [],
"usePolicy": false,
"renotify": {
"enabled": false,
"interval": "30m",
"alertStates": []
}
},
"schemaVersion": "v2alpha1"
}

View File

@@ -19,6 +19,7 @@ from fixtures.logger import setup_logger
from fixtures.maildev import delete_all_mails
from fixtures.notification_channel import (
email_default_config,
msteams_custom_text_config,
msteams_default_config,
opsgenie_default_config,
pagerduty_default_config,
@@ -92,7 +93,7 @@ NOTIFIERS_TEST = [
"body": [
{
"type": "TextBlock",
"text": "Alerts",
"text": "[FIRING:1] threshold_above_at_least_once",
"weight": "Bolder",
"size": "Medium",
"wrap": True,
@@ -100,35 +101,13 @@ NOTIFIERS_TEST = [
},
{
"type": "TextBlock",
"text": "Labels",
"weight": "Bolder",
"size": "Medium",
},
{
"type": "FactSet",
"text": "",
"facts": [
{
"title": "threshold.name",
"value": "critical",
}
],
},
{
"type": "TextBlock",
"text": "Annotations",
"weight": "Bolder",
"size": "Medium",
},
{
"type": "FactSet",
"text": "",
"facts": [
{
"title": "description",
"value": "This alert is fired when the defined metric (current value: 15) crosses the threshold (10)",
},
],
"text": re.compile(
r"^\*\*Alert:\*\* threshold_above_at_least_once \(critical\) - firing\n\n"
r"\*\*Summary:\*\* This alert is fired when the defined metric \(current value: 15\) crosses the threshold \(10\)\n\n"
r"\*\*Description:\*\* This alert is fired when the defined metric \(current value: 15\) crosses the threshold \(10\)\n\n"
r"\*\*Details:\*\*\n\n- \*\*threshold\.name:\*\* critical"
),
"wrap": True,
},
],
"msteams": {"width": "full"},
@@ -147,6 +126,98 @@ NOTIFIERS_TEST = [
],
),
),
types.AlertManagerNotificationTestCase(
name="msteams_notifier_custom_channel_text",
rule_path="ruler/test_scenarios/threshold_above_at_least_once/rule.json",
alert_data=[
types.AlertData(
type="metrics",
data_path="ruler/test_scenarios/threshold_above_at_least_once/alert_data.jsonl",
),
],
channel_config=msteams_custom_text_config,
notification_expectation=types.AMNotificationExpectation(
should_notify=True,
wait_time_seconds=120,
notification_validations=[
types.NotificationValidation(
destination_type="webhook",
validation_data={
"path": "/msteams/custom_text_webhook_url",
"json_body": {
"type": "message",
"attachments": [
{
"contentType": "application/vnd.microsoft.card.adaptive",
"content": {
"type": "AdaptiveCard",
"body": [
{
"type": "TextBlock",
"text": "Teams custom title: threshold_above_at_least_once",
"color": "Attention",
},
{
"type": "TextBlock",
"text": "Teams custom description for threshold_above_at_least_once (critical)",
"wrap": True,
},
],
},
}
],
},
},
),
],
),
),
types.AlertManagerNotificationTestCase(
name="msteams_notifier_rule_body_template",
rule_path="alertmanager/rule_body_template_rule.json",
alert_data=[
types.AlertData(
type="metrics",
data_path="ruler/test_scenarios/threshold_above_at_least_once/alert_data.jsonl",
),
],
channel_config=msteams_custom_text_config,
notification_expectation=types.AMNotificationExpectation(
should_notify=True,
wait_time_seconds=120,
notification_validations=[
types.NotificationValidation(
destination_type="webhook",
validation_data={
"path": "/msteams/custom_text_webhook_url",
"json_body": {
"type": "message",
"attachments": [
{
"contentType": "application/vnd.microsoft.card.adaptive",
"content": {
"type": "AdaptiveCard",
"body": [
{
"type": "TextBlock",
"text": "Teams custom title: rule_body_template",
},
{
"type": "TextBlock",
"text": "Rule body for rule_body_template at severity critical",
"wrap": True,
"color": "Attention",
},
],
},
}
],
},
},
),
],
),
),
types.AlertManagerNotificationTestCase(
name="pagerduty_notifier_default_templating",
rule_path="ruler/test_scenarios/threshold_above_at_least_once/rule.json",

View File

@@ -55,10 +55,18 @@ CONTENT_TEMPLATING_TEST = [
"content": {
"type": "AdaptiveCard",
"body": [
{
"type": "TextBlock",
"text": "[FIRING:1] content_templating_metrics",
},
{
"type": "TextBlock",
"text": re.compile(
r'\[FIRING:1\] content_templating_metrics for \(alertname="content_templating_metrics", container="checkout", namespace="production", node="ip-10-0-1-23", pod="checkout-7d9c8b5f4-x2k9p", ruleSource="http://localhost:8080/alerts/overview\?ruleId=[0-9a-f-]+", severity="critical", threshold\.name="critical"\)'
r"^\*\*Alert:\*\* content_templating_metrics \(critical\) - firing\n\n"
r"\*\*Summary:\*\* High container memory in production/checkout-7d9c8b5f4-x2k9p\n\n"
r"\*\*Description:\*\* Container checkout in pod checkout-7d9c8b5f4-x2k9p \(production\) exceeded memory threshold\n\n"
r"\*\*Details:\*\*\n\n- \*\*container:\*\* checkout\n- \*\*namespace:\*\* production\n"
r"- \*\*node:\*\* ip-10-0-1-23\n- \*\*pod:\*\* checkout-7d9c8b5f4-x2k9p\n- \*\*threshold\.name:\*\* critical$"
),
},
],