Skip to content

Commit add6c8b

Browse files
authored
Use promauto.With(stats) instead of stats.MustRegister() (#8483)
This removes the need to remember to register each metric that we declare, and reduces the likelihood of bugs related to not registering metrics. Using this throughout the codebase means that we'll remember to continue using it in the future.
1 parent c26e53c commit add6c8b

File tree

22 files changed

+212
-297
lines changed

22 files changed

+212
-297
lines changed

ca/ca.go

Lines changed: 17 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import (
2121
"github.com/jmhodges/clock"
2222
"github.com/miekg/pkcs11"
2323
"github.com/prometheus/client_golang/prometheus"
24+
"github.com/prometheus/client_golang/prometheus/promauto"
2425
"go.opentelemetry.io/otel"
2526
"go.opentelemetry.io/otel/attribute"
2627
"go.opentelemetry.io/otel/trace"
@@ -79,34 +80,25 @@ type caMetrics struct {
7980
}
8081

8182
func NewCAMetrics(stats prometheus.Registerer) *caMetrics {
82-
signatureCount := prometheus.NewCounterVec(
83-
prometheus.CounterOpts{
84-
Name: "signatures",
85-
Help: "Number of signatures",
86-
},
87-
[]string{"purpose", "issuer"})
88-
stats.MustRegister(signatureCount)
89-
90-
signErrorCount := prometheus.NewCounterVec(prometheus.CounterOpts{
83+
signatureCount := promauto.With(stats).NewCounterVec(prometheus.CounterOpts{
84+
Name: "signatures",
85+
Help: "Number of signatures",
86+
}, []string{"purpose", "issuer"})
87+
88+
signErrorCount := promauto.With(stats).NewCounterVec(prometheus.CounterOpts{
9189
Name: "signature_errors",
9290
Help: "A counter of signature errors labelled by error type",
9391
}, []string{"type"})
94-
stats.MustRegister(signErrorCount)
95-
96-
lintErrorCount := prometheus.NewCounter(
97-
prometheus.CounterOpts{
98-
Name: "lint_errors",
99-
Help: "Number of issuances that were halted by linting errors",
100-
})
101-
stats.MustRegister(lintErrorCount)
102-
103-
certificates := prometheus.NewCounterVec(
104-
prometheus.CounterOpts{
105-
Name: "certificates",
106-
Help: "Number of certificates issued",
107-
},
108-
[]string{"profile"})
109-
stats.MustRegister(certificates)
92+
93+
lintErrorCount := promauto.With(stats).NewCounter(prometheus.CounterOpts{
94+
Name: "lint_errors",
95+
Help: "Number of issuances that were halted by linting errors",
96+
})
97+
98+
certificates := promauto.With(stats).NewCounterVec(prometheus.CounterOpts{
99+
Name: "certificates",
100+
Help: "Number of certificates issued",
101+
}, []string{"profile"})
110102

111103
return &caMetrics{signatureCount, signErrorCount, lintErrorCount, certificates}
112104
}

cmd/bad-key-revoker/main.go

Lines changed: 26 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99

1010
"github.com/jmhodges/clock"
1111
"github.com/prometheus/client_golang/prometheus"
12+
"github.com/prometheus/client_golang/prometheus/promauto"
1213
"google.golang.org/grpc"
1314
"google.golang.org/protobuf/types/known/emptypb"
1415

@@ -25,19 +26,6 @@ import (
2526

2627
const blockedKeysGaugeLimit = 1000
2728

28-
var keysToProcess = prometheus.NewGauge(prometheus.GaugeOpts{
29-
Name: "bad_keys_to_process",
30-
Help: fmt.Sprintf("A gauge of blockedKeys rows to process (max: %d)", blockedKeysGaugeLimit),
31-
})
32-
var keysProcessed = prometheus.NewCounterVec(prometheus.CounterOpts{
33-
Name: "bad_keys_processed",
34-
Help: "A counter of blockedKeys rows processed labelled by processing state",
35-
}, []string{"state"})
36-
var certsRevoked = prometheus.NewCounter(prometheus.CounterOpts{
37-
Name: "bad_keys_certs_revoked",
38-
Help: "A counter of certificates associated with rows in blockedKeys that have been revoked",
39-
})
40-
4129
// revoker is an interface used to reduce the scope of a RA gRPC client
4230
// to only the single method we need to use, this makes testing significantly
4331
// simpler
@@ -57,6 +45,9 @@ type badKeyRevoker struct {
5745
backoffFactor float64
5846
backoffTicker int
5947
maxExpectedReplicationLag time.Duration
48+
keysToProcess prometheus.Gauge
49+
keysProcessed *prometheus.CounterVec
50+
certsRevoked prometheus.Counter
6051
}
6152

6253
// uncheckedBlockedKey represents a row in the blockedKeys table
@@ -196,7 +187,7 @@ func (bkr *badKeyRevoker) revokeCerts(certs []unrevokedCertificate) error {
196187
if err != nil {
197188
return err
198189
}
199-
certsRevoked.Inc()
190+
bkr.certsRevoked.Inc()
200191
}
201192
return nil
202193
}
@@ -212,7 +203,7 @@ func (bkr *badKeyRevoker) invoke(ctx context.Context) (bool, error) {
212203

213204
// Set the gauge to the number of rows to be processed (max:
214205
// blockedKeysGaugeLimit).
215-
keysToProcess.Set(float64(uncheckedCount))
206+
bkr.keysToProcess.Set(float64(uncheckedCount))
216207

217208
if uncheckedCount >= blockedKeysGaugeLimit {
218209
bkr.logger.AuditInfof("found >= %d unchecked blocked keys left to process", uncheckedCount)
@@ -324,21 +315,31 @@ func main() {
324315
config.BadKeyRevoker.DebugAddr = *debugAddr
325316
}
326317

327-
scope, logger, oTelShutdown := cmd.StatsAndLogging(config.Syslog, config.OpenTelemetry, config.BadKeyRevoker.DebugAddr)
318+
stats, logger, oTelShutdown := cmd.StatsAndLogging(config.Syslog, config.OpenTelemetry, config.BadKeyRevoker.DebugAddr)
328319
defer oTelShutdown(context.Background())
329320
logger.Info(cmd.VersionString())
330321
clk := clock.New()
331322

332-
scope.MustRegister(keysProcessed)
333-
scope.MustRegister(certsRevoked)
334-
335-
dbMap, err := sa.InitWrappedDb(config.BadKeyRevoker.DB, scope, logger)
323+
keysToProcess := promauto.With(stats).NewGauge(prometheus.GaugeOpts{
324+
Name: "bad_keys_to_process",
325+
Help: fmt.Sprintf("A gauge of blockedKeys rows to process (max: %d)", blockedKeysGaugeLimit),
326+
})
327+
keysProcessed := promauto.With(stats).NewCounterVec(prometheus.CounterOpts{
328+
Name: "bad_keys_processed",
329+
Help: "A counter of blockedKeys rows processed labelled by processing state",
330+
}, []string{"state"})
331+
certsRevoked := promauto.With(stats).NewCounter(prometheus.CounterOpts{
332+
Name: "bad_keys_certs_revoked",
333+
Help: "A counter of certificates associated with rows in blockedKeys that have been revoked",
334+
})
335+
336+
dbMap, err := sa.InitWrappedDb(config.BadKeyRevoker.DB, stats, logger)
336337
cmd.FailOnError(err, "While initializing dbMap")
337338

338-
tlsConfig, err := config.BadKeyRevoker.TLS.Load(scope)
339+
tlsConfig, err := config.BadKeyRevoker.TLS.Load(stats)
339340
cmd.FailOnError(err, "TLS config")
340341

341-
conn, err := bgrpc.ClientSetup(config.BadKeyRevoker.RAService, tlsConfig, scope, clk)
342+
conn, err := bgrpc.ClientSetup(config.BadKeyRevoker.RAService, tlsConfig, stats, clk)
342343
cmd.FailOnError(err, "Failed to load credentials and create gRPC connection to RA")
343344
rac := rapb.NewRegistrationAuthorityClient(conn)
344345

@@ -353,6 +354,9 @@ func main() {
353354
backoffIntervalBase: config.BadKeyRevoker.Interval.Duration,
354355
backoffFactor: 1.3,
355356
maxExpectedReplicationLag: config.BadKeyRevoker.MaxExpectedReplicationLag.Duration,
357+
keysToProcess: keysToProcess,
358+
keysProcessed: keysProcessed,
359+
certsRevoked: certsRevoked,
356360
}
357361

358362
// If `BackoffIntervalMax` was not set via the config, set it to 60

cmd/bad-key-revoker/main_test.go

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -276,9 +276,10 @@ func TestRevokeCerts(t *testing.T) {
276276
fc := clock.NewFake()
277277
mr := &mockRevoker{}
278278
bkr := &badKeyRevoker{
279-
dbMap: dbMap,
280-
raClient: mr,
281-
clk: fc,
279+
dbMap: dbMap,
280+
raClient: mr,
281+
clk: fc,
282+
certsRevoked: prometheus.NewCounter(prometheus.CounterOpts{}),
282283
}
283284

284285
err = bkr.revokeCerts([]unrevokedCertificate{
@@ -305,6 +306,7 @@ func TestCertificateAbsent(t *testing.T) {
305306
logger: blog.NewMock(),
306307
clk: fc,
307308
maxExpectedReplicationLag: time.Second * 22,
309+
keysToProcess: prometheus.NewGauge(prometheus.GaugeOpts{}),
308310
}
309311

310312
// populate DB with all the test data
@@ -345,6 +347,8 @@ func TestInvoke(t *testing.T) {
345347
logger: blog.NewMock(),
346348
clk: fc,
347349
maxExpectedReplicationLag: time.Second * 22,
350+
keysToProcess: prometheus.NewGauge(prometheus.GaugeOpts{}),
351+
certsRevoked: prometheus.NewCounter(prometheus.CounterOpts{}),
348352
}
349353

350354
// populate DB with all the test data
@@ -363,7 +367,7 @@ func TestInvoke(t *testing.T) {
363367
test.AssertNotError(t, err, "invoke failed")
364368
test.AssertEquals(t, noWork, false)
365369
test.AssertEquals(t, mr.revoked, 4)
366-
test.AssertMetricWithLabelsEquals(t, keysToProcess, prometheus.Labels{}, 1)
370+
test.AssertMetricWithLabelsEquals(t, bkr.keysToProcess, prometheus.Labels{}, 1)
367371

368372
var checked struct {
369373
ExtantCertificatesChecked bool
@@ -411,6 +415,8 @@ func TestInvokeRevokerHasNoExtantCerts(t *testing.T) {
411415
logger: blog.NewMock(),
412416
clk: fc,
413417
maxExpectedReplicationLag: time.Second * 22,
418+
keysToProcess: prometheus.NewGauge(prometheus.GaugeOpts{}),
419+
certsRevoked: prometheus.NewCounter(prometheus.CounterOpts{}),
414420
}
415421

416422
// populate DB with all the test data

cmd/cert-checker/main.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import (
1818

1919
"github.com/jmhodges/clock"
2020
"github.com/prometheus/client_golang/prometheus"
21+
"github.com/prometheus/client_golang/prometheus/promauto"
2122
zX509 "github.com/zmap/zcrypto/x509"
2223
"github.com/zmap/zlint/v3"
2324
"github.com/zmap/zlint/v3/lint"
@@ -603,11 +604,10 @@ func main() {
603604
saDbMap, err := sa.InitWrappedDb(config.CertChecker.DB, prometheus.DefaultRegisterer, logger)
604605
cmd.FailOnError(err, "While initializing dbMap")
605606

606-
checkerLatency := prometheus.NewHistogram(prometheus.HistogramOpts{
607+
checkerLatency := promauto.NewHistogram(prometheus.HistogramOpts{
607608
Name: "cert_checker_latency",
608609
Help: "Histogram of latencies a cert-checker worker takes to complete a batch",
609610
})
610-
prometheus.DefaultRegisterer.MustRegister(checkerLatency)
611611

612612
pa, err := policy.New(config.PA.Identifiers, config.PA.Challenges, logger)
613613
cmd.FailOnError(err, "Failed to create PA")

crl/storer/storer.go

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import (
1818
smithyhttp "github.com/aws/smithy-go/transport/http"
1919
"github.com/jmhodges/clock"
2020
"github.com/prometheus/client_golang/prometheus"
21+
"github.com/prometheus/client_golang/prometheus/promauto"
2122
"google.golang.org/grpc"
2223
"google.golang.org/protobuf/types/known/emptypb"
2324

@@ -62,25 +63,22 @@ func New(
6263
issuersByNameID[issuer.NameID()] = issuer
6364
}
6465

65-
uploadCount := prometheus.NewCounterVec(prometheus.CounterOpts{
66+
uploadCount := promauto.With(stats).NewCounterVec(prometheus.CounterOpts{
6667
Name: "crl_storer_uploads",
6768
Help: "A counter of the number of CRLs uploaded by crl-storer",
6869
}, []string{"issuer", "result"})
69-
stats.MustRegister(uploadCount)
7070

71-
sizeHistogram := prometheus.NewHistogramVec(prometheus.HistogramOpts{
71+
sizeHistogram := promauto.With(stats).NewHistogramVec(prometheus.HistogramOpts{
7272
Name: "crl_storer_sizes",
7373
Help: "A histogram of the sizes (in bytes) of CRLs uploaded by crl-storer",
7474
Buckets: []float64{0, 256, 1024, 4096, 16384, 65536},
7575
}, []string{"issuer"})
76-
stats.MustRegister(sizeHistogram)
7776

78-
latencyHistogram := prometheus.NewHistogramVec(prometheus.HistogramOpts{
77+
latencyHistogram := promauto.With(stats).NewHistogramVec(prometheus.HistogramOpts{
7978
Name: "crl_storer_upload_times",
8079
Help: "A histogram of the time (in seconds) it took crl-storer to upload CRLs",
8180
Buckets: []float64{0.01, 0.2, 0.5, 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000},
8281
}, []string{"issuer"})
83-
stats.MustRegister(latencyHistogram)
8482

8583
return &crlStorer{
8684
issuers: issuersByNameID,

crl/updater/updater.go

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99

1010
"github.com/jmhodges/clock"
1111
"github.com/prometheus/client_golang/prometheus"
12+
"github.com/prometheus/client_golang/prometheus/promauto"
1213
"google.golang.org/protobuf/types/known/timestamppb"
1314

1415
capb "github.com/letsencrypt/boulder/ca/proto"
@@ -92,18 +93,16 @@ func NewUpdater(
9293
maxAttempts = 1
9394
}
9495

95-
tickHistogram := prometheus.NewHistogramVec(prometheus.HistogramOpts{
96+
tickHistogram := promauto.With(stats).NewHistogramVec(prometheus.HistogramOpts{
9697
Name: "crl_updater_ticks",
9798
Help: "A histogram of crl-updater tick latencies labeled by issuer and result",
9899
Buckets: []float64{0.01, 0.2, 0.5, 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000},
99100
}, []string{"issuer", "result"})
100-
stats.MustRegister(tickHistogram)
101101

102-
updatedCounter := prometheus.NewCounterVec(prometheus.CounterOpts{
102+
updatedCounter := promauto.With(stats).NewCounterVec(prometheus.CounterOpts{
103103
Name: "crl_updater_generated",
104104
Help: "A counter of CRL generation calls labeled by result",
105105
}, []string{"issuer", "result"})
106-
stats.MustRegister(updatedCounter)
107106

108107
return &crlUpdater{
109108
issuersByNameID,

ctpolicy/ctpolicy.go

Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"time"
99

1010
"github.com/prometheus/client_golang/prometheus"
11+
"github.com/prometheus/client_golang/prometheus/promauto"
1112

1213
"github.com/letsencrypt/boulder/core"
1314
"github.com/letsencrypt/boulder/ctpolicy/loglist"
@@ -36,23 +37,15 @@ type CTPolicy struct {
3637

3738
// New creates a new CTPolicy struct
3839
func New(pub pubpb.PublisherClient, sctLogs loglist.List, infoLogs loglist.List, finalLogs loglist.List, stagger time.Duration, log blog.Logger, stats prometheus.Registerer) *CTPolicy {
39-
winnerCounter := prometheus.NewCounterVec(
40-
prometheus.CounterOpts{
41-
Name: "sct_winner",
42-
Help: "Counter of logs which are selected for sct submission, by log URL and result (succeeded or failed).",
43-
},
44-
[]string{"url", "result"},
45-
)
46-
stats.MustRegister(winnerCounter)
40+
winnerCounter := promauto.With(stats).NewCounterVec(prometheus.CounterOpts{
41+
Name: "sct_winner",
42+
Help: "Counter of logs which are selected for sct submission, by log URL and result (succeeded or failed).",
43+
}, []string{"url", "result"})
4744

48-
shardExpiryGauge := prometheus.NewGaugeVec(
49-
prometheus.GaugeOpts{
50-
Name: "ct_shard_expiration_seconds",
51-
Help: "CT shard end_exclusive field expressed as Unix epoch time, by operator and logID.",
52-
},
53-
[]string{"operator", "logID"},
54-
)
55-
stats.MustRegister(shardExpiryGauge)
45+
shardExpiryGauge := promauto.With(stats).NewGaugeVec(prometheus.GaugeOpts{
46+
Name: "ct_shard_expiration_seconds",
47+
Help: "CT shard end_exclusive field expressed as Unix epoch time, by operator and logID.",
48+
}, []string{"operator", "logID"})
5649

5750
for _, log := range sctLogs {
5851
if log.EndExclusive.IsZero() {

email/cache.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77

88
"github.com/golang/groupcache/lru"
99
"github.com/prometheus/client_golang/prometheus"
10+
"github.com/prometheus/client_golang/prometheus/promauto"
1011
)
1112

1213
type EmailCache struct {
@@ -16,10 +17,9 @@ type EmailCache struct {
1617
}
1718

1819
func NewHashedEmailCache(maxEntries int, stats prometheus.Registerer) *EmailCache {
19-
requests := prometheus.NewCounterVec(prometheus.CounterOpts{
20+
requests := promauto.With(stats).NewCounterVec(prometheus.CounterOpts{
2021
Name: "email_cache_requests",
2122
}, []string{"status"})
22-
stats.MustRegister(requests)
2323

2424
return &EmailCache{
2525
cache: lru.New(maxEntries),

0 commit comments

Comments
 (0)