forked from intelsdi-x/snap
/
scheduler.go
636 lines (559 loc) · 18.1 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
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
/*
http://www.apache.org/licenses/LICENSE-2.0.txt
Copyright 2015-2016 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"
"time"
log "github.com/Sirupsen/logrus"
"github.com/intelsdi-x/gomit"
"github.com/intelsdi-x/snap/core"
"github.com/intelsdi-x/snap/core/ctypes"
"github.com/intelsdi-x/snap/core/scheduler_event"
"github.com/intelsdi-x/snap/core/serror"
"github.com/intelsdi-x/snap/pkg/schedule"
"github.com/intelsdi-x/snap/scheduler/wmap"
)
var (
// logger for the scheduler
schedulerLogger = log.WithFields(log.Fields{
"_module": "scheduler",
})
// HandlerRegistrationName registers a handler with the event manager
HandlerRegistrationName = "scheduler"
// ErrMetricManagerNotSet - The error message for metricManager is not set
ErrMetricManagerNotSet = errors.New("MetricManager is not set.")
// ErrSchedulerNotStarted - The error message for scheduler is not started
ErrSchedulerNotStarted = errors.New("Scheduler is not started.")
// ErrTaskAlreadyRunning - The error message for task is already running
ErrTaskAlreadyRunning = errors.New("Task is already running.")
// ErrTaskAlreadyStopped - The error message for task is already stopped
ErrTaskAlreadyStopped = errors.New("Task is already stopped.")
// ErrTaskDisabledNotRunnable - The error message for task is disabled and cannot be started
ErrTaskDisabledNotRunnable = errors.New("Task is disabled. Cannot be started.")
)
type schedulerState int
const (
schedulerStopped schedulerState = iota
schedulerStarted
)
// ManagesMetric is implemented by control
// On startup a scheduler will be created and passed a reference to control
type managesMetrics interface {
collectsMetrics
publishesMetrics
processesMetrics
managesPluginContentTypes
ValidateDeps([]core.Metric, []core.SubscribedPlugin) []serror.SnapError
SubscribeDeps(string, []core.Metric, []core.Plugin) []serror.SnapError
UnsubscribeDeps(string, []core.Metric, []core.Plugin) []serror.SnapError
MatchQueryToNamespaces(core.Namespace) ([]core.Namespace, serror.SnapError)
}
// ManagesPluginContentTypes is an interface to a plugin manager that can tell us what content accept and returns are supported.
type managesPluginContentTypes interface {
GetPluginContentTypes(n string, t core.PluginType, v int) ([]string, []string, error)
}
type collectsMetrics interface {
ExpandWildcards(core.Namespace) ([]core.Namespace, serror.SnapError)
CollectMetrics([]core.Metric, time.Time, string, map[string]map[string]string) ([]core.Metric, []error)
}
type publishesMetrics interface {
PublishMetrics(contentType string, content []byte, pluginName string, pluginVersion int, config map[string]ctypes.ConfigValue, taskID string) []error
}
type processesMetrics interface {
ProcessMetrics(contentType string, content []byte, pluginName string, pluginVersion int, config map[string]ctypes.ConfigValue, taskID string) (string, []byte, []error)
}
type scheduler struct {
workManager *workManager
metricManager managesMetrics
tasks *taskCollection
state schedulerState
eventManager *gomit.EventController
taskWatcherColl *taskWatcherCollection
}
type managesWork interface {
Work(job) queuedJob
}
// New returns an instance of the scheduler
// The MetricManager must be set before the scheduler can be started.
// The MetricManager must be started before it can be used.
func New(cfg *Config) *scheduler {
schedulerLogger.WithFields(log.Fields{
"_block": "New",
"value": cfg.WorkManagerQueueSize,
}).Info("Setting work manager queue size")
schedulerLogger.WithFields(log.Fields{
"_block": "New",
"value": cfg.WorkManagerPoolSize,
}).Info("Setting work manager pool size")
opts := []workManagerOption{
CollectQSizeOption(cfg.WorkManagerQueueSize),
CollectWkrSizeOption(cfg.WorkManagerPoolSize),
PublishQSizeOption(cfg.WorkManagerQueueSize),
PublishWkrSizeOption(cfg.WorkManagerPoolSize),
ProcessQSizeOption(cfg.WorkManagerQueueSize),
ProcessWkrSizeOption(cfg.WorkManagerPoolSize),
}
s := &scheduler{
tasks: newTaskCollection(),
eventManager: gomit.NewEventController(),
taskWatcherColl: newTaskWatcherCollection(),
}
// we are setting the size of the queue and number of workers for
// collect, process and publish consistently for now
s.workManager = newWorkManager(opts...)
s.workManager.Start()
s.eventManager.RegisterHandler(HandlerRegistrationName, s)
return s
}
type taskErrors struct {
errs []serror.SnapError
}
func (t *taskErrors) Errors() []serror.SnapError {
return t.errs
}
func (s *scheduler) Name() string {
return "scheduler"
}
func (s *scheduler) RegisterEventHandler(name string, h gomit.Handler) error {
return s.eventManager.RegisterHandler(name, h)
}
// CreateTask creates and returns task
func (s *scheduler) CreateTask(sch schedule.Schedule, wfMap *wmap.WorkflowMap, startOnCreate bool, opts ...core.TaskOption) (core.Task, core.TaskErrors) {
return s.createTask(sch, wfMap, startOnCreate, "user", opts...)
}
func (s *scheduler) CreateTaskTribe(sch schedule.Schedule, wfMap *wmap.WorkflowMap, startOnCreate bool, opts ...core.TaskOption) (core.Task, core.TaskErrors) {
return s.createTask(sch, wfMap, startOnCreate, "tribe", opts...)
}
func (s *scheduler) createTask(sch schedule.Schedule, wfMap *wmap.WorkflowMap, startOnCreate bool, source string, opts ...core.TaskOption) (core.Task, core.TaskErrors) {
logger := schedulerLogger.WithFields(log.Fields{
"_block": "create-task",
"source": source,
})
// Create a container for task errors
te := &taskErrors{
errs: make([]serror.SnapError, 0),
}
// Return error if we are not started.
if s.state != schedulerStarted {
te.errs = append(te.errs, serror.New(ErrSchedulerNotStarted))
f := buildErrorsLog(te.Errors(), logger)
f.Error("scheduler not started")
return nil, te
}
// Ensure the schedule is valid at this point and time.
if err := sch.Validate(); err != nil {
te.errs = append(te.errs, serror.New(err))
f := buildErrorsLog(te.Errors(), logger)
f.Error("schedule passed not valid")
return nil, te
}
// Generate a workflow from the workflow map
wf, err := wmapToWorkflow(wfMap)
if err != nil {
te.errs = append(te.errs, serror.New(err))
f := buildErrorsLog(te.Errors(), logger)
f.Error(ErrSchedulerNotStarted.Error())
return nil, te
}
// validate plugins and metrics
mts, plugins := s.gatherMetricsAndPlugins(wf)
errs := s.metricManager.ValidateDeps(mts, plugins)
if len(errs) > 0 {
te.errs = append(te.errs, errs...)
return nil, te
}
// Bind plugin content type selections in workflow
err = wf.BindPluginContentTypes(s.metricManager)
if err != nil {
te.errs = append(te.errs, serror.New(err))
f := buildErrorsLog(te.Errors(), logger)
f.Error("unable to bind plugin content types")
return nil, te
}
// Create the task object
task := newTask(sch, wf, s.workManager, s.metricManager, s.eventManager, opts...)
// Add task to taskCollection
if err := s.tasks.add(task); err != nil {
te.errs = append(te.errs, serror.New(err))
f := buildErrorsLog(te.Errors(), logger)
f.Error("errors during task creation")
return nil, te
}
logger.WithFields(log.Fields{
"task-id": task.ID(),
"task-state": task.State(),
}).Info("task created")
event := &scheduler_event.TaskCreatedEvent{
TaskID: task.id,
StartOnCreate: startOnCreate,
Source: source,
}
defer s.eventManager.Emit(event)
if startOnCreate {
logger.WithFields(log.Fields{
"task-id": task.ID(),
"source": source,
}).Info("starting task on creation")
errs := s.StartTask(task.id)
if errs != nil {
te.errs = append(te.errs, errs...)
}
}
return task, te
}
// RemoveTask given a tasks id. The task must be stopped.
// Can return errors ErrTaskNotFound and ErrTaskNotStopped.
func (s *scheduler) RemoveTask(id string) error {
return s.removeTask(id, "user")
}
func (s *scheduler) RemoveTaskTribe(id string) error {
return s.removeTask(id, "tribe")
}
func (s *scheduler) removeTask(id, source string) error {
logger := schedulerLogger.WithFields(log.Fields{
"_block": "remove-task",
"source": source,
})
t, err := s.getTask(id)
if err != nil {
logger.WithFields(log.Fields{
"task id": id,
}).Error(ErrTaskNotFound)
return err
}
event := &scheduler_event.TaskDeletedEvent{
TaskID: t.id,
Source: source,
}
defer s.eventManager.Emit(event)
return s.tasks.remove(t)
}
// GetTasks returns a copy of the tasks in a map where the task id is the key
func (s *scheduler) GetTasks() map[string]core.Task {
tasks := make(map[string]core.Task)
for id, t := range s.tasks.Table() {
tasks[id] = t
}
return tasks
}
// GetTask provided the task id a task is returned
func (s *scheduler) GetTask(id string) (core.Task, error) {
t, err := s.getTask(id)
if err != nil {
schedulerLogger.WithFields(log.Fields{
"_block": "get-task",
"_error": ErrTaskNotFound,
"task-id": id,
}).Error("error getting task")
return nil, err // We do this to send back an explicit nil on the interface
}
return t, nil
}
// StartTask provided a task id a task is started
func (s *scheduler) StartTask(id string) []serror.SnapError {
return s.startTask(id, "user")
}
func (s *scheduler) StartTaskTribe(id string) []serror.SnapError {
return s.startTask(id, "tribe")
}
func (s *scheduler) startTask(id, source string) []serror.SnapError {
logger := schedulerLogger.WithFields(log.Fields{
"_block": "start-task",
"source": source,
})
t, err := s.getTask(id)
if err != nil {
schedulerLogger.WithFields(log.Fields{
"_block": "start-task",
"_error": ErrTaskNotFound,
"task-id": id,
}).Error("error starting task")
return []serror.SnapError{
serror.New(err),
}
}
if t.state == core.TaskDisabled {
logger.WithFields(log.Fields{
"task-id": t.ID(),
}).Error("Task is disabled and must be enabled before starting")
return []serror.SnapError{
serror.New(ErrTaskDisabledNotRunnable),
}
}
if t.state == core.TaskFiring || t.state == core.TaskSpinning {
logger.WithFields(log.Fields{
"task-id": t.ID(),
"task-state": t.State(),
}).Info("task is already running")
return []serror.SnapError{
serror.New(ErrTaskAlreadyRunning),
}
}
mts, plugins := s.gatherMetricsAndPlugins(t.workflow)
cps := returnCorePlugin(plugins)
serrs := s.metricManager.SubscribeDeps(t.ID(), mts, cps)
if len(serrs) > 0 {
// Tear down plugin processes started so far.
uerrs := s.metricManager.UnsubscribeDeps(t.ID(), mts, cps)
errs := append(serrs, uerrs...)
logger.WithFields(log.Fields{
"task-id": t.ID(),
"_error": errs,
}).Error("task failed to start due to dependencies")
return errs
}
event := &scheduler_event.TaskStartedEvent{
TaskID: t.ID(),
Source: source,
}
defer s.eventManager.Emit(event)
t.Spin()
logger.WithFields(log.Fields{
"task-id": t.ID(),
"task-state": t.State(),
}).Info("task started")
return nil
}
// StopTask provided a task id a task is stopped
func (s *scheduler) StopTask(id string) []serror.SnapError {
return s.stopTask(id, "user")
}
func (s *scheduler) StopTaskTribe(id string) []serror.SnapError {
return s.stopTask(id, "tribe")
}
func (s *scheduler) stopTask(id, source string) []serror.SnapError {
logger := schedulerLogger.WithFields(log.Fields{
"_block": "stop-task",
"source": source,
})
t, err := s.getTask(id)
if err != nil {
logger.WithFields(log.Fields{
"_error": err.Error(),
"task-id": id,
}).Error("error stopping task")
return []serror.SnapError{
serror.New(err),
}
}
if t.state == core.TaskStopped {
logger.WithFields(log.Fields{
"task-id": t.ID(),
"task-state": t.State(),
}).Info("task is already stopped")
return []serror.SnapError{
serror.New(ErrTaskAlreadyStopped),
}
}
mts, plugins := s.gatherMetricsAndPlugins(t.workflow)
cps := returnCorePlugin(plugins)
errs := s.metricManager.UnsubscribeDeps(t.ID(), mts, cps)
if len(errs) > 0 {
return errs
}
event := &scheduler_event.TaskStoppedEvent{
TaskID: t.ID(),
Source: source,
}
defer s.eventManager.Emit(event)
t.Stop()
logger.WithFields(log.Fields{
"task-id": t.ID(),
"task-state": t.State(),
}).Info("task stopped")
return nil
}
//EnableTask changes state from disabled to stopped
func (s *scheduler) EnableTask(id string) (core.Task, error) {
t, e := s.getTask(id)
if e != nil {
schedulerLogger.WithFields(log.Fields{
"_block": "enable-task",
"_error": ErrTaskNotFound,
"task-id": id,
}).Error("error enabling task")
return nil, e
}
err := t.Enable()
if err != nil {
schedulerLogger.WithFields(log.Fields{
"_block": "enable-task",
"_error": err.Error(),
"task-id": id,
}).Error("error enabling task")
return nil, err
}
schedulerLogger.WithFields(log.Fields{
"_block": "enable-task",
"task-id": t.ID(),
"task-state": t.State(),
}).Info("task enabled")
return t, nil
}
// Start starts the scheduler
func (s *scheduler) Start() error {
if s.metricManager == nil {
schedulerLogger.WithFields(log.Fields{
"_block": "start-scheduler",
"_error": ErrMetricManagerNotSet.Error(),
}).Error("error on scheduler start")
return ErrMetricManagerNotSet
}
s.state = schedulerStarted
schedulerLogger.WithFields(log.Fields{
"_block": "start-scheduler",
}).Info("scheduler started")
return nil
}
func (s *scheduler) Stop() {
s.state = schedulerStopped
// stop all tasks that are not already stopped
for _, t := range s.tasks.table {
// Kill ensure another task can't turn it back on while we are shutting down
t.Kill()
}
schedulerLogger.WithFields(log.Fields{
"_block": "stop-scheduler",
}).Info("scheduler stopped")
}
// Set metricManager for scheduler
func (s *scheduler) SetMetricManager(mm managesMetrics) {
s.metricManager = mm
schedulerLogger.WithFields(log.Fields{
"_block": "set-metric-manager",
}).Debug("metric manager linked")
}
//
func (s *scheduler) WatchTask(id string, tw core.TaskWatcherHandler) (core.TaskWatcherCloser, error) {
task, err := s.getTask(id)
if err != nil {
schedulerLogger.WithFields(log.Fields{
"_block": "watch-task",
"_error": ErrTaskNotFound,
"task-id": id,
}).Error("error watching task")
return nil, err
}
return s.taskWatcherColl.add(task.ID(), tw)
}
// Central handling for all async events in scheduler
func (s *scheduler) HandleGomitEvent(e gomit.Event) {
switch v := e.Body.(type) {
case *scheduler_event.MetricCollectedEvent:
log.WithFields(log.Fields{
"_module": "scheduler-events",
"_block": "handle-events",
"event-namespace": e.Namespace(),
"task-id": v.TaskID,
"metric-count": len(v.Metrics),
}).Debug("event received")
s.taskWatcherColl.handleMetricCollected(v.TaskID, v.Metrics)
case *scheduler_event.MetricCollectionFailedEvent:
log.WithFields(log.Fields{
"_module": "scheduler-events",
"_block": "handle-events",
"event-namespace": e.Namespace(),
"task-id": v.TaskID,
"errors-count": v.Errors,
}).Debug("event received")
case *scheduler_event.TaskStartedEvent:
log.WithFields(log.Fields{
"_module": "scheduler-events",
"_block": "handle-events",
"event-namespace": e.Namespace(),
"task-id": v.TaskID,
}).Debug("event received")
s.taskWatcherColl.handleTaskStarted(v.TaskID)
case *scheduler_event.TaskStoppedEvent:
log.WithFields(log.Fields{
"_module": "scheduler-events",
"_block": "handle-events",
"event-namespace": e.Namespace(),
"task-id": v.TaskID,
}).Debug("event received")
s.taskWatcherColl.handleTaskStopped(v.TaskID)
case *scheduler_event.TaskDisabledEvent:
log.WithFields(log.Fields{
"_module": "scheduler-events",
"_block": "handle-events",
"event-namespace": e.Namespace(),
"task-id": v.TaskID,
"disabled-reason": v.Why,
}).Debug("event received")
// We need to unsubscribe from deps when a task goes disabled
task, _ := s.getTask(v.TaskID)
mts, plugins := s.gatherMetricsAndPlugins(task.workflow)
cps := returnCorePlugin(plugins)
s.metricManager.UnsubscribeDeps(task.ID(), mts, cps)
s.taskWatcherColl.handleTaskDisabled(v.TaskID, v.Why)
default:
log.WithFields(log.Fields{
"_module": "scheduler-events",
"_block": "handle-events",
"event-namespace": e.Namespace(),
}).Debug("event received")
}
}
func (s *scheduler) getTask(id string) (*task, error) {
task := s.tasks.Get(id)
if task == nil {
return nil, fmt.Errorf("%v: ID(%v)", ErrTaskNotFound, id)
}
return task, nil
}
func (s *scheduler) gatherMetricsAndPlugins(wf *schedulerWorkflow) ([]core.Metric, []core.SubscribedPlugin) {
var (
mts []core.Metric
plugins []core.SubscribedPlugin
)
for _, m := range wf.metrics {
nss, err := s.metricManager.MatchQueryToNamespaces(m.Namespace())
if err != nil {
// use metric directly from the workflow
nss = []core.Namespace{m.Namespace()}
}
for _, ns := range nss {
mts = append(mts, &metric{
namespace: ns,
version: m.Version(),
config: wf.configTree.Get(ns.Strings()),
})
}
}
s.walkWorkflow(wf.processNodes, wf.publishNodes, &plugins)
return mts, plugins
}
func (s *scheduler) walkWorkflow(prnodes []*processNode, pbnodes []*publishNode, plugins *[]core.SubscribedPlugin) {
for _, pr := range prnodes {
*plugins = append(*plugins, pr)
s.walkWorkflow(pr.ProcessNodes, pr.PublishNodes, plugins)
}
for _, pb := range pbnodes {
*plugins = append(*plugins, pb)
}
}
func returnCorePlugin(plugins []core.SubscribedPlugin) []core.Plugin {
cps := make([]core.Plugin, len(plugins))
for i, plugin := range plugins {
cps[i] = plugin
}
return cps
}
func buildErrorsLog(errs []serror.SnapError, logger *log.Entry) *log.Entry {
for i, e := range errs {
logger = logger.WithField(fmt.Sprintf("%s[%d]", "error", i), e.Error())
}
return logger
}