forked from Meituan-Dianping/cat-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
scheduler.go
120 lines (93 loc) · 2.02 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
package cat
type scheduleMixin struct {
isAlive bool
signals chan int
exitSignal int
}
type scheduleMixer interface {
GetName() string
handle(signal int)
process()
afterStart()
beforeStop()
getScheduleMixin() *scheduleMixin
}
func (p *scheduleMixin) handle(signal int) {
switch signal {
case signalShutdown:
p.isAlive = false
}
}
func (p *scheduleMixin) process() {
return
}
func (p *scheduleMixin) afterStart() {
return
}
func (p *scheduleMixin) beforeStop() {
return
}
func (p *scheduleMixin) getScheduleMixin() *scheduleMixin {
return p
}
func background(p scheduleMixer) {
mixin := p.getScheduleMixin()
mixin.isAlive = true
p.afterStart()
for mixin.isAlive {
p.process()
}
p.beforeStop()
close(mixin.signals)
scheduler.signals <- mixin.exitSignal
}
func makeScheduleMixedIn(exitSignal int) scheduleMixin {
return scheduleMixin{
isAlive: false,
signals: make(chan int),
exitSignal: exitSignal,
}
}
type catScheduler struct {
signals chan int
}
var scheduler = catScheduler{
signals: make(chan int),
}
func (p *catScheduler) shutdownAndWaitGroup(items []scheduleMixer) {
var expectedSignals = make(map[int]string)
var count = 0
for _, v := range items {
mixin := v.getScheduleMixin()
if mixin.isAlive {
mixin.signals <- signalShutdown
expectedSignals[mixin.exitSignal] = v.GetName()
count++
}
}
if count == 0 {
return
}
for signal := range p.signals {
if name, ok := expectedSignals[signal]; ok {
count--
logger.Info("%s exited.", name)
} else {
logger.Warning("Unpredicted signal received: %d", signal)
}
if count == 0 {
break
}
}
}
func (p *catScheduler) shutdown() {
group1 := []scheduleMixer{&router, &monitor}
group2 := []scheduleMixer{aggregator.transaction, aggregator.event, aggregator.metric}
group3 := []scheduleMixer{&sender}
disable()
logger.Info("Received shutdown request, scheduling...")
p.shutdownAndWaitGroup(group1)
p.shutdownAndWaitGroup(group2)
p.shutdownAndWaitGroup(group3)
logger.Info("All systems down.")
}