-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathrunner.go
105 lines (83 loc) · 2.27 KB
/
runner.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
package glacier
import (
"fmt"
"reflect"
"sync"
"github.com/mylxsw/glacier/infra"
"github.com/mylxsw/glacier/log"
)
type asyncJob struct {
fn interface{}
}
func (aj asyncJob) Call(resolver infra.Resolver) error {
return resolver.Resolve(aj.fn)
}
// Async 添加一个异步执行函数
func (impl *framework) Async(fns ...interface{}) {
for i, fn := range fns {
if reflect.TypeOf(fn).Kind() != reflect.Func {
panic(fmt.Errorf("invalid argument: fn at %d must be a func", i))
}
impl.lock.Lock()
if impl.status == Started {
impl.asyncJobChannel <- asyncJob{fn: fn}
} else {
impl.asyncJobs = append(impl.asyncJobs, asyncJob{fn: fn})
}
impl.lock.Unlock()
}
}
func (impl *framework) startAsyncRunners() <-chan interface{} {
stop := make(chan interface{})
var parentGraphNode *infra.GraphvizNode
var childGraphNodes []*infra.GraphvizNode
if infra.DEBUG {
parentGraphNode = impl.pushGraphvizNode("start async runners", true)
parentGraphNode.Style = infra.GraphvizNodeStyleImportant
}
impl.asyncJobChannel = make(chan asyncJob)
impl.cc.MustResolve(func(gf infra.Graceful) {
gf.AddShutdownHandler(func() {
close(impl.asyncJobChannel)
})
})
var wg sync.WaitGroup
wg.Add(impl.asyncRunnerCount)
for i := 0; i < impl.asyncRunnerCount; i++ {
if infra.DEBUG {
childGraphNodes = append(childGraphNodes, impl.pushGraphvizNode(fmt.Sprintf("start async runner %d", i), false, parentGraphNode))
log.Debugf("[glacier] async runner %d starting ...", i)
}
go func(i int) {
defer wg.Done()
for job := range impl.asyncJobChannel {
if err := job.Call(impl.cc); err != nil {
log.Errorf("[glacier] async runner [async-runner-%d] failed: %v", i, err)
}
}
if infra.DEBUG {
log.Debugf("[glacier] async runner [async-runner-%d] stopping...", i)
}
}(i)
}
if infra.DEBUG {
impl.pushGraphvizNode("all async runners started", false, childGraphNodes...)
}
go func() {
wg.Wait()
if infra.DEBUG {
impl.pushGraphvizNode("all async runners stopped", false)
log.Debug("[glacier] all async runners stopped")
}
close(stop)
}()
return stop
}
func (impl *framework) consumeAsyncJobs() {
impl.lock.Lock()
defer impl.lock.Unlock()
for _, job := range impl.asyncJobs {
impl.asyncJobChannel <- job
}
impl.asyncJobs = nil
}