-
Notifications
You must be signed in to change notification settings - Fork 9
/
cachet.go
422 lines (355 loc) · 10.5 KB
/
cachet.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
)
type CachetIncident struct {
Id int `json:"id"`
ComponentId int `json:"component_id"`
Status int `json:"status"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
// Cachet is a facade to CachetHQ client calls
type Cachet interface {
// List will fetch the different CachetHQ components (id/name) via a GET /api/v1/components
// it will return a map[componentname]componentid
ListComponents() (map[string]int, error)
SearchComponent(name string) (int, error)
// Return an incident
ReadIncident(incidentId int) (*CachetIncident, error)
// Returns all incidents for a given component, ASC sorted (i.e. the last incident, is the first in the list)
SearchIncidents(componentId int) ([]*CachetIncident, error)
// CreateIncident will create a new incident for the choosen CachetHQ components (id/name) via a POST /api/v1/incidents
// component status: component status: https://docs.cachethq.io/docs/component-statuses
// - status = 1 for alert resolved
// - status = 4 for alert fatal
CreateIncident(componentName string, componentID, status int, componentStatus int) error
// UpdateIncident will create a new incident update for the choosen CachetHQ components (id/name) via a PUT /api/v1/incidents/<incidentid>
// component status: component status: https://docs.cachethq.io/docs/component-statuses
// - status = 1 for alert resolved
// - status = 4 for alert fatal
UpdateIncident(componentName string, componentID, incidentId, status int, message string) error
}
// 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 cachetHqComponentList 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"`
}
type cachetHqIncidemntsList struct {
Meta struct {
Pagination struct {
CurrentPage int `json:"current_page"`
TotalPages int `json:"total_pages"`
} `json:"pagination"`
} `json:"meta"`
Data []CachetIncident `json:"data"`
}
type cachetHqIncidentRead struct {
Data CachetIncident `json:"data"`
}
// cf https://docs.cachethq.io/reference#incidents
type cachetHqIncident struct {
Name string `json:"name"`
Message string `json:"message"`
Status int `json:"status"`
Visible int `json:"visible"`
ComponentID int `json:"component_id"`
ComponentStatus int `json:"component_status"`
}
type CachetImpl struct {
apiURL string
apiKey string
client *http.Client
}
// NewCachetImpl creates a new Cachet interface implementation
func NewCachetImpl(apiURL, apiKey string, client *http.Client) *CachetImpl {
// by precaution, remove the '/' at the end of apiURL
apiURL = strings.TrimRight(apiURL, "/")
return &CachetImpl{
apiURL: apiURL,
apiKey: apiKey,
client: client,
}
}
func (c *CachetImpl) ListComponents() (map[string]int, error) {
componentsID := make(map[string]int)
var message cachetHqComponentList
// we loop "only" on the max first 100 pages
for page := 1; page < 100; page++ {
nextPage := fmt.Sprintf("%s/api/v1/components?page=%d", c.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", c.apiKey)
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if resp.StatusCode != 200 {
if err != nil {
return nil, err
}
log.Println(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
}
func (c *CachetImpl) SearchComponent(name string) (int, error) {
var message cachetHqComponentList
page := fmt.Sprintf("%s/api/v1/components?name=%s&page=1", c.apiURL, name)
req, err := http.NewRequest(http.MethodGet, page, nil)
if err != nil {
return -1, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Cachet-Token", c.apiKey)
resp, err := c.client.Do(req)
if err != nil {
return -1, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if resp.StatusCode != 200 {
if err != nil {
return -1, err
}
log.Println(string(body))
}
if err := json.Unmarshal(body, &message); err != nil {
return -1, err
}
if len(message.Data) == 1 {
return message.Data[0].Id, nil
}
return -1, fmt.Errorf("no component found")
}
func (c *CachetImpl) CreateIncident(componentName string, componentID, status int, componentStatus int) error {
incidentName := fmt.Sprintf("%s down", componentName)
incidentMessage := fmt.Sprintf("Prometheus flagged service %s as down", componentName)
incidentStatus := 2 // "Identified"
// if we are in status = 1 (alert resolved)
if status == 1 {
incidentName = fmt.Sprintf("%s up", componentName)
incidentMessage = fmt.Sprintf("Prometheus flagged service %s as recovered", componentName)
incidentStatus = 4 // "Fixed"
}
incident := &cachetHqIncident{
Name: incidentName,
Message: incidentMessage,
Status: incidentStatus,
ComponentID: componentID,
Visible: 1,
ComponentStatus: componentStatus,
}
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", c.apiURL), &buf)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Cachet-Token", c.apiKey)
resp, err := c.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
log.Println(string(b))
}
//body, _ := ioutil.ReadAll(resp.Body)
//log.Println("response from CachetHQ when sending alert: ", string(body))
return nil
}
func (c *CachetImpl) UpdateIncident(componentName string, componentID, incidentId, status int, message string) error {
incidentName := fmt.Sprintf("%s down", componentName)
incidentMessage := message
incidentStatus := 2 // "Identified"
componentStatus := 4 // "Major Outage"
// if we are in status = 1 (alert resolved)
if status == 1 {
incidentName = fmt.Sprintf("%s up", componentName)
incidentMessage = message
incidentStatus = 4 // "Fixed"
componentStatus = 1 // "Operational"
}
incident := &cachetHqIncident{
Name: incidentName,
Message: incidentMessage,
Status: incidentStatus,
ComponentID: componentID,
Visible: 1,
ComponentStatus: componentStatus,
}
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(incident); err != nil {
return err
}
req, err := http.NewRequest(http.MethodPut, fmt.Sprintf("%s/api/v1/incidents/%d", c.apiURL, incidentId), &buf)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Cachet-Token", c.apiKey)
resp, err := c.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
log.Println(string(b))
}
return nil
}
func (c *CachetImpl) SearchIncidents(componentId int) ([]*CachetIncident, error) {
incidents := make([]*CachetIncident, 0)
var message cachetHqIncidemntsList
// pagination doesn't work
nextPage := fmt.Sprintf("%s/api/v1/incidents?component_id=%d&sort=id&order=desc&per_page=1000", c.apiURL, componentId)
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", c.apiKey)
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if resp.StatusCode != 200 {
if err != nil {
return nil, err
}
log.Println(string(body))
}
if err := json.Unmarshal(body, &message); err != nil {
return nil, err
}
for _, data := range message.Data {
copydata := data
incidents = append(incidents, ©data)
}
return incidents, nil
}
func (c *CachetImpl) ReadIncident(incidentId int) (*CachetIncident, error) {
var incident cachetHqIncidentRead
request := fmt.Sprintf("%s/api/v1/incidents/%d", c.apiURL, incidentId)
req, err := http.NewRequest(http.MethodGet, request, nil)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Cachet-Token", c.apiKey)
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if resp.StatusCode != 200 {
if err != nil {
return nil, err
}
log.Println(string(body))
}
if err := json.Unmarshal(body, &incident); err != nil {
return nil, err
}
return &incident.Data, nil
}