forked from prometheus/client_golang
/
registry.go
317 lines (263 loc) · 7.95 KB
/
registry.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
/*
Copyright (c) 2012, Matt T. Proud
All rights reserved.
Use of this source code is governed by a BSD-style license that can be found in
the LICENSE file.
*/
package registry
import (
"compress/gzip"
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"github.com/prometheus/client_golang/metrics"
"github.com/prometheus/client_golang/utility"
"io"
"log"
"net/http"
"sort"
"strings"
"sync"
"time"
)
const (
acceptEncodingHeader = "Accept-Encoding"
authorization = "Authorization"
authorizationHeader = "WWW-Authenticate"
authorizationHeaderValue = "Basic"
contentEncodingHeader = "Content-Encoding"
contentTypeHeader = "Content-Type"
gzipAcceptEncodingValue = "gzip"
gzipContentEncodingValue = "gzip"
jsonContentType = "application/json"
jsonSuffix = ".json"
)
var (
abortOnMisuse bool
debugRegistration bool
useAggressiveSanityChecks bool
)
/*
This callback accumulates the microsecond duration of the reporting framework's
overhead such that it can be reported.
*/
var requestLatencyAccumulator metrics.CompletionCallback = func(duration time.Duration) {
microseconds := float64(duration / time.Microsecond)
requestLatency.Add(nil, microseconds)
}
// container represents a top-level registered metric that encompasses its
// static metadata.
type container struct {
baseLabels map[string]string
docstring string
metric metrics.Metric
name string
}
/*
Registry is, as the name implies, a registrar where metrics are listed.
In most situations, using DefaultRegistry is sufficient versus creating one's
own.
*/
type Registry struct {
mutex sync.RWMutex
signatureContainers map[string]container
}
/*
This builds a new metric registry. It is not needed in the majority of
cases.
*/
func NewRegistry() *Registry {
return &Registry{
signatureContainers: make(map[string]container),
}
}
/*
This is the default registry with which Metric objects are associated. It
is primarily a read-only object after server instantiation.
*/
var DefaultRegistry = NewRegistry()
/*
Associate a Metric with the DefaultRegistry.
*/
func Register(name, docstring string, baseLabels map[string]string, metric metrics.Metric) error {
return DefaultRegistry.Register(name, docstring, baseLabels, metric)
}
// isValidCandidate returns true if the candidate is acceptable for use. In the
// event of any apparent incorrect use it will report the problem, invalidate
// the candidate, or outright abort.
func (r *Registry) isValidCandidate(name string, baseLabels map[string]string) (signature string, err error) {
if len(name) == 0 {
err = fmt.Errorf("unnamed metric named with baseLabels %s is invalid", baseLabels)
if abortOnMisuse {
panic(err)
} else if debugRegistration {
log.Println(err)
}
}
if _, contains := baseLabels[nameLabel]; contains {
err = fmt.Errorf("metric named %s with baseLabels %s contains reserved label name %s in baseLabels", name, baseLabels, nameLabel)
if abortOnMisuse {
panic(err)
} else if debugRegistration {
log.Println(err)
}
return
}
baseLabels[nameLabel] = name
signature = utility.LabelsToSignature(baseLabels)
if _, contains := r.signatureContainers[signature]; contains {
err = fmt.Errorf("metric named %s with baseLabels %s is already registered", name, baseLabels)
if abortOnMisuse {
panic(err)
} else if debugRegistration {
log.Println(err)
}
return
}
if useAggressiveSanityChecks {
for _, container := range r.signatureContainers {
if container.name == name {
err = fmt.Errorf("metric named %s with baseLabels %s is already registered as %s and risks causing confusion", name, baseLabels, container.baseLabels)
if abortOnMisuse {
panic(err)
} else if debugRegistration {
log.Println(err)
}
return
}
}
}
return
}
/*
Register a metric with a given name. Name should be globally unique.
*/
func (r *Registry) Register(name, docstring string, baseLabels map[string]string, metric metrics.Metric) (err error) {
r.mutex.Lock()
defer r.mutex.Unlock()
if baseLabels == nil {
baseLabels = map[string]string{}
}
signature, err := r.isValidCandidate(name, baseLabels)
if err != nil {
return
}
r.signatureContainers[signature] = container{
baseLabels: baseLabels,
docstring: docstring,
metric: metric,
name: name,
}
return
}
// YieldBasicAuthExporter creates a http.HandlerFunc that is protected by HTTP's
// basic authentication.
func (register *Registry) YieldBasicAuthExporter(username, password string) http.HandlerFunc {
exporter := register.YieldExporter()
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authenticated := false
if auth := r.Header.Get(authorization); auth != "" {
base64Encoded := strings.SplitAfter(auth, " ")[1]
decoded, err := base64.URLEncoding.DecodeString(base64Encoded)
if err == nil {
usernamePassword := strings.Split(string(decoded), ":")
if usernamePassword[0] == username && usernamePassword[1] == password {
authenticated = true
}
}
}
if authenticated {
exporter.ServeHTTP(w, r)
} else {
w.Header().Add(authorizationHeader, authorizationHeaderValue)
http.Error(w, "access forbidden", 401)
}
})
}
func (registry *Registry) dumpToWriter(writer io.Writer) (err error) {
defer func() {
if err != nil {
dumpErrorCount.Increment(nil)
}
}()
numberOfMetrics := len(registry.signatureContainers)
keys := make([]string, 0, numberOfMetrics)
for key := range registry.signatureContainers {
keys = append(keys, key)
}
sort.Strings(keys)
_, err = writer.Write([]byte("["))
if err != nil {
return
}
index := 0
for _, key := range keys {
container := registry.signatureContainers[key]
intermediate := map[string]interface{}{
baseLabelsKey: container.baseLabels,
docstringKey: container.docstring,
metricKey: container.metric.AsMarshallable(),
}
marshaled, err := json.Marshal(intermediate)
if err != nil {
marshalErrorCount.Increment(nil)
index++
continue
}
if index > 0 && index < numberOfMetrics {
_, err = writer.Write([]byte(","))
if err != nil {
return err
}
}
_, err = writer.Write(marshaled)
if err != nil {
return err
}
index++
}
_, err = writer.Write([]byte("]"))
return
}
// decorateWriter annotates the response writer to handle any other behaviors
// that might be beneficial to the client---e.g., GZIP encoding.
func decorateWriter(request *http.Request, writer http.ResponseWriter) io.Writer {
if !strings.Contains(request.Header.Get(acceptEncodingHeader), gzipAcceptEncodingValue) {
return writer
}
writer.Header().Set(contentEncodingHeader, gzipContentEncodingValue)
gziper := gzip.NewWriter(writer)
return gziper
}
/*
Create a http.HandlerFunc that is tied to r Registry such that requests
against it generate a representation of the housed metrics.
*/
func (registry *Registry) YieldExporter() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var instrumentable metrics.InstrumentableCall = func() {
requestCount.Increment(nil)
url := r.URL
if strings.HasSuffix(url.Path, jsonSuffix) {
header := w.Header()
header.Set(ProtocolVersionHeader, APIVersion)
header.Set(contentTypeHeader, jsonContentType)
writer := decorateWriter(r, w)
// TODO(matt): Migrate to ioutil.NopCloser.
if closer, ok := writer.(io.Closer); ok {
defer closer.Close()
}
registry.dumpToWriter(writer)
} else {
w.WriteHeader(http.StatusNotFound)
}
}
metrics.InstrumentCall(instrumentable, requestLatencyAccumulator)
}
}
func init() {
flag.BoolVar(&abortOnMisuse, FlagNamespace+"abortonmisuse", false, "abort if a semantic misuse is encountered (bool).")
flag.BoolVar(&debugRegistration, FlagNamespace+"debugregistration", false, "display information about the metric registration process (bool).")
flag.BoolVar(&useAggressiveSanityChecks, FlagNamespace+"useaggressivesanitychecks", false, "perform expensive validation of metrics (bool).")
}