-
Notifications
You must be signed in to change notification settings - Fork 0
/
hub.go
539 lines (502 loc) · 13.9 KB
/
hub.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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
package net4g
import (
"errors"
"fmt"
"github.com/carsonsx/log4g"
"runtime/debug"
"sync"
"time"
)
func NewNetHub(heartbeat bool, lb bool) *netHub {
hub := new(netHub)
hub.heartbeat = heartbeat
hub.enableLB = lb
hub.start()
return hub
}
type NetHub interface {
Add(key string, conn NetConn)
Key(conn NetConn, key string)
Get(key string) NetConn
Remove(conn NetConn)
Slice() []NetConn
Count() int
Heartbeat(conn NetConn)
Kick(key string)
SetSerializer(serializer Serializer)
Broadcast(v interface{}, filter func(session NetSession) bool, h ...interface{}) error
BroadcastAll(v interface{}, h ...interface{}) error
BroadcastOthers(mySession NetSession, v interface{}, h ...interface{}) error
BroadcastOne(v interface{}, errFunc func(error), h ...interface{}) error
Send(key string, v interface{}) error
MultiSend(keys []string, v interface{}) error
SetGroup(session NetSession, group string)
Group(group string, v interface{}, h ...interface{}) error
GroupOne(group string, v interface{}, errFunc func(error), h ...interface{}) error
RangeConn(f func(NetConn))
RangeSession(f func(session NetSession))
Statistics()
PackCount() (totalRead int64, totalWrite int64, popRead int64, popWrite int64)
DataUsage() (totalRead int64, totalWrite int64, popRead int64, popWrite int64)
Closed() bool
Destroy()
}
type netHub struct {
connections map[string]NetConn
groupsConn map[string][]NetConn
groupsRound map[string]int
groupMutex sync.Mutex
enableLB bool
lbConnections []NetConn
lbRound int
serializer Serializer
addChan chan *chanData
getChan chan *chanData
hasChan chan *chanData
sendChan chan *chanData
sliceChan chan *chanData
keyChan chan *chanData
removeChan chan NetConn
countChan chan *chanData
size int
heartbeat bool
heartbeatTicker *time.Ticker
heartbeatTimeout time.Duration
kickChan chan string
broadcastChan chan *chanData
closeAll chan bool
closing chan bool
closed bool
wg sync.WaitGroup
totalReadCount int64
totalWrittenCount int64
popReadCount int64
popWriteCount int64
totalReadDataUsage int64
totalWrittenDataUsage int64
popReadDataUsage int64
popWriteDataUsage int64
}
type chanData struct {
conn NetConn
conns []NetConn
key string
keys []string
value interface{}
one bool
group string
data []byte
filter func(session NetSession) bool
once bool
errFunc func(err error)
wg sync.WaitGroup
}
func (hub *netHub) start() {
hub.connections = make(map[string]NetConn)
hub.groupsConn = make(map[string][]NetConn)
hub.groupsRound = make(map[string]int)
hub.addChan = make(chan *chanData, 100)
hub.keyChan = make(chan *chanData, 100)
hub.getChan = make(chan *chanData, 1)
hub.hasChan = make(chan *chanData, 1)
hub.sendChan = make(chan *chanData, 1)
hub.sliceChan = make(chan *chanData, 1)
hub.removeChan = make(chan NetConn, 100)
hub.countChan = make(chan *chanData, 1)
hub.kickChan = make(chan string, 10)
hub.broadcastChan = make(chan *chanData, 1000)
hub.closeAll = make(chan bool, 1)
hub.closing = make(chan bool, 1)
hub.wg.Add(1)
go func() {
hub.heartbeatTimeout = (NetConfig.HeartbeatFrequency + NetConfig.NetTolerableTime) * time.Second
hub.heartbeatTicker = time.NewTicker(hub.heartbeatTimeout)
//hub.heartbeatTicker = time.NewTicker(HEART_BEAT_INTERVAL)
if !hub.heartbeat {
hub.heartbeatTicker.Stop()
}
for {
if !hub.do() {
break
}
}
hub.wg.Done()
}()
}
func (hub *netHub) do() (cond bool) {
defer func() {
if r := recover(); r != nil {
log4g.Error("********************* Hub Panic *********************")
log4g.Error(r)
log4g.Error(string(debug.Stack()))
log4g.Error("********************* Hub Panic *********************")
cond = true
}
}()
select {
case cData := <-hub.addChan:
cData.conn.Session().Set(SESSION_CONNECT_KEY, cData.key)
hub.connections[cData.key] = cData.conn
if hub.enableLB {
hub.lbConnections = append(hub.lbConnections, cData.conn)
}
hub.size++
log4g.Info("connection count: %d", len(hub.connections))
cData.wg.Done()
case key := <-hub.kickChan:
if conn, ok := hub.connections[key]; ok {
conn.Close()
hub._delete(conn)
log4g.Warn("kicked connection %s", conn.RemoteAddr().String())
log4g.Info("connection count: %d", len(hub.connections))
}
case cData := <-hub.keyChan:
if _, ok := hub.connections[cData.key]; ok {
log4g.Panic("connection name '%s' existed", cData.key)
}
delete(hub.connections, cData.conn.Session().GetString(SESSION_CONNECT_KEY))
cData.conn.Session().Set(SESSION_CONNECT_KEY, cData.key)
cData.conn.Session().Set(SESSION_CONNECT_KEY_USER, cData.key)
hub.connections[cData.key] = cData.conn
cData.wg.Done()
log4g.Debug("connection key set: %s", cData.key)
case cData := <-hub.getChan:
cData.conn = hub.connections[cData.key]
cData.wg.Done()
case cData := <-hub.hasChan:
cData.one = false
for _, conn := range hub.connections {
if conn.Session().Get(cData.key) == cData.value {
cData.one = true
break
}
}
cData.wg.Done()
case cData := <-hub.sendChan:
for _, key := range cData.keys {
if conn, ok := hub.connections[key]; ok {
conn.Write(cData.data)
}
}
case cData := <-hub.sliceChan:
for _, conn := range hub.connections {
cData.conns = append(cData.conns, conn)
}
cData.wg.Done()
case conn := <-hub.removeChan:
hub._delete(conn)
log4g.Info("removed connection: %s", conn.Session().Get(SESSION_CONNECT_KEY))
log4g.Info("connection count: %d", len(hub.connections))
case t := <-hub.heartbeatTicker.C:
for _, conn := range hub.connections {
if t.UnixNano() > conn.Session().GetInt64(HEART_BEAT_LAST_TIME)+hub.heartbeatTimeout.Nanoseconds() {
log4g.Warn("client timeout: %s", conn.RemoteAddr().String())
hub._delete(conn)
conn.Close()
}
}
case cData := <-hub.broadcastChan:
if cData.key != "" { // Send to one conn
hub.connections[cData.key].Write(cData.data)
} else if cData.one {
connCount := len(hub.lbConnections)
if connCount > 0 {
if hub.lbRound >= connCount {
hub.lbRound = 0
}
log4g.Trace("group size: %d, round robin: %d", connCount, hub.lbRound)
err := hub.lbConnections[hub.lbRound].Write(cData.data)
if err != nil && cData.errFunc != nil {
cData.errFunc(err)
}
hub.lbRound++
} else if cData.errFunc != nil {
err := errors.New("not found any connection")
log4g.Error(err)
cData.errFunc(err)
}
} else if cData.group != "" { // Send to group
log4g.Debug("send to group %s", cData.group)
conns := hub.groupsConn[cData.group]
if cData.once { // send to group's one by round robin
round := hub.groupsRound[cData.group]
groupsConnCount := len(conns)
if groupsConnCount > 0 {
if round >= groupsConnCount {
round = 0
}
//log4g.Debug("group size: %d, round robin: %d", groupsConnCount, round)
conns[round].Write(cData.data)
round++
hub.groupsRound[cData.group] = round
} else {
err := errors.New(fmt.Sprintf("not found any group[%s] connection", cData.group))
log4g.Error(err)
if cData.errFunc != nil {
cData.errFunc(err)
}
}
} else { // send to group's all
for _, conn := range conns {
conn.Write(cData.data)
}
}
} else { // broadcast by filter
//log4g.Debug("broadcast to %d connections", len(hub.connections))
for _, conn := range hub.connections {
if cData.filter == nil || cData.filter(conn.Session()) {
conn.Write(cData.data)
if log4g.IsDebugEnabled() {
//log4g.Debug("[broadcast] sent to %s", conn.Session().Get(SESSION_ID))
}
if cData.once {
break
}
}
}
}
case cData := <-hub.countChan:
for _, conn := range hub.connections {
rc, wc := conn.PopCount()
hub.totalReadCount += rc
hub.totalWrittenCount += wc
hub.popReadCount += rc
hub.popWriteCount += wc
rdu, wdu := conn.PopDataUsage()
hub.totalReadDataUsage += rdu
hub.totalWrittenDataUsage += wdu
hub.popReadDataUsage += rdu
hub.popWriteDataUsage += wdu
}
cData.wg.Done()
case <-hub.closing:
for _, conn := range hub.connections {
conn.Close()
}
return false
}
return true
}
func (hub *netHub) _delete(conn NetConn) {
if _, ok := hub.connections[conn.Session().GetString(SESSION_CONNECT_KEY)]; !ok {
return
}
delete(hub.connections, conn.Session().GetString(SESSION_CONNECT_KEY))
for i, _conn := range hub.lbConnections {
if _conn == conn {
hub.lbConnections = append(hub.lbConnections[:i], hub.lbConnections[i+1:]...)
break
}
}
gName := conn.Session().GetString(SESSION_GROUP_NAME)
if gName != "" {
hub.groupMutex.Lock()
groups := hub.groupsConn[gName]
for i, c := range groups {
if c == conn {
hub.groupsConn[gName] = append(groups[:i], groups[i+1:]...)
break
}
}
hub.groupMutex.Unlock()
}
hub.size--
if hub.size < 0 { // why?
hub.size = 0
}
}
func (hub *netHub) Add(key string, conn NetConn) {
hub.Heartbeat(conn)
cData := new(chanData)
cData.key = key
cData.conn = conn
cData.wg.Add(1)
hub.addChan <- cData
cData.wg.Wait()
}
func (hub *netHub) Key(conn NetConn, key string) {
if conn.Session().Get(SESSION_CONNECT_KEY) != key {
cData := new(chanData)
cData.conn = conn
cData.key = key
cData.wg.Add(1)
hub.keyChan <- cData
cData.wg.Wait()
}
}
func (hub *netHub) Get(key string) NetConn {
cData := new(chanData)
cData.key = key
cData.wg.Add(1)
hub.getChan <- cData
cData.wg.Wait()
return cData.conn
}
func (hub *netHub) Remove(conn NetConn) {
hub.removeChan <- conn
}
func (hub *netHub) Slice() []NetConn {
cData := new(chanData)
cData.wg.Add(1)
hub.sliceChan <- cData
cData.wg.Wait()
return cData.conns
}
func (hub *netHub) Count() int {
return hub.size
}
func (hub *netHub) Heartbeat(conn NetConn) {
if hub.heartbeat {
conn.Session().Set(HEART_BEAT_LAST_TIME, time.Now().UnixNano())
}
}
func (hub *netHub) Kick(key string) {
hub.kickChan <- key
}
func (hub *netHub) SetSerializer(serializer Serializer) {
hub.serializer = serializer
}
func (hub *netHub) Broadcast(v interface{}, filter func(session NetSession) bool, h ...interface{}) error {
b, err := Serialize(hub.serializer, v, h...)
if err != nil {
log4g.Error(err)
return err
}
cData := new(chanData)
cData.data = b
cData.filter = filter
hub.broadcastChan <- cData
return nil
}
func (hub *netHub) BroadcastAll(v interface{}, h ...interface{}) error {
return hub.Broadcast(v, nil)
}
func (hub *netHub) BroadcastOthers(mySession NetSession, v interface{}, h ...interface{}) error {
return hub.Broadcast(v, func(session NetSession) bool {
return mySession != session
})
}
func (hub *netHub) BroadcastOne(v interface{}, errFunc func(error), h ...interface{}) error {
data, err := Serialize(hub.serializer, v, h...)
if err != nil {
log4g.Error(err)
return err
}
if !hub.enableLB {
panic("required to enable load balance")
}
if hub.closed {
text := "hub was closed"
log4g.Error(text)
return errors.New(text)
}
cData := new(chanData)
cData.one = true
cData.data = data
cData.errFunc = errFunc
hub.broadcastChan <- cData
return nil
}
func (hub *netHub) Send(key string, v interface{}) error {
return hub.MultiSend([]string{key}, v)
}
func (hub *netHub) MultiSend(keys []string, v interface{}) error {
data, err := Serialize(hub.serializer, v)
if err != nil {
return err
}
cData := new(chanData)
cData.keys = keys
cData.data = data
hub.sendChan <- cData
return nil
}
func (hub *netHub) SetGroup(session NetSession, group string) {
if group != "" {
hub.groupMutex.Lock()
conn := hub.Get(session.GetString(SESSION_CONNECT_KEY))
if conn != nil {
groups := hub.groupsConn[group]
hub.groupsConn[group] = append(groups, conn)
session.Set(SESSION_GROUP_NAME, group)
log4g.Debug("set group %s for %s", group, conn.RemoteAddr().String())
log4g.Debug("group size: %d", len(hub.groupsConn[group]))
}
hub.groupMutex.Unlock()
}
}
func (hub *netHub) Group(group string, v interface{}, h ...interface{}) error {
data, err := Serialize(hub.serializer, v, h...)
if err != nil {
log4g.Error(err)
return err
}
cData := new(chanData)
cData.group = group
cData.data = data
hub.broadcastChan <- cData
return nil
}
func (hub *netHub) GroupOne(group string, v interface{}, errFunc func(error), h ...interface{}) error {
data, err := Serialize(hub.serializer, v, h...)
if err != nil {
log4g.Error(err)
return err
}
cData := new(chanData)
cData.group = group
cData.data = data
cData.once = true
cData.errFunc = errFunc
hub.broadcastChan <- cData
return nil
}
func (hub *netHub) RangeConn(f func(NetConn)) {
conns := hub.Slice()
for _, conn := range conns {
f(conn)
}
}
func (hub *netHub) RangeSession(f func(session NetSession)) {
conns := hub.Slice()
for _, conn := range conns {
f(conn.Session())
}
}
func (hub *netHub) Statistics() {
cData := new(chanData)
cData.wg.Add(1)
hub.countChan <- cData
cData.wg.Wait()
}
func (hub *netHub) PackCount() (totalRead int64, totalWrite int64, popRead int64, popWrite int64) {
totalRead = hub.totalReadCount
totalWrite = hub.totalWrittenCount
popRead = hub.popReadCount
hub.popReadCount = 0
popWrite = hub.popWriteCount
hub.popWriteCount = 0
return
}
func (hub *netHub) DataUsage() (totalRead int64, totalWrite int64, popRead int64, popWrite int64) {
totalRead = hub.totalReadDataUsage
totalWrite = hub.totalWrittenDataUsage
popRead = hub.popReadDataUsage
hub.popReadDataUsage = 0
popWrite = hub.popWriteDataUsage
hub.popWriteDataUsage = 0
return
}
func (hub *netHub) Closed() bool {
return hub.closed
}
func (hub *netHub) Destroy() {
hub.closing <- true
hub.wg.Wait()
//close(hub.addChan)
//close(hub.removeChan)
//close(hub.broadcastChan)
//close(hub.closing)
hub.closed = true
log4g.Info("closed net hub")
}