Skip to content

Commit 2ee202a

Browse files
authored
Merge pull request #404 from 1978629634/fsync-freelock
Do not acquire lock for file.Sync() fsync call
2 parents 7af45d6 + 79575d8 commit 2ee202a

File tree

2 files changed

+24
-7
lines changed

2 files changed

+24
-7
lines changed

Diff for: klog.go

+20-5
Original file line numberDiff line numberDiff line change
@@ -1011,7 +1011,8 @@ func (l *loggingT) exit(err error) {
10111011
logExitFunc(err)
10121012
return
10131013
}
1014-
l.flushAll()
1014+
files := l.flushAll()
1015+
l.syncAll(files)
10151016
OsExit(2)
10161017
}
10171018

@@ -1223,24 +1224,38 @@ func StartFlushDaemon(interval time.Duration) {
12231224
// lockAndFlushAll is like flushAll but locks l.mu first.
12241225
func (l *loggingT) lockAndFlushAll() {
12251226
l.mu.Lock()
1226-
l.flushAll()
1227+
files := l.flushAll()
12271228
l.mu.Unlock()
1229+
// Some environments are slow when syncing and holding the lock might cause contention.
1230+
l.syncAll(files)
12281231
}
12291232

1230-
// flushAll flushes all the logs and attempts to "sync" their data to disk.
1233+
// flushAll flushes all the logs
12311234
// l.mu is held.
1232-
func (l *loggingT) flushAll() {
1235+
func (l *loggingT) flushAll() []flushSyncWriter {
1236+
files := make([]flushSyncWriter, 0, severity.NumSeverity)
12331237
// Flush from fatal down, in case there's trouble flushing.
12341238
for s := severity.FatalLog; s >= severity.InfoLog; s-- {
12351239
file := l.file[s]
12361240
if file != nil {
12371241
_ = file.Flush() // ignore error
1238-
_ = file.Sync() // ignore error
12391242
}
1243+
files = append(files, file)
12401244
}
12411245
if logging.loggerOptions.flush != nil {
12421246
logging.loggerOptions.flush()
12431247
}
1248+
return files
1249+
}
1250+
1251+
// syncAll attempts to "sync" their data to disk.
1252+
func (l *loggingT) syncAll(files []flushSyncWriter) {
1253+
// Flush from fatal down, in case there's trouble flushing.
1254+
for _, file := range files {
1255+
if file != nil {
1256+
_ = file.Sync() // ignore error
1257+
}
1258+
}
12441259
}
12451260

12461261
// CopyStandardLogTo arranges for messages written to the Go "log" package's

Diff for: klog_test.go

+4-2
Original file line numberDiff line numberDiff line change
@@ -546,7 +546,8 @@ func TestOpenAppendOnStart(t *testing.T) {
546546
}
547547

548548
// ensure we wrote what we expected
549-
logging.flushAll()
549+
files := logging.flushAll()
550+
logging.syncAll(files)
550551
b, err := ioutil.ReadFile(logging.logFile)
551552
if err != nil {
552553
t.Fatalf("unexpected error: %v", err)
@@ -817,7 +818,8 @@ func BenchmarkLogs(b *testing.B) {
817818
Warning("warning")
818819
Info("info")
819820
}
820-
logging.flushAll()
821+
files := logging.flushAll()
822+
logging.syncAll(files)
821823
}
822824

823825
// Test the logic on checking log size limitation.

0 commit comments

Comments
 (0)