/
worker.go
146 lines (127 loc) · 2.57 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
135
136
137
138
139
140
141
142
143
144
145
146
// Copyright ©2017 The go-hep Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package fwk
import (
"context"
"fmt"
)
type workercontrol struct {
evts chan ctxType
done chan struct{}
errc chan error
runctx context.Context
}
type worker struct {
slot int
keys []string
//store datastore
ctxs []ctxType
msg msgstream
evts <-chan ctxType
done chan<- struct{}
errc chan<- error
runctx context.Context
}
func newWorker(i int, app *appmgr, ctrl *workercontrol) *worker {
wrk := &worker{
slot: i,
keys: app.dflow.keys(),
ctxs: make([]ctxType, len(app.tsks)),
msg: newMsgStream(fmt.Sprintf("%s-worker-%03d", app.name, i), app.msg.lvl, nil),
evts: ctrl.evts,
done: ctrl.done,
errc: ctrl.errc,
runctx: ctrl.runctx,
}
for j, tsk := range app.tsks {
wrk.ctxs[j] = ctxType{
id: -1,
slot: i,
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.runTask(wrk.runctx, ievt, tsks)
case <-wrk.runctx.Done():
//wrk.store.close()
return
}
}
}
func (wrk *worker) runTask(ctx context.Context, ievt ctxType, tsks []Task) {
wrk.msg.Debugf(">>> running evt=%d...\n", ievt.ID())
evtstore := ievt.store.(*datastore)
evtctx, evtCancel := context.WithCancel(wrk.runctx)
defer evtCancel()
evt := taskrunner{
ievt: ievt.ID(),
errc: make(chan error, len(tsks)),
evtctx: evtctx,
}
for i, tsk := range tsks {
ctx := wrk.ctxs[i]
ctx.store = evtstore
ctx.ctx = evtctx
go evt.run(i, ctx, tsk)
}
ndone := 0
errloop:
for {
select {
case err, ok := <-evt.errc:
if !ok {
return
}
ndone++
if err != nil {
evtstore.close()
wrk.msg.flush()
wrk.errc <- err
return
}
if ndone == len(tsks) {
break errloop
}
case <-evtctx.Done():
evtstore.close()
wrk.msg.flush()
return
}
}
err := evtstore.reset(wrk.keys)
evtstore.close()
wrk.msg.flush()
if err != nil {
wrk.errc <- err
return
}
}
type taskrunner struct {
errc chan error
evtctx context.Context
ievt int64
}
func (run taskrunner) run(i int, ctx ctxType, 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.evtctx.Done():
ctx.msg.flush()
}
}