blob: 5f6f2ed372c4c90034df7bf6f48dd89618754f60 [file] [log] [blame]
Robin Thellend8eb77522014-08-28 14:12:01 -07001package ipc
2
3import (
4 "sync"
5 "time"
6
Jiri Simsa519c5072014-09-17 21:37:57 -07007 "veyron.io/veyron/veyron/lib/stats"
8 "veyron.io/veyron/veyron/lib/stats/histogram"
Robin Thellend8eb77522014-08-28 14:12:01 -07009
Jiri Simsa519c5072014-09-17 21:37:57 -070010 "veyron.io/veyron/veyron2/naming"
Robin Thellend8eb77522014-08-28 14:12:01 -070011)
12
13type ipcStats struct {
14 mu sync.RWMutex
15 prefix string
16 methods map[string]*perMethodStats
17}
18
19func newIPCStats(prefix string) *ipcStats {
20 return &ipcStats{prefix: prefix, methods: make(map[string]*perMethodStats)}
21}
22
23type perMethodStats struct {
24 latency *histogram.Histogram
25}
26
Robin Thellenddf428232014-10-06 12:50:44 -070027func (s *ipcStats) stop() {
28 stats.Delete(s.prefix)
29}
30
Robin Thellend8eb77522014-08-28 14:12:01 -070031func (s *ipcStats) record(method string, latency time.Duration) {
32 // Try first with a read lock. This will succeed in the most common
33 // case. If it fails, try again with a write lock and create the stats
34 // objects if they are still not there.
35 s.mu.RLock()
36 m, ok := s.methods[method]
37 s.mu.RUnlock()
38 if !ok {
39 m = s.newPerMethodStats(method)
40 }
41 m.latency.Add(int64(latency / time.Millisecond))
42}
43
44// newPerMethodStats creates a new perMethodStats object if one doesn't exist
45// already. It returns the newly created object, or the already existing one.
46func (s *ipcStats) newPerMethodStats(method string) *perMethodStats {
47 s.mu.Lock()
48 defer s.mu.Unlock()
49 m, ok := s.methods[method]
50 if !ok {
51 name := naming.Join(s.prefix, method, "latency-ms")
52 s.methods[method] = &perMethodStats{
53 latency: stats.NewHistogram(name, histogram.Options{
54 NumBuckets: 25,
55 GrowthFactor: 1,
56 SmallestBucketSize: 1,
57 MinValue: 0,
58 }),
59 }
60 m = s.methods[method]
61 }
62 return m
63}