forked from goodrain/rainbond
-
Notifications
You must be signed in to change notification settings - Fork 0
/
engine.go
428 lines (402 loc) · 11.1 KB
/
engine.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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
// Copyright (C) 2014-2018 Goodrain Co., Ltd.
// RAINBOND, Application Management Platform
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. For any non-GPL usage of Rainbond,
// one or multiple Commercial Licenses authorized by Goodrain Co., Ltd.
// must be obtained first.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package task
import (
"context"
"fmt"
"io/ioutil"
"os"
"path"
"strings"
"sync"
"time"
"github.com/goodrain/rainbond/util/watch"
"github.com/goodrain/rainbond/util"
"github.com/goodrain/rainbond/util/etcd/etcdlock"
"github.com/Sirupsen/logrus"
client "github.com/coreos/etcd/clientv3"
"github.com/coreos/etcd/mvcc/mvccpb"
"github.com/goodrain/rainbond/cmd/node/option"
"github.com/goodrain/rainbond/node/api/model"
"github.com/goodrain/rainbond/node/core/config"
"github.com/goodrain/rainbond/node/core/job"
"github.com/goodrain/rainbond/node/core/store"
"github.com/goodrain/rainbond/node/masterserver/node"
"github.com/goodrain/rainbond/node/nodeserver"
"github.com/pquerna/ffjson/ffjson"
)
// TaskEngine 任务引擎
// 处理任务的执行,结果处理,任务自动调度
// TODO:执行记录清理工作
type TaskEngine struct {
ctx context.Context
cancel context.CancelFunc
config *option.Conf
tasks map[string]*model.Task
jobs nodeserver.Jobs
tasksLock, jobsLock sync.Mutex
dataCenterConfig *config.DataCenterConfig
nodeCluster *node.Cluster
currentNode *model.HostNode
down chan struct{}
masterID client.LeaseID
scheduler *Scheduler
masterRun bool
}
//CreateTaskEngine 创建task管理引擎
func CreateTaskEngine(nodeCluster *node.Cluster, node *model.HostNode) *TaskEngine {
ctx, cancel := context.WithCancel(context.Background())
task := &TaskEngine{
ctx: ctx,
cancel: cancel,
tasks: make(map[string]*model.Task),
jobs: make(nodeserver.Jobs),
config: option.Config,
dataCenterConfig: config.GetDataCenterConfig(),
nodeCluster: nodeCluster,
currentNode: node,
down: make(chan struct{}),
}
scheduler := createScheduler(task)
task.scheduler = scheduler
return task
}
//Start start
func (t *TaskEngine) Start(errchan chan error) error {
//load all task and wath change event
go t.loadAndWatchTasks(errchan)
t.LoadStaticTask()
go util.Exec(t.ctx, func() error {
t.start(errchan)
return nil
}, 1)
return nil
}
func (t *TaskEngine) start(errchan chan error) {
master, err := etcdlock.CreateMasterLock(t.config.Etcd.Endpoints, "/rainbond/nodetaskscheduler", t.currentNode.HostName, 10)
if err != nil {
errchan <- err
return
}
master.Start()
defer master.Stop()
for {
select {
case event := <-master.EventsChan():
if event.Type == etcdlock.MasterAdded {
logrus.Infof("Current node(%s) have task scheduler authority", t.currentNode.HostName)
go t.startScheduler()
go t.startHandleJobRecord()
t.masterRun = true
}
if event.Type == etcdlock.MasterDeleted {
if t.masterRun {
errchan <- fmt.Errorf("master node delete")
}
return
}
if event.Type == etcdlock.MasterError {
if event.Error.Error() == "elect: session expired" {
//TODO:if etcd error. worker restart
}
//if this is master node, exit
if t.masterRun {
errchan <- event.Error
}
return
}
}
}
}
//Stop task engine stop
func (t *TaskEngine) Stop() {
t.cancel()
}
//watchTasks watchTasks
func (t *TaskEngine) loadAndWatchTasks(errChan chan error) {
watcher := watch.New(store.DefalutClient.Client, "")
taskwatchChan, err := watcher.WatchList(t.ctx, "/rainbond/store/tasks/", "")
if err != nil {
errChan <- err
}
defer taskwatchChan.Stop()
for ev := range taskwatchChan.ResultChan() {
switch ev.Type {
case watch.Added, watch.Modified:
task := new(model.Task)
if err := task.Decode(ev.GetValue()); err != nil {
logrus.Errorf("decode task info error :%s", err)
continue
}
t.CacheTask(task)
case watch.Deleted:
task := new(model.Task)
if err := task.Decode(ev.GetPreValue()); err != nil {
logrus.Errorf("decode task info error :%s", err)
continue
}
t.RemoveTask(task)
case watch.Error:
errChan <- ev.Error
}
}
}
func (t *TaskEngine) getTaskFromKey(key string) *model.Task {
index := strings.LastIndex(key, "/")
if index < 0 {
return nil
}
id := key[index+1:]
return t.GetTask(id)
}
//RemoveTask 从缓存移除task
func (t *TaskEngine) RemoveTask(task *model.Task) {
t.tasksLock.Lock()
defer t.tasksLock.Unlock()
if _, ok := t.tasks[task.ID]; ok {
delete(t.tasks, task.ID)
}
}
func (t *TaskEngine) getTaskFromKV(kv *mvccpb.KeyValue) *model.Task {
var task model.Task
if err := ffjson.Unmarshal(kv.Value, &task); err != nil {
logrus.Error("parse task info error:", err.Error())
return nil
}
return &task
}
//LoadStaticTask 从文件加载task
//TODO:动态加载
func (t *TaskEngine) LoadStaticTask() {
logrus.Infof("start load static task form path:%s", t.config.StaticTaskPath)
file, err := os.Stat(t.config.StaticTaskPath)
if err != nil {
logrus.Errorf("load static task error %s", err.Error())
return
}
if file.IsDir() {
files, err := ioutil.ReadDir(t.config.StaticTaskPath)
if err != nil {
logrus.Errorf("load static task error %s", err.Error())
return
}
for _, file := range files {
if file.IsDir() {
continue
} else if strings.HasSuffix(file.Name(), ".json") {
t.loadFile(path.Join(t.config.StaticTaskPath, file.Name()))
}
}
} else {
t.loadFile(t.config.StaticTaskPath)
}
}
func (t *TaskEngine) loadFile(path string) {
taskBody, err := ioutil.ReadFile(path)
if err != nil {
logrus.Errorf("read static task file %s error.%s", path, err.Error())
return
}
var filename string
index := strings.LastIndex(path, "/")
if index < 0 {
filename = path
}
filename = path[index+1:]
if strings.Contains(filename, "group") {
var group model.TaskGroup
if err := ffjson.Unmarshal(taskBody, &group); err != nil {
logrus.Errorf("unmarshal static task file %s error.%s", path, err.Error())
return
}
if group.Name == "" {
logrus.Errorf("task group name can not be empty. file %s", path)
return
}
if group.ID == "" {
group.ID = group.Name
}
if group.Tasks == nil {
logrus.Errorf("task group tasks can not be empty. file %s", path)
return
}
for _, task := range group.Tasks {
task.GroupID = group.ID
if task.Name == "" {
logrus.Errorf("task name can not be empty. file %s", path)
return
}
if task.ID == "" {
task.ID = task.Name
}
if task.Temp == nil {
logrus.Errorf("task [%s] temp can not be empty.", task.Name)
return
}
if task.Temp.ID == "" {
task.Temp.ID = task.Temp.Name
}
t.AddTask(task)
}
t.UpdateGroup(&group)
logrus.Infof("Load a static group %s.", group.Name)
}
if strings.Contains(filename, "task") {
var task model.Task
if err := ffjson.Unmarshal(taskBody, &task); err != nil {
logrus.Errorf("unmarshal static task file %s error.%s", path, err.Error())
return
}
if task.Name == "" {
logrus.Errorf("task name can not be empty. file %s", path)
return
}
if task.ID == "" {
task.ID = task.Name
}
if task.Temp == nil {
logrus.Errorf("task [%s] temp can not be empty.", task.Name)
return
}
if task.Temp.ID == "" {
task.Temp.ID = task.Temp.Name
}
t.AddTask(&task)
logrus.Infof("Load a static task %s.", task.Name)
}
}
//GetTask gettask
func (t *TaskEngine) GetTask(taskID string) *model.Task {
t.tasksLock.Lock()
defer t.tasksLock.Unlock()
if task, ok := t.tasks[taskID]; ok {
return task
}
res, err := store.DefalutClient.Get("/rainbond/store/tasks/" + taskID)
if err != nil {
return nil
}
if res.Count < 1 {
return nil
}
var task model.Task
if err := ffjson.Unmarshal(res.Kvs[0].Value, &task); err != nil {
return nil
}
if task.Status == nil {
task.Status = map[string]model.TaskStatus{}
}
return &task
}
//AddTask 添加task
//新添加task
func (t *TaskEngine) AddTask(task *model.Task) error {
oldTask := t.GetTask(task.ID)
if oldTask != nil {
task.Status = oldTask.Status
task.OutPut = oldTask.OutPut
task.EventID = oldTask.EventID
task.CreateTime = oldTask.CreateTime
task.ExecCount = oldTask.ExecCount
task.StartTime = oldTask.StartTime
if oldTask.Scheduler.Status != nil {
task.Scheduler.Status = oldTask.Scheduler.Status
}
}
if task.Temp == nil {
return fmt.Errorf("task temp can not be nil")
}
if task.EventID == "" {
task.EventID = task.ID
}
if len(task.Nodes) == 0 {
task.Nodes = t.nodeCluster.GetLabelsNode(task.Temp.Labels)
}
if task.Status == nil {
task.Status = map[string]model.TaskStatus{}
}
if task.CreateTime.IsZero() {
task.CreateTime = time.Now()
}
if task.Temp.CreateTime.IsZero() {
task.Temp.CreateTime = time.Now()
}
if task.Scheduler.Mode == "" {
task.Scheduler.Mode = "Passive"
}
if task.RunMode == "" {
task.RunMode = string(job.OnlyOnce)
}
t.CacheTask(task)
_, err := store.DefalutClient.Put("/rainbond/store/tasks/"+task.ID, task.String())
if err != nil {
return err
}
if task.Scheduler.Mode == "Intime" {
for _, node := range t.nodeCluster.GetLabelsNode(task.Temp.Labels) {
t.PutSchedul(task.ID, node)
}
}
return nil
}
//UpdateTask 更新task
func (t *TaskEngine) UpdateTask(task *model.Task) {
t.tasksLock.Lock()
defer t.tasksLock.Unlock()
t.tasks[task.ID] = task
_, err := store.DefalutClient.Put("/rainbond/store/tasks/"+task.ID, task.String())
if err != nil {
logrus.Errorf("update task error,%s", err.Error())
}
}
//UpdateGroup 更新taskgroup
func (t *TaskEngine) UpdateGroup(group *model.TaskGroup) {
group.Tasks = nil
_, err := store.DefalutClient.Put("/rainbond/store/taskgroups/"+group.ID, group.String())
if err != nil {
logrus.Errorf("update taskgroup error,%s", err.Error())
}
}
//GetTaskGroup 获取taskgroup
func (t *TaskEngine) GetTaskGroup(taskGroupID string) *model.TaskGroup {
res, err := store.DefalutClient.Get("/rainbond/store/taskgroups/" + taskGroupID)
if err != nil {
return nil
}
if res.Count < 1 {
return nil
}
var group model.TaskGroup
if err := ffjson.Unmarshal(res.Kvs[0].Value, &group); err != nil {
return nil
}
return &group
}
//CacheTask 缓存task
func (t *TaskEngine) CacheTask(task *model.Task) {
t.tasksLock.Lock()
defer t.tasksLock.Unlock()
if task.Status == nil {
task.Status = map[string]model.TaskStatus{}
}
t.tasks[task.ID] = task
}
//AddGroupConfig 添加组会话配置
func (t *TaskEngine) AddGroupConfig(groupID string, configs map[string]string) {
ctx := t.dataCenterConfig.GetGroupConfig(groupID)
for k, v := range configs {
ctx.Add(k, v)
}
}