Repository navigation
Expand file tree
/
Copy pathprometheus_test.go
More file actions
693 lines (526 loc) · 22.7 KB
/
Copy pathprometheus_test.go
File metadata and controls
693 lines (526 loc) · 22.7 KB
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
/*
* Copyright 2026 Zigflow authors <https://github.com/zigflow/helpers/graphs/contributors>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package temporal
import (
"bytes"
"context"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"sync"
"syscall"
"testing"
"time"
prom "github.com/prometheus/client_golang/prometheus"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.temporal.io/sdk/client"
)
// freeListenAddress is an address the OS will turn into an unused port, so tests
// never depend on a specific port being available.
const freeListenAddress = "127.0.0.1:0"
// promFatalEnv names the child process used to observe the fatal error path and
// selects which failure that child triggers.
const promFatalEnv = "TEMPORAL_HELPERS_TEST_PROMETHEUS_FATAL"
// fatalModeRegister selects the registration failure in the fatal child
// process.
const fatalModeRegister = "register"
// Names used by the error handler tests. The metric is registered up front by
// the test so that tally's own registration of the same name fails.
const (
collidingMetric = "colliding_counter"
collidingHelp = "registered by the test so that tally's registration collides"
)
// errorHandlerMessage is the error NewPrometheusHandler returns when it is given
// more than one error handler.
const errorHandlerMessage = "only a single error handler may be supplied"
// metricsPath is the path the metrics handler is served on.
const metricsPath = "/metrics"
// prometheusStartMessage is logged by NewPrometheusHandler when it starts a
// server of its own.
const prometheusStartMessage = "Starting Prometheus service"
// newTestPrometheusHandler builds a handler, failing the test if that does not
// work, and closes it when the test finishes. Tests that assert on Close call it
// themselves; the cleanup is only a backstop.
func newTestPrometheusHandler(
t *testing.T,
listenAddress, prefix string,
registry *prom.Registry,
onError ...func(error),
) *PrometheusHandler {
t.Helper()
handler, err := NewPrometheusHandler(listenAddress, prefix, registry, onError...)
require.NoError(t, err)
require.NotNil(t, handler)
t.Cleanup(func() { _ = handler.Close() })
return handler
}
// startExplicitPrometheusHandler starts a handler on an explicit loopback port,
// moving to a different port if the one it picked was claimed in the meantime.
// An explicit port has to be known before the handler binds it, so this follows
// the same pick-and-retry approach as startHealthCheck. Any error other than
// "address already in use" fails the test immediately.
func startExplicitPrometheusHandler(
t *testing.T,
prefix string,
registry *prom.Registry,
onError func(error),
) (handler *PrometheusHandler, address string) {
t.Helper()
for range maxAddressAttempts {
address = freeLoopbackAddress(t)
handler, err := NewPrometheusHandler(address, prefix, registry, onError)
if err == nil {
t.Cleanup(func() { _ = handler.Close() })
return handler, address
}
require.ErrorIs(t, err, syscall.EADDRINUSE, "unexpected error starting the Prometheus handler")
}
t.Fatalf("no free loopback port found after %d attempts", maxAddressAttempts)
return nil, ""
}
// getMetrics fetches /metrics from address and returns the body. The listener
// is bound before NewPrometheusHandler returns, so the request is accepted even
// if the server has not been scheduled yet and no retry is needed.
func getMetrics(t *testing.T, address string) string {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+address+metricsPath, http.NoBody)
require.NoError(t, err)
resp, err := newTestHTTPClient(t).Do(req)
require.NoError(t, err, "%s is serving metrics", address)
defer func() { _ = resp.Body.Close() }()
raw, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
return string(raw)
}
// startedAddress returns the address a handler logged as listening on.
func startedAddress(t *testing.T, logs *logCapture) string {
t.Helper()
// The entry is written before NewPrometheusHandler returns.
entry, ok := logs.find(prometheusStartMessage)
require.True(t, ok, "the start message is logged")
return requireAssignedAddress(t, entry, "127.0.0.1")
}
// collidingCounter builds a counter registered under the name tally derives for
// prefix and name - "<prefix>_<name>_total" - but with a different help string,
// so registering both in one registry is a guaranteed error.
func collidingCounter(prefix, name string) (collector prom.Collector, fqName string) {
fqName = prefix + "_" + name + "_total"
return prom.NewCounter(prom.CounterOpts{Name: fqName, Help: collidingHelp}), fqName
}
// collidingRegistry returns a dedicated registry that already holds the metric
// tally will try to register, along with that metric's name.
func collidingRegistry(t *testing.T, prefix string) (registry *prom.Registry, fqName string) {
t.Helper()
registry = prom.NewRegistry()
collector, fqName := collidingCounter(prefix, collidingMetric)
require.NoError(t, registry.Register(collector))
return registry, fqName
}
// errorRecorder records the errors an onError handler is called with. It is
// mutex guarded because tally may report from its own goroutine.
type errorRecorder struct {
mu sync.Mutex
errs []error
}
func (r *errorRecorder) onError(err error) {
r.mu.Lock()
defer r.mu.Unlock()
r.errs = append(r.errs, err)
}
func (r *errorRecorder) errors() []error {
r.mu.Lock()
defer r.mu.Unlock()
return append([]error(nil), r.errs...)
}
// isolateDefaultServeMux swaps http.DefaultServeMux for an empty mux and
// restores the original when the test finishes. Tests that give
// NewPrometheusHandler no listen address need this: tally registers its handler
// on whatever mux is installed, and that mux panics on a second registration of
// the same path. Callers must not be parallel.
func isolateDefaultServeMux(t *testing.T) *http.ServeMux {
t.Helper()
original := http.DefaultServeMux
t.Cleanup(func() { http.DefaultServeMux = original })
mux := http.NewServeMux()
http.DefaultServeMux = mux
return mux
}
// isolateDefaultRegistry swaps the Prometheus default registerer and gatherer
// for a dedicated registry and restores the originals when the test finishes, so
// a test exercising the nil registry path leaves no metrics behind in the real
// default registry. Callers must not be parallel.
func isolateDefaultRegistry(t *testing.T) *prom.Registry {
t.Helper()
originalRegisterer, originalGatherer := prom.DefaultRegisterer, prom.DefaultGatherer
t.Cleanup(func() {
prom.DefaultRegisterer, prom.DefaultGatherer = originalRegisterer, originalGatherer
})
registry := prom.NewRegistry()
prom.DefaultRegisterer, prom.DefaultGatherer = registry, registry
return registry
}
// registeredMetricNames returns the names of every metric family in a registry.
func registeredMetricNames(t *testing.T, registry *prom.Registry) []string {
t.Helper()
families, err := registry.Gather()
require.NoError(t, err)
names := make([]string, 0, len(families))
for _, family := range families {
names = append(names, family.GetName())
}
return names
}
func TestNewPrometheusHandler(t *testing.T) {
t.Parallel()
t.Run("registers metrics against the supplied registry", func(t *testing.T) {
t.Parallel()
registry := prom.NewRegistry()
handler := newTestPrometheusHandler(t, freeListenAddress, "myprefix", registry)
// Creating a metric registers it with the registry immediately.
handler.Counter("things_done").Inc(1)
assert.Contains(t, registeredMetricNames(t, registry), "myprefix_things_done_total")
})
t.Run("no prefix leaves metric names unprefixed", func(t *testing.T) {
t.Parallel()
registry := prom.NewRegistry()
handler := newTestPrometheusHandler(t, freeListenAddress, "", registry)
handler.Counter("unprefixed_things").Inc(1)
assert.Contains(t, registeredMetricNames(t, registry), "unprefixed_things_total")
})
t.Run("metric names are sanitised for prometheus", func(t *testing.T) {
t.Parallel()
registry := prom.NewRegistry()
handler := newTestPrometheusHandler(t, freeListenAddress, "my.prefix", registry)
handler.Counter("things.done").Inc(1)
handler.Gauge("things.pending").Update(1)
names := registeredMetricNames(t, registry)
assert.Contains(t, names, "my_prefix_things_done_total")
assert.Contains(t, names, "my_prefix_things_pending")
})
t.Run("tags become sanitised prometheus labels", func(t *testing.T) {
t.Parallel()
registry := prom.NewRegistry()
handler := newTestPrometheusHandler(t, freeListenAddress, "tagged", registry)
handler.WithTags(map[string]string{"task.queue": "my-queue"}).Counter("tagged_things").Inc(1)
families, err := registry.Gather()
require.NoError(t, err)
var labels []string
for _, family := range families {
if family.GetName() != "tagged_tagged_things_total" {
continue
}
for _, metric := range family.GetMetric() {
for _, label := range metric.GetLabel() {
labels = append(labels, label.GetName()+"="+label.GetValue())
}
}
}
// Label names and values are both sanitised by the configured options.
assert.Equal(t, []string{"task_queue=my_queue"}, labels)
})
t.Run("rejects a listen address without a port", func(t *testing.T) {
t.Parallel()
handler, err := NewPrometheusHandler("not-a-valid-address", "noport", prom.NewRegistry())
require.Error(t, err)
assert.ErrorContains(t, err, "error listening for Prometheus")
assert.Nil(t, handler)
})
t.Run("returns a bind failure synchronously", func(t *testing.T) {
t.Parallel()
// The test holds the port for its whole duration, so the bind is
// guaranteed to fail.
occupied, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", freeListenAddress)
require.NoError(t, err)
t.Cleanup(func() { _ = occupied.Close() })
recorder := &errorRecorder{}
handler, err := NewPrometheusHandler(occupied.Addr().String(), "occupied", prom.NewRegistry(), recorder.onError)
require.Error(t, err)
assert.ErrorContains(t, err, "error listening for Prometheus")
assert.ErrorIs(t, err, syscall.EADDRINUSE)
assert.Nil(t, handler)
assert.Empty(t, recorder.errors(), "a bind failure is returned, not reported")
})
t.Run("serves on an explicit port until closed", func(t *testing.T) {
t.Parallel()
recorder := &errorRecorder{}
handler, address := startExplicitPrometheusHandler(t, "explicitport", prom.NewRegistry(), recorder.onError)
handler.Counter("things_done").Inc(1)
assert.Contains(t, getMetrics(t, address), "explicitport_things_done_total")
require.NoError(t, handler.Close())
requireNotServing(t, newTestHTTPClient(t), address)
assert.Empty(t, recorder.errors(), "an expected shutdown is not reported as an error")
})
}
// TestPrometheusHandlerZeroValueClose covers Close on a handler that owns
// nothing.
func TestPrometheusHandlerZeroValueClose(t *testing.T) {
t.Parallel()
var handler PrometheusHandler
assert.NoError(t, handler.Close())
}
// TestNewPrometheusHandlerAssignedPort covers port 0, where the log is the only
// way to learn the address. It is not parallel because it captures the global
// logger.
func TestNewPrometheusHandlerAssignedPort(t *testing.T) {
t.Run("serves on the logged address until closed", func(t *testing.T) {
logs := captureLogs(t)
recorder := &errorRecorder{}
handler := newTestPrometheusHandler(t, freeListenAddress, "assignedport", prom.NewRegistry(), recorder.onError)
address := startedAddress(t, logs)
handler.Counter("things_done").Inc(1)
assert.Contains(t, getMetrics(t, address), "assignedport_things_done_total", "metrics are served on the logged address")
require.NoError(t, handler.Close())
// The Serve goroutine cannot be observed directly. Waiting until the
// address stops answering means it has seen the closed listener, and
// a regression that reported the expected shutdown would do so then.
requireNotServing(t, newTestHTTPClient(t), address)
assert.Empty(t, recorder.errors(), "an expected shutdown is not reported as an error")
})
t.Run("closing straight after construction stops the server", func(t *testing.T) {
logs := captureLogs(t)
recorder := &errorRecorder{}
handler := newTestPrometheusHandler(t, freeListenAddress, "closedearly", prom.NewRegistry(), recorder.onError)
address := startedAddress(t, logs)
// Close may run before the Serve goroutine has been scheduled.
require.NoError(t, handler.Close())
requireNotServing(t, newTestHTTPClient(t), address)
assert.Empty(t, recorder.errors(), "an expected shutdown is not reported as an error")
})
}
// TestNewPrometheusHandlerNilRegistry covers the branch where no registry is
// given and metrics go to the Prometheus default registerer instead. It is not
// parallel and swaps the default registerer and gatherer for a dedicated
// registry, so the metric it registers cannot collide with a repeat run of the
// test or leak into anything else that uses the real default registry.
func TestNewPrometheusHandlerNilRegistry(t *testing.T) {
registry := isolateDefaultRegistry(t)
logs := captureLogs(t)
handler := newTestPrometheusHandler(t, freeListenAddress, "defaultregistry", nil)
handler.Counter("things_done").Inc(1)
families, err := prom.DefaultGatherer.Gather()
require.NoError(t, err)
names := make([]string, 0, len(families))
for _, family := range families {
names = append(names, family.GetName())
}
assert.Contains(t, names, "defaultregistry_things_done_total")
assert.Equal(t, names, registeredMetricNames(t, registry), "the default gatherer is the registry the metric was registered with")
body := getMetrics(t, startedAddress(t, logs))
assert.Contains(t, body, "defaultregistry_things_done_total", "the server gathers from the default registry")
}
// TestNewPrometheusHandlerWithoutListenAddress covers the branch where no listen
// address is given and the metrics handler is instead attached to Go's default
// HTTP mux. It is not parallel and installs its own mux for the duration of the
// test, because "/metrics" is registered on whatever mux is installed and a mux
// panics if the same path is registered twice. It also captures the global
// logger, to show that no server of its own is started.
func TestNewPrometheusHandlerWithoutListenAddress(t *testing.T) {
mux := isolateDefaultServeMux(t)
logs := captureLogs(t)
registry := prom.NewRegistry()
handler := newTestPrometheusHandler(t, "", "defaultmux", registry)
_, ok := logs.find(prometheusStartMessage)
assert.False(t, ok, "no server is started, so no listening address is logged")
handler.Counter("things_done").Inc(1)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, httptest.NewRequestWithContext(context.Background(), http.MethodGet, metricsPath, http.NoBody))
assert.Equal(t, http.StatusOK, rec.Code)
assert.Contains(t, rec.Body.String(), "defaultmux_things_done_total")
}
// TestWithPrometheusMetrics covers the connection option wrapper.
func TestWithPrometheusMetrics(t *testing.T) {
t.Parallel()
registry := prom.NewRegistry()
o := mustApplyOptions(t, WithPrometheusMetrics(freeListenAddress, "clientoption", registry))
require.NotNil(t, o.MetricsHandler)
handler, ok := o.MetricsHandler.(*PrometheusHandler)
require.True(t, ok, "the option installs a *PrometheusHandler")
t.Cleanup(func() { _ = handler.Close() })
o.MetricsHandler.Counter("things_done").Inc(1)
assert.Contains(t, registeredMetricNames(t, registry), "clientoption_things_done_total")
}
// TestNewPrometheusHandlerErrorHandler covers the optional onError argument.
//
// The trigger for every case is the same deterministic failure: a dedicated
// registry already holds the metric tally derives from the prefix and metric
// name, so tally's own registration of it fails and the reporter reports that
// error through ConfigurationOptions.OnError. tally reports registration errors
// synchronously, while the metric is being allocated, so every assertion here is
// synchronous and nothing waits or sleeps.
//
// This test is not parallel: one subtest installs its own default serve mux.
func TestNewPrometheusHandlerErrorHandler(t *testing.T) {
t.Run("rejects more than one error handler", func(t *testing.T) {
// The reporter is never created, so tally never registers its handler
// on the default mux. An isolated mux lets that be asserted.
mux := isolateDefaultServeMux(t)
tests := []struct {
name string
handlers []func(error)
}{
{
name: "two handlers",
handlers: []func(error){func(error) {}, func(error) {}},
},
{
name: "three handlers",
handlers: []func(error){func(error) {}, func(error) {}, func(error) {}},
},
{
name: "a handler and an explicit nil",
handlers: []func(error){func(error) {}, nil},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
// No listen address, so a reporter would register on the mux.
handler, err := NewPrometheusHandler("", "multiplehandlers", prom.NewRegistry(), test.handlers...)
require.Error(t, err)
assert.ErrorContains(t, err, errorHandlerMessage)
assert.Nil(t, handler, "no handler is returned alongside the error")
rec := httptest.NewRecorder()
req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, metricsPath, http.NoBody)
mux.ServeHTTP(rec, req)
assert.Equal(t, http.StatusNotFound, rec.Code, "the reporter must not have been created or started")
})
}
})
t.Run("uses the supplied error handler", func(t *testing.T) {
const prefix = "customhandler"
registry, fqName := collidingRegistry(t, prefix)
recorder := &errorRecorder{}
handler := newTestPrometheusHandler(t, freeListenAddress, prefix, registry, recorder.onError)
// The supplied handler swallows the error, so allocating the metric
// neither panics (tally's default) nor exits (our default).
require.NotPanics(t, func() {
handler.Counter(collidingMetric).Inc(1)
})
errs := recorder.errors()
require.Len(t, errs, 1, "the supplied handler is called once, for the failed registration")
assert.ErrorContains(t, errs[0], fqName)
assert.ErrorContains(t, errs[0], "different label names or a different help string")
})
t.Run("passes an explicit nil handler through to tally", func(t *testing.T) {
const prefix = "nilhandler"
registry, fqName := collidingRegistry(t, prefix)
handler := newTestPrometheusHandler(t, freeListenAddress, prefix, registry, nil)
// tally treats a nil ConfigurationOptions.OnError as "use my default",
// and its default panics with the registration error. Recovering here
// keeps that contained: reaching this assertion at all proves the nil
// was passed through rather than replaced by our default handler, which
// would have called log.Fatal and taken the test binary with it.
recovered := func() (recovered any) {
defer func() { recovered = recover() }()
handler.Counter(collidingMetric).Inc(1)
return nil
}()
require.NotNil(t, recovered, "tally panics when OnError is nil")
panicErr, ok := recovered.(error)
require.True(t, ok, "tally panics with the registration error, got %T", recovered)
assert.ErrorContains(t, panicErr, fqName)
})
}
// TestNewPrometheusHandlerDefaultErrorHandler documents that with no onError
// argument the default handler is still log.Fatal for a metric registration
// that cannot be made. That failure produces no error from NewPrometheusHandler,
// and log.Fatal terminates the process, so it has to be observed from a child
// process. Listen failures are returned synchronously and are covered by
// TestNewPrometheusHandler.
func TestNewPrometheusHandlerDefaultErrorHandler(t *testing.T) {
if mode := os.Getenv(promFatalEnv); mode != "" {
runDefaultErrorHandlerChild(mode)
return
}
tests := []struct {
name string
mode string
// expected fragments of the child's stderr
expected []string
}{
{
name: "registration failure",
mode: fatalModeRegister,
expected: []string{"Error in Prometheus reporter", "different label names or a different help string"},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
// The child is killed by log.Fatal; the timeout only stops the test
// hanging forever if that ever stops being true.
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
//nolint:gosec // deliberately re-executes this test binary
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestNewPrometheusHandlerDefaultErrorHandler$")
cmd.Env = append(os.Environ(), promFatalEnv+"="+test.mode)
var stderr bytes.Buffer
cmd.Stderr = &stderr
err := cmd.Run()
var exitErr *exec.ExitError
require.ErrorAs(t, err, &exitErr, "stderr: %s", stderr.String())
assert.Equal(t, 1, exitErr.ExitCode(), "stderr: %s", stderr.String())
for _, expected := range test.expected {
assert.Contains(t, stderr.String(), expected)
}
})
}
}
// runDefaultErrorHandlerChild is the child half of
// TestNewPrometheusHandlerDefaultErrorHandler. It always calls
// NewPrometheusHandler without an onError argument, so the default handler is
// the one under test, and it expects never to return.
func runDefaultErrorHandlerChild(mode string) {
switch mode {
case fatalModeRegister:
const prefix = "child"
registry := prom.NewRegistry()
collector, _ := collidingCounter(prefix, collidingMetric)
if err := registry.Register(collector); err != nil {
fmt.Fprintln(os.Stderr, "unexpected error registering the colliding metric:", err)
os.Exit(2)
}
handler := mustChildHandler(freeListenAddress, prefix, registry)
// Allocating the metric fails to register it, which the default handler
// turns into a fatal error.
handler.Counter(collidingMetric).Inc(1)
default:
fmt.Fprintln(os.Stderr, "unknown child mode:", mode)
os.Exit(2)
}
fmt.Fprintln(os.Stderr, "the process was not terminated")
os.Exit(3)
}
// mustChildHandler builds a handler with the default error handler, exiting the
// child process if that does not work.
func mustChildHandler(listenAddress, prefix string, registry *prom.Registry) client.MetricsHandler {
handler, err := NewPrometheusHandler(listenAddress, prefix, registry)
if err != nil {
fmt.Fprintln(os.Stderr, "unexpected error from NewPrometheusHandler:", err)
os.Exit(2)
}
if handler == nil {
fmt.Fprintln(os.Stderr, "unexpected nil handler")
os.Exit(2)
}
return handler
}