-
Notifications
You must be signed in to change notification settings - Fork 22
/
tasks.go
399 lines (355 loc) · 12.6 KB
/
tasks.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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
package task
import (
"encoding/json"
"errors"
"fmt"
"os"
"runtime/debug"
"strconv"
"strings"
"sync"
)
var ErrNotSupportTaskType = errors.New("not support task type")
type (
Task interface {
TaskID() string
GetConfig() *TaskConfig
Start()
Stop()
SetTimeout(int64)
RunOnce() error
SetTaskService(service *TaskService)
Reset(conf *TaskConfig) error
CounterInfo() *CounterInfo
}
ExceptionHandleFunc func(*TaskContext, error)
// TaskService task 容器
TaskService struct {
Config *AppConfig
taskMap map[string]Task
taskMutex *sync.RWMutex
counterTask Task
logger Logger
handlerMap map[string]TaskHandle
handlerMutex *sync.RWMutex
ExceptionHandler ExceptionHandleFunc
OnBeforeHandler TaskHandle
OnEndHandler TaskHandle
contextPool *sync.Pool
}
TaskHandle func(*TaskContext) error
)
func defaultExceptionHandler(ctx *TaskContext, err error) {
stack := string(debug.Stack())
fmt.Println("[", ctx.TaskID, "] ", ctx.TaskData, " error [", err.Error(), "] => ", stack)
}
func StartNewService() *TaskService {
service := new(TaskService)
service.taskMutex = new(sync.RWMutex)
service.taskMap = make(map[string]Task)
service.handlerMutex = new(sync.RWMutex)
service.handlerMap = make(map[string]TaskHandle)
service.ExceptionHandler = defaultExceptionHandler
service.contextPool = &sync.Pool{
New: func() interface{} {
return &TaskContext{}
},
}
service.Logger().Debug("StartTaskService PackageVersion[" + PackageVersion() + "]")
return service
}
// UseDefaultLogCounterTask use default LogCounterTask in TaskService
func (service *TaskService) UseDefaultLogCounterTask() {
counterTask, err := NewCronTask(defaultCounterTaskName, true, "0 * * * * *", service.defaultLogCounterInfo, nil)
if err != nil {
fmt.Println("Init Counter Task error", err)
}
counterTask.SetTaskService(service)
counterTask.Start()
service.counterTask = counterTask
}
// SetExceptionHandler 设置自定义异常处理方法
func (service *TaskService) SetExceptionHandler(handler ExceptionHandleFunc) {
service.ExceptionHandler = handler
}
// SetOnBeforeHandler set handler which exec before task run
func (service *TaskService) SetOnBeforeHandler(handler TaskHandle) {
service.OnBeforeHandler = handler
}
// SetOnEndHandler set handler which exec after task run
func (service *TaskService) SetOnEndHandler(handler TaskHandle) {
service.OnEndHandler = handler
}
// LoadConfig 如果指定配置文件,初始化配置
// Deprecated: Use the LoadFileConfig instead
func (service *TaskService) LoadConfig(configFile string, confType ...interface{}) *TaskService {
return service.LoadFileConfig(configFile, confType...)
}
// LoadFileConfig 如果指定配置文件,初始化配置
func (service *TaskService) LoadFileConfig(configFile string, confType ...interface{}) *TaskService {
cType := ConfigType_Xml
if len(confType) > 0 && confType[0] == ConfigType_Json {
cType = ConfigType_Json
}
if len(confType) > 0 && confType[0] == ConfigType_Yaml {
cType = ConfigType_Yaml
}
var config *AppConfig
if cType == ConfigType_Json {
config = JsonConfigHandler(configFile)
} else if cType == ConfigType_Yaml {
config = YamlConfigHandler(configFile)
} else {
config = XmlConfigHandler(configFile)
}
service.applyConfig(config)
return service
}
// applyConfig apply task config with AppConfig
func (service *TaskService) applyConfig(config *AppConfig) *TaskService {
service.Config = config
if service.logger == nil {
if service.Config.Global.LogPath != "" {
service.SetLogger(NewFileLogger(service.Config.Global.LogPath))
} else {
service.SetLogger(NewFmtLogger())
}
}
for _, v := range service.Config.Tasks {
if handler, exists := service.GetHandler(v.HandlerName); exists {
if v.TaskType == TaskType_Cron && v.Express != "" {
_, err := service.CreateCronTask(v.TaskID, v.IsRun, v.Express, handler, v)
if err != nil {
service.Logger().Warn("CreateCronTask failed [" + err.Error() + "] [" + fmt.Sprint(v) + "]")
} else {
service.Logger().Debug("CreateCronTask success [" + fmt.Sprint(v) + "]")
}
} else if v.TaskType == TaskType_Loop && v.Interval > 0 {
_, err := service.CreateLoopTask(v.TaskID, v.IsRun, v.DueTime, v.Interval, handler, v)
if err != nil {
service.Logger().Warn("CreateLoopTask failed [" + err.Error() + "] [" + fmt.Sprint(v) + "]")
} else {
service.Logger().Debug("CreateLoopTask success [" + fmt.Sprint(v) + "]")
}
} else if v.TaskType == TaskType_Queue && v.Interval > 0 {
_, err := service.CreateQueueTask(v.TaskID, v.IsRun, v.Interval, handler, v, v.QueueSize)
if err != nil {
service.Logger().Warn("CreateQueueTask failed [" + err.Error() + "] [" + fmt.Sprint(v) + "]")
} else {
service.Logger().Debug("CreateQueueTask success [" + fmt.Sprint(v) + "]")
}
} else {
service.Logger().Warn("CreateTask failed not match config [" + fmt.Sprint(v) + "]")
}
} else {
service.Logger().Warn("CreateTask failed not exists handler [" + fmt.Sprint(v) + "]")
}
}
return service
}
// LoadConfigHandler load config handler and init task config
func (service *TaskService) LoadConfigHandler(configHandler ConfigHandle, configSource string) *TaskService {
config, err := configHandler(configSource)
if err != nil {
panic("Task:LoadConfigHandler 配置源[" + configSource + "]解析失败: " + err.Error())
os.Exit(1)
} else {
service.applyConfig(config)
}
return service
}
// RegisterHandler register handler by name
func (service *TaskService) RegisterHandler(name string, handler TaskHandle) *TaskService {
service.handlerMutex.Lock()
service.handlerMap[name] = handler
service.handlerMutex.Unlock()
return service
}
// GetHandler get handler by handler name
func (service *TaskService) GetHandler(name string) (TaskHandle, bool) {
service.handlerMutex.RLock()
v, exists := service.handlerMap[name]
service.handlerMutex.RUnlock()
return v, exists
}
// SetLogger set logger which Implements Logger interface
func (service *TaskService) SetLogger(logger Logger) {
service.logger = logger
}
// Logger get Logger
func (service *TaskService) Logger() Logger {
if service.logger == nil {
service.logger = NewFmtLogger()
}
return service.logger
}
// CreateTask create new task with TaskConfig and register to task service
func (service *TaskService) CreateTask(config TaskConfig) (Task, error) {
if config.TaskType == TaskType_Cron {
return service.CreateCronTask(config.TaskID, config.IsRun, config.Express, config.Handler, config.TaskData)
} else if config.TaskType == TaskType_Loop {
return service.CreateLoopTask(config.TaskID, config.IsRun, config.DueTime, config.Interval, config.Handler, config.TaskData)
} else if config.TaskType == TaskType_Loop {
return service.CreateLoopTask(config.TaskID, config.IsRun, config.DueTime, config.Interval, config.Handler, config.TaskData)
}
return nil, ErrNotSupportTaskType
}
// CreateCronTask create new cron task and register to task service
func (service *TaskService) CreateCronTask(taskID string, isRun bool, express string, handler TaskHandle, taskData interface{}) (Task, error) {
task, err := NewCronTask(taskID, isRun, express, handler, taskData)
if err != nil {
return task, err
}
task.SetTaskService(service)
service.AddTask(task)
return task, nil
}
// CreateLoopTask create new loop task and register to task service
func (service *TaskService) CreateLoopTask(taskID string, isRun bool, dueTime int64, interval int64, handler TaskHandle, taskData interface{}) (Task, error) {
task, err := NewLoopTask(taskID, isRun, dueTime, interval, handler, taskData)
if err != nil {
return task, err
}
task.SetTaskService(service)
service.AddTask(task)
return task, nil
}
// CreateQueueTask create new queue task and register to task service
func (service *TaskService) CreateQueueTask(taskID string, isRun bool, interval int64, handler TaskHandle, taskData interface{}, queueSize int64) (Task, error) {
task, err := NewQueueTask(taskID, isRun, interval, handler, taskData, queueSize)
if err != nil {
return task, err
}
task.SetTaskService(service)
service.AddTask(task)
return task, nil
}
// GetTask get TaskInfo by TaskID
func (service *TaskService) GetTask(taskID string) (t Task, exists bool) {
service.taskMutex.RLock()
defer service.taskMutex.RUnlock()
t, exists = service.taskMap[taskID]
return t, exists
}
// AddTask add new task point
func (service *TaskService) AddTask(t Task) {
service.taskMutex.Lock()
service.taskMap[t.TaskID()] = t
service.taskMutex.Unlock()
service.Logger().Info(fmt.Sprint("Task:AddTask => ", t.TaskID(), t.GetConfig()))
}
// RemoveTask remove task by taskid
func (service *TaskService) RemoveTask(taskID string) {
//1.stop task running
t, isExists := service.GetTask(taskID)
if !isExists {
return
}
t.Stop()
service.Logger().Info(fmt.Sprint("Task:RemoveTask::StopTask => ", taskID))
//2.delete task from taskMap
service.taskMutex.Lock()
delete(service.taskMap, taskID)
service.taskMutex.Unlock()
service.Logger().Info(fmt.Sprint("Task:RemoveTask => ", taskID))
}
// Count get all task's count
func (service *TaskService) Count() int {
return len(service.taskMap)
}
// PrintAllCronTask print all task info
// Deprecated: Use the PrintAllTasks instead
func (service *TaskService) PrintAllCronTask() string {
body := ""
for _, v := range service.taskMap {
str, _ := json.Marshal(v)
body += string(str) + "\r\n"
}
return body
}
// PrintAllCronTask print all task info
func (service *TaskService) PrintAllTasks() string {
body := ""
for _, v := range service.taskMap {
str, _ := json.Marshal(v)
body += string(str) + "\r\n"
}
return body
}
// PrintAllTaskCounterInfo print all task counter data
func (service *TaskService) PrintAllTaskCounterInfo() string {
body := ""
for _, v := range service.taskMap {
body += fmt.Sprintln(v.TaskID(), "Run", v.CounterInfo().RunCounter.Count())
body += fmt.Sprintln(v.TaskID(), "Error", v.CounterInfo().ErrorCounter.Count())
}
return body
}
// GetAllTaskCountInfo return all show count info
func (service *TaskService) GetAllTaskCountInfo() []ShowCountInfo {
showInfos := []ShowCountInfo{}
for _, t := range service.GetAllTasks() {
showInfos = append(showInfos, ShowCountInfo{TaskID: t.TaskID(), Lable: "RUN", Count: t.CounterInfo().RunCounter.Count()})
showInfos = append(showInfos, ShowCountInfo{TaskID: t.TaskID(), Lable: "ERROR", Count: t.CounterInfo().ErrorCounter.Count()})
}
return showInfos
}
// GetAllTasks get all tasks
func (service *TaskService) GetAllTasks() map[string]Task {
return service.taskMap
}
// RemoveAllTask remove all task
func (service *TaskService) RemoveAllTask() {
service.StopAllTask()
service.taskMap = make(map[string]Task)
service.Logger().Info("Task:RemoveAllTask")
}
// StopAllTask stop all task
func (service *TaskService) StopAllTask() {
service.Logger().Info("Task:StopAllTask begin...")
for _, v := range service.taskMap {
v.Stop()
service.Logger().Info(fmt.Sprint("Task:StopAllTask::StopTask => ", v.TaskID()))
}
service.Logger().Info("Task:StopAllTask end[" + string(len(service.taskMap)) + "]")
}
// StartAllTask start all task
func (service *TaskService) StartAllTask() {
service.Logger().Info("Task:StartAllTask begin...")
for _, v := range service.taskMap {
service.Logger().Info("Task:StartAllTask::StartTask => " + v.TaskID())
v.Start()
}
service.Logger().Info("Task:StartAllTask end[" + strconv.Itoa(len(service.taskMap)) + "]")
}
func (service *TaskService) debugExpress(set *ExpressSet) {
service.Logger().Debug(fmt.Sprint("parseExpress(", set.rawExpress, " , ", set.expressType, ") => ", set.timeMap))
}
func (service *TaskService) defaultLogCounterInfo(ctx *TaskContext) error {
showInfos := []*ShowCountInfo{}
for _, t := range service.GetAllTasks() {
//service.Logger().Debug(t.TaskID(), " Start:", t.CounterInfo().StartTime.Format(fullTimeLayout), " RUN:", t.CounterInfo().RunCounter.Count(), " ERROR:", t.CounterInfo().ErrorCounter.Count())
showInfos = append(showInfos, &ShowCountInfo{TaskID: t.TaskID(), Lable: "RUN", Count: t.CounterInfo().RunCounter.Count()})
showInfos = append(showInfos, &ShowCountInfo{TaskID: t.TaskID(), Lable: "ERROR", Count: t.CounterInfo().ErrorCounter.Count()})
}
if len(showInfos) > 0 {
str, _ := json.Marshal(showInfos)
service.Logger().Debug(string(str))
}
return nil
}
// ValidateTaskType validate the TaskType is supported
func ValidateTaskType(taskType string) bool {
if taskType == "" {
return false
}
checkType := strings.ToLower(taskType)
if checkType != TaskType_Cron && checkType != TaskType_Loop && checkType != TaskType_Queue {
return false
}
return true
}
// PackageVersion return packageVersion info
func PackageVersion() string {
return packageVersion
}