Correct replacing of log file
Do not leak resources in case of errors and ensure data is synced to disk before replacing files.pull/820/head
parent
8b5f68b899
commit
b66cb1a0de
21
log.go
21
log.go
|
@ -573,7 +573,8 @@ func (l *Log) compact(index uint64, term uint64) error {
|
||||||
}
|
}
|
||||||
|
|
||||||
// create a new log file and add all the entries
|
// create a new log file and add all the entries
|
||||||
file, err := os.OpenFile(l.path+".new", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
|
new_file_path := l.path + ".new"
|
||||||
|
file, err := os.OpenFile(new_file_path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
@ -582,25 +583,27 @@ func (l *Log) compact(index uint64, term uint64) error {
|
||||||
entry.Position = position
|
entry.Position = position
|
||||||
|
|
||||||
if _, err = entry.encode(file); err != nil {
|
if _, err = entry.encode(file); err != nil {
|
||||||
|
file.Close()
|
||||||
|
os.Remove(new_file_path)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// close the current log file
|
file.Sync()
|
||||||
l.file.Close()
|
|
||||||
|
|
||||||
// remove the current log file to .bak
|
old_file := l.file
|
||||||
err = os.Remove(l.path)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// rename the new log file
|
// rename the new log file
|
||||||
err = os.Rename(l.path+".new", l.path)
|
err = os.Rename(new_file_path, l.path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
file.Close()
|
||||||
|
os.Remove(new_file_path)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
l.file = file
|
l.file = file
|
||||||
|
|
||||||
|
// close the old log file
|
||||||
|
old_file.Close()
|
||||||
|
|
||||||
// compaction the in memory log
|
// compaction the in memory log
|
||||||
l.entries = entries
|
l.entries = entries
|
||||||
l.startIndex = index
|
l.startIndex = index
|
||||||
|
|
Loading…
Reference in New Issue