forked from smallnest/rpcx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
metrics.go
84 lines (69 loc) · 2.2 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
package plugin
import (
"net"
"net/rpc"
"time"
"github.com/rcrowley/go-metrics"
)
//MetricsPlugin collects metrics of a rpc server
type MetricsPlugin struct {
Registry metrics.Registry
seqs map[uint64]int64
}
//NewMetricsPlugin creates a new MetricsPlugirn
func NewMetricsPlugin() *MetricsPlugin {
return &MetricsPlugin{Registry: metrics.NewRegistry(), seqs: make(map[uint64]int64, 100)}
}
// Register handles registering event.
func (plugin *MetricsPlugin) Register(name string, rcvr interface{}) error {
serviceCounter := metrics.GetOrRegisterCounter("serviceCounter", plugin.Registry)
serviceCounter.Inc(1)
return nil
}
// HandleConnAccept handles connections from clients
func (plugin *MetricsPlugin) HandleConnAccept(net.Conn) bool {
clientMeter := metrics.GetOrRegisterMeter("clientMeter", plugin.Registry)
clientMeter.Mark(1)
return true
}
// PreReadRequestHeader marks start time of calling service
func (plugin *MetricsPlugin) PreReadRequestHeader(r *rpc.Request) error {
plugin.seqs[r.Seq] = time.Now().UnixNano()
return nil
}
// PostReadRequestHeader counts read
func (plugin *MetricsPlugin) PostReadRequestHeader(r *rpc.Request) error {
if r.ServiceMethod == "" {
return nil
}
m := metrics.GetOrRegisterMeter("service_"+r.ServiceMethod+"_Read_Counter", plugin.Registry)
m.Mark(1)
return nil
}
// PostWriteResponse count write
func (plugin *MetricsPlugin) PostWriteResponse(r *rpc.Response, body interface{}) error {
if r.ServiceMethod == "" {
return nil
}
m := metrics.GetOrRegisterMeter("service_"+r.ServiceMethod+"_Write_Counter", plugin.Registry)
m.Mark(1)
t := plugin.seqs[r.Seq]
if t > 0 {
t = time.Now().UnixNano() - t
if t < 30*time.Minute.Nanoseconds() { //it is impossible that calltime exceeds 30 minute
//Historgram
h := metrics.GetOrRegisterHistogram("service_"+r.ServiceMethod+"_CallTime", plugin.Registry,
metrics.NewExpDecaySample(1028, 0.015))
h.Update(t)
}
}
return nil
}
// Name return name of this plugin.
func (plugin *MetricsPlugin) Name() string {
return "MetricsPlugin"
}
// Description return description of this plugin.
func (plugin *MetricsPlugin) Description() string {
return "a register plugin which collects metrics of a rpc server"
}