/
config_prometheus.go
330 lines (282 loc) · 9.64 KB
/
config_prometheus.go
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
// Copyright (c) 2020 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package instrument
import (
"fmt"
"log"
"net"
"net/http"
"os"
"strings"
prom "github.com/m3db/prometheus_client_golang/prometheus"
"github.com/m3db/prometheus_client_golang/prometheus/promhttp"
dto "github.com/m3db/prometheus_client_model/go"
extprom "github.com/prometheus/client_golang/prometheus"
"github.com/uber-go/tally/prometheus"
)
// PrometheusConfiguration is a configuration for a Prometheus reporter.
type PrometheusConfiguration struct {
// HandlerPath if specified will be used instead of using the default
// HTTP handler path "/metrics".
HandlerPath string `yaml:"handlerPath"`
// ListenAddress if specified will be used instead of just registering the
// handler on the default HTTP serve mux without listening.
ListenAddress string `yaml:"listenAddress"`
// TimerType is the default Prometheus type to use for Tally timers.
TimerType string `yaml:"timerType"`
// DefaultHistogramBuckets if specified will set the default histogram
// buckets to be used by the reporter.
DefaultHistogramBuckets []prometheus.HistogramObjective `yaml:"defaultHistogramBuckets"`
// DefaultSummaryObjectives if specified will set the default summary
// objectives to be used by the reporter.
DefaultSummaryObjectives []prometheus.SummaryObjective `yaml:"defaultSummaryObjectives"`
// OnError specifies what to do when an error either with listening
// on the specified listen address or registering a metric with the
// Prometheus. By default the registerer will panic.
OnError string `yaml:"onError"`
}
// HistogramObjective is a Prometheus histogram bucket.
// See: https://godoc.org/github.com/prometheus/client_golang/prometheus#HistogramOpts
type HistogramObjective struct {
Upper float64 `yaml:"upper"`
}
// SummaryObjective is a Prometheus summary objective.
// See: https://godoc.org/github.com/prometheus/client_golang/prometheus#SummaryOpts
type SummaryObjective struct {
Percentile float64 `yaml:"percentile"`
AllowedError float64 `yaml:"allowedError"`
}
// PrometheusConfigurationOptions allows some programatic options, such as using a
// specific registry and what error callback to register.
type PrometheusConfigurationOptions struct {
// Registry if not nil will specify the specific registry to use
// for registering metrics.
Registry *prom.Registry
// ExternalRegistries if set (with combination of a specified Registry)
// will also
ExternalRegistries []PrometheusExternalRegistry
// HandlerListener is the listener to register the server handler on.
HandlerListener net.Listener
// HandlerOpts is the reporter HTTP handler options, not specifying will
// use defaults.
HandlerOpts promhttp.HandlerOpts
// OnError allows for customization of what to do when a metric
// registration error fails, the default is to panic.
OnError func(e error)
}
// PrometheusExternalRegistry is an external Prometheus registry
// to also expose as part of the handler.
type PrometheusExternalRegistry struct {
// Registry is the external prometheus registry to list.
Registry *extprom.Registry
// SubScope will add a prefix to all metric names exported by
// this registry.
SubScope string
}
// NewReporter creates a new M3 Prometheus reporter from this configuration.
func (c PrometheusConfiguration) NewReporter(
configOpts PrometheusConfigurationOptions,
) (prometheus.Reporter, error) {
var opts prometheus.Options
if configOpts.Registry != nil {
opts.Registerer = configOpts.Registry
}
if configOpts.OnError != nil {
opts.OnRegisterError = configOpts.OnError
} else {
switch c.OnError {
case "stderr":
opts.OnRegisterError = func(err error) {
fmt.Fprintf(os.Stderr, "tally prometheus reporter error: %v\n", err)
}
case "log":
opts.OnRegisterError = func(err error) {
log.Printf("tally prometheus reporter error: %v\n", err)
}
case "none":
opts.OnRegisterError = func(err error) {}
default:
opts.OnRegisterError = func(err error) {
panic(err)
}
}
}
switch c.TimerType {
case "summary":
opts.DefaultTimerType = prometheus.SummaryTimerType
case "histogram":
opts.DefaultTimerType = prometheus.HistogramTimerType
}
if len(c.DefaultHistogramBuckets) > 0 {
values := make([]float64, 0, len(c.DefaultHistogramBuckets))
for _, value := range c.DefaultHistogramBuckets {
values = append(values, value.Upper)
}
opts.DefaultHistogramBuckets = values
}
if len(c.DefaultSummaryObjectives) > 0 {
values := make(map[float64]float64, len(c.DefaultSummaryObjectives))
for _, value := range c.DefaultSummaryObjectives {
values[value.Percentile] = value.AllowedError
}
opts.DefaultSummaryObjectives = values
}
reporter := prometheus.NewReporter(opts)
path := "/metrics"
if handlerPath := strings.TrimSpace(c.HandlerPath); handlerPath != "" {
path = handlerPath
}
handler := reporter.HTTPHandler()
if configOpts.Registry != nil {
gatherer := newMultiGatherer(configOpts.Registry, configOpts.ExternalRegistries)
handler = promhttp.HandlerFor(gatherer, promhttp.HandlerOpts{})
}
addr := strings.TrimSpace(c.ListenAddress)
if addr == "" && configOpts.HandlerListener == nil {
// If address not specified and server not specified, register
// on default mux.
http.Handle(path, handler)
} else {
mux := http.NewServeMux()
mux.Handle(path, handler)
listener := configOpts.HandlerListener
if listener == nil {
// Address must be specified if server was nil.
var err error
listener, err = net.Listen("tcp", addr)
if err != nil {
return nil, fmt.Errorf(
"prometheus handler listen address error: %v", err)
}
}
go func() {
server := &http.Server{Handler: mux}
if err := server.Serve(listener); err != nil {
opts.OnRegisterError(err)
}
}()
}
return reporter, nil
}
func newMultiGatherer(
primary *prom.Registry,
ext []PrometheusExternalRegistry,
) prom.Gatherer {
return &multiGatherer{
primary: primary,
ext: ext,
}
}
var _ prom.Gatherer = (*multiGatherer)(nil)
type multiGatherer struct {
primary *prom.Registry
ext []PrometheusExternalRegistry
}
func (g *multiGatherer) Gather() ([]*dto.MetricFamily, error) {
results, err := g.primary.Gather()
if err != nil {
return nil, err
}
if len(g.ext) == 0 {
return results, nil
}
for _, secondary := range g.ext {
gathered, err := secondary.Registry.Gather()
if err != nil {
return nil, err
}
for _, elem := range gathered {
entry := &dto.MetricFamily{
Name: elem.Name,
Help: elem.Help,
Metric: make([]*dto.Metric, 0, len(elem.Metric)),
}
if secondary.SubScope != "" && entry.Name != nil {
scopedName := fmt.Sprintf("%s_%s", secondary.SubScope, *entry.Name)
entry.Name = &scopedName
}
if v := elem.Type; v != nil {
metricType := dto.MetricType(*v)
entry.Type = &metricType
}
for _, metricElem := range elem.Metric {
metricEntry := &dto.Metric{
Label: make([]*dto.LabelPair, 0, len(metricElem.Label)),
TimestampMs: metricElem.TimestampMs,
}
if v := metricElem.Gauge; v != nil {
metricEntry.Gauge = &dto.Gauge{
Value: v.Value,
}
}
if v := metricElem.Counter; v != nil {
metricEntry.Counter = &dto.Counter{
Value: v.Value,
}
}
if v := metricElem.Summary; v != nil {
metricEntry.Summary = &dto.Summary{
SampleCount: v.SampleCount,
SampleSum: v.SampleSum,
Quantile: make([]*dto.Quantile, 0, len(v.Quantile)),
}
for _, quantileElem := range v.Quantile {
quantileEntry := &dto.Quantile{
Quantile: quantileElem.Quantile,
Value: quantileElem.Value,
}
metricEntry.Summary.Quantile =
append(metricEntry.Summary.Quantile, quantileEntry)
}
}
if v := metricElem.Untyped; v != nil {
metricEntry.Untyped = &dto.Untyped{
Value: v.Value,
}
}
if v := metricElem.Histogram; v != nil {
metricEntry.Histogram = &dto.Histogram{
SampleCount: v.SampleCount,
SampleSum: v.SampleSum,
Bucket: make([]*dto.Bucket, 0, len(v.Bucket)),
}
for _, bucketElem := range v.Bucket {
bucketEntry := &dto.Bucket{
CumulativeCount: bucketElem.CumulativeCount,
UpperBound: bucketElem.UpperBound,
}
metricEntry.Histogram.Bucket =
append(metricEntry.Histogram.Bucket, bucketEntry)
}
}
for _, labelElem := range metricElem.Label {
labelEntry := &dto.LabelPair{
Name: labelElem.Name,
Value: labelElem.Value,
}
metricEntry.Label = append(metricEntry.Label, labelEntry)
}
entry.Metric = append(entry.Metric, metricEntry)
}
results = append(results, entry)
}
}
return results, nil
}