Robin Thellend | 8eb7752 | 2014-08-28 14:12:01 -0700 | [diff] [blame] | 1 | package ipc |
| 2 | |
| 3 | import ( |
| 4 | "sync" |
| 5 | "time" |
| 6 | |
Jiri Simsa | 519c507 | 2014-09-17 21:37:57 -0700 | [diff] [blame] | 7 | "veyron.io/veyron/veyron/lib/stats" |
| 8 | "veyron.io/veyron/veyron/lib/stats/histogram" |
Robin Thellend | 8eb7752 | 2014-08-28 14:12:01 -0700 | [diff] [blame] | 9 | |
Jiri Simsa | 519c507 | 2014-09-17 21:37:57 -0700 | [diff] [blame] | 10 | "veyron.io/veyron/veyron2/naming" |
Robin Thellend | 8eb7752 | 2014-08-28 14:12:01 -0700 | [diff] [blame] | 11 | ) |
| 12 | |
| 13 | type ipcStats struct { |
| 14 | mu sync.RWMutex |
| 15 | prefix string |
| 16 | methods map[string]*perMethodStats |
| 17 | } |
| 18 | |
| 19 | func newIPCStats(prefix string) *ipcStats { |
| 20 | return &ipcStats{prefix: prefix, methods: make(map[string]*perMethodStats)} |
| 21 | } |
| 22 | |
| 23 | type perMethodStats struct { |
| 24 | latency *histogram.Histogram |
| 25 | } |
| 26 | |
Robin Thellend | df42823 | 2014-10-06 12:50:44 -0700 | [diff] [blame] | 27 | func (s *ipcStats) stop() { |
| 28 | stats.Delete(s.prefix) |
| 29 | } |
| 30 | |
Robin Thellend | 8eb7752 | 2014-08-28 14:12:01 -0700 | [diff] [blame] | 31 | func (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. |
| 46 | func (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 | } |