-
Notifications
You must be signed in to change notification settings - Fork 20
/
cron.go
203 lines (173 loc) · 4.59 KB
/
cron.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
package worker
import (
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"os/signal"
"path/filepath"
"reflect"
"strings"
"sync"
"syscall"
"time"
)
type cronJob struct {
JobID string
Pid int
Command string
Delete bool `json:"-"`
}
func (job cronJob) ToString() string {
marshal, _ := json.Marshal(job)
return fmt.Sprintf("## BEGIN QOR JOB %v # %v\n%v\n## END QOR JOB\n", job.JobID, string(marshal), job.Command)
}
// Cron implemented a worker Queue based on cronjob
type Cron struct {
Jobs []*cronJob
CronJobs []string
mutex sync.Mutex `sql:"-"`
}
// NewCronQueue initialize a Cron queue
func NewCronQueue() *Cron {
return &Cron{}
}
func (cron *Cron) parseJobs() []*cronJob {
cron.mutex.Lock()
cron.Jobs = []*cronJob{}
cron.CronJobs = []string{}
if out, err := exec.Command("crontab", "-l").Output(); err == nil {
var inQorJob bool
for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
if strings.HasPrefix(line, "## BEGIN QOR JOB") {
inQorJob = true
if idx := strings.Index(line, "{"); idx > 1 {
var job cronJob
if json.Unmarshal([]byte(line[idx-1:]), &job) == nil {
cron.Jobs = append(cron.Jobs, &job)
}
}
}
if !inQorJob {
cron.CronJobs = append(cron.CronJobs, line)
}
if strings.HasPrefix(line, "## END QOR JOB") {
inQorJob = false
}
}
}
return cron.Jobs
}
func (cron *Cron) writeCronJob() error {
defer cron.mutex.Unlock()
cmd := exec.Command("crontab", "-")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
stdin, _ := cmd.StdinPipe()
for _, cronJob := range cron.CronJobs {
stdin.Write([]byte(cronJob + "\n"))
}
for _, job := range cron.Jobs {
if !job.Delete {
stdin.Write([]byte(job.ToString() + "\n"))
}
}
stdin.Close()
return cmd.Run()
}
// Add a job to cron queue
func (cron *Cron) Add(job QorJobInterface) (err error) {
cron.parseJobs()
defer cron.writeCronJob()
var binaryFile string
if binaryFile, err = filepath.Abs(os.Args[0]); err == nil {
var jobs []*cronJob
for _, cronJob := range cron.Jobs {
if cronJob.JobID != job.GetJobID() {
jobs = append(jobs, cronJob)
}
}
if scheduler, ok := job.GetArgument().(Scheduler); ok && scheduler.GetScheduleTime() != nil {
scheduleTime := scheduler.GetScheduleTime().In(time.Local)
job.SetStatus(JobStatusScheduled)
currentPath, _ := os.Getwd()
jobs = append(jobs, &cronJob{
JobID: job.GetJobID(),
Command: fmt.Sprintf("%d %d %d %d * cd %v; %v --qor-job %v\n", scheduleTime.Minute(), scheduleTime.Hour(), scheduleTime.Day(), scheduleTime.Month(), currentPath, binaryFile, job.GetJobID()),
})
} else {
cmd := exec.Command(binaryFile, "--qor-job", job.GetJobID())
if err = cmd.Start(); err == nil {
jobs = append(jobs, &cronJob{JobID: job.GetJobID(), Pid: cmd.Process.Pid})
cmd.Process.Release()
}
}
cron.Jobs = jobs
}
return
}
// Run a job from cron queue
func (cron *Cron) Run(qorJob QorJobInterface) error {
job := qorJob.GetJob()
if job.Handler != nil {
go func() {
sigint := make(chan os.Signal, 1)
// interrupt signal sent from terminal
signal.Notify(sigint, syscall.SIGINT)
// sigterm signal sent from kubernetes
signal.Notify(sigint, syscall.SIGTERM)
i := <-sigint
qorJob.SetProgressText(fmt.Sprintf("Worker killed by signal %s", i.String()))
qorJob.SetStatus(JobStatusKilled)
qorJob.StopReferesh()
os.Exit(int(reflect.ValueOf(i).Int()))
}()
qorJob.StartReferesh()
defer qorJob.StopReferesh()
err := job.Handler(qorJob.GetSerializableArgument(qorJob), qorJob)
if err == nil {
cron.parseJobs()
defer cron.writeCronJob()
for _, cronJob := range cron.Jobs {
if cronJob.JobID == qorJob.GetJobID() {
cronJob.Delete = true
}
}
}
return err
}
return errors.New("no handler found for job " + job.Name)
}
// Kill a job from cron queue
func (cron *Cron) Kill(job QorJobInterface) (err error) {
cron.parseJobs()
defer cron.writeCronJob()
for _, cronJob := range cron.Jobs {
if cronJob.JobID == job.GetJobID() {
if process, err := os.FindProcess(cronJob.Pid); err == nil {
if err = process.Kill(); err == nil {
cronJob.Delete = true
return nil
}
}
return err
}
}
return errors.New("failed to find job")
}
// Remove a job from cron queue
func (cron *Cron) Remove(job QorJobInterface) error {
cron.parseJobs()
defer cron.writeCronJob()
for _, cronJob := range cron.Jobs {
if cronJob.JobID == job.GetJobID() {
if cronJob.Pid == 0 {
cronJob.Delete = true
return nil
}
return errors.New("failed to remove current job as it is running")
}
}
return errors.New("failed to find job")
}