Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

templates: add (org-aware) AlertingListURL to ExternalData and fix Slack receiver #241

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions receivers/slack/slack.go
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ func handleSlackJSONResponse(resp *http.Response, logger logging.Logger) (string
return result.Ts, nil
}

func (sn *Notifier) commonAlertGeneratorURL(_ context.Context, alerts []*types.Alert) bool {
func (sn *Notifier) commonAlertGeneratorURL(_ context.Context, alerts templates.ExtendedAlerts) bool {
if len(alerts[0].GeneratorURL) == 0 {
return false
}
Expand All @@ -298,13 +298,13 @@ func (sn *Notifier) commonAlertGeneratorURL(_ context.Context, alerts []*types.A

func (sn *Notifier) createSlackMessage(ctx context.Context, alerts []*types.Alert) (*slackMessage, error) {
var tmplErr error
tmpl, _ := templates.TmplText(ctx, sn.tmpl, alerts, sn.log, &tmplErr)
tmpl, data := templates.TmplText(ctx, sn.tmpl, alerts, sn.log, &tmplErr)

ruleURL := receivers.JoinURLPath(sn.tmpl.ExternalURL.String(), "/alerting/list", sn.log)
ruleURL := data.AlertingListURL

// If all alerts have the same GeneratorURL, use that.
if sn.commonAlertGeneratorURL(ctx, alerts) {
ruleURL = alerts[0].GeneratorURL
if sn.commonAlertGeneratorURL(ctx, data.Alerts) {
ruleURL = data.Alerts[0].GeneratorURL
}

title, truncated := receivers.TruncateInRunes(tmpl(sn.settings.Title), slackMaxTitleLenRunes)
Expand Down
39 changes: 39 additions & 0 deletions receivers/slack/slack_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,45 @@ func TestNotify_IncomingWebhook(t *testing.T) {
},
},
},
}, {
name: "Message is sent with orgId",
settings: Config{
EndpointURL: APIURL,
URL: "https://example.com/hooks/xxxx",
Token: "",
Recipient: "#test",
Text: templates.DefaultMessageEmbed,
Title: templates.DefaultMessageTitleEmbed,
Username: "Grafana",
IconEmoji: ":emoji:",
IconURL: "",
MentionChannel: "",
MentionUsers: nil,
MentionGroups: nil,
},
alerts: []*types.Alert{{
Alert: model.Alert{
Labels: model.LabelSet{"alertname": "alert1", "lbl1": "val1"},
Annotations: model.LabelSet{"ann1": "annv1", "__orgId__": "123"},
},
}},
expectedMessage: &slackMessage{
Channel: "#test",
Username: "Grafana",
IconEmoji: ":emoji:",
Attachments: []attachment{
{
Title: "[FIRING:1] (val1)",
TitleLink: "http://localhost/alerting/list?orgId=123",
Text: "**Firing**\n\nValue: [no value]\nLabels:\n - alertname = alert1\n - lbl1 = val1\nAnnotations:\n - ann1 = annv1\nSilence: http://localhost/alerting/silence/new?alertmanager=grafana&matcher=alertname%3Dalert1&matcher=lbl1%3Dval1&orgId=123\n",
Fallback: "[FIRING:1] (val1)",
Fields: nil,
Footer: "Grafana v" + appVersion,
FooterIcon: "https://grafana.com/static/assets/img/fav32.png",
Color: "#D63232",
},
},
},
}}

for _, test := range tests {
Expand Down
39 changes: 30 additions & 9 deletions templates/template_data.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ type ExtendedData struct {
CommonLabels KV `json:"commonLabels"`
CommonAnnotations KV `json:"commonAnnotations"`

ExternalURL string `json:"externalURL"`
ExternalURL string `json:"externalURL"`
AlertingListURL string `json:"alertingListURL"`
}

// FromContent calls Parse on all provided template content and returns the resulting Template. Content equivalent to templates.FromGlobs.
Expand Down Expand Up @@ -134,14 +135,15 @@ func extendAlert(alert template.Alert, externalURL string, logger log.Logger) *E
}
externalPath := u.Path

generatorURL, err := url.Parse(extended.GeneratorURL)
if err != nil {
level.Debug(logger).Log("msg", "failed to parse generator URL while extending template data", "url", extended.GeneratorURL, "error", err.Error())
return extended
}

orgID := alert.Annotations[models.OrgIDAnnotation]
if len(orgID) > 0 {

if len(extended.GeneratorURL) > 0 && len(orgID) > 0 {
generatorURL, err := url.Parse(extended.GeneratorURL)
if err != nil {
level.Debug(logger).Log("msg", "failed to parse generator URL while extending template data", "url", extended.GeneratorURL, "error", err.Error())
return extended
}

extended.GeneratorURL = setOrgIDQueryParam(generatorURL, orgID)
}

Expand Down Expand Up @@ -208,6 +210,24 @@ func setOrgIDQueryParam(url *url.URL, orgID string) string {
return url.String()
}

func parseAlertingListURL(data *Data, logger log.Logger) string {
externalURL, err := url.Parse(data.ExternalURL)
if err != nil {
level.Debug(logger).Log("msg", "failed to parse external URL while extending template data", "url", data.ExternalURL, "error", err.Error())

return ""
}

externalURL.Path = path.Join(externalURL.Path, "/alerting/list")

orgID := data.CommonAnnotations[models.OrgIDAnnotation]
if len(orgID) > 0 {
return setOrgIDQueryParam(externalURL, orgID)
}

return externalURL.String()
}

func ExtendData(data *Data, logger log.Logger) *ExtendedData {
alerts := make([]ExtendedAlert, 0, len(data.Alerts))

Expand All @@ -224,7 +244,8 @@ func ExtendData(data *Data, logger log.Logger) *ExtendedData {
CommonLabels: removePrivateItems(data.CommonLabels),
CommonAnnotations: removePrivateItems(data.CommonAnnotations),

ExternalURL: data.ExternalURL,
ExternalURL: data.ExternalURL,
AlertingListURL: parseAlertingListURL(data, logger),
}
return extended
}
Expand Down
52 changes: 52 additions & 0 deletions templates/template_data_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package templates

import (
"testing"

"github.com/prometheus/alertmanager/template"
"github.com/stretchr/testify/require"

"github.com/grafana/alerting/logging"
"github.com/grafana/alerting/models"
)

func TestParseAlertingListURL(t *testing.T) {
testcases := []struct {
name string
data *Data
expectedURI string
}{
{
name: "without org annotation",
data: &Data{
ExternalURL: "http://localhost:3000",
},
expectedURI: "http://localhost:3000/alerting/list",
},
{
name: "with org annotation",
data: &Data{
ExternalURL: "http://localhost:3000",
CommonAnnotations: template.KV{
models.OrgIDAnnotation: "1234",
},
},
expectedURI: "http://localhost:3000/alerting/list?orgId=1234",
},
{
name: "with invalid external URL",
data: &Data{
ExternalURL: `http%//[email protected]`,
},
expectedURI: "",
},
}

for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) {
actualURI := parseAlertingListURL(tc.data, &logging.FakeLogger{})

require.Equal(t, tc.expectedURI, actualURI)
})
}
}