Alerting: only delete mute time if not used by route (#50193)

* Alerting: only delete mute time if not used by route

* add a testcase

* import package only once

* replace apimodels with definitions
This commit is contained in:
Jean-Philippe Quéméner 2022-06-04 07:48:24 +02:00 committed by GitHub
parent fd34700225
commit 8de4ffe61f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 70 additions and 0 deletions

View File

@ -159,6 +159,9 @@ func (svc *MuteTimingService) DeleteMuteTiming(ctx context.Context, name string,
if revision.cfg.AlertmanagerConfig.MuteTimeIntervals == nil {
return nil
}
if isMuteTimeInUse(name, []*definitions.Route{revision.cfg.AlertmanagerConfig.Route}) {
return fmt.Errorf("mute time '%s' is currently used by a notification policy", name)
}
for i, existing := range revision.cfg.AlertmanagerConfig.MuteTimeIntervals {
if name == existing.Name {
intervals := revision.cfg.AlertmanagerConfig.MuteTimeIntervals
@ -190,3 +193,20 @@ func (svc *MuteTimingService) DeleteMuteTiming(ctx context.Context, name string,
return nil
})
}
func isMuteTimeInUse(name string, routes []*definitions.Route) bool {
if len(routes) == 0 {
return false
}
for _, route := range routes {
for _, mtName := range route.MuteTimeIntervals {
if mtName == name {
return true
}
}
if isMuteTimeInUse(name, route.Routes) {
return true
}
}
return false
}

View File

@ -356,6 +356,18 @@ func TestMuteTimingService(t *testing.T) {
require.ErrorContains(t, err, "failed to save config")
})
t.Run("when mute timing is used in route", func(t *testing.T) {
sut := createMuteTimingSvcSut()
sut.config.(*MockAMConfigStore).EXPECT().
getsConfig(models.AlertConfiguration{
AlertmanagerConfiguration: configWithMuteTimingsInRoute,
})
err := sut.DeleteMuteTiming(context.Background(), "asdf", 1)
require.Error(t, err)
})
})
})
}
@ -408,3 +420,41 @@ var configWithMuteTimings = `
}
}
`
var configWithMuteTimingsInRoute = `
{
"template_files": {
"a": "template"
},
"alertmanager_config": {
"route": {
"receiver": "grafana-default-email",
"routes": [
{
"receiver": "grafana-default-email",
"mute_time_intervals": ["asdf"]
}
]
},
"mute_time_intervals": [{
"name": "asdf",
"time_intervals": [{
"times": [],
"weekdays": ["monday"]
}]
}],
"receivers": [{
"name": "grafana-default-email",
"grafana_managed_receiver_configs": [{
"uid": "",
"name": "email receiver",
"type": "email",
"isDefault": true,
"settings": {
"addresses": "<example@email.com>"
}
}]
}]
}
}
`