Skip to content

Commit 7f6207d

Browse files
committed
util/log: fix data race in (*StructuredLogSpy).Intercept
We were reading the formatter and filters without taking the lock. The formatter doesn't appear to be set after initialization so I moved it out of the lock struct. For the filters, I moved the locking up a few lines. Fixes #150556 Release note: None
1 parent fccbd7e commit 7f6207d

File tree

1 file changed

+8
-8
lines changed

1 file changed

+8
-8
lines changed

pkg/util/log/logtestutils/structured_log_spy.go

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,9 @@ type StructuredLogSpy[T any] struct {
126126
// that match the event type in the log message.
127127
eventTypeRe []*regexp.Regexp
128128

129+
// Function to transform log entries into the desired format.
130+
format func(entry logpb.Entry) (T, error)
131+
129132
mu struct {
130133
syncutil.RWMutex
131134

@@ -135,9 +138,6 @@ type StructuredLogSpy[T any] struct {
135138
// to determine if the log should be intercepted.
136139
filters []func(entry logpb.Entry, formattedEntry T) bool
137140

138-
// Function to transform log entries into the desired format.
139-
format func(entry logpb.Entry) (T, error)
140-
141141
// lastReadIdx is a map of channel to int, representing the last read log
142142
// line read when calling GetUnreadLogs.
143143
lastReadIdx map[logpb.Channel]int
@@ -161,6 +161,7 @@ func NewStructuredLogSpy[T any](
161161
filters ...func(entry logpb.Entry, formattedEntry T) bool,
162162
) *StructuredLogSpy[T] {
163163
s := &StructuredLogSpy[T]{
164+
format: format,
164165
testState: testState,
165166
channels: make(map[logpb.Channel]struct{}, len(channels)),
166167
}
@@ -170,7 +171,6 @@ func NewStructuredLogSpy[T any](
170171
}
171172
s.mu.lastReadIdx = make(map[logpb.Channel]int, len(channels))
172173
s.mu.logs = make(map[logpb.Channel][]T, len(s.channels))
173-
s.mu.format = format
174174
s.mu.filters = append(s.mu.filters, filters...)
175175
s.eventTypes = eventTypes
176176
for _, eventType := range eventTypes {
@@ -287,21 +287,21 @@ func (s *StructuredLogSpy[T]) Intercept(entry []byte) {
287287
}
288288
}
289289

290-
formattedLog, err := s.mu.format(logEntry)
290+
formattedLog, err := s.format(logEntry)
291291
if err != nil {
292292
s.testState.Fatal(err)
293293
}
294294

295+
s.mu.Lock()
296+
defer s.mu.Unlock()
297+
295298
if s.mu.filters != nil {
296299
for _, filter := range s.mu.filters {
297300
if !filter(logEntry, formattedLog) {
298301
return
299302
}
300303
}
301304
}
302-
303-
s.mu.Lock()
304-
defer s.mu.Unlock()
305305
s.mu.logs[logEntry.Channel] = append(s.mu.logs[logEntry.Channel], formattedLog)
306306
}
307307

0 commit comments

Comments
 (0)