This repository has been archived by the owner on Nov 23, 2018. It is now read-only.
/
cmd.go
308 lines (260 loc) · 5.9 KB
/
cmd.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
296
297
298
299
300
301
302
303
304
305
306
307
308
package qmd
import (
"bytes"
"errors"
"io/ioutil"
"os"
"os/exec"
"strings"
"sync"
"syscall"
"time"
"github.com/goware/lg"
)
type Cmd struct {
*exec.Cmd `json:"cmd"`
JobID string
State CmdState
StartTime time.Time
EndTime time.Time
Duration time.Duration
StatusCode int
CallbackURL string
Err error
Priority Priority
CmdOut bytes.Buffer
QmdOut bytes.Buffer
QmdOutFile string
StoreDir string
ExtraWorkDirFiles map[string]string
// Started channel block until the cmd is started.
Started chan struct{}
// Finished channel block until the cmd is finished/killed/invalidated.
Finished chan struct{}
// WaitOnce guards the Wait() logic, so it can be called multiple times.
WaitOnce sync.Once
// StartOnce guards the Start() logic, so it can be called multiple times.
StartOnce sync.Once
}
type CmdState int
const (
Initialized CmdState = iota
Running
Finished
Terminated
Invalidated
Failed
)
type Priority int
const (
PriorityLow Priority = iota
PriorityHigh
PriorityUrgent
)
func (s Priority) String() string {
switch s {
case PriorityLow:
return "low"
case PriorityHigh:
return "high"
case PriorityUrgent:
return "urgent"
}
panic("unreachable")
}
func (qmd *Qmd) Cmd(from *exec.Cmd) (*Cmd, error) {
cmd := &Cmd{
Cmd: from,
State: Initialized,
Started: make(chan struct{}),
Finished: make(chan struct{}),
StoreDir: qmd.Config.StoreDir,
}
cmd.Cmd.Dir = qmd.Config.WorkDir
return cmd, nil
}
func (cmd *Cmd) Start() error {
cmd.StartOnce.Do(cmd.startOnce)
// Wait for cmd to start.
<-cmd.Started
return cmd.Err
}
func (cmd *Cmd) startOnce() {
lg.Debugf("Cmd:\tStarting %v", cmd.JobID)
cmd.Cmd.Dir += "/" + cmd.JobID
cmd.QmdOutFile = cmd.Cmd.Dir + "/QMD_OUT"
cmd.Cmd.Env = append(os.Environ(),
"QMD_TMP="+cmd.Cmd.Dir,
"QMD_STORE="+cmd.StoreDir,
"QMD_OUT="+cmd.QmdOutFile,
)
cmd.Cmd.SysProcAttr = &syscall.SysProcAttr{
Setpgid: true,
//TODO: Chroot: cmd.Cmd.Dir,
}
cmd.Cmd.Stdout = &cmd.CmdOut
cmd.Cmd.Stderr = &cmd.CmdOut
// Create working directory.
err := os.MkdirAll(cmd.Cmd.Dir, 0777)
if err != nil {
cmd.Err = err
}
// Create QMD_OUT file.
qmdOut, err := os.Create(cmd.QmdOutFile)
if err != nil {
cmd.Err = err
}
qmdOut.Close()
for file, data := range cmd.ExtraWorkDirFiles {
// Must be a simple filename without slashes.
if strings.Index(file, "/") != -1 {
cmd.Err = errors.New("extra files must not contain any slashes in the path")
goto failedToStart
}
err = ioutil.WriteFile(cmd.Cmd.Dir+"/"+file, []byte(data), 0644)
if err != nil {
cmd.Err = err
goto failedToStart
}
}
if err := cmd.Cmd.Start(); err != nil {
cmd.Err = err
goto failedToStart
}
cmd.StartTime = time.Now()
cmd.State = Running
close(cmd.Started)
cmd.Err = nil
return
failedToStart:
cmd.StatusCode = -1
cmd.State = Failed
cmd.WaitOnce.Do(func() {
close(cmd.Finished)
})
close(cmd.Started)
lg.Debugf("Cmd:\tFailed to start %v: %v", cmd.JobID, cmd.Err)
}
// Wait waits for cmd to finish.
// It closes the Stdout and Stderr pipes.
func (cmd *Cmd) Wait() error {
// Wait for Start(), if not already invoked.
<-cmd.Started
// Prevent running cmd.Wait() multiple times.
cmd.WaitOnce.Do(cmd.waitOnce)
// Wait for cmd to finish.
<-cmd.Finished
return cmd.Err
}
func (cmd *Cmd) waitOnce() {
err := cmd.Cmd.Wait()
cmd.Duration = time.Since(cmd.StartTime)
cmd.EndTime = cmd.StartTime.Add(cmd.Duration)
if cmd.State != Terminated {
cmd.State = Finished
}
if err != nil {
cmd.Err = err
if e, ok := err.(*exec.ExitError); ok {
if s, ok := e.Sys().(syscall.WaitStatus); ok {
cmd.StatusCode = s.ExitStatus()
}
}
}
if f, err := os.Open(cmd.QmdOutFile); err == nil {
_, err := cmd.QmdOut.ReadFrom(f)
if err != nil {
cmd.Err = err
}
f.Close()
}
close(cmd.Finished)
lg.Debugf("Cmd:\tFinished %v", cmd.JobID)
}
func (cmd *Cmd) Run() error {
err := cmd.Start()
if err != nil {
return err
}
err = cmd.Wait()
if err != nil {
return err
}
return nil
}
func (cmd *Cmd) Kill() error {
switch cmd.State {
case Running:
cmd.State = Terminated
lg.Debugf("Cmd:\tKilling %v\n", cmd.JobID)
pgid, err := syscall.Getpgid(cmd.Cmd.Process.Pid)
if err != nil {
// Fall-back on error. Kill the main process only.
cmd.Cmd.Process.Kill()
break
}
// Kill the whole process group.
syscall.Kill(-pgid, 15)
case Finished:
lg.Debug("Cmd:\tKilling pgroup %v\n", cmd.JobID)
pgid, err := syscall.Getpgid(cmd.Cmd.Process.Pid)
if err != nil {
break
}
// Make sure to kill the whole process group,
// so there are no subprocesses left.
syscall.Kill(-pgid, 15)
case Initialized:
// This one is tricky, as the cmd's Start() might have
// been called and is already in progress, but the cmd's
// state is not Running yet.
usCallingStartOnce := false
cmd.StartOnce.Do(func() {
cmd.WaitOnce.Do(func() {
cmd.State = Invalidated
cmd.StatusCode = -2
cmd.Err = errors.New("invalidated")
lg.Debugf("Cmd: Invalidating %v\n", cmd.JobID)
close(cmd.Finished)
})
close(cmd.Started)
usCallingStartOnce = true
})
if !usCallingStartOnce {
// It was cmd.Start() that called StartOnce.Do(), not us,
// thus we need to wait for Started and try to Kill again:
<-cmd.Started
cmd.Kill()
}
}
return cmd.Err
}
func (cmd *Cmd) Cleanup() error {
lg.Debugf("Cmd:\tCleaning %v\n", cmd.JobID)
// Make sure to kill the whole process group,
// so there are no subprocesses left.
cmd.Kill()
// Remove working directory.
err := os.RemoveAll(cmd.Cmd.Dir)
if err != nil {
return err
}
return nil
}
func (s CmdState) String() string {
switch s {
case Initialized:
return "Initialized"
case Running:
return "Running"
case Finished:
return "Finished"
case Terminated:
return "Terminated (killed by us)"
case Invalidated:
return "Invalidated before start"
case Failed:
return "Failed to start"
}
panic("unreachable")
}