This repository has been archived by the owner on Jan 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
213 lines (179 loc) · 4.54 KB
/
main.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
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"regexp"
"strings"
"time"
"text/template"
"github.com/fortnoxab/ginprometheus"
"github.com/gin-gonic/gin"
"github.com/jonaz/ginlogrus"
"github.com/jonaz/gograce"
alerttemplate "github.com/prometheus/alertmanager/template"
"github.com/sirupsen/logrus"
)
var port = flag.String("port", "8080", "Port to listen to")
var postPath = flag.String("path", "/alertmanager", "What path to listen to for POST requests")
var logFormat = flag.String("log-format", "json", "can be empty string or json")
var logLevel = flag.String("log-level", "info", "Can be one of:"+strings.Join(validLogLevels(), ","))
var templateString = flag.String("template-string", messageTemplate, "template for the messages sent to hangouts chat")
var messageTemplate = `<users/all>
*{{ .Labels.alertname }} - {{.Status | toUpper}}*
{{ range .Labels.SortedPairs -}}
*{{ .Name }}*: {{ .Value}}
{{ end -}}
{{ range .Annotations.SortedPairs -}}
*{{ .Name }}*: {{ .Value}}
{{ end -}}
Source: <{{ .GeneratorURL }}|Show in Prometheus>
`
func main() {
flag.Parse()
lvl, err := logrus.ParseLevel(*logLevel)
if err != nil {
log.Fatalln(err)
}
log.Printf("Setting logrus logging level to %s\n", lvl)
logrus.SetLevel(lvl)
if *logFormat == "json" {
logrus.SetFormatter(&logrus.JSONFormatter{})
}
srv, shutdown := gograce.NewServerWithTimeout(5 * time.Second)
srv.Handler = getWebRouter()
srv.Addr = ":" + *port
logrus.Error(srv.ListenAndServe())
<-shutdown
}
func validLogLevels() []string {
lvls := make([]string, len(logrus.AllLevels))
for k, v := range logrus.AllLevels {
lvls[k] = v.String()
}
return lvls
}
func getWebRouter() http.Handler {
router := gin.New()
router.Use(ginlogrus.New(logrus.StandardLogger(), "/health", "/metrics"), gin.Recovery())
m := ginprometheus.New("http")
m.Use(router)
router.GET("/health", func(c *gin.Context) {
c.Status(http.StatusOK)
})
router.POST(*postPath, handleAlert)
return router
}
// defaultFuncs is copied from alertmanager templates
var defaultFuncs = template.FuncMap{
"toUpper": strings.ToUpper,
"toLower": strings.ToLower,
"title": strings.Title,
// join is equal to strings.Join but inverts the argument order
// for easier pipelining in templates.
"join": func(sep string, s []string) string {
return strings.Join(s, sep)
},
"reReplaceAll": func(pattern, repl, text string) string {
re := regexp.MustCompile(pattern)
return re.ReplaceAllString(text, repl)
},
}
type alertData struct {
alerttemplate.Alert
QueryParams url.Values
}
type textRequest struct {
Text string `json:"text"`
}
func handleAlert(c *gin.Context) {
defer c.Request.Body.Close()
dec := json.NewDecoder(c.Request.Body)
data := alerttemplate.Data{}
err := dec.Decode(&data)
if err != nil {
logrus.Error(err)
c.AbortWithStatus(http.StatusInternalServerError)
return
}
for _, alert := range data.Alerts {
err := sendAlert(alert, c.Request.URL.Query())
if err != nil {
c.Error(err)
continue
}
}
if len(c.Errors.Errors()) > 0 {
for _, v := range c.Errors {
logrus.Error(v)
}
c.AbortWithStatus(http.StatusInternalServerError)
return
}
c.Status(http.StatusOK)
}
func sendAlert(data alerttemplate.Alert, getParams url.Values) error {
hangoutsURL, err := url.Parse(getParams.Get("url"))
if err != nil {
return err
}
mentionAll, err := url.Parse(getParams.Get("mention"))
if err != nil {
return err
}
alert := &alertData{
Alert: data,
QueryParams: getParams,
}
tmpl, err := generateTemplate(*templateString, alert)
if err != nil {
return err
}
if mentionAll.String() == "false" {
tmpl = strings.Replace(tmpl, "<users/all>\n", "", 1)
}
textReq := &textRequest{
Text: tmpl,
}
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
err = enc.Encode(&textReq)
if err != nil {
return err
}
return sendChatMessage(hangoutsURL, buf)
}
func sendChatMessage(u *url.URL, data io.Reader) error {
req, err := http.NewRequest("POST", u.String(), data)
if err != nil {
return err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("Error from google: %s", string(body))
}
return nil
}
func generateTemplate(s string, data interface{}) (string, error) {
tmpl, err := template.New("").Funcs(defaultFuncs).Parse(s)
if err != nil {
return "", err
}
var to bytes.Buffer
err = tmpl.Execute(&to, data)
return to.String(), err
}