-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
job.go
77 lines (65 loc) · 1.42 KB
/
job.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
package job
import (
"log"
json "github.com/json-iterator/go"
"github.com/robfig/cron/v3"
"github.com/chabad360/covey/models"
"github.com/chabad360/covey/storage"
"github.com/chabad360/covey/task"
)
var (
cronTab = cron.New()
)
// Init loads up the the jobs and starts the cronTab.
func Init() {
q, err := storage.DB.Table("jobs").Where("cron != ''").Select("id", "cron").Rows()
if err != nil {
log.Panic(err)
}
defer q.Close()
for q.Next() {
var id string
var c string
if err = q.Scan(&id, &c); err != nil {
log.Panic(err)
}
if err = addCron(id, c); err != nil {
log.Panic(err)
}
}
cronTab.Start()
}
func addCron(id string, cron string) error {
_, err := cronTab.AddFunc(cron, func() {
if j, ok := storage.GetJob(id); ok {
if _, err := run(j); err != nil {
log.Panic(err)
}
}
})
if err != nil {
return err
}
return nil
}
// Run runs each task in succession on the specified nodes (concurrently).
// There seems to be a bug where the tasks can occasionally be sent in the wrong order.
func run(j *models.Job) ([]string, error) {
var th []string
for _, t := range j.Tasks {
for _, node := range j.Nodes {
t.Node = node
x, err := json.Marshal(t)
if err != nil {
log.Panic(err)
}
r, err := task.NewTask(x)
if err != nil {
log.Panic(err)
}
th = append(th, r.ID)
}
}
j.TaskHistory = append(j.TaskHistory, th...)
return th, storage.UpdateJob(j)
}