-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.go
282 lines (241 loc) · 6.1 KB
/
main.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
package main
import (
"bytes"
"flag"
"fmt"
"log"
"os"
"os/exec"
"strings"
"syscall"
"text/template"
"time"
"github.com/symfonycorp/croncape/process"
)
var version = "dev"
type request struct {
command []string
emails string
from string
timeout time.Duration
transport string
verbose bool
}
type result struct {
request request
stdout bytes.Buffer
stderr bytes.Buffer
started time.Time
stopped time.Time
killed bool
code int
}
func main() {
wd, err := os.Getwd()
if err != nil {
log.Fatalln(err)
}
req := request{
emails: os.Getenv("MAILTO"),
from: os.Getenv("MAILFROM"),
}
var versionf bool
flag.DurationVar(&req.timeout, "t", 0, `Timeout for the command, like "-t 2h", "-t 2m", or "-t 30s". After the timeout, the command is killed, disabled by default`)
flag.StringVar(&req.transport, "p", "auto", `Transport to use, like "-p auto", "-p mail", "-p sendmail"`)
flag.BoolVar(&req.verbose, "v", false, "Enable sending emails even if command is successful")
flag.BoolVar(&versionf, "version", false, "Output the version")
flag.Parse()
if versionf {
fmt.Println(version)
os.Exit(0)
}
req.command = flag.Args()
if len(req.command) == 0 {
fmt.Println("You must pass a command to execute")
os.Exit(1)
}
r := execCmd(wd, req)
if r.killed || r.code != 0 || r.request.verbose {
if r.request.emails == "" {
fmt.Println(r.render().String())
} else {
r.sendEmail()
}
}
}
func execCmd(path string, req request) result {
r := result{
started: time.Now(),
request: req,
}
cmd := exec.Command(req.command[0], req.command[1:]...)
cmd.Dir = path
cmd.Stdout = &r.stdout
cmd.Stderr = &r.stderr
cmd.Env = os.Environ()
cmd.SysProcAttr = &syscall.SysProcAttr{}
process.Deathsig(cmd.SysProcAttr)
if err := cmd.Start(); err != nil {
r.stderr.WriteString("\n" + err.Error() + "\n")
r.code = 127
} else {
var timer *time.Timer
if req.timeout > 0 {
timer = time.NewTimer(req.timeout)
defer timer.Stop()
go func(timer *time.Timer, cmd *exec.Cmd) {
for range timer.C {
r.killed = true
if err := process.Kill(cmd); err != nil {
r.stderr.WriteString(fmt.Sprintf("\nUnabled to kill the process: %s\n", err))
}
}
}(timer, cmd)
}
if err := cmd.Wait(); err != nil {
// unsuccessful exit code?
r.code = -1
if exitError, ok := err.(*exec.ExitError); ok {
r.code = exitError.Sys().(syscall.WaitStatus).ExitStatus()
}
}
}
r.stopped = time.Now()
return r
}
func (r *result) sendEmail() {
emails := strings.Split(r.request.emails, ",")
paths := make(map[string]string)
if r.request.transport == "auto" {
paths = map[string]string{"sendmail": "sendmail", "/usr/sbin/sendmail": "sendmail", "mail": "mail", "/usr/bin/mail": "mail"}
} else if r.request.transport == "sendmail" {
paths = map[string]string{"sendmail": "sendmail", "/usr/sbin/sendmail": "sendmail"}
} else if r.request.transport == "mail" {
paths = map[string]string{"mail": "mail", "/usr/bin/mail": "mail"}
} else {
fmt.Printf("Unsupported transport %s\n", r.request.transport)
os.Exit(1)
}
var err error
var transportType string
var transportPath string
for p, t := range paths {
p, err = exec.LookPath(p)
if err == nil {
transportType = t
transportPath = p
break
}
}
switch transportType {
default:
fmt.Printf("Unable to find a path for %s\n", r.request.transport)
os.Exit(1)
case "mail":
for _, email := range emails {
args := []string{"-s", r.subject()}
if from := r.request.from; from != "" {
args = append(args, "-a", from)
}
args = append(args, strings.TrimSpace(email))
cmd := exec.Command(transportPath, args...)
cmd.Stdin = r.render()
cmd.Env = os.Environ()
if err := cmd.Run(); err != nil {
fmt.Printf("Could not send email to %s: %s\n", email, err)
os.Exit(1)
}
}
case "sendmail":
var message string
if len(emails) > 1 {
message = fmt.Sprintf("To: %s\r\nCc: %s\r\nSubject: %s\r\n\r\n%s", emails[0], strings.Join(emails[1:], ","), r.subject(), r.render().String())
} else {
message = fmt.Sprintf("To: %s\r\nSubject: %s\r\n\r\n%s", emails[0], r.subject(), r.render().String())
}
if from := r.request.from; from != "" {
message = fmt.Sprintf("From: %s\r\n%s", from, message)
}
cmd := exec.Command(transportPath, "-t")
cmd.Stdin = strings.NewReader(message)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Env = os.Environ()
if err := cmd.Run(); err != nil {
fmt.Printf("Could not send email to %s: %s\n", emails, err)
os.Exit(1)
}
}
}
func (r *result) subject() string {
hostname := "undefined"
var err error
if env := os.Getenv("MAILHOST"); env != "" {
hostname = env
} else if hostname, err = os.Hostname(); err != nil {
hostname = "undefined"
}
if r.killed {
return fmt.Sprintf("Cron on host %s: Timeout", hostname)
}
if r.code == 0 {
return fmt.Sprintf("Cron on host %s: Command Successful", hostname)
}
return fmt.Sprintf("Cron on host %s: Failure", hostname)
}
func (r *result) title() string {
var msg string
if r.killed {
msg = "Cron timeout detected"
} else if r.code == 0 {
msg = "Cron success"
} else {
msg = "Cron failure detected"
}
return msg + "\n" + strings.Repeat("=", len(msg))
}
func (r *result) duration() time.Duration {
return r.stopped.Sub(r.started)
}
func (r *result) render() *bytes.Buffer {
tpl := template.Must(template.New("email").Parse(`{{.Title}}
{{.Command}}
METADATA
--------
Exit Code: {{.Code}}
Start: {{.Started}}
Stop: {{.Stopped}}
Duration: {{.Duration}}
ERROR OUTPUT
------------
{{.Stderr}}
STANDARD OUTPUT
---------------
{{.Stdout}}
`))
data := struct {
Title string
Command string
Started time.Time
Stopped time.Time
Duration time.Duration
Code int
Stderr string
Stdout string
}{
Title: r.title(),
Command: strings.Join(r.request.command, " "),
Started: r.started,
Stopped: r.stopped,
Duration: r.duration(),
Code: r.code,
Stderr: r.stderr.String(),
Stdout: r.stdout.String(),
}
contents := bytes.Buffer{}
if err := tpl.Execute(&contents, data); err != nil {
fmt.Println(err)
os.Exit(1)
}
return &contents
}