From a89b9ff69470b52d1ba48cfd642c56e169cd94b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Timoth=C3=A9e=20Floure?= Date: Sun, 3 May 2020 08:54:18 +0200 Subject: [PATCH] Properly handle incoming hooks --- main.go | 26 +++++++++++++++----------- mock-webhook.sh | 12 ++++++++++++ 2 files changed, 27 insertions(+), 11 deletions(-) create mode 100755 mock-webhook.sh diff --git a/main.go b/main.go index 97daa6e..d6d0a14 100644 --- a/main.go +++ b/main.go @@ -6,13 +6,13 @@ import ( "fmt" "log" "net/http" - "io/ioutil" "encoding/json" + "github.com/prometheus/alertmanager/template" "github.com/matrix-org/gomatrix" ) -type Alert struct { - +func generateMatrixMessageBody(alert template.Alert) string { + return alert.Status + " // " + alert.Annotations["summary"] } func main() { @@ -77,16 +77,20 @@ You will find more details on: http://git.sr.ht/~fnux/matrix-prometheus-alertman return } - var alert Alert - reqBody, _ := ioutil.ReadAll(r.Body) - json.Unmarshal(reqBody, &alert) + payload := template.Data{} + if err := json.NewDecoder(r.Body).Decode(&payload); err != nil { + w.WriteHeader(http.StatusBadRequest) + } - // Check validity + logger.Printf("Received valid hook from %v", r.RemoteAddr) - logger.Printf("Sending message") - _, err := matrixClient.SendText(*target, "spouik spouik spouik") - if err != nil { - logger.Fatalf("Failed to send message: %v", err) + for _, alert := range payload.Alerts { + body := generateMatrixMessageBody(alert) + logger.Printf("> %v", body) + _, err := matrixClient.SendText(*target, body) + if err != nil { + logger.Fatalf("Could not forward to Matrix: %v", err) + } } w.WriteHeader(http.StatusOK) diff --git a/mock-webhook.sh b/mock-webhook.sh new file mode 100755 index 0000000..bd3a175 --- /dev/null +++ b/mock-webhook.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# +# Send a dummy hook to localhost:9088 for testing purposes. + +TARGET=http://localhost:9088/alert +PAYLOAD=$(cat << EOF +{"receiver":"matrix","status":"firing","alerts":[{"status":"firing","labels":{"alertname":"instance_down","instance":"example1"},"annotations":{"info":"The instance example1 is down","summary":"instance example1 is down"},"startsAt":"2020-05-03T08:30:06.275828332+02:00","endsAt":"0001-01-01T00:00:00Z","generatorURL":""}],"groupLabels":{"alertname":"instance_down"},"commonLabels":{"alertname":"instance_down","instance":"example1"},"commonAnnotations":{"info":"The instance example1 is down","summary":"instance example1 is down"},"externalURL":"http://control:9093","version":"4","groupKey":"{}:{alertname=\"instance_down\"}"} +EOF +) + +curl -X POST -d "$PAYLOAD" "$TARGET" +