-
Notifications
You must be signed in to change notification settings - Fork 479
/
sending_service.go
294 lines (263 loc) · 9.02 KB
/
sending_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
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
/*******************************************************************************
* Copyright 2018 Dell Technologies Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*******************************************************************************/
package notifications
import (
"bytes"
"crypto/tls"
"errors"
"fmt"
"net"
"net/http"
mail "net/smtp"
"strconv"
"strings"
"time"
"github.com/edgexfoundry/edgex-go/internal/pkg/db"
notificationsConfig "github.com/edgexfoundry/edgex-go/internal/support/notifications/config"
"github.com/edgexfoundry/edgex-go/internal/support/notifications/interfaces"
"github.com/edgexfoundry/go-mod-core-contracts/clients/logger"
"github.com/edgexfoundry/go-mod-core-contracts/models"
)
func sendViaChannel(
n models.Notification,
c models.Channel,
receiver string,
lc logger.LoggingClient,
dbClient interfaces.DBClient,
config notificationsConfig.ConfigurationStruct) {
lc.Debug("Sending notification: " + n.Slug + ", via channel: " + c.String())
var tr models.TransmissionRecord
if c.Type == models.ChannelType(models.Email) {
tr = sendMail(n.Content, c.MailAddresses, n.ContentType, lc, config.Smtp)
} else {
tr = restSend(n.Content, c.Url, n.ContentType, lc)
}
t, err := persistTransmission(tr, n, c, receiver, lc, dbClient)
if err == nil {
handleFailedTransmission(t, lc, dbClient, config)
}
}
func resendViaChannel(
t models.Transmission,
lc logger.LoggingClient,
dbClient interfaces.DBClient,
config notificationsConfig.ConfigurationStruct) {
var tr models.TransmissionRecord
if t.Channel.Type == models.ChannelType(models.Email) {
tr = sendMail(t.Notification.Content, t.Channel.MailAddresses, t.Notification.ContentType, lc, config.Smtp)
} else {
tr = restSend(t.Notification.Content, t.Channel.Url, t.Notification.ContentType, lc)
}
t.ResendCount = t.ResendCount + 1
t.Status = tr.Status
t.Records = append(t.Records, tr)
err := dbClient.UpdateTransmission(t)
if err == nil {
handleFailedTransmission(t, lc, dbClient, config)
}
}
func getTransmissionRecord(msg string, st models.TransmissionStatus) models.TransmissionRecord {
tr := models.TransmissionRecord{}
tr.Sent = db.MakeTimestamp()
tr.Status = st
tr.Response = msg
return tr
}
func persistTransmission(
tr models.TransmissionRecord,
n models.Notification,
c models.Channel,
rec string,
lc logger.LoggingClient,
dbClient interfaces.DBClient) (models.Transmission, error) {
trx := models.Transmission{Notification: n, Receiver: rec, Channel: c, ResendCount: 0, Status: tr.Status}
trx.Records = []models.TransmissionRecord{tr}
id, err := dbClient.AddTransmission(trx)
if err != nil {
lc.Error("Transmission cannot be persisted: " + trx.String())
return trx, err
}
//We need to fetch this transmission for later use in retries, otherwise timestamp information will be lost.
trx, err = dbClient.GetTransmissionById(id)
if err != nil {
lc.Error("error fetching newly saved transmission: " + id)
return models.Transmission{}, err
}
return trx, nil
}
func sendMail(
message string,
addressees []string,
contentType string,
lc logger.LoggingClient,
smtp notificationsConfig.SmtpInfo) models.TransmissionRecord {
tr := getTransmissionRecord("SMTP server received", models.Sent)
smtpMessage := buildSmtpMessage(smtp.Sender, smtp.Subject, addressees, contentType, message)
err := smtpSend(addressees, smtpMessage, smtp)
if err != nil {
lc.Error("Problems sending message to: " + strings.Join(addressees, ",") + ", issue: " + err.Error())
tr.Status = models.Failed
tr.Response = err.Error()
return tr
}
return tr
}
func buildSmtpMessage(sender string, subject string, toAddresses []string, contentType string, message string) []byte {
smtpNewline := "\r\n"
// required CRLF at ends of lines and CRLF between header and body for SMTP RFC 822 style email
buf := bytes.NewBufferString("Subject: " + subject + smtpNewline)
buf.WriteString("From: " + sender + smtpNewline)
buf.WriteString("To: " + strings.Join(toAddresses, ",") + smtpNewline)
// only add MIME header if notification content type was set
// maybe provide charset overrides as well?
if contentType != "" {
buf.WriteString(fmt.Sprintf("MIME-version: 1.0;\r\nContent-Type: %s; charset=\"UTF-8\";\r\n", contentType))
}
buf.WriteString(smtpNewline)
//maximum line size is 1000
//split on newline first then break further as needed
for _, line := range strings.Split(message, smtpNewline) {
ln := 998
idx := 0
for len(line) > idx+ln {
buf.WriteString(line[idx:idx+ln] + smtpNewline)
idx += ln
}
buf.WriteString(line[idx:] + smtpNewline)
}
return []byte(buf.String())
}
func restSend(message string, url string, contentType string, lc logger.LoggingClient) models.TransmissionRecord {
tr := getTransmissionRecord("", models.Sent)
if contentType == "" {
contentType = "text/plain"
}
rs, err := http.Post(url, contentType, bytes.NewBuffer([]byte(message)))
if err != nil {
lc.Error("Problems sending message to: " + url)
lc.Error("Error indication was: " + err.Error())
tr.Status = models.Failed
tr.Response = err.Error()
return tr
}
tr.Response = "Got response status code: " + rs.Status
return tr
}
func handleFailedTransmission(
t models.Transmission,
lc logger.LoggingClient,
dbClient interfaces.DBClient,
config notificationsConfig.ConfigurationStruct) {
n := t.Notification
if t.ResendCount >= config.Writable.ResendLimit {
lc.Error("Too many transmission resend attempts! Giving up on transmission: " + t.ID + ", for notification: " + n.Slug)
}
if t.Status == models.Failed && n.Status != models.Escalated {
lc.Debug("Handling failed transmission for: " + t.ID + " for notification: " + t.Notification.Slug + ", resends so far: " + strconv.Itoa(t.ResendCount))
if n.Severity == models.Critical {
if t.ResendCount < config.Writable.ResendLimit {
time.AfterFunc(time.Second*5, func() {
criticalSeverityResend(t, lc, dbClient, config)
})
} else {
escalate(t, lc, dbClient, config)
t.Status = models.Trxescalated
dbClient.UpdateTransmission(t)
}
}
}
}
func deduceAuth(s notificationsConfig.SmtpInfo) (mail.Auth, error) {
if s.CheckUsername() == "" && s.Password == "" {
return nil, errors.New("Notifications: Expecting username")
}
if s.CheckUsername() != "" && s.Password == "" {
return nil, nil
}
if s.CheckUsername() == "" && s.Password != "" {
return nil, errors.New("Notifications: Expecting username")
}
return mail.PlainAuth("", s.CheckUsername(), s.Password, s.Host), nil
}
// The function smtpSend replicates the functionality provided by the SendMail function
// from smtp package. A rivision of standard function was needed because smtp.SendMail
// does not allow for set-reset of InsecureSkipVerify flag of tls.Config structure. This
// flag is needed to be manipulated for allowing the self-signed certificates.
//
// As it is replicating the functionality from smtp.SendMail, it borrows heavily from the
// original function in its design and implementation. This version adds new functionality
// for handling the SmtpInfo configuration and authentication management, along with the
// requirement of ability to set-reset the InsecureSkipVerify flag.
//
// This is using a lot of unexported methods and types from smtp package through exported
// interfaces, which makes it a little bit trickier to modify. Since, the intention for
// this function is to use it as a support function for handling the low level SMTP
// protocol mechanism, it is not exported.
func smtpSend(to []string, msg []byte, s notificationsConfig.SmtpInfo) error {
addr := s.Host + ":" + strconv.Itoa(s.Port)
auth, err := deduceAuth(s)
if err != nil {
return err
}
c, err := mail.Dial(addr)
if err != nil {
return errors.New("Notifications: Error dialing address")
}
defer c.Close()
serverName, _, err := net.SplitHostPort(addr)
if err != nil {
return err
}
if err = c.Hello(addr); err != nil {
return err
}
if ok, _ := c.Extension("STARTTLS"); ok {
config := &tls.Config{ServerName: serverName}
config.InsecureSkipVerify = s.EnableSelfSignedCert
if err = c.StartTLS(config); err != nil {
return err
}
}
if auth != nil {
if ok, _ := c.Extension("AUTH"); !ok {
return errors.New("Notifications: server doesn't support AUTH")
}
err = c.Auth(auth)
if err != nil {
return err
}
}
if err = c.Mail(s.Sender); err != nil {
return err
}
for _, addr := range to {
if err = c.Rcpt(addr); err != nil {
return err
}
}
w, err := c.Data()
if err != nil {
return err
}
_, err = w.Write(msg)
if err != nil {
return err
}
err = w.Close()
if err != nil {
return err
}
return c.Quit()
}