prometheus: support regex silencing of alerts (#14474)

This change allows us to perform regex silences in `observability.silenceAlerts`.
This commit is contained in:
Robert Lin 2020-10-08 10:18:20 +08:00 committed by GitHub
parent b748e77805
commit 05e523a550
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 52 additions and 3 deletions

View File

@ -1,6 +1,9 @@
package main
import (
"fmt"
"strings"
"github.com/prometheus/alertmanager/api/v2/models"
)
@ -12,12 +15,17 @@ func boolP(v bool) *bool {
return &v
}
const (
matcherRegexPrefix = "^("
matcherRegexSuffix = ")$"
)
// newMatchersFromSilence creates Alertmanager alert matchers from a configured silence
func newMatchersFromSilence(silence string) models.Matchers {
return models.Matchers{{
Name: stringP("alertname"),
Value: stringP(silence),
IsRegex: boolP(false),
Value: stringP(fmt.Sprintf("%s%s%s", matcherRegexPrefix, silence, matcherRegexSuffix)),
IsRegex: boolP(true),
}}
}
@ -25,7 +33,7 @@ func newMatchersFromSilence(silence string) models.Matchers {
func newSilenceFromMatchers(matchers models.Matchers) string {
for _, m := range matchers {
if *m.Name == "alertname" {
return *m.Value
return strings.TrimSuffix(strings.TrimPrefix(*m.Value, matcherRegexPrefix), matcherRegexSuffix)
}
}
return ""

View File

@ -0,0 +1,41 @@
package main
import (
"testing"
)
func TestMatchersAndSilences(t *testing.T) {
tests := []struct {
name string
silence string
wantMatcherAlertnames []string
}{
{
name: "add strict match",
silence: "hello",
wantMatcherAlertnames: []string{"^(hello)$"},
},
{
name: "accept regex",
silence: ".*hello.*",
wantMatcherAlertnames: []string{"^(.*hello.*)$"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
matchers := newMatchersFromSilence(tt.silence)
for i, m := range matchers {
if *m.Name == "alertname" {
if *m.Value != tt.wantMatcherAlertnames[i] {
t.Errorf("newMatchersFromSilence got %s, want %s",
*m.Value, tt.wantMatcherAlertnames[i])
}
}
}
silence := newSilenceFromMatchers(matchers)
if silence != tt.silence {
t.Errorf("newSilenceFromMatchers() = %v, want %v", silence, tt.silence)
}
})
}
}