-
Notifications
You must be signed in to change notification settings - Fork 4
/
email.go
280 lines (246 loc) · 8.16 KB
/
email.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
package email
//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 . EmailDialer
import (
"bytes"
"crypto/tls"
"fmt"
"html/template"
"github.com/hashicorp/go-multierror"
"github.com/mitchellh/mapstructure"
"gopkg.in/gomail.v2"
"github.com/orange-cloudfoundry/statusetat/config"
"github.com/orange-cloudfoundry/statusetat/extemplate"
"github.com/orange-cloudfoundry/statusetat/models"
"github.com/orange-cloudfoundry/statusetat/notifiers"
)
func init() {
notifiers.RegisterNotifier(&Email{})
}
const (
DefaultSubjectIncident = "[{{ .TitleSite }} {{ .Incident.State | textIncidentState | title }} Incident] {{ .IncidentTitle | title }}"
DefaultTxtIncident = `<h1>{{ .IncidentTitle | title }} - <span style="color: {{ .Incident.State | colorHexIncidentState }};">{{ .Incident.State | textIncidentState | title }}</span></h1>
<ul>
<li><b>Impacted components</b>: {{ join .Incident.Components.Inline ", " }}</li>
<li><b>Impact</b>: {{ .Incident.ComponentState | textState }}</li>
<li><b>Trigger at</b>: {{ .Incident.CreatedAt | timeFormat }}</li>
<li><b>Link</b>: <a href="{{ .Link }}">{{ .Link }}</a></li>
</ul>
<h2>Message</h2>
<p>
{{ .Content | markdown }}
</p>
`
DefaultTxtScheduled = `<h1>Scheduled Maintenance{{if eq .Incident.State 0 }} has started{{end}}{{if eq .Incident.State 1 }} has finished{{end}}: {{ .IncidentTitle | title }}</h1>
<ul>
<li><b>Components involved</b>: {{ join .Incident.Components.Inline ", " }}</li>
<li><b>Scheduled at</b>: {{ .Incident.CreatedAt | timeFormat }}</li>
<li><b>{{if not ( eq .Incident.State 1) }}Planned{{else}}Final{{end}} Duration</b>: {{ humanDuration .Incident.CreatedAt .Incident.ScheduledEnd }}</li>
<li><b>Link</b>: <a href="{{ .Link }}">{{ .Link }}</a></li>
</ul>
<h2>Message</h2>
<p>
{{ .Content | markdown }}
</p>
`
DefaultSubjectScheduled = "[{{ .TitleSite }} Scheduled task{{if eq .Incident.State 0 }} has started{{end}}{{if eq .Incident.State 1 }} has finished{{end}}] {{ .IncidentTitle | title }}"
DefaultFrom = "no-reply@local"
)
type EmailDialer interface {
DialAndSend(m ...*gomail.Message) error
}
type OptsEmail struct {
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
Username string `mapstructure:"username"`
Password string `mapstructure:"password"`
UseSSl bool `mapstructure:"use_ssl"`
SubjectIncident string `mapstructure:"subject_incident"`
TxtIncident string `mapstructure:"txt_incident"`
SubjectScheduled string `mapstructure:"subject_scheduled"`
TxtScheduled string `mapstructure:"txt_scheduled"`
Subscribers []string `mapstructure:"subscribers"`
From string `mapstructure:"from"`
SkipInsecure bool `mapstructure:"insecure_skip_verify"`
}
type Email struct {
dialer EmailDialer
id string
opts OptsEmail
titleSite string
tplSubjectIncident *template.Template
tplTxtIncident *template.Template
tplSubjectScheduled *template.Template
tplTxtScheduled *template.Template
baseUrl string
}
func (n *Email) SetDialer(dialer EmailDialer) {
n.dialer = dialer
}
type SmtpInfo struct {
User string
Password string
Host string
Port int
}
func (n Email) Creator(params map[string]interface{}, baseInfo config.BaseInfo) (notifiers.Notifier, error) {
var opts OptsEmail
err := mapstructure.Decode(params, &opts)
if err != nil {
return nil, err
}
if opts.SubjectIncident == "" {
opts.SubjectIncident = DefaultSubjectIncident
}
tplSubjIncident, err := template.New("subjectIncident").Funcs(extemplate.Funcs()).Parse(opts.SubjectIncident)
if err != nil {
return nil, fmt.Errorf("Error when parsing template subject incident: %s", err.Error())
}
if opts.SubjectScheduled == "" {
opts.SubjectScheduled = DefaultSubjectScheduled
}
tplSubjScheduled, err := template.New("subjectScheduled").Funcs(extemplate.Funcs()).Parse(opts.SubjectScheduled)
if err != nil {
return nil, fmt.Errorf("Error when parsing template subject scheduled: %s", err.Error())
}
if opts.TxtIncident == "" {
opts.TxtIncident = DefaultTxtIncident
}
tplTxtIncident, err := template.New("TxtIncident").Funcs(extemplate.Funcs()).Parse(opts.TxtIncident)
if err != nil {
return nil, fmt.Errorf("Error when parsing template text incident: %s", err.Error())
}
if opts.TxtScheduled == "" {
opts.TxtScheduled = DefaultTxtScheduled
}
tplTxtScheduled, err := template.New("TxtScheduled").Funcs(extemplate.Funcs()).Parse(opts.TxtScheduled)
if err != nil {
return nil, fmt.Errorf("Error when parsing template text scheduled: %s", err.Error())
}
if opts.Host == "" {
return nil, fmt.Errorf("Host for email is mandatory")
}
if opts.From == "" {
opts.From = DefaultFrom
}
dialer := loadDialer(opts)
return &Email{
dialer: dialer,
id: opts.Host,
opts: opts,
titleSite: baseInfo.Title,
tplSubjectIncident: tplSubjIncident,
tplTxtIncident: tplTxtIncident,
tplSubjectScheduled: tplSubjScheduled,
tplTxtScheduled: tplTxtScheduled,
baseUrl: baseInfo.BaseURL,
}, nil
}
func loadDialer(opts OptsEmail) *gomail.Dialer {
port := 25
if opts.Port > 0 {
port = opts.Port
}
dialer := &gomail.Dialer{
Host: opts.Host,
Port: port,
Username: opts.Username,
Password: opts.Password,
SSL: opts.UseSSl,
}
if opts.SkipInsecure {
dialer.TLSConfig = &tls.Config{InsecureSkipVerify: opts.SkipInsecure}
}
return dialer
}
func (n Email) Name() string {
return "email"
}
func (n Email) Description() string {
return `Sending notifications for incident and scheduled task only to subscribers which subscribed by email or/and set in config.
If admin trigger manually an notification this notifier **will not** re-notify subscribed users.`
}
func (n Email) Id() string {
return n.id
}
func (n Email) Notify(notifyReq *models.NotifyRequest) error {
incident := notifyReq.Incident
if len(incident.Messages) > 1 && incident.State != models.Resolved {
return nil
}
subscribers := make([]string, 0)
subscribers = append(subscribers, notifyReq.Subscribers...)
subscribers = append(subscribers, n.opts.Subscribers...)
return n.notifySubscriber(incident, subscribers)
}
func (n Email) notifySubscriber(incident models.Incident, subscribers []string) error {
if len(subscribers) == 0 {
return nil
}
if len(incident.Messages) > 1 && incident.State != models.Resolved {
return nil
}
subject, text, err := n.incidentToMail(incident)
if err != nil {
return err
}
var result error
for _, sub := range subscribers {
finalText := text + fmt.Sprintf(`<br/><br/>
<hr/>
<a href="%s/v1/unsubscribe?email=%s">Click here for unsubscribe to email</a>`, n.baseUrl, sub)
err := n.sendEmailTo(subject, finalText, sub)
if err != nil {
result = multierror.Append(result, err)
}
}
return result
}
func (n Email) incidentToMail(incident models.Incident) (subject string, textHtml string, err error) {
title := incident.MainMessage().Title
msg := incident.MainMessage()
if incident.State == models.Resolved {
msg = incident.LastMessage()
}
incidentStruct := struct {
Incident models.Incident
TitleSite string
IncidentTitle string
Link string
UnsubscribeLink string
Content string
}{
IncidentTitle: title,
Incident: incident,
TitleSite: n.titleSite,
Link: fmt.Sprintf("%s/incidents/%s", n.baseUrl, incident.GUID),
Content: msg.Content,
}
subjTpl := n.tplSubjectIncident
txtTpl := n.tplTxtIncident
if incident.IsScheduled {
subjTpl = n.tplSubjectScheduled
txtTpl = n.tplTxtScheduled
}
buf := &bytes.Buffer{}
err = subjTpl.Execute(buf, incidentStruct)
if err != nil {
return "", "", err
}
subject = buf.String()
buf.Reset()
err = txtTpl.Execute(buf, incidentStruct)
if err != nil {
return "", "", err
}
textHtml = buf.String()
return subject, textHtml, nil
}
func (n Email) sendEmailTo(subject, textHtml, to string) error {
m := gomail.NewMessage()
m.SetHeader("From", n.opts.From)
m.SetHeader("To", to)
m.SetHeader("Subject", subject)
m.SetHeader("Auto-submitted", "auto-generated")
m.SetBody("text/html", textHtml)
return n.dialer.DialAndSend(m)
}