-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.go
134 lines (120 loc) · 2.3 KB
/
worker.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
package fwk
import (
"fmt"
)
type workercontrol struct {
evts chan int64
quit chan struct{}
done chan struct{}
errc chan error
}
type worker struct {
slot int
keys []string
store datastore
ctxs []context
msg msgstream
evts <-chan int64
quit <-chan struct{}
done chan<- struct{}
errc chan<- error
}
func newWorker(i int, app *appmgr, ctrl *workercontrol) *worker {
wrk := &worker{
slot: i,
keys: app.dflow.keys(),
store: *app.store,
ctxs: make([]context, len(app.tsks)),
msg: NewMsgStream(fmt.Sprintf("%s-worker-%03d", app.name, i), app.msg.lvl, nil),
evts: ctrl.evts,
quit: ctrl.quit,
done: ctrl.done,
errc: ctrl.errc,
}
wrk.store.store = make(map[string]achan, len(wrk.keys))
for j, tsk := range app.tsks {
wrk.ctxs[j] = context{
id: -1,
slot: i,
store: &wrk.store,
msg: NewMsgStream(tsk.Name(), app.msg.lvl, nil),
mgr: nil, // nobody's supposed to access mgr's state during event-loop
}
}
go wrk.run(app.tsks)
return wrk
}
func (wrk *worker) run(tsks []Task) {
defer func() {
wrk.done <- struct{}{}
}()
for {
select {
case ievt, ok := <-wrk.evts:
if !ok {
return
}
wrk.msg.Debugf(">>> running evt=%d...\n", ievt)
err := wrk.store.reset(wrk.keys)
if err != nil {
wrk.errc <- err
return
}
evt := taskrunner{
ievt: ievt,
errc: make(chan error, len(tsks)),
quit: make(chan struct{}),
}
for i, tsk := range tsks {
go evt.run(i, wrk.ctxs[i], tsk)
}
ndone := 0
errloop:
for {
select {
case err, ok := <-evt.errc:
if !ok {
return
}
ndone++
if err != nil {
close(evt.quit)
wrk.store.close()
wrk.msg.flush()
wrk.errc <- err
return
}
if ndone == len(tsks) {
break errloop
}
case <-wrk.quit:
wrk.store.close()
close(evt.quit)
wrk.msg.flush()
return
}
}
wrk.store.close()
close(evt.quit)
wrk.msg.flush()
case <-wrk.quit:
wrk.store.close()
return
}
}
}
type taskrunner struct {
errc chan error
quit chan struct{}
ievt int64
}
func (run taskrunner) run(i int, ctx context, tsk Task) {
ctx.id = run.ievt
select {
case run.errc <- tsk.Process(ctx):
// FIXME(sbinet) dont be so eager to flush...
ctx.msg.flush()
case <-run.quit:
ctx.msg.flush()
}
}