-
Notifications
You must be signed in to change notification settings - Fork 495
/
service.go
406 lines (350 loc) · 9.4 KB
/
service.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
package bigpanda
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"html"
"io"
"net/http"
"net/url"
"strings"
"sync/atomic"
text "text/template"
"time"
"github.com/influxdata/kapacitor/alert"
khttp "github.com/influxdata/kapacitor/http"
"github.com/influxdata/kapacitor/keyvalue"
"github.com/influxdata/kapacitor/models"
"github.com/pkg/errors"
)
const (
defaultTokenPrefix = "Bearer"
)
type Diagnostic interface {
WithContext(ctx ...keyvalue.T) Diagnostic
TemplateError(err error, kv keyvalue.T)
Error(msg string, err error)
}
type Service struct {
configValue atomic.Value
clientValue atomic.Value
diag Diagnostic
}
func NewService(c Config, d Diagnostic) (*Service, error) {
s := &Service{
diag: d,
}
s.configValue.Store(c)
s.clientValue.Store(khttp.NewDefaultClientWithTLS(&tls.Config{InsecureSkipVerify: c.InsecureSkipVerify}, khttp.DefaultValidator))
return s, nil
}
func (s *Service) Open() error {
return nil
}
func (s *Service) Close() error {
return nil
}
func (s *Service) config() Config {
return s.configValue.Load().(Config)
}
func (s *Service) Update(newConfig []interface{}) error {
if l := len(newConfig); l != 1 {
return fmt.Errorf("expected only one new config object, got %d", l)
}
if c, ok := newConfig[0].(Config); !ok {
return fmt.Errorf("expected config object to be of type %T, got %T", c, newConfig[0])
} else {
s.configValue.Store(c)
s.clientValue.Store(khttp.NewDefaultClientWithTLS(&tls.Config{InsecureSkipVerify: c.InsecureSkipVerify}, khttp.DefaultValidator))
}
return nil
}
func (s *Service) Global() bool {
return s.config().Global
}
func (s *Service) StateChangesOnly() bool {
return s.config().StateChangesOnly
}
type testOptions struct {
AppKey string `json:"app_key"`
Message string `json:"message"`
Level alert.Level `json:"level"`
Data alert.EventData `json:"event_data"`
Timestamp time.Time `json:"timestamp"`
Host string `json:"host"`
PrimaryProperty string `json:"primary_property"`
SecondaryProperty string `json:"secondary_property"`
}
func (s *Service) TestOptions() interface{} {
return &testOptions{
AppKey: "012345",
Message: "test bigpanda message",
Level: alert.Critical,
Data: alert.EventData{
Name: "testBigPanda",
Tags: make(map[string]string),
Fields: make(map[string]interface{}),
Result: models.Result{},
},
Timestamp: time.Now(),
Host: "serverA",
}
}
func (s *Service) Test(options interface{}) error {
o, ok := options.(*testOptions)
if !ok {
return fmt.Errorf("unexpected options type %T", options)
}
hc := &HandlerConfig{
AppKey: o.AppKey,
Host: o.Host,
PrimaryProperty: o.PrimaryProperty,
SecondaryProperty: o.SecondaryProperty,
}
attrs := make(map[string]string, 0)
return s.Alert("", o.Message, "", o.Level, o.Timestamp, o.Data, hc, attrs)
}
func (s *Service) Alert(id string, message string, details string, level alert.Level, timestamp time.Time, data alert.EventData, hc *HandlerConfig, attrs map[string]string) error {
req, err := s.preparePost(id, message, details, level, timestamp, data, hc, attrs)
if err != nil {
return err
}
client := s.clientValue.Load().(*http.Client)
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
type response struct {
Error string `json:"error"`
}
r := &response{Error: fmt.Sprintf("failed to understand BigPanda response. code: %d content: %s", resp.StatusCode, string(body))}
b := bytes.NewReader(body)
dec := json.NewDecoder(b)
dec.Decode(r)
return errors.New(r.Error)
}
return nil
}
// BigPanda alert
// See https://docs.bigpanda.io/reference#alerts
/*
curl -X POST -H "Content-Type: application/json" \
-H "Authorization: Bearer <YOUR TOKEN>" \
https://api.bigpanda.io/data/v2/alerts \
-d '{ "app_key": "<YOUR APP KEY>", "status": "critical", "host": "production-database-1", "check": "CPU overloaded" }'
{
"app_key": "123",
"status": "critical",
"host": "production-database-1",
"timestamp": 1402302570,
"check": "CPU overloaded",
"description": "CPU is above upper limit (70%)",
"cluster": "production-databases",
"my_unique_attribute": "my_unique_value"
}
statuses: ok, critical, warning, acknowledged
"primary_property": "application",
"secondary_property": "host"
*/
func (s *Service) preparePost(id string, message string, details string, level alert.Level, timestamp time.Time, data alert.EventData, hc *HandlerConfig, attrs map[string]string) (*http.Request, error) {
c := s.config()
if !c.Enabled {
return nil, errors.New("service is not enabled")
}
bpUrl := hc.URL
if bpUrl == "" {
bpUrl = c.URL
}
alertUrl, err := url.Parse(bpUrl)
if err != nil {
return nil, err
}
var status string
switch level {
case alert.OK:
status = "ok"
case alert.Warning:
status = "warning"
case alert.Critical:
status = "critical"
case alert.Info:
status = "ok"
default:
status = "critical"
}
bpData := make(map[string]interface{})
if message != "" {
bpData["description"] = message
}
// ignore default details containing full json event
if details != "" {
unescapeString := html.UnescapeString(details)
if !strings.HasPrefix(unescapeString, "{") {
bpData["details"] = unescapeString
}
}
if id != "" {
bpData["check"] = id
}
bpData["task"] = fmt.Sprintf("%s:%s", data.TaskName, data.Name)
bpData["timestamp"] = timestamp.Unix()
bpData["status"] = status
// primary and secondary property
if hc.PrimaryProperty != "" {
bpData["primary_property"] = hc.PrimaryProperty
}
if hc.SecondaryProperty != "" {
bpData["secondary_property"] = hc.SecondaryProperty
}
// app key
if hc.AppKey != "" {
bpData["app_key"] = hc.AppKey
} else {
bpData["app_key"] = c.AppKey
}
// host is included in additional attributes
// auto option evaluation
auto := func(key string) bool {
return strings.Contains(strings.ToLower(c.AutoAttributes), key)
}
// add tags as additional attributes
if auto("tags") {
for k, v := range data.Tags {
bpData[k] = v
}
}
// fields tags as additional attributes
if auto("fields") {
for k, v := range data.Fields {
switch value := v.(type) {
case string:
bpData[k] = value
default:
b, err := json.Marshal(value)
if err != nil {
return nil, err
}
bpData[k] = string(b)
}
}
}
// add additional attributes (includes "host" attribute)
for k, v := range attrs {
bpData[k] = v
}
var postTemp bytes.Buffer
enc := json.NewEncoder(&postTemp)
if err := enc.Encode(bpData); err != nil {
return nil, err
}
var post bytes.Buffer
if err := json.Compact(&post, postTemp.Bytes()); err != nil {
return nil, err
}
req, err := http.NewRequest("POST", alertUrl.String(), &post)
req.Header.Add("Authorization", defaultTokenPrefix+" "+c.Token)
req.Header.Add("Content-Type", "application/json")
if err != nil {
return nil, err
}
return req, nil
}
// HandlerConfig defines the high-level struct required to connect to BigPanda
type HandlerConfig struct {
// BigPanda AppKey
AppKey string `mapstructure:"app-key"`
// webhook URL used to post alert.
// If empty uses the service URL from the configuration.
URL string `mapstructure:"url"`
// object that caused the alert
Host string `mapstructure:"host"`
// custom primary BigPanda property
PrimaryProperty string `mapstructure:"primary-property"`
// custom secondary BigPanda property
SecondaryProperty string `mapstructure:"secondary-property"`
// additional attributes
Attributes map[string]interface{} `mapstructure:"attributes"`
}
type handler struct {
s *Service
c HandlerConfig
diag Diagnostic
}
func (s *Service) Handler(c HandlerConfig, ctx ...keyvalue.T) (alert.Handler, error) {
return &handler{
s: s,
c: c,
diag: s.diag.WithContext(ctx...),
}, nil
}
func (h *handler) Handle(event alert.Event) {
td := event.TemplateData()
attrs, err := h.renderAttributes(&td)
if err != nil {
// error already reported
return
}
if err := h.s.Alert(
event.State.ID,
event.State.Message,
event.State.Details,
event.State.Level,
event.State.Time,
event.Data,
&h.c,
attrs,
); err != nil {
h.diag.Error("failed to send event to BigPanda", err)
}
}
func (h *handler) renderAttributes(td *alert.TemplateData) (map[string]string, error) {
var buf bytes.Buffer
render := func(name, template string) (string, error) {
if template != "" {
buf.Reset()
templateImpl, err := text.New(name).Parse(template)
if err != nil {
return "", err
}
templateImpl.Execute(&buf, td)
if err != nil {
return "", err
}
return buf.String(), nil
}
return "", nil
}
rendered := make(map[string]string)
rHost, err := render("host", h.c.Host)
if err != nil {
h.diag.TemplateError(err, keyvalue.KV("host", h.c.Host))
return nil, err
}
rendered["host"] = rHost
for k, v := range h.c.Attributes {
switch value := v.(type) {
case string:
rValue, err := render(k, value)
if err != nil {
h.diag.TemplateError(err, keyvalue.KV(k, value))
return nil, err
}
rendered[k] = rValue
default:
b, err := json.Marshal(value)
if err != nil {
h.diag.WithContext(keyvalue.KV("key", k)).Error("failed to encode tag value", err)
return nil, err
}
rendered[k] = string(b)
}
}
return rendered, nil
}