mirror of
https://github.com/sourcegraph/sourcegraph.git
synced 2026-02-06 17:31:43 +00:00
prometheus: support regex silencing of alerts (#14474)
This change allows us to perform regex silences in `observability.silenceAlerts`.
This commit is contained in:
parent
b748e77805
commit
05e523a550
@ -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 ""
|
||||
|
||||
41
docker-images/prometheus/cmd/prom-wrapper/silence_test.go
Normal file
41
docker-images/prometheus/cmd/prom-wrapper/silence_test.go
Normal 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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user