forked from influxdata/kapacitor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
104 lines (90 loc) · 1.82 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
package hipchat
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"log"
"net/http"
"net/url"
"github.com/influxdata/kapacitor"
)
type Service struct {
room string
token string
url string
global bool
logger *log.Logger
}
func NewService(c Config, l *log.Logger) *Service {
return &Service{
room: c.Room,
token: c.Token,
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(room, token, message string, level kapacitor.AlertLevel) error {
//Generate HipChat API Url including room and authentication token
if room == "" {
room = s.room
}
if token == "" {
token = s.token
}
var Url *url.URL
Url, err := url.Parse(s.url + "/" + room + "/notification?auth_token=" + token)
if err != nil {
return err
}
var color string
switch level {
case kapacitor.WarnAlert:
color = "yellow"
case kapacitor.CritAlert:
color = "red"
default:
color = "green"
}
postData := make(map[string]interface{})
postData["from"] = kapacitor.Product
postData["color"] = color
postData["message"] = message
postData["notify"] = true
var post bytes.Buffer
enc := json.NewEncoder(&post)
err = enc.Encode(postData)
if err != nil {
return err
}
resp, err := http.Post(Url.String(), "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 {
Error string `json:"error"`
}
r := &response{Error: "failed to understand HipChat response: " + string(body)}
b := bytes.NewReader(body)
dec := json.NewDecoder(b)
dec.Decode(r)
return errors.New(r.Error)
}
return nil
}