forked from influxdata/kapacitor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
94 lines (83 loc) · 1.87 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
package victorops
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
"github.com/influxdata/kapacitor"
)
type Service struct {
routingKey string
url string
global bool
logger *log.Logger
}
func NewService(c Config, l *log.Logger) *Service {
return &Service{
routingKey: c.RoutingKey,
url: c.URL + "/" + c.APIKey + "/",
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(routingKey, messageType, message, entityID string, t time.Time, details interface{}) error {
voData := make(map[string]interface{})
voData["message_type"] = messageType
voData["entity_id"] = entityID
voData["state_message"] = message
voData["timestamp"] = t.Unix()
voData["monitoring_tool"] = kapacitor.Product
if details != nil {
b, err := json.Marshal(details)
if err != nil {
return err
}
voData["data"] = string(b)
}
if routingKey == "" {
routingKey = s.routingKey
}
// Post data to VO
var post bytes.Buffer
enc := json.NewEncoder(&post)
err := enc.Encode(voData)
if err != nil {
return err
}
resp, err := http.Post(s.url+routingKey, "application/json", &post)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
if resp.StatusCode == http.StatusNotFound {
return errors.New("URL or API key not found: 404")
}
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 VictorOps 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
}