forked from xxl-job/xxl-job-executor-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
executor.go
375 lines (343 loc) · 9.67 KB
/
executor.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
package xxl
import (
"context"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"
)
// Executor 执行器
type Executor interface {
// Init 初始化
Init(...Option)
// LogHandler 日志查询
LogHandler(handler LogHandler)
// Use 使用中间件
Use(middlewares ...Middleware)
// RegTask 注册任务
RegTask(pattern string, task TaskFunc)
// RunTask 运行任务
RunTask(writer http.ResponseWriter, request *http.Request)
// KillTask 杀死任务
KillTask(writer http.ResponseWriter, request *http.Request)
// TaskLog 任务日志
TaskLog(writer http.ResponseWriter, request *http.Request)
// Beat 心跳检测
Beat(writer http.ResponseWriter, request *http.Request)
// IdleBeat 忙碌检测
IdleBeat(writer http.ResponseWriter, request *http.Request)
// Run 运行服务
Run() error
// Stop 停止服务
Stop()
}
// NewExecutor 创建执行器
func NewExecutor(opts ...Option) Executor {
return newExecutor(opts...)
}
func newExecutor(opts ...Option) *executor {
options := newOptions(opts...)
e := &executor{
opts: options,
}
return e
}
type executor struct {
opts Options
address string
regList *taskList //注册任务列表
runList *taskList //正在执行任务列表
mu sync.RWMutex
log Logger
logHandler LogHandler //日志查询handler
middlewares []Middleware //中间件
}
func (e *executor) Init(opts ...Option) {
for _, o := range opts {
o(&e.opts)
}
e.log = e.opts.l
e.regList = &taskList{
data: make(map[string]*Task),
}
e.runList = &taskList{
data: make(map[string]*Task),
}
e.address = e.opts.ExecutorIp + ":" + e.opts.ExecutorPort
go e.registry()
}
// LogHandler 日志handler
func (e *executor) LogHandler(handler LogHandler) {
e.logHandler = handler
}
func (e *executor) Use(middlewares ...Middleware) {
e.middlewares = middlewares
}
func (e *executor) Run() (err error) {
// 创建路由器
mux := http.NewServeMux()
// 设置路由规则
mux.HandleFunc("/run", e.runTask)
mux.HandleFunc("/kill", e.killTask)
mux.HandleFunc("/log", e.taskLog)
mux.HandleFunc("/beat", e.beat)
mux.HandleFunc("/idleBeat", e.idleBeat)
// 创建服务器
server := &http.Server{
Addr: ":" + e.opts.ExecutorPort,
WriteTimeout: time.Second * 3,
Handler: mux,
}
// 监听端口并提供服务
e.log.Info("Starting server at " + e.address)
go server.ListenAndServe()
quit := make(chan os.Signal)
signal.Notify(quit, syscall.SIGKILL, syscall.SIGQUIT, syscall.SIGINT, syscall.SIGTERM)
<-quit
e.registryRemove()
return nil
}
func (e *executor) Stop() {
e.registryRemove()
}
// RegTask 注册任务
func (e *executor) RegTask(pattern string, task TaskFunc) {
var t = &Task{}
t.fn = e.chain(task)
e.regList.Set(pattern, t)
return
}
// 运行一个任务
func (e *executor) runTask(writer http.ResponseWriter, request *http.Request) {
e.mu.Lock()
defer e.mu.Unlock()
req, _ := ioutil.ReadAll(request.Body)
param := &RunReq{}
err := json.Unmarshal(req, ¶m)
if err != nil {
_, _ = writer.Write(returnCall(param, FailureCode, "params err"))
e.log.Error("参数解析错误:" + string(req))
return
}
e.log.Info("任务参数:%v", param)
if !e.regList.Exists(param.ExecutorHandler) {
_, _ = writer.Write(returnCall(param, FailureCode, "Task not registered"))
e.log.Error("任务[" + Int64ToStr(param.JobID) + "]没有注册:" + param.ExecutorHandler)
return
}
//阻塞策略处理
if e.runList.Exists(Int64ToStr(param.JobID)) {
if param.ExecutorBlockStrategy == coverEarly { //覆盖之前调度
oldTask := e.runList.Get(Int64ToStr(param.JobID))
if oldTask != nil {
oldTask.Cancel()
e.runList.Del(Int64ToStr(oldTask.Id))
}
} else { //单机串行,丢弃后续调度 都进行阻塞
_, _ = writer.Write(returnCall(param, FailureCode, "There are tasks running"))
e.log.Error("任务[" + Int64ToStr(param.JobID) + "]已经在运行了:" + param.ExecutorHandler)
return
}
}
cxt := context.Background()
task := e.regList.Get(param.ExecutorHandler)
if param.ExecutorTimeout > 0 {
task.Ext, task.Cancel = context.WithTimeout(cxt, time.Duration(param.ExecutorTimeout)*time.Second)
} else {
task.Ext, task.Cancel = context.WithCancel(cxt)
}
task.Id = param.JobID
task.Name = param.ExecutorHandler
task.Param = param
task.log = e.log
e.runList.Set(Int64ToStr(task.Id), task)
go task.Run(func(code int64, msg string) {
e.callback(task, code, msg)
})
e.log.Info("任务[" + Int64ToStr(param.JobID) + "]开始执行:" + param.ExecutorHandler)
_, _ = writer.Write(returnGeneral())
}
// 删除一个任务
func (e *executor) killTask(writer http.ResponseWriter, request *http.Request) {
e.mu.Lock()
defer e.mu.Unlock()
req, _ := ioutil.ReadAll(request.Body)
param := &killReq{}
_ = json.Unmarshal(req, ¶m)
if !e.runList.Exists(Int64ToStr(param.JobID)) {
_, _ = writer.Write(returnKill(param, FailureCode))
e.log.Error("任务[" + Int64ToStr(param.JobID) + "]没有运行")
return
}
task := e.runList.Get(Int64ToStr(param.JobID))
task.Cancel()
e.runList.Del(Int64ToStr(param.JobID))
_, _ = writer.Write(returnGeneral())
}
// 任务日志
func (e *executor) taskLog(writer http.ResponseWriter, request *http.Request) {
var res *LogRes
data, err := ioutil.ReadAll(request.Body)
req := &LogReq{}
if err != nil {
e.log.Error("日志请求失败:" + err.Error())
reqErrLogHandler(writer, req, err)
return
}
err = json.Unmarshal(data, &req)
if err != nil {
e.log.Error("日志请求解析失败:" + err.Error())
reqErrLogHandler(writer, req, err)
return
}
e.log.Info("日志请求参数:%+v", req)
if e.logHandler != nil {
res = e.logHandler(req)
} else {
res = defaultLogHandler(req)
}
str, _ := json.Marshal(res)
_, _ = writer.Write(str)
}
// 心跳检测
func (e *executor) beat(writer http.ResponseWriter, request *http.Request) {
e.log.Info("心跳检测")
_, _ = writer.Write(returnGeneral())
}
// 忙碌检测
func (e *executor) idleBeat(writer http.ResponseWriter, request *http.Request) {
e.mu.Lock()
defer e.mu.Unlock()
defer request.Body.Close()
req, _ := ioutil.ReadAll(request.Body)
param := &idleBeatReq{}
err := json.Unmarshal(req, ¶m)
if err != nil {
_, _ = writer.Write(returnIdleBeat(FailureCode))
e.log.Error("参数解析错误:" + string(req))
return
}
if e.runList.Exists(Int64ToStr(param.JobID)) {
_, _ = writer.Write(returnIdleBeat(FailureCode))
e.log.Error("idleBeat任务[" + Int64ToStr(param.JobID) + "]正在运行")
return
}
e.log.Info("忙碌检测任务参数:%v", param)
_, _ = writer.Write(returnGeneral())
}
// 注册执行器到调度中心
func (e *executor) registry() {
t := time.NewTimer(time.Second * 0) //初始立即执行
defer t.Stop()
req := &Registry{
RegistryGroup: "EXECUTOR",
RegistryKey: e.opts.RegistryKey,
RegistryValue: "http://" + e.address,
}
param, err := json.Marshal(req)
if err != nil {
log.Fatal("执行器注册信息解析失败:" + err.Error())
}
for {
<-t.C
t.Reset(time.Second * time.Duration(20)) //20秒心跳防止过期
func() {
result, err := e.post("/api/registry", string(param))
if err != nil {
e.log.Error("执行器注册失败1:" + err.Error())
return
}
defer result.Body.Close()
body, err := ioutil.ReadAll(result.Body)
if err != nil {
e.log.Error("执行器注册失败2:" + err.Error())
return
}
res := &res{}
_ = json.Unmarshal(body, &res)
if res.Code != SuccessCode {
e.log.Error("执行器注册失败3:" + string(body))
return
}
e.log.Info("执行器注册成功:" + string(body))
}()
}
}
// 执行器注册摘除
func (e *executor) registryRemove() {
t := time.NewTimer(time.Second * 0) //初始立即执行
defer t.Stop()
req := &Registry{
RegistryGroup: "EXECUTOR",
RegistryKey: e.opts.RegistryKey,
RegistryValue: "http://" + e.address,
}
param, err := json.Marshal(req)
if err != nil {
e.log.Error("执行器摘除失败:" + err.Error())
return
}
res, err := e.post("/api/registryRemove", string(param))
if err != nil {
e.log.Error("执行器摘除失败:" + err.Error())
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
e.log.Info("执行器摘除成功:" + string(body))
}
// 回调任务列表
func (e *executor) callback(task *Task, code int64, msg string) {
e.runList.Del(Int64ToStr(task.Id))
res, err := e.post("/api/callback", string(returnCall(task.Param, code, msg)))
if err != nil {
e.log.Error("callback err : ", err.Error())
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
e.log.Error("callback ReadAll err : ", err.Error())
return
}
e.log.Info("任务回调成功:" + string(body))
}
// post
func (e *executor) post(action, body string) (resp *http.Response, err error) {
request, err := http.NewRequest("POST", e.opts.ServerAddr+action, strings.NewReader(body))
if err != nil {
return nil, err
}
request.Header.Set("Content-Type", "application/json;charset=UTF-8")
request.Header.Set("XXL-JOB-ACCESS-TOKEN", e.opts.AccessToken)
client := http.Client{
Timeout: e.opts.Timeout,
}
return client.Do(request)
}
// RunTask 运行任务
func (e *executor) RunTask(writer http.ResponseWriter, request *http.Request) {
e.runTask(writer, request)
}
// KillTask 删除任务
func (e *executor) KillTask(writer http.ResponseWriter, request *http.Request) {
e.killTask(writer, request)
}
// TaskLog 任务日志
func (e *executor) TaskLog(writer http.ResponseWriter, request *http.Request) {
e.taskLog(writer, request)
}
// Beat 心跳检测
func (e *executor) Beat(writer http.ResponseWriter, request *http.Request) {
e.beat(writer, request)
}
// IdleBeat 忙碌检测
func (e *executor) IdleBeat(writer http.ResponseWriter, request *http.Request) {
e.idleBeat(writer, request)
}