forked from influxdata/kapacitor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
task_master.go
464 lines (418 loc) · 10.4 KB
/
task_master.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
package kapacitor
import (
"errors"
"fmt"
"log"
"sync"
"time"
"github.com/influxdata/kapacitor/models"
"github.com/influxdata/kapacitor/pipeline"
"github.com/influxdata/kapacitor/services/httpd"
"github.com/influxdata/kapacitor/tick"
"github.com/influxdb/influxdb/client"
"github.com/influxdb/influxdb/cluster"
)
type LogService interface {
NewLogger(prefix string, flag int) *log.Logger
}
type UDFService interface {
FunctionList() []string
FunctionInfo(name string) (UDFProcessInfo, bool)
}
var ErrTaskMasterClosed = errors.New("TaskMaster is closed")
var ErrTaskMasterOpen = errors.New("TaskMaster is open")
// An execution framework for a set of tasks.
type TaskMaster struct {
HTTPDService interface {
AddRoutes([]httpd.Route) error
DelRoutes([]httpd.Route)
URL() string
}
TaskStore interface {
SaveSnapshot(name string, snapshot *TaskSnapshot) error
HasSnapshot(name string) bool
LoadSnapshot(name string) (*TaskSnapshot, error)
}
DeadmanService pipeline.DeadmanService
UDFService UDFService
InfluxDBService interface {
NewClient() (*client.Client, error)
}
SMTPService interface {
Global() bool
SendMail(to []string, subject string, msg string) error
}
OpsGenieService interface {
Global() bool
Alert(teams []string, recipients []string, messageType, message, entityID string, t time.Time, details interface{}) error
}
VictorOpsService interface {
Global() bool
Alert(routingKey, messageType, message, entityID string, t time.Time, extra interface{}) error
}
PagerDutyService interface {
Global() bool
Alert(incidentKey, desc string, details interface{}) error
}
SlackService interface {
Global() bool
Alert(channel, message string, level AlertLevel) error
}
HipChatService interface {
Global() bool
Alert(room, token, message string, level AlertLevel) error
}
AlertaService interface {
Alert(token, resource, event, environment, severity, status, group, value, message, origin string, data interface{}) error
}
SensuService interface {
Alert(name, output string, level AlertLevel) error
}
TalkService interface {
Alert(title, text string) error
}
LogService LogService
// Incoming streams
writePointsIn StreamCollector
// Forks of incoming streams
forks map[string]fork
// Set of incoming batches
batches map[string][]BatchCollector
// Executing tasks
tasks map[string]*ExecutingTask
logger *log.Logger
closed bool
drained bool
mu sync.RWMutex
wg sync.WaitGroup
}
// A fork of the main data stream filtered by a set of DBRPs
type fork struct {
Edge *Edge
dbrps map[DBRP]bool
}
// Create a new Executor with a given clock.
func NewTaskMaster(l LogService) *TaskMaster {
return &TaskMaster{
forks: make(map[string]fork),
batches: make(map[string][]BatchCollector),
tasks: make(map[string]*ExecutingTask),
LogService: l,
logger: l.NewLogger("[task_master] ", log.LstdFlags),
closed: true,
}
}
// Returns a new TaskMaster instance with the same services as the current one.
func (tm *TaskMaster) New() *TaskMaster {
n := NewTaskMaster(tm.LogService)
n.HTTPDService = tm.HTTPDService
n.UDFService = tm.UDFService
n.DeadmanService = tm.DeadmanService
n.TaskStore = tm.TaskStore
n.InfluxDBService = tm.InfluxDBService
n.SMTPService = tm.SMTPService
n.OpsGenieService = tm.OpsGenieService
n.VictorOpsService = tm.VictorOpsService
n.PagerDutyService = tm.PagerDutyService
n.SlackService = tm.SlackService
n.HipChatService = tm.HipChatService
n.AlertaService = tm.AlertaService
n.SensuService = tm.SensuService
n.TalkService = tm.TalkService
return n
}
func (tm *TaskMaster) Open() (err error) {
tm.mu.Lock()
defer tm.mu.Unlock()
if !tm.closed {
return ErrTaskMasterOpen
}
tm.closed = false
tm.drained = false
tm.writePointsIn, err = tm.stream("write_points")
if err != nil {
tm.closed = true
return
}
tm.logger.Println("I! opened")
return
}
func (tm *TaskMaster) StopTasks() {
tm.mu.Lock()
defer tm.mu.Unlock()
for _, et := range tm.tasks {
tm.stopTask(et.Task.Name)
}
}
func (tm *TaskMaster) Close() error {
tm.Drain()
tm.mu.Lock()
defer tm.mu.Unlock()
if tm.closed {
return ErrTaskMasterClosed
}
tm.closed = true
for _, et := range tm.tasks {
tm.stopTask(et.Task.Name)
}
tm.logger.Println("I! closed")
return nil
}
func (tm *TaskMaster) Drain() {
tm.waitForForks()
tm.mu.Lock()
defer tm.mu.Unlock()
for name := range tm.forks {
tm.delFork(name)
}
}
// Create a new task in the context of a TaskMaster
func (tm *TaskMaster) NewTask(
name,
script string,
tt TaskType,
dbrps []DBRP,
snapshotInterval time.Duration,
) (*Task, error) {
t := &Task{
Name: name,
Type: tt,
DBRPs: dbrps,
SnapshotInterval: snapshotInterval,
}
scope := tm.CreateTICKScope()
var srcEdge pipeline.EdgeType
switch tt {
case StreamTask:
srcEdge = pipeline.StreamEdge
case BatchTask:
srcEdge = pipeline.BatchEdge
}
p, err := pipeline.CreatePipeline(script, srcEdge, scope, tm.DeadmanService)
if err != nil {
return nil, err
}
t.Pipeline = p
return t, nil
}
func (tm *TaskMaster) waitForForks() {
if tm.drained {
return
}
tm.drained = true
tm.writePointsIn.Close()
tm.wg.Wait()
}
func (tm *TaskMaster) CreateTICKScope() *tick.Scope {
scope := tick.NewScope()
scope.Set("influxql", newInfluxQL())
scope.Set("time", func(d time.Duration) time.Duration { return d })
// Add dynamic methods to the scope for UDFs
if tm.UDFService != nil {
for _, f := range tm.UDFService.FunctionList() {
f := f
info, _ := tm.UDFService.FunctionInfo(f)
scope.SetDynamicMethod(
f,
tick.DynamicMethod(func(self interface{}, args ...interface{}) (interface{}, error) {
parent, ok := self.(pipeline.Node)
if !ok {
return nil, fmt.Errorf("cannot call %s on %T", f, self)
}
udf := pipeline.NewUDF(
parent,
f,
info.Commander,
info.Timeout,
info.Wants,
info.Provides,
info.Options,
)
return udf, nil
}),
)
}
}
return scope
}
func (tm *TaskMaster) StartTask(t *Task) (*ExecutingTask, error) {
tm.mu.Lock()
defer tm.mu.Unlock()
if tm.closed {
return nil, errors.New("task master is closed cannot start a task")
}
tm.logger.Println("D! Starting task:", t.Name)
et, err := NewExecutingTask(tm, t)
if err != nil {
return nil, err
}
var ins []*Edge
switch et.Task.Type {
case StreamTask:
e, err := tm.newFork(et.Task.Name, et.Task.DBRPs)
if err != nil {
return nil, err
}
ins = []*Edge{e}
case BatchTask:
count, err := et.BatchCount()
if err != nil {
return nil, err
}
ins = make([]*Edge, count)
for i := 0; i < count; i++ {
in := newEdge(t.Name, "batch", fmt.Sprintf("batch%d", i), pipeline.BatchEdge, tm.LogService)
ins[i] = in
tm.batches[t.Name] = append(tm.batches[t.Name], in)
}
}
var snapshot *TaskSnapshot
if tm.TaskStore.HasSnapshot(t.Name) {
snapshot, err = tm.TaskStore.LoadSnapshot(t.Name)
if err != nil {
return nil, err
}
}
err = et.start(ins, snapshot)
if err != nil {
return nil, err
}
tm.tasks[et.Task.Name] = et
tm.logger.Println("I! Started task:", t.Name)
tm.logger.Println("D!", string(t.Dot()))
return et, nil
}
func (tm *TaskMaster) BatchCollectors(name string) []BatchCollector {
return tm.batches[name]
}
func (tm *TaskMaster) StopTask(name string) error {
tm.mu.Lock()
defer tm.mu.Unlock()
return tm.stopTask(name)
}
// internal stopTask function. The caller must have acquired
// the lock in order to call this function
func (tm *TaskMaster) stopTask(name string) (err error) {
if et, ok := tm.tasks[name]; ok {
delete(tm.tasks, name)
if et.Task.Type == StreamTask {
tm.delFork(name)
}
err = et.stop()
if err != nil {
tm.logger.Println("E! Stopped task:", name, err)
} else {
tm.logger.Println("I! Stopped task:", name)
}
}
return
}
func (tm *TaskMaster) IsExecuting(name string) bool {
tm.mu.RLock()
defer tm.mu.RUnlock()
_, executing := tm.tasks[name]
return executing
}
func (tm *TaskMaster) ExecutingDot(name string) string {
tm.mu.RLock()
defer tm.mu.RUnlock()
et, executing := tm.tasks[name]
if executing {
return string(et.EDot())
}
return ""
}
func (tm *TaskMaster) Stream(name string) (StreamCollector, error) {
tm.mu.Lock()
defer tm.mu.Unlock()
return tm.stream(name)
}
func (tm *TaskMaster) stream(name string) (StreamCollector, error) {
if tm.closed {
return nil, ErrTaskMasterClosed
}
in := newEdge("TASK_MASTER", name, "stream", pipeline.StreamEdge, tm.LogService)
tm.drained = false
tm.wg.Add(1)
go tm.runForking(in)
return in, nil
}
func (tm *TaskMaster) runForking(in *Edge) {
defer tm.wg.Done()
for p, ok := in.NextPoint(); ok; p, ok = in.NextPoint() {
tm.forkPoint(p)
}
}
func (tm *TaskMaster) forkPoint(p models.Point) {
tm.mu.RLock()
defer tm.mu.RUnlock()
for _, fork := range tm.forks {
dbrp := DBRP{
Database: p.Database,
RetentionPolicy: p.RetentionPolicy,
}
if fork.dbrps[dbrp] {
fork.Edge.CollectPoint(p)
}
}
}
func (tm *TaskMaster) WritePoints(pts *cluster.WritePointsRequest) error {
if tm.closed {
return ErrTaskMasterClosed
}
for _, mp := range pts.Points {
p := models.Point{
Database: pts.Database,
RetentionPolicy: pts.RetentionPolicy,
Name: mp.Name(),
Group: models.NilGroup,
Tags: models.Tags(mp.Tags()),
Fields: models.Fields(mp.Fields()),
Time: mp.Time(),
}
err := tm.writePointsIn.CollectPoint(p)
if err != nil {
return err
}
}
return nil
}
func (tm *TaskMaster) NewFork(taskName string, dbrps []DBRP) (*Edge, error) {
tm.mu.Lock()
defer tm.mu.Unlock()
return tm.newFork(taskName, dbrps)
}
// internal newFork, must have acquired lock before calling.
func (tm *TaskMaster) newFork(taskName string, dbrps []DBRP) (*Edge, error) {
if tm.closed {
return nil, ErrTaskMasterClosed
}
e := newEdge(taskName, "stream", "stream0", pipeline.StreamEdge, tm.LogService)
tm.forks[taskName] = fork{
Edge: e,
dbrps: CreateDBRPMap(dbrps),
}
return e, nil
}
func (tm *TaskMaster) DelFork(name string) {
tm.mu.Lock()
defer tm.mu.Unlock()
tm.delFork(name)
}
// internal delFork function, must have lock to call
func (tm *TaskMaster) delFork(name string) {
fork := tm.forks[name]
delete(tm.forks, name)
if fork.Edge != nil {
fork.Edge.Close()
}
}
func (tm *TaskMaster) SnapshotTask(name string) (*TaskSnapshot, error) {
tm.mu.RLock()
et, ok := tm.tasks[name]
tm.mu.RUnlock()
if ok {
return et.Snapshot()
}
return nil, fmt.Errorf("task %s is not running or does not exist", name)
}