-
Notifications
You must be signed in to change notification settings - Fork 0
/
gocron.go
295 lines (266 loc) · 6.63 KB
/
gocron.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
// Copyright 2018 Mathieu Lonjaret
// Package gocron allows to regularly run a job, and to be notified,
// when that run failed. Notifications can happen through e-mail, browser
// notifications, or a local file.
package gocron
import (
"fmt"
"html/template"
"io/ioutil"
"log"
"net"
"net/http"
"net/smtp"
"os"
"os/exec"
"runtime"
"time"
)
// TODO(mpl): docs
// TODO(mpl): option to skip running if previous run is still running.
// Activity detection as well? probably not.
type Cron struct {
Interval time.Duration
LifeTime time.Duration // if set, we (and our webserver) exit after this time
Job func() error
Mail *MailAlert
Notif *Notification
File *StaticFile
}
func (c *Cron) Run() {
start := time.Now()
// TODO(mpl): maybe give the option to not have a file? meh.
c.File = c.File.init()
c.Notif.init()
mailchan := make(chan struct{})
for {
if jobErr := c.Job(); jobErr != nil {
if err := c.Notif.Send(jobErr); err != nil {
notiFail := fmt.Errorf("Could not open notification: %v", err)
if err := c.File.WriteAlert(notiFail); err != nil {
log.Fatal(err)
}
}
if err := c.File.WriteAlert(jobErr); err != nil {
log.Fatal(err)
}
// TODO(mpl): c.Mail.Send indeed does check that c.Mail is not nil, but I don't
// want the time out message in the log if we did not even try to send e-mail.
// Better fix later.
if c.Mail != nil {
go func() {
if err := c.Mail.Send(jobErr); err != nil {
mailFail := fmt.Errorf("Could not send mail alert %q: %v",
c.Mail.Msg(), err)
if err := c.File.WriteAlert(mailFail); err != nil {
log.Fatal(err)
}
mailchan <- struct{}{}
}
}()
select {
case <-mailchan:
case <-time.After(10 * time.Second):
mailFail := fmt.Errorf("timed out sending mail alert %q", c.Mail.Msg())
c.File.WriteAlert(mailFail)
}
}
}
// TODO(mpl): maybe remove this, now that we have LifeTime. But it is breaking,
// so think about it.
if c.Interval == 0 {
break
}
time.Sleep(c.Interval)
if time.Now().After(start.Add(c.LifeTime)) {
return
}
}
}
type MailAlert struct {
Subject string
msg string
To []string
From string
SMTP string
}
func (m *MailAlert) Msg() string {
if m == nil {
return ""
}
return m.msg
}
func (m *MailAlert) Send(alert error) error {
if m == nil {
return nil
}
m.msg = fmt.Sprintf("Subject: %s\nFrom: %s\n\n%v", m.Subject, m.From, alert)
c, err := smtp.Dial(m.SMTP)
if err != nil {
return err
}
defer c.Close()
if err = c.Mail(m.From); err != nil {
return err
}
for _, rcpt := range m.To {
if err = c.Rcpt(rcpt); err != nil {
return err
}
}
w, err := c.Data()
if err != nil {
return err
}
_, err = w.Write([]byte(m.msg))
if err != nil {
return err
}
err = w.Close()
if err != nil {
return err
}
return c.Quit()
}
type StaticFile struct {
Path string
Msg string
}
func (s *StaticFile) init() *StaticFile {
if s == nil || s.Path == "" {
tempFile, err := ioutil.TempFile("", "gocron")
if err != nil {
log.Fatal("Could not create temp file for static file alerts: %v", err)
}
return &StaticFile{Path: tempFile.Name()}
}
return s
}
func (s *StaticFile) WriteAlert(jobErr error) error {
// TODO(mpl): use s.Msg as logger prefix maybe
// s.Msg = fmt.Sprintf("%s %v\n", s.Msg, err)
f, err := os.OpenFile(s.Path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0700)
if err != nil {
return fmt.Errorf("could not open or create file %v: %v", s.Path, err)
}
defer f.Close()
log.SetOutput(f)
log.Printf("%v", jobErr)
return nil
}
const idstring = "http://golang.org/pkg/http/#ListenAndServe"
type Notification struct {
Host string
Msg string
Timeout time.Duration // if set, we close the tab after this duration
tpl *template.Template
pageBody string
windowTimeout int64
notiTimeout int64
}
func (n *Notification) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
data := struct {
Noti string
Body string
WindowTimeout int64
}{
Noti: n.Msg,
Body: n.pageBody,
WindowTimeout: n.windowTimeout,
}
w.Header().Set("Server", idstring)
if err := n.tpl.Execute(w, &data); err != nil {
println(fmt.Sprintf("Could not execute template: %v", err))
}
}
func (n *Notification) init() {
if n == nil {
return
}
if n.Timeout > 0 {
n.windowTimeout = int64((n.Timeout + time.Duration(3)*time.Second) / time.Millisecond)
n.notiTimeout = int64(n.Timeout / time.Millisecond)
}
n.tpl = template.Must(template.New("main").Parse(mainHTML()))
mux := http.NewServeMux()
mux.Handle("/", n)
hostc := make(chan struct{})
go func() {
// TODO(mpl): shutdown (conns) properly when we die?
addr, err := net.ResolveTCPAddr("tcp", n.Host)
if err != nil {
log.Fatal(err)
}
listener, err := net.ListenTCP("tcp", addr)
if err != nil {
log.Fatal(err)
}
n.Host = listener.Addr().String()
// TODO(mpl): I dont think this fake synchro is actually useful.
hostc <- struct{}{}
if err := http.Serve(listener, mux); err != nil {
log.Fatalf("Could not start http server for notifications: %v", err)
}
}()
<-hostc
}
func (n *Notification) Send(err error) error {
if n == nil {
return nil
}
n.pageBody = fmt.Sprintf("%v", err)
url := "http://" + n.Host
cmd := "xdg-open"
if runtime.GOOS == "darwin" {
cmd = "open"
}
return exec.Command(cmd, url).Run()
}
func mainHTML() string {
s := `<!DOCTYPE HTML >
<html>
<head>
<title>Reminder</title>
</head>
<body>
<script>
{{if .WindowTimeout}}
setTimeout(window.close, {{.WindowTimeout}});
{{end}}
window.onload=function(){notify('{{.Noti}}')};
function notify(notiBody) {
if (!("Notification" in window)) {
console.log("Notifications not supported on this browser.");
return;
}
// Let's check whether notification permissions have already been granted
if (Notification.permission === "granted") {
// If it's okay let's create a notification
var notification = new Notification('gocron notification', { body: notiBody});
return;
}
// Otherwise, we need to ask the user for permission
if (Notification.permission !== "denied") {
Notification.requestPermission().then(function (permission) {
// If the user accepts, let's create a notification
if (permission === "granted") {
var notification = new Notification('gocron notification', { body: notiBody});
} else {
console.log("Notifications are denied.");
}
});
}
}
</script>
<a id="notifyLink" href="#" onclick="notify('notifications are enabled');return false;">Enable notifications?</a>
<h2> {{.Noti}} </h2>
{{.Body}}
</body>
</html>
`
return s
}