-
Notifications
You must be signed in to change notification settings - Fork 166
/
syncrename.go
96 lines (79 loc) · 2.39 KB
/
syncrename.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package wal
import (
"bufio"
"fmt"
"io"
"os"
"github.com/rs/zerolog"
)
type WriterSeekerCloser interface {
io.Writer
io.Seeker
io.Closer
}
// SyncOnCloseRenameFile is a composite of buffered writer over a given file
// which flushes/sync on closing and renames to `targetName` as a last step.
// Typical usecase is to write data to a temporary file and only rename it
// to target one as the last step. This help avoid situation when writing is
// interrupted and unusable file but with target name exists.
type SyncOnCloseRenameFile struct {
logger zerolog.Logger
file *os.File
targetName string
savedError error // savedError is the first error returned from Write. Close() renames temp file to target file only if savedError is nil.
*bufio.Writer
}
func (s *SyncOnCloseRenameFile) Sync() error {
err := s.Flush()
if err != nil {
return fmt.Errorf("cannot flush buffer: %w", err)
}
return s.file.Sync()
}
func (s *SyncOnCloseRenameFile) Close() error {
if s.savedError != nil {
// If there is any error saved from previous op, close temp file without renaming to target file.
return s.closeOnError()
}
err := s.Flush()
if err != nil {
return fmt.Errorf("cannot flush buffer: %w", err)
}
err = s.file.Sync()
if err != nil {
return fmt.Errorf("cannot sync file %s: %w", s.file.Name(), err)
}
// s.file.Sync() was already called, so we pass fsync=false
err = evictFileFromLinuxPageCache(s.file, false, s.logger)
if err != nil {
s.logger.Warn().Msgf("failed to evict file %s from Linux page cache: %s", s.targetName, err)
// No need to return this error because we're only "advising" Linux to evict a file from cache.
}
err = s.file.Close()
if err != nil {
return fmt.Errorf("error while closing file %s: %w", s.file.Name(), err)
}
err = os.Rename(s.file.Name(), s.targetName)
if err != nil {
return fmt.Errorf("error while renaming from %s to %s: %w", s.file.Name(), s.targetName, err)
}
return nil
}
func (s *SyncOnCloseRenameFile) Write(b []byte) (int, error) {
n, err := s.Writer.Write(b)
if err != nil && s.savedError == nil {
s.savedError = err
}
return n, err
}
// closeOnError closes and deletes temp file.
func (s *SyncOnCloseRenameFile) closeOnError() error {
fileName := s.file.Name()
// Close temp file
err := s.file.Close()
if err != nil {
return err
}
// Remove temp file because it is incomplete/invalid.
return os.Remove(fileName)
}