-
Notifications
You must be signed in to change notification settings - Fork 0
/
scheduler.go
332 lines (280 loc) · 7.04 KB
/
scheduler.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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
package scheduler
import (
"encoding/json"
"errors"
"log"
"time"
"github.com/google/uuid"
"gorm.io/gorm"
)
const (
DefaultSleepDuration = 30 * time.Second
MinimalSleepDuration = 1 * time.Second
)
type (
TaskStatus uint
// TaskManager base
TaskManager struct {
id string
db *gorm.DB
funcs TaskFuncsMap
sleepDuration time.Duration
}
// Task
Task struct {
ID uint `gorm:"primary_key"`
Alias string
Name string
Arguments string
Singleton bool
Status TaskStatus
Schedule uint
ScheduledAt time.Time
CreatedAt time.Time
UpdatedAt time.Time
}
// Aggregate config for new scheduler
Config struct {
Db *gorm.DB
Sleep time.Duration
Jobs TaskSettings
}
// Aggregate settings for jobs
TaskSettings map[string]struct {
Func TaskFunc
Args FuncArgs
Interval uint
RunAt time.Time
}
// TaskFunc type func by task
TaskFunc func(args FuncArgs) (status TaskStatus, when interface{})
// TaskFuncsMap - list by TaskFunc's (key - task alias, value - TaskFunc)
TaskFuncsMap map[string]TaskFunc
// TaskPlan - list for initializing singleton tasks (key - task alias, value - start interval in minutes)
TaskPlan map[string]uint
FuncArgs map[string]interface{}
)
const (
TaskStatusWait TaskStatus = iota
TaskStatusDeferred
TaskStatusInProgress
TaskStatusDone
)
var ErrFuncNotFoundInTaskFuncsMap = errors.New("function not found in TaskFuncsMap")
// New TaskManager
func New(db *gorm.DB, funcs *TaskFuncsMap, sleepDuration time.Duration) *TaskManager {
sleep := sleepDuration
if sleep == 0 {
sleep = DefaultSleepDuration
} else if sleep < MinimalSleepDuration {
sleep = MinimalSleepDuration
}
return &TaskManager{
id: uuid.New().String(),
db: db,
funcs: *funcs,
sleepDuration: sleep,
}
}
// New TaskManager with config
func NewWithConfig(c Config) (*TaskManager, error) {
taskFuncsMap := TaskFuncsMap{}
for alias, item := range c.Jobs {
taskFuncsMap[alias] = item.Func
}
taskManager := New(c.Db, &taskFuncsMap, c.Sleep)
err := taskManager.SetTasks(c.Jobs)
if err != nil {
return nil, err
}
return taskManager, nil
}
// Configure add (or update if exist) tasks to TaskManager from TaskSettings
func (tm *TaskManager) SetTasks(ts TaskSettings) (err error) {
for alias, item := range ts {
if _, ok := tm.funcs[alias]; ok {
var task Task
err = tm.db.FirstOrInit(&task, Task{Alias: alias}).Error
argsStr := item.Args.String()
if task.ID == 0 { // Add
task.Schedule = item.Interval
task.Status = TaskStatusWait
task.Singleton = true
scheduledAt := time.Now()
if !item.RunAt.IsZero() {
scheduledAt = item.RunAt
}
task.ScheduledAt = scheduledAt
// save arguments if exist literal initialization and map not empty
if item.Args != nil && len(item.Args) > 0 {
task.Arguments = argsStr
}
err = tm.db.Save(&task).Error
} else { // update
updateMap := make(map[string]interface{})
if task.Schedule != item.Interval {
updateMap["schedule"] = item.Interval
}
// update arguments if exist literal initialization
if item.Args != nil && task.Arguments != argsStr {
// if exist initialization want do empty string
if len(item.Args) == 0 {
argsStr = ""
}
updateMap["arguments"] = argsStr
}
if len(updateMap) > 0 {
go func() {
err = tm.db.Model(task).Updates(updateMap).Error
}()
}
}
}
}
return err
}
// Configure add (or update if exist) tasks to TaskManager from TaskPlan
func (tm *TaskManager) Configure(funcs TaskPlan) {
for alias, schedule := range funcs {
if _, ok := tm.funcs[alias]; ok {
var task Task
tm.db.FirstOrInit(&task, Task{Alias: alias})
if task.ID == 0 { // Add
task.Schedule = schedule
task.Status = TaskStatusWait
task.ScheduledAt = time.Now()
task.Singleton = true
tm.db.Save(&task)
} else if task.Schedule != schedule { // Update
go func() {
tm.db.Model(task).Update("schedule", schedule)
}()
}
}
}
}
// ClearTasks Removes tasks from DB if they are not in TaskManager
func (tm *TaskManager) ClearTasks() {
dbTasks := make([]Task, 0)
tm.db.Find(&dbTasks)
for _, dbt := range dbTasks {
if _, ok := tm.funcs[dbt.Alias]; !ok {
go func() {
tm.db.Delete(dbt)
}()
}
}
}
// Run infinite TaskManager loop
func (tm *TaskManager) Run() {
for {
func() {
tx := tm.db.Begin()
defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()
var task Task
err := tx.Raw(`
UPDATE tasks SET updated_at = ?
WHERE id = (
SELECT id
FROM tasks
WHERE scheduled_at < now() AND status = ?
ORDER BY scheduled_at LIMIT 1 FOR UPDATE SKIP LOCKED)
RETURNING *;
`,
time.Now(),
TaskStatusWait,
).Scan(&task).Error
if err != nil {
log.Println(err)
}
if task.ID == 0 {
tx.Rollback()
time.Sleep(tm.sleepDuration)
} else {
if fn, ok := tm.funcs[task.Alias]; ok {
go tm.exec(&task, fn, tx)
} else {
task.Status = TaskStatusDeferred
tx.Save(&task)
tx.Commit()
}
}
}()
}
}
// Executing a task with panic recovery,
// changing the task status and
// setting a new task scheduling time after its completion.
func (tm *TaskManager) exec(task *Task, fn TaskFunc, tx *gorm.DB) {
defer func() {
if r := recover(); r != nil {
log.Printf("[Scheduler][Recovery %s] panic recovered:\n%s\n\n", task.Alias, r)
task.Status = TaskStatusWait
if task.Schedule > 0 {
task.ScheduledAt = task.ScheduledAt.Add(time.Minute * time.Duration(task.Schedule))
}
tx.Save(task)
tx.Commit()
}
}()
funcArgs := task.ParseArgs()
status, when := fn(funcArgs)
switch status { // nolint:exhaustive TaskStatusInProgress = default
case TaskStatusDone, TaskStatusWait, TaskStatusDeferred:
task.Status = status
default:
task.Status = TaskStatusDeferred
}
switch v := when.(type) {
case time.Duration:
task.ScheduledAt = task.ScheduledAt.Add(v)
case time.Time:
task.ScheduledAt = v
default:
if task.Schedule > 0 {
d := time.Minute * time.Duration(task.Schedule)
task.ScheduledAt = task.ScheduledAt.Add(time.Now().Sub(task.ScheduledAt).Truncate(d) + d)
} else {
task.Status = TaskStatusDeferred
}
}
tx.Save(task)
tx.Commit()
}
// Add new no-Singleton task in DB
func (tm *TaskManager) Add(alias string, name string, args FuncArgs, runAt time.Time, intervalMinutes uint) error {
if _, ok := tm.funcs[alias]; !ok {
return ErrFuncNotFoundInTaskFuncsMap
}
task := Task{
Alias: alias,
Name: name,
Status: TaskStatusWait,
ScheduledAt: runAt,
Schedule: intervalMinutes,
Arguments: args.String(),
}
return tm.db.Save(&task).Error
}
func (t *Task) ParseArgs() FuncArgs {
if t.Arguments == "" {
return nil
}
args := make(FuncArgs)
err := json.Unmarshal([]byte(t.Arguments), &args)
if err != nil {
log.Print("ParseArgs() err:", err)
}
return args
}
func (args *FuncArgs) String() string {
str, err := json.Marshal(args)
if err != nil {
log.Print("FuncArgs.String() err:", err)
}
return string(str)
}