Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix klog lock release on panic error #272

Merged
merged 1 commit into from Dec 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 12 additions & 2 deletions klog.go
Expand Up @@ -917,7 +917,15 @@ func LogToStderr(stderr bool) {

// output writes the data to the log files and releases the buffer.
func (l *loggingT) output(s severity, log *logr.Logger, buf *buffer, depth int, file string, line int, alsoToStderr bool) {
var isLocked = true
l.mu.Lock()
defer func() {
if isLocked {
// Unlock before returning in case that it wasn't done already.
l.mu.Unlock()
}
}()

if l.traceLocation.isSet() {
if l.traceLocation.match(file, line) {
buf.Write(stacks(false))
Expand Down Expand Up @@ -980,6 +988,7 @@ func (l *loggingT) output(s severity, log *logr.Logger, buf *buffer, depth int,
// If we got here via Exit rather than Fatal, print no stacks.
if atomic.LoadUint32(&fatalNoStacks) > 0 {
l.mu.Unlock()
isLocked = false
timeoutFlush(10 * time.Second)
os.Exit(1)
}
Expand All @@ -997,11 +1006,12 @@ func (l *loggingT) output(s severity, log *logr.Logger, buf *buffer, depth int,
}
}
l.mu.Unlock()
isLocked = false
timeoutFlush(10 * time.Second)
os.Exit(255) // C++ uses -1, which is silly because it's anded with 255 anyway.
astraw99 marked this conversation as resolved.
Show resolved Hide resolved
os.Exit(255) // C++ uses -1, which is silly because it's anded(&) with 255 anyway.
}
l.putBuffer(buf)
l.mu.Unlock()

if stats := severityStats[s]; stats != nil {
atomic.AddInt64(&stats.lines, 1)
atomic.AddInt64(&stats.bytes, int64(len(data)))
Expand Down
32 changes: 32 additions & 0 deletions klog_test.go
Expand Up @@ -1844,3 +1844,35 @@ func TestKObjs(t *testing.T) {
})
}
}

// Benchmark test for lock with/without defer
type structWithLock struct {
m sync.Mutex
n int64
}

func BenchmarkWithoutDeferUnLock(b *testing.B) {
s := structWithLock{}
for i := 0; i < b.N; i++ {
s.addWithoutDefer()
}
}

func BenchmarkWithDeferUnLock(b *testing.B) {
s := structWithLock{}
for i := 0; i < b.N; i++ {
s.addWithDefer()
}
}

func (s *structWithLock) addWithoutDefer() {
s.m.Lock()
s.n++
s.m.Unlock()
}

func (s *structWithLock) addWithDefer() {
s.m.Lock()
defer s.m.Unlock()
s.n++
}