~fnux/matrix-alertmanager-receiver

a89b9ff69470b52d1ba48cfd642c56e169cd94b1 — Timothée Floure 6 months ago b3074be
Properly handle incoming hooks
2 files changed, 27 insertions(+), 11 deletions(-)

M main.go
A mock-webhook.sh
M main.go => main.go +15 -11
@@ 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)

A mock-webhook.sh => mock-webhook.sh +12 -0
@@ 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"