From 9043ccfb5efd487996b3666888f922507259a181 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thorben=20G=C3=BCnther?= Date: Wed, 12 Oct 2022 16:35:04 +0200 Subject: [PATCH] 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. --- config.go | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ main.go | 22 ++++++++++++++++++++++ 2 files changed, 71 insertions(+) diff --git a/config.go b/config.go index 3108a24..10a405f 100644 --- a/config.go +++ b/config.go @@ -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") diff --git a/main.go b/main.go index 36a2b33..c15dcf0 100644 --- a/main.go +++ b/main.go @@ -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)