forked from nzin/prometheus-cachethq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webserver.go
317 lines (278 loc) · 8.75 KB
/
webserver.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
// cf https://docs.cachethq.io/reference#update-a-component
// {
// "data": {
// "id": 1,
// "name": "Component Name",
// "description": "Description",
// "link": "",
// "status": 1,
// "order": 0,
// "group_id": 0,
// "created_at": "2015-08-01 12:00:00",
// "updated_at": "2015-08-01 12:00:00",
// "deleted_at": null,
// "status_name": "Operational",
// "tags": [
// "slug-of-tag": "Tag Name"
// ]
// }
//}
type cachetHqMessage struct {
Status int `json:"status"`
}
// cf https://docs.cachethq.io/reference#get-components
// {
// "meta": {
// "pagination": {
// "total": 1,
// "count": 1,
// "per_page": 20,
// "current_page": 1,
// "total_pages": 1,
// "links": {
// "next_page": null,
// "previous_page": null
// }
// }
// },
// "data": [
// {
// "id": 1,
// "name": "API",
// "description": "This is the Cachet API.",
// "link": "",
// "status": 1,
// "order": 0,
// "group_id": 0,
// "created_at": "2015-07-24 14:42:10",
// "updated_at": "2015-07-24 14:42:10",
// "deleted_at": null,
// "status_name": "Operational",
// "tags": [
// "slug-of-tag": "Tag Name"
// ]
// }
// ]
//}
type cachetHqMessageList struct {
Meta struct {
Pagination struct {
CurrentPage int `json:"current_page"`
TotalPages int `json:"total_pages"`
} `json:"pagination"`
} `json:"meta"`
Data []struct {
Id int `json:"id"`
Name string `json:"name"`
} `json:"data"`
}
// cf https://docs.cachethq.io/reference#incidents
type cachetHqIncident struct {
Name string `json:"name"`
Message string `json:"message"`
Status int `json:"status"`
ComponentID int `json:"component_id"`
ComponentStatus int `json:"component_status"`
Visible int `json:"visible"`
}
// cachetList will fetch the different CachetHQ components (id/name) via a GET /api/v1/components
// it will return a map[componentname]componentid
func cachetList(apiURL, apiKEY string, client *http.Client) (map[string]int, error) {
componentsId := make(map[string]int)
var message cachetHqMessageList
// by precaution, remove the '/' at the end of apiURL
apiURL = strings.TrimRight(apiURL, "/")
// we loop "only" on the max first 100 pages
for page := 1; page < 100; page++ {
nextPage := fmt.Sprintf("%s/api/v1/components?page=%d", apiURL, page)
req, err := http.NewRequest(http.MethodGet, nextPage, nil)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Cachet-Token", apiKEY)
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
// log.Println("response from CachetHQ when listing component's pages: ", string(body))
if err := json.Unmarshal(body, &message); err != nil {
return nil, err
}
for _, data := range message.Data {
componentsId[data.Name] = data.Id
}
// is there a next page?
if message.Meta.Pagination.CurrentPage >= message.Meta.Pagination.TotalPages {
// nope
return componentsId, nil
}
}
return componentsId, nil
}
// alert will update the choosen CachetHQ components (id/name) via a PUT /api/v1/components/<componentid>
// component status: component status: https://docs.cachethq.io/docs/component-statuses
// - status = 1 for alert resolved
// - status = 4 for alert fatal
func cachetAlert(cachetVisibility bool, componentName string, componentID, componentStatus int, apiURL, apiKEY string, client *http.Client) error {
incidentName := fmt.Sprintf("%s down", componentName)
incidentMessage := fmt.Sprintf("Prometheus flagged service %s as down", componentName)
incidentStatus := 4 // "Identified"
// if we are in status = 1 (alert resolved)
if componentStatus == 1 {
incidentName = fmt.Sprintf("%s up", componentName)
incidentMessage = fmt.Sprintf("Prometheus flagged service %s as recovered", componentName)
}
visible := 0
if cachetVisibility {
visible = 1
}
incident := &cachetHqIncident{
Name: incidentName,
Message: incidentMessage,
Status: incidentStatus,
ComponentID: componentID,
ComponentStatus: componentStatus,
Visible: visible,
}
// by precaution, remove the '/' at the end of apiURL
apiURL = strings.TrimRight(apiURL, "/")
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(incident); err != nil {
return err
}
req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/incidents", apiURL), &buf)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Cachet-Token", apiKEY)
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
//body, _ := ioutil.ReadAll(resp.Body)
//log.Println("response from CachetHQ when sending alert: ", string(body))
return nil
}
/*
cf https://prometheus.io/docs/alerting/configuration/#webhook_config
{
"version": "4",
"groupKey": <string>, // key identifying the group of alerts (e.g. to deduplicate)
"status": "<resolved|firing>",
"receiver": <string>,
"groupLabels": <object>,
"commonLabels": <object>,
"commonAnnotations": <object>,
"externalURL": <string>, // backlink to the Alertmanager.
"alerts": [
{
"labels": <object>,
"annotations": <object>,
"startsAt": "<rfc3339>",
"endsAt": "<rfc3339>"
},
...
]
}
*/
type PrometheusAlertDetail struct {
Labels map[string]string `json:"labels"`
Annotations map[string]string `json:"annotations"`
StartAt string `json:"startsAt"`
EndsAt string `json:"endsAt"`
Status string `json:"status"`
}
type PrometheusAlert struct {
Version string `json:"version" binding:"required"`
GroupKey string `json:"groupKey"`
Status string `json:"status" binding:"required"`
Receiver string `json:"receiver"`
GroupLabels map[string]string `json:"groupLabels"`
CommonLabels map[string]string `json:"commonLabels"`
CommonAnnotations map[string]string `json:"commonAnnotations"`
ExternalURL string `json:"externalURL"`
Alerts []PrometheusAlertDetail `json:"alerts"`
}
// SubmitAlert receive an alert from Prometheus, and try to forward it to CachetHQ
func SubmitAlert(c *gin.Context, config *PrometheusCachetConfig) {
// check the Bearer
if config.PrometheusToken != "" {
bearer := c.GetHeader("Authorization")
if bearer != fmt.Sprintf("Bearer %s", config.PrometheusToken) {
if config.LogLevel == LOG_DEBUG {
log.Println("wrong Authorization header:", bearer)
}
c.JSON(http.StatusBadRequest, gin.H{"error": "wrong Authorization header"})
return
}
}
// read the payload
var alerts PrometheusAlert
if err := c.ShouldBindJSON(&alerts); err == nil {
// talk to CachetHQ
list, err := cachetList(config.CachetURL, config.CachetToken, config.HttpClient)
if err != nil {
if config.LogLevel == LOG_DEBUG {
log.Println(err)
}
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// prometheus can send 2 times the same alerts info in one call
alreadyFired := make(map[int]int)
for _, alert := range alerts.Alerts {
// fire something
if componentID, ok := list[alert.Labels[config.LabelName]]; ok {
if alreadyFired[componentID] == 0 {
alreadyFired[componentID] = 1
status := 1 // "resolved"
if alert.Status == "firing" {
status = 4
}
if err := cachetAlert(config.CachetIncidentVisibility, alert.Labels[config.LabelName], componentID, status, config.CachetURL, config.CachetToken, config.HttpClient); err != nil {
if config.LogLevel == LOG_DEBUG {
log.Println(err)
}
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
}
}
}
} else {
if config.LogLevel == LOG_DEBUG {
log.Println(err)
}
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "OK"})
}
func PrepareGinRouter(config *PrometheusCachetConfig) *gin.Engine {
router := gin.New()
router.Use(gin.LoggerWithWriter(gin.DefaultWriter, "/health"))
router.Use(gin.Recovery())
router.GET("/health", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "OK"})
})
router.POST("/alert", func(c *gin.Context) {
SubmitAlert(c, config)
})
return router
}