mirror of https://github.com/shunfei/cronsun
noticer: job 执行失败时发送邮件
parent
48d8565690
commit
4059ac9bc6
|
@ -34,12 +34,14 @@ func main() {
|
|||
return
|
||||
}
|
||||
|
||||
noticer, err := models.NewMail(10 * time.Second)
|
||||
if err != nil {
|
||||
log.Error(err.Error())
|
||||
return
|
||||
if conf.Config.Mail.Enable {
|
||||
noticer, err := models.NewMail(10 * time.Second)
|
||||
if err != nil {
|
||||
log.Error(err.Error())
|
||||
return
|
||||
}
|
||||
go models.StartNoticer(noticer)
|
||||
}
|
||||
go models.StartNoticer(noticer)
|
||||
|
||||
go func() {
|
||||
err := httpServer.Serve(httpL)
|
||||
|
|
|
@ -79,9 +79,12 @@ type webConfig struct {
|
|||
|
||||
type MailConf struct {
|
||||
Enable bool
|
||||
To []string
|
||||
// 如果配置,则按 http api 方式发送,否则按 smtp 方式发送
|
||||
HttpApi string
|
||||
// 如果此时间段内没有邮件发送,则关闭 SMTP 连接,单位/秒
|
||||
Keepalive int64
|
||||
gomail.Dialer
|
||||
*gomail.Dialer
|
||||
}
|
||||
|
||||
type Security struct {
|
||||
|
|
|
@ -1,5 +1,7 @@
|
|||
{
|
||||
"Enable": true,
|
||||
"To": ["na@nb.com"],
|
||||
"#HttpAPI": "如有此字段,则按 http api 方式发送",
|
||||
"#Keepalive": "如果此时间段内没有邮件发送,则关闭 SMTP 连接,单位/秒",
|
||||
"Keepalive": 30,
|
||||
"#doc": "https://godoc.org/github.com/go-gomail/gomail#Dialer",
|
||||
|
|
|
@ -62,6 +62,8 @@ type Job struct {
|
|||
AvgTime int64 `json:"avg_time"`
|
||||
// 执行失败发送通知
|
||||
FailNotify bool `json:"fail_notify"`
|
||||
// 发送通知地址
|
||||
To []string
|
||||
|
||||
// 执行任务的结点,用于记录 job log
|
||||
runOn string
|
||||
|
@ -537,9 +539,45 @@ func (j *Job) Success(t time.Time, out string) {
|
|||
}
|
||||
|
||||
func (j *Job) Fail(t time.Time, msg string) {
|
||||
j.Notify(t, msg)
|
||||
CreateJobLog(j, t, msg, false)
|
||||
}
|
||||
|
||||
func (j *Job) Notify(t time.Time, msg string) {
|
||||
if !conf.Config.Mail.Enable || !j.FailNotify {
|
||||
return
|
||||
}
|
||||
|
||||
ts := t.Format(time.RFC3339)
|
||||
body := "job: " + j.Key() + "\n" +
|
||||
"node: " + j.runOn + "\n" +
|
||||
"time: " + ts + "\n" +
|
||||
"err: " + msg
|
||||
|
||||
m := Message{
|
||||
Subject: "node[" + j.runOn + "] job[" + j.ID + "] time[" + ts + " exec failed",
|
||||
Body: body,
|
||||
}
|
||||
if len(conf.Config.Mail.To) > 0 {
|
||||
m.To = append(m.To, conf.Config.Mail.To...)
|
||||
}
|
||||
if len(j.To) > 0 {
|
||||
m.To = append(m.To, j.To...)
|
||||
}
|
||||
|
||||
data, err := json.Marshal(m)
|
||||
if err != nil {
|
||||
log.Warnf("job[%s] send notice fail, err: %s", j.Key(), err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
_, err = DefalutClient.Put(conf.Config.Noticer+"/"+j.runOn, string(data))
|
||||
if err != nil {
|
||||
log.Warnf("job[%s] send notice fail, err: %s", j.Key(), err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (j *Job) Avg(t, et time.Time) {
|
||||
execTime := int64(et.Sub(t) / time.Millisecond)
|
||||
if j.AvgTime == 0 {
|
||||
|
|
Loading…
Reference in New Issue