-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmain.go
99 lines (87 loc) · 2.45 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strings"
"sync"
"github.com/andygrunwald/cachet"
"github.com/prometheus/alertmanager/template"
)
type alerts struct {
client *cachet.Client
incidents map[string]int
mutex sync.Mutex
}
func (alt *alerts) cachetAlert(status, name, message string) {
if _, ok := alt.incidents[name]; ok {
if strings.ToUpper(status) == "RESOLVED" {
log.Printf("Resolving alert \"%s\".\n", name)
alt.client.Incidents.Delete(alt.incidents[name])
alt.mutex.Lock()
delete(alt.incidents, name)
alt.mutex.Unlock()
} else {
log.Printf("Alert \"%s\" already reported.\n", name)
}
return
}
incident := &cachet.Incident{
Name: name,
Message: message,
Status: cachet.IncidentStatusInvestigating,
}
newIncident, _, _ := alt.client.Incidents.Create(incident)
log.Printf("Reported: %s\n", newIncident.Name)
id := newIncident.ID
alt.mutex.Lock()
alt.incidents[name] = id
alt.mutex.Unlock()
log.Printf("ID: %d\n", newIncident.ID)
}
func (alt *alerts) prometheusAlert(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
log.Println("Receiving alert...")
data := template.Data{}
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
log.Printf("Error decoding alert: %s", err.Error())
log.Println(r.Body)
return
}
status := data.Status
// log.Printf("Alerts: Status=%v", data.Status)
for _, alert := range data.Alerts {
// log.Printf("Alert: status=%s,Labels=%v,Annotations=%v", alert.Status, alert.Labels, alert.Annotations)
alt.cachetAlert(status, alert.Labels["alertname"], alert.Annotations["summary"])
}
}
func health(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Alive")
}
func main() {
statusPage := os.Getenv("CACHET_URL")
if len(statusPage) == 0 {
panic("CACHET_URL must not be empty.")
}
client, err := cachet.NewClient(statusPage, nil)
if err != nil {
panic(err)
}
apiKey := os.Getenv("CACHET_KEY")
if len(apiKey) == 0 {
panic("CACHET_KEY must not be empty.")
}
client.Authentication.SetTokenAuth(apiKey)
// client.Authentication.SetBasicAuth("[email protected]", "test123")
alerts := alerts{incidents: make(map[string]int), client: client}
http.HandleFunc("/health", health)
http.HandleFunc("/webhook", alerts.prometheusAlert)
listenAddress := ":80"
if os.Getenv("PORT") != "" {
listenAddress = ":" + os.Getenv("PORT")
}
log.Printf("Listening on %v", listenAddress)
log.Fatal(http.ListenAndServe(listenAddress, nil))
}