forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sender.go
451 lines (377 loc) · 10.5 KB
/
sender.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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
package notifiers
import (
"bytes"
"crypto/sha256"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"mime/multipart"
"net"
"net/http"
"net/smtp"
"net/textproto"
"strconv"
"strings"
"time"
"github.com/prometheus/common/model"
"github.com/rancher/types/apis/management.cattle.io/v3"
)
type Message struct {
Title string
Content string
}
type wechatToken struct {
AccessToken string `json:"access_token"`
}
type wechatResponse struct {
Code int `json:"code"`
Error string `json:"error"`
}
func SendMessage(notifier *v3.Notifier, recipient string, msg *Message) error {
if notifier.Spec.SlackConfig != nil {
if recipient == "" {
recipient = notifier.Spec.SlackConfig.DefaultRecipient
}
return TestSlack(notifier.Spec.SlackConfig.URL, recipient, msg.Content)
}
if notifier.Spec.SMTPConfig != nil {
s := notifier.Spec.SMTPConfig
if recipient == "" {
recipient = s.DefaultRecipient
}
return TestEmail(s.Host, s.Password, s.Username, int(s.Port), s.TLS, msg.Title, msg.Content, recipient, s.Sender)
}
if notifier.Spec.PagerdutyConfig != nil {
return TestPagerduty(notifier.Spec.PagerdutyConfig.ServiceKey, msg.Content)
}
if notifier.Spec.WechatConfig != nil {
s := notifier.Spec.WechatConfig
if recipient == "" {
recipient = s.DefaultRecipient
}
return TestWechat(notifier.Spec.WechatConfig.Secret, notifier.Spec.WechatConfig.Agent, notifier.Spec.WechatConfig.Corp, notifier.Spec.WechatConfig.RecipientType, recipient, msg.Content)
}
if notifier.Spec.WebhookConfig != nil {
return TestWebhook(notifier.Spec.WebhookConfig.URL, msg.Content)
}
return errors.New("Notifier not configured")
}
func TestPagerduty(key, msg string) error {
if msg == "" {
msg = "Pagerduty setting validated"
}
pd := &pagerDutyEvent{
RoutingKey: key,
EventAction: "trigger",
Payload: pagerDutyEventPayload{
Summary: msg,
Source: "rancher",
Severity: "info",
Group: "Rancher alert testing",
},
}
url := "https://events.pagerduty.com/v2/enqueue"
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(pd); err != nil {
return err
}
resp, err := http.Post(url, "application/json", &buf)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
return fmt.Errorf("http status code is %d, not include in the 2xx success HTTP status codes", resp.StatusCode)
}
return nil
}
func TestWechat(secret, agent, corp, receiverType, receiver, msg string) error {
if msg == "" {
msg = "Wechat setting validated"
}
req, err := http.NewRequest(http.MethodGet, "https://qyapi.weixin.qq.com/cgi-bin/gettoken", nil)
if err != nil {
return err
}
q := req.URL.Query()
q.Add("corpid", corp)
q.Add("corpsecret", secret)
req.URL.RawQuery = q.Encode()
client := &http.Client{
Timeout: 15 * time.Second,
}
var wechatToken wechatToken
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
requestBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if err := json.Unmarshal(requestBytes, &wechatToken); err != nil {
return err
}
if wechatToken.AccessToken == "" {
return fmt.Errorf("Invalid APISecret for CorpID. %s", corp)
}
wc := &wechatEvent{
AgentID: agent,
MsgType: "text",
Text: wechatEventPayload{
Content: msg,
},
}
switch receiverType {
case "tag":
wc.ToTag = receiver
case "user":
wc.ToUser = receiver
default:
wc.ToParty = receiver
}
url := "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + wechatToken.AccessToken
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(wc); err != nil {
return err
}
resp, err = http.Post(url, "application/json", &buf)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
return fmt.Errorf("http status code is %d, not include in the 2xx success HTTP status codes", resp.StatusCode)
}
requestBytes, err = ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
var weResp wechatResponse
if err := json.Unmarshal(requestBytes, &weResp); err != nil {
return err
}
if weResp.Code != 0 {
return fmt.Errorf("Failed to send Wechat message. %s", weResp.Error)
}
return nil
}
func TestWebhook(url, msg string) error {
if msg == "" {
msg = "Webhook setting validated"
}
alertList := model.Alerts{
&model.Alert{
Labels: map[model.LabelName]model.LabelValue{
model.LabelName("test_msg"): model.LabelValue(msg),
},
},
}
alertData, err := json.Marshal(alertList)
if err != nil {
return err
}
resp, err := http.Post(url, "application/json", bytes.NewBuffer(alertData))
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
return fmt.Errorf("http status code is %d, not include in the 2xx success HTTP status codes", resp.StatusCode)
}
return nil
}
func TestSlack(url, channel, msg string) error {
if msg == "" {
msg = "Slack setting validated"
}
req := struct {
Text string `json:"text"`
Channel string `json:"channel"`
}{}
req.Text = msg
req.Channel = channel
data, err := json.Marshal(req)
if err != nil {
return err
}
resp, err := http.Post(url, "application/json", bytes.NewBuffer(data))
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("http status code is not 200")
}
res, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if string(res) != "ok" {
return fmt.Errorf("http response is not ok")
}
return nil
}
func TestEmail(host, password, username string, port int, requireTLS bool, title, content, receiver, sender string) error {
if content == "" {
content = "Alert Name: Test SMTP setting"
}
c, err := smtpInit(host, port)
if err != nil {
return err
}
defer c.Quit()
if err := smtpPrepare(c, host, password, username, port, requireTLS); err != nil {
return err
}
return smtpSend(c, title, content, receiver, sender)
}
func smtpInit(host string, port int) (*smtp.Client, error) {
var c *smtp.Client
smartHost := host + ":" + strconv.Itoa(port)
timeout := 15 * time.Second
if port == 465 {
conn, err := tls.DialWithDialer(&net.Dialer{Timeout: timeout}, "tcp", smartHost, &tls.Config{ServerName: host})
if err != nil {
return nil, fmt.Errorf("Failed to connect smtp server: %v", err)
}
c, err = smtp.NewClient(conn, smartHost)
if err != nil {
return nil, fmt.Errorf("Failed to connect smtp server: %v", err)
}
} else {
conn, err := net.DialTimeout("tcp", smartHost, timeout)
if err != nil {
return nil, fmt.Errorf("Failed to connect smtp server: %v", err)
}
c, err = smtp.NewClient(conn, smartHost)
if err != nil {
return nil, fmt.Errorf("Failed to connect smtp server: %v", err)
}
}
return c, nil
}
func smtpPrepare(c *smtp.Client, host, password, username string, port int, requireTLS bool) error {
smartHost := host + ":" + strconv.Itoa(port)
if requireTLS {
if ok, _ := c.Extension("STARTTLS"); !ok {
return fmt.Errorf("Require TLS but %q does not advertise the STARTTLS extension", smartHost)
}
tlsConf := &tls.Config{ServerName: host}
if err := c.StartTLS(tlsConf); err != nil {
return fmt.Errorf("Starttls failed: %v", err)
}
}
if ok, mech := c.Extension("AUTH"); ok {
if password != "" && username != "" {
auth, err := auth(mech, username, password)
if err != nil {
return fmt.Errorf("Authentication failed: %v", err)
}
if auth != nil {
if err := c.Auth(auth); err != nil {
return fmt.Errorf("Authentication failed: %v", err)
}
}
}
}
return nil
}
func smtpSend(c *smtp.Client, title, content, receiver, sender string) error {
if err := c.Mail(sender); err != nil {
return fmt.Errorf("Failed to set sender: %v", err)
}
if err := c.Rcpt(receiver); err != nil {
return fmt.Errorf("Failed to set recipient: %v", err)
}
wc, err := c.Data()
if err != nil {
return err
}
defer wc.Close()
fmt.Fprintf(wc, "%s: %s\r\n", "From", sender)
fmt.Fprintf(wc, "%s: %s\r\n", "To", receiver)
fmt.Fprintf(wc, "%s: %s\r\n", "Subject", title)
buffer := &bytes.Buffer{}
multipartWriter := multipart.NewWriter(buffer)
fmt.Fprintf(wc, "Date: %s\r\n", time.Now().Format(time.RFC1123Z))
fmt.Fprintf(wc, "Content-Type: multipart/alternative; boundary=%s\r\n", multipartWriter.Boundary())
fmt.Fprintf(wc, "MIME-Version: 1.0\r\n")
fmt.Fprintf(wc, "\r\n")
w, err := multipartWriter.CreatePart(textproto.MIMEHeader{"Content-Type": {"text/html; charset=UTF-8"}})
if err != nil {
return fmt.Errorf("Failed to send test email: %s", err)
}
_, err = w.Write([]byte(content))
if err != nil {
return fmt.Errorf("Failed to send test email: %s", err)
}
multipartWriter.Close()
_, err = wc.Write(buffer.Bytes())
if err != nil {
return fmt.Errorf("Failed to send test email: %s", err)
}
return nil
}
type pagerDutyEventPayload struct {
Summary string `json:"summary"`
Source string `json:"source"`
Severity string `json:"severity"`
Group string `json:"group"`
}
type pagerDutyEvent struct {
RoutingKey string `json:"routing_key"`
EventAction string `json:"event_action"`
Payload pagerDutyEventPayload `json:"payload"`
}
func hashKey(s string) string {
h := sha256.New()
h.Write([]byte(s))
return fmt.Sprintf("%x", h.Sum(nil))
}
type wechatEventPayload struct {
Content string `json:"content"`
}
type wechatEvent struct {
ToParty string `json:"toparty"`
ToUser string `json:"touser"`
ToTag string `json:"totag"`
AgentID string `json:"agentid"`
MsgType string `json:"msgtype"`
Text wechatEventPayload `json:"text"`
}
func auth(mechs string, username, password string) (smtp.Auth, error) {
for _, mech := range strings.Split(mechs, " ") {
switch mech {
case "LOGIN":
if password == "" {
continue
}
return &loginAuth{username, password}, nil
}
}
return nil, fmt.Errorf("smtp server does not support login auth")
}
type loginAuth struct {
username, password string
}
func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
return "LOGIN", []byte{}, nil
}
// Used for AUTH LOGIN. (Maybe password should be encrypted)
func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
if more {
switch strings.ToLower(string(fromServer)) {
case "username:":
return []byte(a.username), nil
case "password:":
return []byte(a.password), nil
default:
return nil, errors.New("unexpected server challenge")
}
}
return nil, nil
}