-
Notifications
You must be signed in to change notification settings - Fork 118
/
dispatcher.go
221 lines (199 loc) · 6.13 KB
/
dispatcher.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
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package dispatcher
import (
"fmt"
"sync"
"sync/atomic"
"time"
"go.uber.org/zap"
"github.com/apache/incubator-yunikorn-k8shim/pkg/common/events"
"github.com/apache/incubator-yunikorn-k8shim/pkg/conf"
"github.com/apache/incubator-yunikorn-k8shim/pkg/log"
)
var dispatcher *Dispatcher
var once sync.Once
type EventType int8
const (
EventTypeApp EventType = iota
EventTypeTask
EventTypeNode
EventTypeScheduler
)
var (
AsyncDispatchLimit int32
AsyncDispatchCheckInterval = 3 * time.Second
DispatchTimeout time.Duration
asyncDispatchCount int32 = 0
)
// central dispatcher that dispatches scheduling events.
type Dispatcher struct {
eventChan chan events.SchedulingEvent
stopChan chan struct{}
handlers map[EventType]func(interface{})
running atomic.Value
lock sync.RWMutex
}
func init() {
eventChannelCapacity := conf.GetSchedulerConf().EventChannelCapacity
once.Do(func() {
if dispatcher == nil {
dispatcher = &Dispatcher{
eventChan: make(chan events.SchedulingEvent, eventChannelCapacity),
handlers: make(map[EventType]func(interface{})),
stopChan: make(chan struct{}),
running: atomic.Value{},
lock: sync.RWMutex{},
}
dispatcher.setRunning(false)
}
})
DispatchTimeout = conf.GetSchedulerConf().DispatchTimeout
AsyncDispatchLimit = int32(eventChannelCapacity / 10)
if AsyncDispatchLimit < 10000 {
AsyncDispatchLimit = 10000
}
log.Logger.Info("Init dispatcher",
zap.Int("EventChannelCapacity", eventChannelCapacity),
zap.Int32("AsyncDispatchLimit", AsyncDispatchLimit),
zap.Float64("DispatchTimeoutInSeconds", DispatchTimeout.Seconds()))
}
func RegisterEventHandler(eventType EventType, handlerFn func(interface{})) {
dispatcher.lock.Lock()
defer dispatcher.lock.Unlock()
dispatcher.handlers[eventType] = handlerFn
}
// a thread-safe way to get event handlers
func getEventHandler(eventType EventType) func(interface{}) {
dispatcher.lock.RLock()
defer dispatcher.lock.RUnlock()
return dispatcher.handlers[eventType]
}
// dispatches scheduler events to actual app/task handler,
// each app/task has its own state machine and maintain their own states.
// currently all events share same channel, so they are dispatched
// one by one in order.
func Dispatch(event events.SchedulingEvent) {
// currently if dispatch fails, we simply log the error
// we may revisit this later, e.g add retry here
if err := dispatcher.dispatch(event); err != nil {
log.Logger.Warn("failed to dispatch SchedulingEvent",
zap.Error(err))
}
}
func (p *Dispatcher) isRunning() bool {
return p.running.Load().(bool)
}
func (p *Dispatcher) setRunning(flag bool) {
p.running.Store(flag)
}
func (p *Dispatcher) dispatch(event events.SchedulingEvent) error {
if !p.isRunning() {
return fmt.Errorf("dispatcher is not running")
}
select {
case p.eventChan <- event:
return nil
default:
p.asyncDispatch(event)
return nil
}
}
// async-dispatch try to enqueue the event in every 3 seconds util timeout,
// it's only called when event channel is full.
func (p *Dispatcher) asyncDispatch(event events.SchedulingEvent) {
count := atomic.AddInt32(&asyncDispatchCount, 1)
log.Logger.Warn("event channel is full, transition to async-dispatch mode",
zap.Int32("asyncDispatchCount", count))
if count > AsyncDispatchLimit {
panic(fmt.Errorf("dispatcher exceeds async-dispatch limit"))
}
go func(beginTime time.Time, stop chan struct{}) {
defer atomic.AddInt32(&asyncDispatchCount, -1)
for p.isRunning() {
select {
case <-stop:
return
case p.eventChan <- event:
return
case <-time.After(AsyncDispatchCheckInterval):
elapseTime := time.Since(beginTime)
if elapseTime >= DispatchTimeout {
log.Logger.Error("dispatch timeout",
zap.Float64("elapseSeconds", elapseTime.Seconds()))
return
}
log.Logger.Warn("event channel is full, keep waiting...",
zap.Float64("elapseSeconds", elapseTime.Seconds()))
}
}
}(time.Now(), p.stopChan)
}
func (p *Dispatcher) drain() {
for len(p.eventChan) > 0 {
log.Logger.Info("wait dispatcher to drain",
zap.Int("remaining events", len(p.eventChan)))
time.Sleep(1 * time.Second)
}
log.Logger.Info("dispatcher is draining out")
}
func Start() {
log.Logger.Info("starting the dispatcher")
go func() {
for {
select {
case event := <-dispatcher.eventChan:
switch v := event.(type) {
case events.ApplicationEvent:
getEventHandler(EventTypeApp)(v)
case events.TaskEvent:
getEventHandler(EventTypeTask)(v)
case events.SchedulerEvent:
getEventHandler(EventTypeScheduler)(v)
case events.SchedulerNodeEvent:
getEventHandler(EventTypeNode)(v)
default:
log.Logger.Fatal("unsupported event",
zap.Any("event", v))
}
case <-dispatcher.stopChan:
log.Logger.Info("shutting down event channel")
dispatcher.setRunning(false)
return
}
}
}()
dispatcher.setRunning(true)
}
// stop the dispatcher and wait at most 5 seconds gracefully
func Stop() {
log.Logger.Info("stopping the dispatcher")
select {
case dispatcher.stopChan <- struct{}{}:
maxTimeout := 5
for dispatcher.isRunning() && maxTimeout > 0 {
log.Logger.Info("waiting for dispatcher to be stopped",
zap.Int("remainingSeconds", maxTimeout))
time.Sleep(1 * time.Second)
maxTimeout--
}
if !dispatcher.isRunning() {
log.Logger.Info("dispatcher stopped")
}
default:
log.Logger.Info("dispatcher is already stopped")
}
}