Set ntfy priority depending on Prometheus labels

It is possible to configure a priority for an arbitrary label.
Furthermore a priority/order of those arbitrary labels should be
defined. The Alertmanager payload is checked for these and the
priority will be selected from the highest valued label that has one
set in the configuration file.
This commit is contained in:
Thorben Günther 2022-10-12 16:35:04 +02:00
parent 9435feba8d
commit 9043ccfb5e
No known key found for this signature in database
GPG key ID: 415CD778D8C5AFED
2 changed files with 71 additions and 0 deletions

View file

@ -2,6 +2,7 @@ package main
import (
"fmt"
"strings"
"git.sr.ht/~emersion/go-scfg"
)
@ -12,6 +13,7 @@ type config struct {
User string
Password string
ntfy ntfyConfig
labels labels
}
type ntfyConfig struct {
@ -20,6 +22,15 @@ type ntfyConfig struct {
Password string
}
type labels struct {
Order []string
Label map[string]labelConfig
}
type labelConfig struct {
Priority string
}
func readConfig(path string) (*config, error) {
cfg, err := scfg.Load(path)
if err != nil {
@ -59,6 +70,44 @@ func readConfig(path string) (*config, error) {
}
}
labelsDir := cfg.Get("labels")
if labelsDir != nil {
d = labelsDir.Children.Get("order")
if d != nil {
var order string
if err := d.ParseParams(&order); err != nil {
return nil, err
}
config.labels.Order = strings.Split(order, ",")
}
labels := make(map[string]labelConfig)
for _, labelName := range config.labels.Order {
labelDir := labelsDir.Children.Get(labelName)
if labelDir != nil {
labelConfig := new(labelConfig)
var name string
if err := labelDir.ParseParams(&name); err != nil {
return nil, err
}
d = labelDir.Children.Get("priority")
if d != nil {
if err := d.ParseParams(&labelConfig.Priority); err != nil {
return nil, err
}
}
labels[fmt.Sprintf("%s:%s", labelName, name)] = *labelConfig
}
}
config.labels.Label = labels
}
ntfyDir := cfg.Get("ntfy")
if ntfyDir == nil {
return nil, fmt.Errorf("%q directive missing", "ntfy")

22
main.go
View file

@ -98,6 +98,28 @@ func (rcv *receiver) handleWebhooks(w http.ResponseWriter, r *http.Request) {
}
req.Header.Set("X-Title", title)
var priority string
for _, labelName := range rcv.cfg.labels.Order {
val, ok := event.CommonLabels[labelName]
if !ok {
continue
}
labelConfig, ok := rcv.cfg.labels.Label[fmt.Sprintf("%s:%s", labelName, val)]
if !ok {
continue
}
if priority == "" {
priority = labelConfig.Priority
}
}
if priority != "" {
req.Header.Set("X-Priority", priority)
}
resp, err := client.Do(req)
if err != nil {
rcv.logger.Error(err)