Skip to content

Commit ddf91da

Browse files
Fix concurrent map write panic in monitoring middleware (#14335) (#14350)
Fix panic due to monitoring middleware concurrent map write. (cherry picked from commit 5cd8b7d) Co-authored-by: Carson Ip <carsonip@users.noreply.github.com> Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
1 parent fb19432 commit ddf91da

File tree

2 files changed

+12
-10
lines changed

2 files changed

+12
-10
lines changed

changelogs/head.asciidoc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ https://github.com/elastic/apm-server/compare/8.15\...main[View commits]
77
==== Bug fixes
88

99
- Track all bulk request response status codes {pull}13574[13574]
10+
- Fix a concurrent map write panic in monitoring middleware {pull}14335[14335]
1011

1112
[float]
1213
==== Breaking Changes

internal/beater/middleware/monitoring_middleware.go

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ package middleware
2020
import (
2121
"context"
2222
"net/http"
23+
"sync"
2324
"time"
2425

2526
"go.opentelemetry.io/otel"
@@ -37,8 +38,8 @@ type monitoringMiddleware struct {
3738
meter metric.Meter
3839

3940
ints map[request.ResultID]*monitoring.Int
40-
counters map[string]metric.Int64Counter
41-
histograms map[string]metric.Int64Histogram
41+
counters sync.Map
42+
histograms sync.Map
4243
}
4344

4445
func (m *monitoringMiddleware) Middleware() Middleware {
@@ -79,23 +80,23 @@ func (m *monitoringMiddleware) inc(id request.ResultID) {
7980

8081
func (m *monitoringMiddleware) getCounter(n string) metric.Int64Counter {
8182
name := "http.server." + n
82-
if met, ok := m.counters[name]; ok {
83-
return met
83+
if met, ok := m.counters.Load(name); ok {
84+
return met.(metric.Int64Counter)
8485
}
8586

8687
nm, _ := m.meter.Int64Counter(name)
87-
m.counters[name] = nm
88+
m.counters.LoadOrStore(name, nm)
8889
return nm
8990
}
9091

9192
func (m *monitoringMiddleware) getHistogram(n string, opts ...metric.Int64HistogramOption) metric.Int64Histogram {
9293
name := "http.server." + n
93-
if met, ok := m.histograms[name]; ok {
94-
return met
94+
if met, ok := m.histograms.Load(name); ok {
95+
return met.(metric.Int64Histogram)
9596
}
9697

9798
nm, _ := m.meter.Int64Histogram(name, opts...)
98-
m.histograms[name] = nm
99+
m.histograms.LoadOrStore(name, nm)
99100
return nm
100101
}
101102

@@ -109,8 +110,8 @@ func MonitoringMiddleware(m map[request.ResultID]*monitoring.Int, mp metric.Mete
109110
mid := &monitoringMiddleware{
110111
meter: mp.Meter("internal/beater/middleware"),
111112
ints: m,
112-
counters: map[string]metric.Int64Counter{},
113-
histograms: map[string]metric.Int64Histogram{},
113+
counters: sync.Map{},
114+
histograms: sync.Map{},
114115
}
115116

116117
return mid.Middleware()

0 commit comments

Comments
 (0)