File: namespace.go

package info (click to toggle)
golang-github-docker-go-metrics 0.0~git20180209.399ea8c-1
  • links: PTS, VCS
  • area: main
  • in suites: buster, experimental, sid
  • size: 152 kB
  • sloc: makefile: 2
file content (315 lines) | stat: -rw-r--r-- 8,920 bytes parent folder | download
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
package metrics

import (
	"fmt"
	"sync"

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

type Labels map[string]string

// NewNamespace returns a namespaces that is responsible for managing a collection of
// metrics for a particual namespace and subsystem
//
// labels allows const labels to be added to all metrics created in this namespace
// and are commonly used for data like application version and git commit
func NewNamespace(name, subsystem string, labels Labels) *Namespace {
	if labels == nil {
		labels = make(map[string]string)
	}
	return &Namespace{
		name:      name,
		subsystem: subsystem,
		labels:    labels,
	}
}

// Namespace describes a set of metrics that share a namespace and subsystem.
type Namespace struct {
	name      string
	subsystem string
	labels    Labels
	mu        sync.Mutex
	metrics   []prometheus.Collector
}

// WithConstLabels returns a namespace with the provided set of labels merged
// with the existing constant labels on the namespace.
//
//  Only metrics created with the returned namespace will get the new constant
//  labels.  The returned namespace must be registered separately.
func (n *Namespace) WithConstLabels(labels Labels) *Namespace {
	n.mu.Lock()
	ns := &Namespace{
		name:      n.name,
		subsystem: n.subsystem,
		labels:    mergeLabels(n.labels, labels),
	}
	n.mu.Unlock()
	return ns
}

func (n *Namespace) NewCounter(name, help string) Counter {
	c := &counter{pc: prometheus.NewCounter(n.newCounterOpts(name, help))}
	n.Add(c)
	return c
}

func (n *Namespace) NewLabeledCounter(name, help string, labels ...string) LabeledCounter {
	c := &labeledCounter{pc: prometheus.NewCounterVec(n.newCounterOpts(name, help), labels)}
	n.Add(c)
	return c
}

func (n *Namespace) newCounterOpts(name, help string) prometheus.CounterOpts {
	return prometheus.CounterOpts{
		Namespace:   n.name,
		Subsystem:   n.subsystem,
		Name:        makeName(name, Total),
		Help:        help,
		ConstLabels: prometheus.Labels(n.labels),
	}
}

func (n *Namespace) NewTimer(name, help string) Timer {
	t := &timer{
		m: prometheus.NewHistogram(n.newTimerOpts(name, help)),
	}
	n.Add(t)
	return t
}

func (n *Namespace) NewLabeledTimer(name, help string, labels ...string) LabeledTimer {
	t := &labeledTimer{
		m: prometheus.NewHistogramVec(n.newTimerOpts(name, help), labels),
	}
	n.Add(t)
	return t
}

func (n *Namespace) newTimerOpts(name, help string) prometheus.HistogramOpts {
	return prometheus.HistogramOpts{
		Namespace:   n.name,
		Subsystem:   n.subsystem,
		Name:        makeName(name, Seconds),
		Help:        help,
		ConstLabels: prometheus.Labels(n.labels),
	}
}

func (n *Namespace) NewGauge(name, help string, unit Unit) Gauge {
	g := &gauge{
		pg: prometheus.NewGauge(n.newGaugeOpts(name, help, unit)),
	}
	n.Add(g)
	return g
}

func (n *Namespace) NewLabeledGauge(name, help string, unit Unit, labels ...string) LabeledGauge {
	g := &labeledGauge{
		pg: prometheus.NewGaugeVec(n.newGaugeOpts(name, help, unit), labels),
	}
	n.Add(g)
	return g
}

func (n *Namespace) newGaugeOpts(name, help string, unit Unit) prometheus.GaugeOpts {
	return prometheus.GaugeOpts{
		Namespace:   n.name,
		Subsystem:   n.subsystem,
		Name:        makeName(name, unit),
		Help:        help,
		ConstLabels: prometheus.Labels(n.labels),
	}
}

func (n *Namespace) Describe(ch chan<- *prometheus.Desc) {
	n.mu.Lock()
	defer n.mu.Unlock()

	for _, metric := range n.metrics {
		metric.Describe(ch)
	}
}

func (n *Namespace) Collect(ch chan<- prometheus.Metric) {
	n.mu.Lock()
	defer n.mu.Unlock()

	for _, metric := range n.metrics {
		metric.Collect(ch)
	}
}

func (n *Namespace) Add(collector prometheus.Collector) {
	n.mu.Lock()
	n.metrics = append(n.metrics, collector)
	n.mu.Unlock()
}

func (n *Namespace) NewDesc(name, help string, unit Unit, labels ...string) *prometheus.Desc {
	name = makeName(name, unit)
	namespace := n.name
	if n.subsystem != "" {
		namespace = fmt.Sprintf("%s_%s", namespace, n.subsystem)
	}
	name = fmt.Sprintf("%s_%s", namespace, name)
	return prometheus.NewDesc(name, help, labels, prometheus.Labels(n.labels))
}

// mergeLabels merges two or more labels objects into a single map, favoring
// the later labels.
func mergeLabels(lbs ...Labels) Labels {
	merged := make(Labels)

	for _, target := range lbs {
		for k, v := range target {
			merged[k] = v
		}
	}

	return merged
}

func makeName(name string, unit Unit) string {
	if unit == "" {
		return name
	}

	return fmt.Sprintf("%s_%s", name, unit)
}

func (n *Namespace) NewDefaultHttpMetrics(handlerName string) []*HTTPMetric {
	return n.NewHttpMetricsWithOpts(handlerName, HTTPHandlerOpts{
		DurationBuckets:     defaultDurationBuckets,
		RequestSizeBuckets:  defaultResponseSizeBuckets,
		ResponseSizeBuckets: defaultResponseSizeBuckets,
	})
}

func (n *Namespace) NewHttpMetrics(handlerName string, durationBuckets, requestSizeBuckets, responseSizeBuckets []float64) []*HTTPMetric {
	return n.NewHttpMetricsWithOpts(handlerName, HTTPHandlerOpts{
		DurationBuckets:     durationBuckets,
		RequestSizeBuckets:  requestSizeBuckets,
		ResponseSizeBuckets: responseSizeBuckets,
	})
}

func (n *Namespace) NewHttpMetricsWithOpts(handlerName string, opts HTTPHandlerOpts) []*HTTPMetric {
	var httpMetrics []*HTTPMetric
	inFlightMetric := n.NewInFlightGaugeMetric(handlerName)
	requestTotalMetric := n.NewRequestTotalMetric(handlerName)
	requestDurationMetric := n.NewRequestDurationMetric(handlerName, opts.DurationBuckets)
	requestSizeMetric := n.NewRequestSizeMetric(handlerName, opts.RequestSizeBuckets)
	responseSizeMetric := n.NewResponseSizeMetric(handlerName, opts.ResponseSizeBuckets)
	httpMetrics = append(httpMetrics, inFlightMetric, requestDurationMetric, requestTotalMetric, requestSizeMetric, responseSizeMetric)
	return httpMetrics
}

func (n *Namespace) NewInFlightGaugeMetric(handlerName string) *HTTPMetric {
	labels := prometheus.Labels(n.labels)
	labels["handler"] = handlerName
	metric := prometheus.NewGauge(prometheus.GaugeOpts{
		Namespace:   n.name,
		Subsystem:   n.subsystem,
		Name:        "in_flight_requests",
		Help:        "The in-flight HTTP requests",
		ConstLabels: prometheus.Labels(labels),
	})
	httpMetric := &HTTPMetric{
		Collector:   metric,
		handlerType: InstrumentHandlerInFlight,
	}
	n.Add(httpMetric)
	return httpMetric
}

func (n *Namespace) NewRequestTotalMetric(handlerName string) *HTTPMetric {
	labels := prometheus.Labels(n.labels)
	labels["handler"] = handlerName
	metric := prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Namespace:   n.name,
			Subsystem:   n.subsystem,
			Name:        "requests_total",
			Help:        "Total number of HTTP requests made.",
			ConstLabels: prometheus.Labels(labels),
		},
		[]string{"code", "method"},
	)
	httpMetric := &HTTPMetric{
		Collector:   metric,
		handlerType: InstrumentHandlerCounter,
	}
	n.Add(httpMetric)
	return httpMetric
}
func (n *Namespace) NewRequestDurationMetric(handlerName string, buckets []float64) *HTTPMetric {
	if len(buckets) == 0 {
		panic("DurationBuckets must be provided")
	}
	labels := prometheus.Labels(n.labels)
	labels["handler"] = handlerName
	opts := prometheus.HistogramOpts{
		Namespace:   n.name,
		Subsystem:   n.subsystem,
		Name:        "request_duration_seconds",
		Help:        "The HTTP request latencies in seconds.",
		Buckets:     buckets,
		ConstLabels: prometheus.Labels(labels),
	}
	metric := prometheus.NewHistogramVec(opts, []string{"method"})
	httpMetric := &HTTPMetric{
		Collector:   metric,
		handlerType: InstrumentHandlerDuration,
	}
	n.Add(httpMetric)
	return httpMetric
}

func (n *Namespace) NewRequestSizeMetric(handlerName string, buckets []float64) *HTTPMetric {
	if len(buckets) == 0 {
		panic("RequestSizeBuckets must be provided")
	}
	labels := prometheus.Labels(n.labels)
	labels["handler"] = handlerName
	opts := prometheus.HistogramOpts{
		Namespace:   n.name,
		Subsystem:   n.subsystem,
		Name:        "request_size_bytes",
		Help:        "The HTTP request sizes in bytes.",
		Buckets:     buckets,
		ConstLabels: prometheus.Labels(labels),
	}
	metric := prometheus.NewHistogramVec(opts, []string{})
	httpMetric := &HTTPMetric{
		Collector:   metric,
		handlerType: InstrumentHandlerRequestSize,
	}
	n.Add(httpMetric)
	return httpMetric
}

func (n *Namespace) NewResponseSizeMetric(handlerName string, buckets []float64) *HTTPMetric {
	if len(buckets) == 0 {
		panic("ResponseSizeBuckets must be provided")
	}
	labels := prometheus.Labels(n.labels)
	labels["handler"] = handlerName
	opts := prometheus.HistogramOpts{
		Namespace:   n.name,
		Subsystem:   n.subsystem,
		Name:        "response_size_bytes",
		Help:        "The HTTP response sizes in bytes.",
		Buckets:     buckets,
		ConstLabels: prometheus.Labels(labels),
	}
	metrics := prometheus.NewHistogramVec(opts, []string{})
	httpMetric := &HTTPMetric{
		Collector:   metrics,
		handlerType: InstrumentHandlerResponseSize,
	}
	n.Add(httpMetric)
	return httpMetric
}