fix(notify/victorops): Catch routing_key templating errors (#2467)

* test(notify/victorops): Add test for templating errors

Signed-off-by: Jack Baldry <jack.baldry@grafana.com>

* fix(notify/victorops): Catch routing_key templating errors

Signed-off-by: Jack Baldry <jack.baldry@grafana.com>
This commit is contained in:
Jack Baldry 2021-01-29 13:40:33 +00:00 committed by GitHub
parent e6824a3110
commit bf94d58d56
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 92 additions and 0 deletions

View File

@ -72,6 +72,9 @@ func (n *Notifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error)
apiURL = n.conf.APIURL.Copy()
)
apiURL.Path += fmt.Sprintf("%s/%s", n.conf.APIKey, tmpl(n.conf.RoutingKey))
if err != nil {
return false, fmt.Errorf("templating error: %s", err)
}
buf, err := n.createVictorOpsPayload(ctx, as...)
if err != nil {

View File

@ -17,6 +17,8 @@ import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"time"
@ -116,3 +118,90 @@ func TestVictorOpsRedactedURL(t *testing.T) {
test.AssertNotifyLeaksNoSecret(t, ctx, notifier, secret)
}
func TestVictorOpsTemplating(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
dec := json.NewDecoder(r.Body)
out := make(map[string]interface{})
err := dec.Decode(&out)
if err != nil {
panic(err)
}
}))
defer srv.Close()
u, _ := url.Parse(srv.URL)
tests := []struct {
name string
cfg *config.VictorOpsConfig
errMsg string
}{
{
name: "default valid templates",
cfg: &config.VictorOpsConfig{},
},
{
name: "invalid message_type",
cfg: &config.VictorOpsConfig{
MessageType: "{{ .CommonLabels.alertname }",
},
errMsg: "templating error",
},
{
name: "invalid entity_display_name",
cfg: &config.VictorOpsConfig{
EntityDisplayName: "{{ .CommonLabels.alertname }",
},
errMsg: "templating error",
},
{
name: "invalid state_message",
cfg: &config.VictorOpsConfig{
StateMessage: "{{ .CommonLabels.alertname }",
},
errMsg: "templating error",
},
{
name: "invalid monitoring tool",
cfg: &config.VictorOpsConfig{
MonitoringTool: "{{ .CommonLabels.alertname }",
},
errMsg: "templating error",
},
{
name: "invalid routing_key",
cfg: &config.VictorOpsConfig{
RoutingKey: "{{ .CommonLabels.alertname }",
},
errMsg: "templating error",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
tc.cfg.HTTPConfig = &commoncfg.HTTPClientConfig{}
tc.cfg.APIURL = &config.URL{URL: u}
vo, err := New(tc.cfg, test.CreateTmpl(t), log.NewNopLogger())
require.NoError(t, err)
ctx := context.Background()
ctx = notify.WithGroupKey(ctx, "1")
_, err = vo.Notify(ctx, []*types.Alert{{
Alert: model.Alert{
Labels: model.LabelSet{
"lbl1": "val1",
},
StartsAt: time.Now(),
EndsAt: time.Now().Add(time.Hour),
},
},
}...)
if tc.errMsg == "" {
require.NoError(t, err)
} else {
require.Contains(t, err.Error(), tc.errMsg)
}
})
}
}