From 8933ccd82569358f28b8fe30b69e67dcae428ee3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thorben=20G=C3=BCnther?= Date: Fri, 3 Feb 2023 17:35:38 +0100 Subject: [PATCH] Support sending grouped alerts on their own --- main.go | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 72 insertions(+), 5 deletions(-) diff --git a/main.go b/main.go index 3c4de2c..b4ad29c 100644 --- a/main.go +++ b/main.go @@ -49,7 +49,64 @@ type notification struct { tags string } -func (rcv *receiver) newNotification(p *payload) *notification { +func (rcv *receiver) singleAlertNotifications(p *payload) []*notification { + var notifications []*notification + for _, alert := range p.Alerts { + n := new(notification) + + // create title + n.title = fmt.Sprintf("[%s]", strings.ToUpper(alert.Status)) + if name, ok := alert.Labels["alertname"]; ok { + n.title = fmt.Sprintf("%s %s", n.title, name) + } + + for _, value := range p.GroupLabels { + n.title = fmt.Sprintf("%s %s", n.title, value) + } + + // create body + n.body = "Labels:\n" + for key, value := range alert.Labels { + n.body = fmt.Sprintf("%s%s = %s\n", n.body, key, value) + } + + n.body += "\nAnnotations:\n" + for key, value := range alert.Annotations { + n.body = fmt.Sprintf("%s%s = %s\n", n.body, key, value) + } + + var tags []string + for _, labelName := range rcv.cfg.labels.Order { + val, ok := alert.Labels[labelName] + if !ok { + continue + } + + labelConfig, ok := rcv.cfg.labels.Label[fmt.Sprintf("%s:%s", labelName, val)] + if !ok { + continue + } + + if n.priority == "" { + n.priority = labelConfig.Priority + } + + for _, val := range labelConfig.Tags { + if !sliceContains(tags, val) { + tags = append(tags, val) + } + } + } + + n.tags = strings.Join(tags, ",") + + notifications = append(notifications, n) + } + + return notifications +} + +func (rcv *receiver) multiAlertNotification(p *payload) *notification { n := new(notification) // create title @@ -175,10 +232,20 @@ func (rcv *receiver) handleWebhooks(w http.ResponseWriter, r *http.Request) { return } - notification := rcv.newNotification(&event) - err := rcv.publish(notification) - if err != nil { - rcv.logger.Error(err) + if rcv.cfg.alertMode == single { + notifications := rcv.singleAlertNotifications(&event) + for _, n := range notifications { + err := rcv.publish(n) + if err != nil { + rcv.logger.Errorf("Failed to publish notification: %v", err) + } + } + } else { + notification := rcv.multiAlertNotification(&event) + err := rcv.publish(notification) + if err != nil { + rcv.logger.Errorf("Failed to publish notification: %v", err) + } } }