forked from jcelliott/turnpike
/
websocket_stats.go
79 lines (69 loc) · 1.42 KB
/
websocket_stats.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
package turnpike
import (
"fmt"
"sync"
"time"
)
// Global websocket statistics. Periodically gets reported and cleared.
var wsStats websocketStats
const wsStatsRate = 60 * time.Second
var wsStatsDone chan bool
const (
WSStatsNewPeer = iota
WSStatsSend
WSStatsRecv
WSStatsClose
WSStatsErrPeerTimeout
WSStatsErrPeerClosed
WSStatsItemCount
)
type websocketStats struct {
count [WSStatsItemCount]uint64
lock sync.RWMutex
}
func (s *websocketStats) bumpCount(item int) {
if (item < 0) || (item >= WSStatsItemCount) {
return
}
s.lock.Lock()
defer s.lock.Unlock()
s.count[item]++
}
func (s *websocketStats) formatAndClear() string {
s.lock.Lock()
defer s.lock.Unlock()
str := fmt.Sprintf(
"WS New: %d Send: %d Recv: %d Close: %d PeerTO: %d PeerClosed: %d",
s.count[WSStatsNewPeer],
s.count[WSStatsSend],
s.count[WSStatsRecv],
s.count[WSStatsClose],
s.count[WSStatsErrPeerTimeout],
s.count[WSStatsErrPeerClosed],
)
for i := 0; i < WSStatsItemCount; i++ {
s.count[i] = 0
}
return str
}
// Periodically log the stats then clear them for next time.
// This gets run from the logger init function.
func InitWSStats() {
log.Println("Initializing WS Stats")
ticker := time.NewTicker(wsStatsRate)
go func() {
for {
select {
case <-wsStatsDone:
ticker.Stop()
return
case <-ticker.C:
s := wsStats.formatAndClear()
log.Info(s)
}
}
}()
}
func DoneWSStats() {
wsStatsDone <- true
}