File: timer.go

package info (click to toggle)
docker.io 18.09.5+dfsg1-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 65,324 kB
  • sloc: sh: 9,757; makefile: 833; ansic: 239; python: 162; asm: 10
file content (73 lines) | stat: -rw-r--r-- 1,968 bytes parent folder | download | duplicates (6)
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
package metrics

import (
	"time"

	"github.com/prometheus/client_golang/prometheus"
)

// StartTimer begins a timer observation at the callsite. When the target
// operation is completed, the caller should call the return done func().
func StartTimer(timer Timer) (done func()) {
	start := time.Now()
	return func() {
		timer.Update(time.Since(start))
	}
}

// Timer is a metric that allows collecting the duration of an action in seconds
type Timer interface {
	// Update records an observation, duration, and converts to the target
	// units.
	Update(duration time.Duration)

	// UpdateSince will add the duration from the provided starting time to the
	// timer's summary with the precisions that was used in creation of the timer
	UpdateSince(time.Time)
}

// LabeledTimer is a timer that must have label values populated before use.
type LabeledTimer interface {
	WithValues(labels ...string) Timer
}

type labeledTimer struct {
	m *prometheus.HistogramVec
}

func (lt *labeledTimer) WithValues(labels ...string) Timer {
	return &timer{m: lt.m.WithLabelValues(labels...)}
}

func (lt *labeledTimer) Describe(c chan<- *prometheus.Desc) {
	lt.m.Describe(c)
}

func (lt *labeledTimer) Collect(c chan<- prometheus.Metric) {
	lt.m.Collect(c)
}

type timer struct {
	m prometheus.Observer
}

func (t *timer) Update(duration time.Duration) {
	t.m.Observe(duration.Seconds())
}

func (t *timer) UpdateSince(since time.Time) {
	t.m.Observe(time.Since(since).Seconds())
}

func (t *timer) Describe(c chan<- *prometheus.Desc) {
	c <- t.m.(prometheus.Metric).Desc()
}

func (t *timer) Collect(c chan<- prometheus.Metric) {
	// Are there any observers that don't implement Collector? It is really
	// unclear what the point of the upstream change was, but we'll let this
	// panic if we get an observer that doesn't implement collector. In this
	// case, we should almost always see metricVec objects, so this should
	// never panic.
	t.m.(prometheus.Collector).Collect(c)
}