This repository has been archived by the owner on Nov 8, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 296
/
task.go
507 lines (442 loc) · 12.5 KB
/
task.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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
/*
http://www.apache.org/licenses/LICENSE-2.0.txt
Copyright 2015 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package scheduler
import (
"errors"
"fmt"
"net"
"strconv"
"sync"
"time"
log "github.com/Sirupsen/logrus"
"github.com/intelsdi-x/gomit"
"github.com/pborman/uuid"
"github.com/intelsdi-x/snap/core"
"github.com/intelsdi-x/snap/core/scheduler_event"
"github.com/intelsdi-x/snap/grpc/controlproxy"
"github.com/intelsdi-x/snap/pkg/schedule"
"github.com/intelsdi-x/snap/scheduler/wmap"
)
const (
// DefaultDeadlineDuration - The default timeout is 5 second
DefaultDeadlineDuration = time.Second * 5
// DefaultStopOnFailure is used to set the number of failures before a task is disabled
DefaultStopOnFailure = 10
)
var (
taskLogger = schedulerLogger.WithField("_module", "scheduler-task")
// ErrTaskNotFound - The error message for task not found
ErrTaskNotFound = errors.New("Task not found")
// ErrTaskNotStopped - The error message for task must be stopped
ErrTaskNotStopped = errors.New("Task must be stopped")
// ErrTaskHasAlreadyBeenAdded - The error message for task has already been added
ErrTaskHasAlreadyBeenAdded = errors.New("Task has already been added")
// ErrTaskDisabledOnFailures - The error message for task disabled due to consecutive failures
ErrTaskDisabledOnFailures = errors.New("Task disabled due to consecutive failures")
// ErrTaskNotDisabled - The error message for task must be disabled
ErrTaskNotDisabled = errors.New("Task must be disabled")
)
type task struct {
sync.Mutex //protects state
id string
name string
schResponseChan chan schedule.Response
killChan chan struct{}
schedule schedule.Schedule
workflow *schedulerWorkflow
state core.TaskState
creationTime time.Time
lastFireTime time.Time
manager managesWork
metricsManager managesMetrics
deadlineDuration time.Duration
hitCount uint
missedIntervals uint
failureMutex sync.Mutex
failedRuns uint
lastFailureMessage string
lastFailureTime time.Time
stopOnFailure int
eventEmitter gomit.Emitter
RemoteManagers managers
}
//NewTask creates a Task
func newTask(s schedule.Schedule, wf *schedulerWorkflow, m *workManager, mm managesMetrics, emitter gomit.Emitter, opts ...core.TaskOption) (*task, error) {
//Task would always be given a default name.
//However if a user want to change this name, she can pass optional arguments, in form of core.TaskOption
//The new name then get over written.
taskID := uuid.New()
name := fmt.Sprintf("Task-%s", taskID)
wf.eventEmitter = emitter
mgrs := newManagers(mm)
err := createTaskClients(&mgrs, wf)
if err != nil {
return nil, err
}
task := &task{
id: taskID,
name: name,
schResponseChan: make(chan schedule.Response),
schedule: s,
state: core.TaskStopped,
creationTime: time.Now(),
workflow: wf,
manager: m,
metricsManager: mm,
deadlineDuration: DefaultDeadlineDuration,
stopOnFailure: DefaultStopOnFailure,
eventEmitter: emitter,
RemoteManagers: mgrs,
}
//set options
for _, opt := range opts {
opt(task)
}
return task, nil
}
// Option sets the options specified.
// Returns an option to optionally restore the last arg's previous value.
func (t *task) Option(opts ...core.TaskOption) core.TaskOption {
var previous core.TaskOption
for _, opt := range opts {
previous = opt(t)
}
return previous
}
//Returns the name of the task
func (t *task) GetName() string {
return t.name
}
func (t *task) SetName(name string) {
t.name = name
}
// CreateTime returns the time the task was created.
func (t *task) CreationTime() *time.Time {
return &t.creationTime
}
func (t *task) DeadlineDuration() time.Duration {
return t.deadlineDuration
}
func (t *task) SetDeadlineDuration(d time.Duration) {
t.deadlineDuration = d
}
func (t *task) SetTaskID(id string) {
t.id = id
}
// HitCount returns the number of times the task has fired.
func (t *task) HitCount() uint {
return t.hitCount
}
// Id returns the tasks Id.
func (t *task) ID() string {
return t.id
}
// LastRunTime returns the time of the tasks last run.
func (t *task) LastRunTime() *time.Time {
return &t.lastFireTime
}
// MissedCount returns the number of intervals missed.
func (t *task) MissedCount() uint {
return t.missedIntervals
}
// FailedRuns returns the number of intervals missed.
func (t *task) FailedCount() uint {
return t.failedRuns
}
// LastFailureMessage returns the last error from a task run
func (t *task) LastFailureMessage() string {
return t.lastFailureMessage
}
// State returns state of the task.
func (t *task) State() core.TaskState {
return t.state
}
// Status returns the state of the workflow.
func (t *task) Status() WorkflowState {
return t.workflow.State()
}
func (t *task) SetStopOnFailure(v int) {
t.stopOnFailure = v
}
func (t *task) SetID(id string) {
t.id = id
}
func (t *task) GetStopOnFailure() int {
return t.stopOnFailure
}
// Spin will start a task spinning in its own routine while it waits for its
// schedule.
func (t *task) Spin() {
// We need to lock long enough to change state
t.Lock()
defer t.Unlock()
// Reset the lastFireTime at each Spin.
// This ensures misses are tracked only forward of the point
// in time that a task starts spinning. E.g. stopping a task,
// waiting a period of time, and starting the task won't show
// misses for the interval while stopped.
t.lastFireTime = time.Now()
if t.state == core.TaskStopped {
t.state = core.TaskSpinning
t.killChan = make(chan struct{})
// spin in a goroutine
go t.spin()
}
}
func (t *task) Stop() {
t.Lock()
defer t.Unlock()
if t.state == core.TaskFiring || t.state == core.TaskSpinning {
t.state = core.TaskStopping
close(t.killChan)
}
}
//Enable changes the state from Disabled to Stopped
func (t *task) Enable() error {
t.Lock()
defer t.Unlock()
if t.state != core.TaskDisabled {
return ErrTaskNotDisabled
}
t.state = core.TaskStopped
return nil
}
func (t *task) Kill() {
t.Lock()
defer t.Unlock()
if t.state == core.TaskFiring || t.state == core.TaskSpinning {
close(t.killChan)
t.state = core.TaskDisabled
}
}
func (t *task) WMap() *wmap.WorkflowMap {
return t.workflow.workflowMap
}
func (t *task) Schedule() schedule.Schedule {
return t.schedule
}
func (t *task) spin() {
var consecutiveFailures int
for {
taskLogger.Debug("task spin loop")
// Start go routine to wait on schedule
go t.waitForSchedule()
// wait here on
// schResponseChan - response from schedule
// killChan - signals task needs to be stopped
select {
case sr := <-t.schResponseChan:
switch sr.State() {
// If response show this schedule is stil active we fire
case schedule.Active:
t.missedIntervals += sr.Missed()
t.lastFireTime = time.Now()
t.hitCount++
t.fire()
if t.lastFailureTime == t.lastFireTime {
consecutiveFailures++
taskLogger.WithFields(log.Fields{
"_block": "spin",
"task-id": t.id,
"task-name": t.name,
"consecutive failures": consecutiveFailures,
"consecutive failure limit": t.stopOnFailure,
"error": t.lastFailureMessage,
}).Warn("Task failed")
} else {
consecutiveFailures = 0
}
if t.stopOnFailure >= 0 && consecutiveFailures >= t.stopOnFailure {
taskLogger.WithFields(log.Fields{
"_block": "spin",
"task-id": t.id,
"task-name": t.name,
"consecutive failures": consecutiveFailures,
"error": t.lastFailureMessage,
}).Error(ErrTaskDisabledOnFailures)
// You must lock on state change for tasks
t.Lock()
t.state = core.TaskDisabled
t.Unlock()
// Send task disabled event
event := new(scheduler_event.TaskDisabledEvent)
event.TaskID = t.id
event.Why = fmt.Sprintf("Task disabled with error: %s", t.lastFailureMessage)
defer t.eventEmitter.Emit(event)
return
}
// Schedule has ended
case schedule.Ended:
// You must lock task to change state
t.Lock()
t.state = core.TaskEnded
t.Unlock()
return //spin
// Schedule has errored
case schedule.Error:
// You must lock task to change state
t.Lock()
t.state = core.TaskDisabled
t.Unlock()
return //spin
}
case <-t.killChan:
// Only here can it truly be stopped
t.Lock()
t.state = core.TaskStopped
t.lastFireTime = time.Time{}
t.Unlock()
return
}
}
}
func (t *task) fire() {
t.Lock()
defer t.Unlock()
t.state = core.TaskFiring
t.workflow.Start(t)
t.state = core.TaskSpinning
}
func (t *task) waitForSchedule() {
select {
case <-t.killChan:
return
case t.schResponseChan <- t.schedule.Wait(t.lastFireTime):
}
}
// RecordFailure updates the failed runs and last failure properties
func (t *task) RecordFailure(e []error) {
// We synchronize this update to ensure it is atomic
t.failureMutex.Lock()
defer t.failureMutex.Unlock()
t.failedRuns++
t.lastFailureTime = t.lastFireTime
t.lastFailureMessage = e[len(e)-1].Error()
}
type taskCollection struct {
*sync.Mutex
table map[string]*task
}
func newTaskCollection() *taskCollection {
return &taskCollection{
Mutex: &sync.Mutex{},
table: make(map[string]*task),
}
}
// Get given a task id returns a Task or nil if not found
func (t *taskCollection) Get(id string) *task {
t.Lock()
defer t.Unlock()
if t, ok := t.table[id]; ok {
return t
}
return nil
}
// Add given a reference to a task adds it to the collection of tasks. An
// error is returned if the task already exists in the collection.
func (t *taskCollection) add(task *task) error {
t.Lock()
defer t.Unlock()
if _, ok := t.table[task.id]; !ok {
//If we don't already have this task in the collection save it
t.table[task.id] = task
} else {
taskLogger.WithFields(log.Fields{
"_module": "scheduler-taskCollection",
"_block": "add",
"task id": task.id,
}).Error(ErrTaskHasAlreadyBeenAdded.Error())
return ErrTaskHasAlreadyBeenAdded
}
return nil
}
// remove will remove a given task from tasks. The task must be stopped.
// Can return errors ErrTaskNotFound and ErrTaskNotStopped.
func (t *taskCollection) remove(task *task) error {
t.Lock()
defer t.Unlock()
if _, ok := t.table[task.id]; ok {
if task.state != core.TaskStopped && task.state != core.TaskDisabled {
taskLogger.WithFields(log.Fields{
"_block": "remove",
"task id": task.id,
}).Error(ErrTaskNotStopped)
return ErrTaskNotStopped
}
delete(t.table, task.id)
} else {
taskLogger.WithFields(log.Fields{
"_block": "remove",
"task id": task.id,
}).Error(ErrTaskNotFound)
return ErrTaskNotFound
}
return nil
}
// Table returns a copy of the taskCollection
func (t *taskCollection) Table() map[string]*task {
t.Lock()
defer t.Unlock()
tasks := make(map[string]*task)
for id, t := range t.table {
tasks[id] = t
}
return tasks
}
// createTaskClients walks the workflowmap and creates clients for this task
// remoteManagers so that nodes that require proxy request can make them.
func createTaskClients(mgrs *managers, wf *schedulerWorkflow) error {
return walkWorkflow(wf.processNodes, wf.publishNodes, mgrs)
}
func walkWorkflow(prnodes []*processNode, pbnodes []*publishNode, mgrs *managers) error {
for _, pr := range prnodes {
if pr.Target != "" {
host, port, err := net.SplitHostPort(pr.Target)
if err != nil {
return err
}
p, err := strconv.Atoi(port)
if err != nil {
return err
}
proxy, err := controlproxy.New(host, p)
if err != nil {
return err
}
mgrs.Add(pr.Target, proxy)
}
err := walkWorkflow(pr.ProcessNodes, pr.PublishNodes, mgrs)
if err != nil {
return err
}
}
for _, pu := range pbnodes {
if pu.Target != "" {
host, port, err := net.SplitHostPort(pu.Target)
if err != nil {
return err
}
p, err := strconv.Atoi(port)
if err != nil {
return err
}
proxy, err := controlproxy.New(host, p)
if err != nil {
return err
}
mgrs.Add(pu.Target, proxy)
}
}
return nil
}