-
Notifications
You must be signed in to change notification settings - Fork 492
/
service.go
91 lines (80 loc) · 1.71 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
package pagerduty
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"github.com/influxdata/kapacitor"
)
const eventType = "trigger"
type Service struct {
HTTPDService interface {
URL() string
}
serviceKey string
url string
global bool
logger *log.Logger
}
func NewService(c Config, l *log.Logger) *Service {
return &Service{
serviceKey: c.ServiceKey,
url: c.URL,
global: c.Global,
logger: l,
}
}
func (s *Service) Open() error {
return nil
}
func (s *Service) Close() error {
return nil
}
func (s *Service) Global() bool {
return s.global
}
func (s *Service) Alert(incidentKey, desc string, details interface{}) error {
pData := make(map[string]string)
pData["service_key"] = s.serviceKey
pData["event_type"] = eventType
pData["description"] = desc
pData["client"] = kapacitor.Product
pData["client_url"] = s.HTTPDService.URL()
if details != nil {
b, err := json.Marshal(details)
if err != nil {
return err
}
pData["details"] = string(b)
}
// Post data to PagerDuty
var post bytes.Buffer
enc := json.NewEncoder(&post)
err := enc.Encode(pData)
if err != nil {
return err
}
resp, err := http.Post(s.url, "application/json", &post)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
type response struct {
Message string `json:"message"`
}
r := &response{Message: fmt.Sprintf("failed to understand PagerDuty response. code: %d content: %s", resp.StatusCode, string(body))}
b := bytes.NewReader(body)
dec := json.NewDecoder(b)
dec.Decode(r)
return errors.New(r.Message)
}
return nil
}