-
Notifications
You must be signed in to change notification settings - Fork 5
/
metrics.go
118 lines (90 loc) · 2.05 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
package p2p
import (
"fmt"
"strings"
"time"
)
type Metrics struct {
topic string
addr string
tm time.Time
handshake time.Duration
read time.Duration
handle time.Duration
write time.Duration
stat []string
}
func newMetrics(addr string) (m *Metrics) {
return &Metrics{
addr: addr,
tm: time.Now(),
handshake: -1,
read: -1,
handle: -1,
write: -1,
stat: []string{fmt.Sprintf("addr (%s)", addr)},
}
}
func (m *Metrics) reset() {
m.tm = time.Now()
}
func (m *Metrics) setTopic(topic string) {
m.topic = topic
}
const statPattern = "%s (%s)"
func (m *Metrics) fixHandshake() {
m.handshake = time.Since(m.tm)
m.stat = append(m.stat, fmt.Sprintf(statPattern, "handshake", prepareValue(m.handshake)))
m.reset()
}
func (m *Metrics) fixReadDuration() {
m.read = time.Since(m.tm)
m.stat = append(m.stat, fmt.Sprintf(statPattern, "read", prepareValue(m.read)))
m.reset()
}
func (m *Metrics) fixHandleDuration() {
m.handle = time.Since(m.tm)
m.stat = append(m.stat, fmt.Sprintf(statPattern, "handle", prepareValue(m.handle)))
m.reset()
}
func (m *Metrics) fixWriteDuration() {
m.write = time.Since(m.tm)
m.stat = append(m.stat, fmt.Sprintf(statPattern, "write", prepareValue(m.write)))
m.reset()
}
func (m *Metrics) string() (line string) {
var total time.Duration
if m.handshake >= 0 {
total += m.handshake
}
if m.read >= 0 {
total += m.read
}
if m.handle >= 0 {
total += m.handle
}
if m.write >= 0 {
total += m.write
}
if total > 0 {
m.stat = append(m.stat, fmt.Sprintf(statPattern, "total", prepareValue(total)))
}
line = fmt.Sprintf("%s: %s", m.topic, strings.Join(m.stat, ", "))
return line
}
func prepareValue(dur time.Duration) (size string) {
const valuePattern = "%d %ss"
ns := dur.Nanoseconds()
if ns < 1000 {
return fmt.Sprintf(valuePattern, ns, "n")
}
mcs := dur.Microseconds()
if mcs < 1000 {
return fmt.Sprintf(valuePattern, mcs, "µ")
}
ms := dur.Milliseconds()
if ms < 1000 {
return fmt.Sprintf(valuePattern, ms, "m")
}
return fmt.Sprintf("%.2f s", dur.Seconds())
}