blob: 7ccdcceb07567e638c13071befd91b71a8a70145 [file] [log] [blame]
Jiri Simsad7616c92015-03-24 23:44:30 -07001// Copyright 2015 The Vanadium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
Robin Thellendac59e972014-08-19 18:26:11 -07005package stats
6
7import (
8 "time"
9
Jiri Simsaffceefa2015-02-28 11:03:34 -080010 "v.io/x/ref/lib/stats/histogram"
Robin Thellendac59e972014-08-19 18:26:11 -070011)
12
13// NewHistogram creates a new Histogram StatsObject with the given name and
14// returns a pointer to it.
15func NewHistogram(name string, opts histogram.Options) *histogram.Histogram {
16 lock.Lock()
17 defer lock.Unlock()
18
19 node := findNodeLocked(name, true)
20 h := histogram.New(opts)
21 hw := &histogramWrapper{h}
22 node.object = hw
23
24 addHistogramChild(node, name+"/delta1h", hw, time.Hour, hw.Delta1h)
25 addHistogramChild(node, name+"/delta10m", hw, 10*time.Minute, hw.Delta10m)
26 addHistogramChild(node, name+"/delta1m", hw, time.Minute, hw.Delta1m)
27 return h
28}
29
30type histogramWrapper struct {
31 h *histogram.Histogram
32}
33
34func (hw histogramWrapper) LastUpdate() time.Time {
35 return hw.h.LastUpdate()
36}
37
38func (hw histogramWrapper) Value() interface{} {
39 return hw.h.Value()
40}
41
42func (hw histogramWrapper) Delta1h() interface{} {
43 return hw.h.Delta1h()
44}
45
46func (hw histogramWrapper) Delta10m() interface{} {
47 return hw.h.Delta10m()
48}
49
50func (hw histogramWrapper) Delta1m() interface{} {
51 return hw.h.Delta1m()
52}
53
54type histogramChild struct {
55 h *histogramWrapper
56 period time.Duration
57 value func() interface{}
58}
59
60func (hc histogramChild) LastUpdate() time.Time {
61 now := time.Now()
62 if t := hc.h.LastUpdate().Add(hc.period); t.Before(now) {
63 return t
64 }
65 return now
66}
67
68func (hc histogramChild) Value() interface{} {
69 return hc.value()
70}
71
72func addHistogramChild(parent *node, name string, h *histogramWrapper, period time.Duration, value func() interface{}) {
73 child := findNodeLocked(name, true)
74 child.object = &histogramChild{h, period, value}
75}