Skip to content

Commit 59c00e3

Browse files
authored
Fix data-race in metric without code and method but with WithLabelFromCtx (#1318)
This commit fixes a data race that exists when the metric used in any `promhttp` middleware doesn't collect the `code` and `method` but uses `WithLabelFromCtx` to collect values from context. The problem happens because when no `code` and `method` tags are collected, the `labels` function returns a pre-initialized map `emptyLabels` for every request. When one or multipe `WithLabelFromCtx` options are configured, the returned map from the `labels` function call is used to collect the metrics from context which creates a multi-write data race. Signed-off-by: Tiago Silva <[email protected]>
1 parent 7f2db5f commit 59c00e3

File tree

2 files changed

+4
-7
lines changed

2 files changed

+4
-7
lines changed

prometheus/promhttp/instrument_server.go

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -389,15 +389,12 @@ func isLabelCurried(c prometheus.Collector, label string) bool {
389389
return true
390390
}
391391

392-
// emptyLabels is a one-time allocation for non-partitioned metrics to avoid
393-
// unnecessary allocations on each request.
394-
var emptyLabels = prometheus.Labels{}
395-
396392
func labels(code, method bool, reqMethod string, status int, extraMethods ...string) prometheus.Labels {
393+
labels := prometheus.Labels{}
394+
397395
if !(code || method) {
398-
return emptyLabels
396+
return labels
399397
}
400-
labels := prometheus.Labels{}
401398

402399
if code {
403400
labels["code"] = sanitizeCode(status)

prometheus/promhttp/instrument_server_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -250,7 +250,7 @@ func TestLabels(t *testing.T) {
250250
}{
251251
"empty": {
252252
varLabels: []string{},
253-
wantLabels: emptyLabels,
253+
wantLabels: prometheus.Labels{},
254254
reqMethod: "GET",
255255
respStatus: 200,
256256
ok: true,

0 commit comments

Comments
 (0)