forked from influxdata/kapacitor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
125 lines (106 loc) · 2.34 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
package opsgenie
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"log"
"net/http"
"time"
"github.com/influxdata/kapacitor"
)
type Service struct {
apikey string
teams []string
recipients []string
url string
recovery_url string
global bool
logger *log.Logger
}
func NewService(c Config, l *log.Logger) *Service {
return &Service{
teams: c.Teams,
recipients: c.Recipients,
apikey: c.APIKey,
url: c.URL + "/",
recovery_url: c.RecoveryURL + "/",
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(teams []string, recipients []string, messageType, message, entityID string, t time.Time, details interface{}) error {
ogData := make(map[string]interface{})
url := s.url
ogData["apiKey"] = s.apikey
ogData["entity"] = entityID
ogData["alias"] = entityID
ogData["message"] = message
ogData["note"] = ""
ogData["monitoring_tool"] = kapacitor.Product
//Extra Fields (can be used for filtering)
ogDetails := make(map[string]interface{})
ogDetails["Level"] = messageType
ogDetails["Monitoring Tool"] = "Kapacitor"
ogData["details"] = ogDetails
switch messageType {
case "RECOVERY":
url = s.recovery_url
ogData["note"] = message
}
if details != nil {
b, err := json.Marshal(details)
if err != nil {
return err
}
ogData["description"] = string(b)
}
if len(teams) == 0 {
teams = s.teams
}
if len(teams) > 0 {
ogData["teams"] = teams
}
if len(recipients) == 0 {
recipients = s.recipients
}
if len(recipients) > 0 {
ogData["recipients"] = recipients
}
// Post data to VO
var post bytes.Buffer
enc := json.NewEncoder(&post)
err := enc.Encode(ogData)
if err != nil {
return err
}
resp, err := http.Post(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: "failed to understand OpsGenie response: " + string(body)}
b := bytes.NewReader(body)
dec := json.NewDecoder(b)
dec.Decode(r)
return errors.New(r.Message)
}
return nil
}