-
Notifications
You must be signed in to change notification settings - Fork 0
/
metrics.go
126 lines (98 loc) · 2.51 KB
/
metrics.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
package localrelay
import (
"sync"
"time"
)
// Metrics stores information such as bandwidth usage
// conn stats etc
type Metrics struct {
up, down int
dialFail, dialSuccess uint64
activeConns int
totalConns uint64
totalRequests uint64
// dialTimes holds recent durations of how long it takes a
// relay to dial a remote
dialTimes []int64
m sync.RWMutex
}
// Upload returns the amount of bytes uploaded through the relay
func (m *Metrics) Upload() int {
m.m.RLock()
defer m.m.RUnlock()
return m.up
}
// Download returns the amount of bytes downloaded through the relay
func (m *Metrics) Download() int {
m.m.RLock()
defer m.m.RUnlock()
return m.down
}
// Connections returns the amount of active and total connections
func (m *Metrics) Connections() (active int, total uint64) {
m.m.RLock()
defer m.m.RUnlock()
return m.activeConns, m.totalConns
}
// Requests returns the amount of requests made via http
func (m *Metrics) Requests() uint64 {
m.m.RLock()
defer m.m.RUnlock()
return m.totalRequests
}
// Dialer returns the successful dials and failed dials
func (m *Metrics) Dialer() (success, failed uint64) {
m.m.RLock()
defer m.m.RUnlock()
return m.dialSuccess, m.dialFail
}
// DialerAvg returns the 10 point average dial time
// this average includes failed dials
func (m *Metrics) DialerAvg() (milliseconds int) {
m.m.RLock()
defer m.m.RUnlock()
if len(m.dialTimes) == 0 {
return 0
}
x := int64(0)
for i := 0; i < len(m.dialTimes); i++ {
x += m.dialTimes[i]
}
return int(x) / len(m.dialTimes)
}
// bandwidth will increment the bandwidth statistics
func (m *Metrics) bandwidth(up, down int) {
m.m.Lock()
defer m.m.Unlock()
m.up += up
m.down += down
}
// dial will increment the dialer success/fail statistics
func (m *Metrics) dial(success, failed uint64, t time.Time) {
m.m.Lock()
defer m.m.Unlock()
m.dialSuccess += success
m.dialFail += failed
// 10 point moving average
if len(m.dialTimes) >= 10 {
m.dialTimes = append(m.dialTimes[1:], time.Since(t).Milliseconds())
} else {
m.dialTimes = append(m.dialTimes, time.Since(t).Milliseconds())
}
}
// connections will update the active connections metric
func (m *Metrics) connections(delta int) {
m.m.Lock()
defer m.m.Unlock()
// Calculate total connections
if delta > 0 {
m.totalConns += uint64(delta)
}
m.activeConns += delta
}
// requests will update the requests metric
func (m *Metrics) requests(delta int) {
m.m.Lock()
defer m.m.Unlock()
m.totalRequests += uint64(delta)
}