/
scheduler.go
388 lines (309 loc) · 8.07 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
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
package scheduler
/**
* scheduler.go - schedule operations on backends and manages them
*
* @author Yaroslav Pogrebnyak <yyyaroslav@gmail.com>
*/
import (
"fmt"
"time"
"github.com/yyyar/gobetween/core"
"github.com/yyyar/gobetween/discovery"
"github.com/yyyar/gobetween/healthcheck"
"github.com/yyyar/gobetween/logging"
"github.com/yyyar/gobetween/metrics"
"github.com/yyyar/gobetween/stats"
"github.com/yyyar/gobetween/stats/counters"
)
/**
* Backend Operation action
*/
type OpAction int
/**
* Constants for backend operation
*/
const (
IncrementConnection OpAction = iota
DecrementConnection
IncrementRefused
IncrementTx
IncrementRx
)
/**
* Operation on backend
*/
type Op struct {
target core.Target
op OpAction
param interface{}
}
/**
* Request to elect backend
*/
type ElectRequest struct {
Context core.Context
Response chan core.Backend
Err chan error
}
/**
* Scheduler
*/
type Scheduler struct {
/* Balancer impl */
Balancer core.Balancer
/* Discovery impl */
Discovery *discovery.Discovery
/* Healthcheck impl */
Healthcheck *healthcheck.Healthcheck
/* ----- backends ------*/
/* Current cached backends map */
backends map[core.Target]*core.Backend
/* Stats */
StatsHandler *stats.Handler
/* ----- channels ----- */
/* Backend operation channel */
ops chan Op
/* Stop channel */
stop chan bool
/* Elect backend channel */
elect chan ElectRequest
}
/**
* Start scheduler
*/
func (this *Scheduler) Start() {
log := logging.For("scheduler")
log.Info("Starting scheduler ", this.StatsHandler.Name)
this.ops = make(chan Op)
this.elect = make(chan ElectRequest)
this.stop = make(chan bool)
this.backends = make(map[core.Target]*core.Backend)
this.Discovery.Start()
this.Healthcheck.Start()
// backends stats pusher ticker
backendsPushTicker := time.NewTicker(2 * time.Second)
/**
* Goroutine updates and manages backends
*/
go func() {
for {
select {
/* ----- discovery ----- */
// handle newly discovered backends
case backends := <-this.Discovery.Discover():
this.HandleBackendsUpdate(backends)
this.Healthcheck.In <- this.Targets()
this.StatsHandler.BackendsCounter.In <- this.Targets()
/* ------ healthcheck ----- */
// handle backend healthcheck result
case checkResult := <-this.Healthcheck.Out:
this.HandleBackendLiveChange(checkResult.Target, checkResult.Live)
/* ----- stats ----- */
// push current backends to stats handler
case <-backendsPushTicker.C:
this.StatsHandler.Backends <- this.Backends()
// handle new bandwidth stats of a backend
case bs := <-this.StatsHandler.BackendsCounter.Out:
this.HandleBackendStatsChange(bs.Target, &bs)
/* ----- operations ----- */
// handle backend operation
case op := <-this.ops:
this.HandleOp(op)
// elect backend
case electReq := <-this.elect:
this.HandleBackendElect(electReq)
/* ----- stop ----- */
// handle scheduler stop
case <-this.stop:
log.Info("Stopping scheduler ", this.StatsHandler.Name)
backendsPushTicker.Stop()
this.Discovery.Stop()
this.Healthcheck.Stop()
metrics.RemoveServer(fmt.Sprintf("%s", this.StatsHandler.Name), this.backends)
return
}
}
}()
}
/**
* Returns targets of current backends
*/
func (this *Scheduler) Targets() []core.Target {
keys := make([]core.Target, 0, len(this.backends))
for k := range this.backends {
keys = append(keys, k)
}
return keys
}
/**
* Return current backends
*/
func (this *Scheduler) Backends() []core.Backend {
backends := make([]core.Backend, 0, len(this.backends))
for _, b := range this.backends {
backends = append(backends, *b)
}
return backends
}
/**
* Updated backend stats
*/
func (this *Scheduler) HandleBackendStatsChange(target core.Target, bs *counters.BandwidthStats) {
backend, ok := this.backends[target]
if !ok {
logging.For("scheduler").Warn("No backends for checkResult ", target)
return
}
backend.Stats.RxBytes = bs.RxTotal
backend.Stats.TxBytes = bs.TxTotal
backend.Stats.RxSecond = bs.RxSecond
backend.Stats.TxSecond = bs.TxSecond
metrics.ReportHandleBackendStatsChange(fmt.Sprintf("%s", this.StatsHandler.Name), target, this.backends)
}
/**
* Updated backend live status
*/
func (this *Scheduler) HandleBackendLiveChange(target core.Target, live bool) {
backend, ok := this.backends[target]
if !ok {
logging.For("scheduler").Warn("No backends for checkResult ", target)
return
}
backend.Stats.Live = live
metrics.ReportHandleBackendLiveChange(fmt.Sprintf("%s", this.StatsHandler.Name), target, live)
}
/**
* Update backends map
*/
func (this *Scheduler) HandleBackendsUpdate(backends []core.Backend) {
// first mark all existing backends as not discovered
for _, b := range this.backends {
b.Stats.Discovered = false
}
for _, b := range backends {
oldB, ok := this.backends[b.Target]
if ok {
// if we have this backend, update it's discovery properties
oldB.MergeFrom(b)
// mark found backend as discovered
oldB.Stats.Discovered = true
continue
}
b := b // b has to be local variable in order to make unique pointers
b.Stats.Discovered = true
this.backends[b.Target] = &b
}
//remove not discovered backends without active connections
for t, b := range this.backends {
if b.Stats.Discovered || b.Stats.ActiveConnections > 0 {
continue
}
metrics.RemoveBackend(this.StatsHandler.Name, b)
delete(this.backends, t)
}
}
/**
* Perform backend election
*/
func (this *Scheduler) HandleBackendElect(req ElectRequest) {
// Filter only live and discovered backends
var backends []*core.Backend
for _, b := range this.backends {
if !b.Stats.Live {
continue
}
if !b.Stats.Discovered {
continue
}
backends = append(backends, b)
}
// Elect backend
backend, err := this.Balancer.Elect(req.Context, backends)
if err != nil {
req.Err <- err
return
}
req.Response <- *backend
}
/**
* Handle operation on the backend
*/
func (this *Scheduler) HandleOp(op Op) {
// Increment global counter, even if
// backend for this count may be out of discovery pool
switch op.op {
case IncrementTx:
this.StatsHandler.Traffic <- core.ReadWriteCount{CountWrite: op.param.(uint), Target: op.target}
return
case IncrementRx:
this.StatsHandler.Traffic <- core.ReadWriteCount{CountRead: op.param.(uint), Target: op.target}
return
}
log := logging.For("scheduler")
backend, ok := this.backends[op.target]
if !ok {
log.Warn("Trying op ", op.op, " on not tracked target ", op.target)
return
}
switch op.op {
case IncrementRefused:
backend.Stats.RefusedConnections++
case IncrementConnection:
backend.Stats.ActiveConnections++
backend.Stats.TotalConnections++
case DecrementConnection:
backend.Stats.ActiveConnections--
default:
log.Warn("Don't know how to handle op ", op.op)
}
metrics.ReportHandleOp(fmt.Sprintf("%s", this.StatsHandler.Name), op.target, this.backends)
}
/**
* Stop scheduler
*/
func (this *Scheduler) Stop() {
this.stop <- true
}
/**
* Take elect backend for proxying
*/
func (this *Scheduler) TakeBackend(context core.Context) (*core.Backend, error) {
r := ElectRequest{context, make(chan core.Backend), make(chan error)}
this.elect <- r
select {
case err := <-r.Err:
return nil, err
case backend := <-r.Response:
return &backend, nil
}
}
/**
* Increment connection refused count for backend
*/
func (this *Scheduler) IncrementRefused(backend core.Backend) {
this.ops <- Op{backend.Target, IncrementRefused, nil}
}
/**
* Increment backend connection counter
*/
func (this *Scheduler) IncrementConnection(backend core.Backend) {
this.ops <- Op{backend.Target, IncrementConnection, nil}
}
/**
* Decrement backends connection counter
*/
func (this *Scheduler) DecrementConnection(backend core.Backend) {
this.ops <- Op{backend.Target, DecrementConnection, nil}
}
/**
* Increment Rx stats for backend
*/
func (this *Scheduler) IncrementRx(backend core.Backend, c uint) {
this.ops <- Op{backend.Target, IncrementRx, c}
}
/**
* Increment Tx stats for backends
*/
func (this *Scheduler) IncrementTx(backend core.Backend, c uint) {
this.ops <- Op{backend.Target, IncrementTx, c}
}