Skip to content

Commit

Permalink
Merge pull request #279 from pohly/test-integration-race-detection-trace
Browse files Browse the repository at this point in the history
trace: fix race condition
  • Loading branch information
k8s-ci-robot committed Apr 6, 2023
2 parents 38a27ef + 43193cd commit d93618c
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions trace/trace.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,11 @@ func durationToMilliseconds(timeDuration time.Duration) int64 {
}

type traceItem interface {
// rLock must be called before invoking time or writeItem.
rLock()
// rUnlock must be called after processing the item is complete.
rUnlock()

// time returns when the trace was recorded as completed.
time() time.Time
// writeItem outputs the traceItem to the buffer. If stepThreshold is non-nil, only output the
Expand All @@ -79,6 +84,10 @@ type traceStep struct {
fields []Field
}

// rLock doesn't need to do anything because traceStep instances are immutable.
func (s traceStep) rLock() {}
func (s traceStep) rUnlock() {}

func (s traceStep) time() time.Time {
return s.stepTime
}
Expand Down Expand Up @@ -106,6 +115,14 @@ type Trace struct {
traceItems []traceItem
}

func (t *Trace) rLock() {
t.lock.RLock()
}

func (t *Trace) rUnlock() {
t.lock.RUnlock()
}

func (t *Trace) time() time.Time {
if t.endTime != nil {
return *t.endTime
Expand Down Expand Up @@ -231,8 +248,10 @@ func (t *Trace) logTrace() {
func (t *Trace) writeTraceSteps(b *bytes.Buffer, formatter string, stepThreshold *time.Duration) {
lastStepTime := t.startTime
for _, stepOrTrace := range t.traceItems {
stepOrTrace.rLock()
stepOrTrace.writeItem(b, formatter, lastStepTime, stepThreshold)
lastStepTime = stepOrTrace.time()
stepOrTrace.rUnlock()
}
}

Expand Down

0 comments on commit d93618c

Please sign in to comment.