Skip to content

Commit 7585bbc

Browse files
authored
Extract function SyncParent to reuse in elastic agent (#36)
* extract function * add import * remove old
1 parent 45d6da9 commit 7585bbc

File tree

3 files changed

+30
-4
lines changed

3 files changed

+30
-4
lines changed

file/helper_aix.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ import (
2424

2525
// SafeFileRotate safely rotates an existing file under path and replaces it with the tempfile
2626
func SafeFileRotate(path, tempfile string) error {
27-
parent := filepath.Dir(path)
2827

2928
if e := os.Rename(tempfile, path); e != nil {
3029
return e
@@ -35,6 +34,14 @@ func SafeFileRotate(path, tempfile string) error {
3534
// contain the new file being rotated in.
3635
// On AIX, fsync will fail if the file is opened in read-only mode,
3736
// which is the case with os.Open.
37+
return SyncParent(path)
38+
39+
}
40+
41+
// SyncParent fsyncs parent directory
42+
func SyncParent(path string) error {
43+
parent := filepath.Dir(path)
44+
3845
f, err := os.OpenFile(parent, os.O_RDWR, 0)
3946
if err != nil {
4047
return nil // ignore error

file/helper_other.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@ import (
2727

2828
// SafeFileRotate safely rotates an existing file under path and replaces it with the tempfile
2929
func SafeFileRotate(path, tempfile string) error {
30-
parent := filepath.Dir(path)
3130

3231
if e := os.Rename(tempfile, path); e != nil {
3332
return e
@@ -36,6 +35,12 @@ func SafeFileRotate(path, tempfile string) error {
3635
// best-effort fsync on parent directory. The fsync is required by some
3736
// filesystems, so to update the parents directory metadata to actually
3837
// contain the new file being rotated in.
38+
return SyncParent(path)
39+
}
40+
41+
// SyncParent fsyncs parent directory
42+
func SyncParent(path string) error {
43+
parent := filepath.Dir(path)
3944
f, err := os.Open(parent)
4045

4146
// nolint: nilerr // ignore error

file/helper_windows.go

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,25 @@ func SafeFileRotate(path, tempfile string) error {
4141
return e
4242
}
4343

44+
// .old file will still exist if path file is already there, it should be removed
45+
_ = os.Remove(old)
46+
4447
// sync all files
48+
return SyncParent(path)
49+
}
50+
51+
// SyncParent fsyncs parent directory
52+
func SyncParent(path string) error {
4553
parent := filepath.Dir(path)
4654
if f, err := os.OpenFile(parent, os.O_SYNC|os.O_RDWR, 0755); err == nil {
47-
_ = f.Sync()
48-
f.Close()
55+
err := f.Sync()
56+
if err != nil {
57+
return err
58+
}
59+
err = f.Close()
60+
if err != nil {
61+
return err
62+
}
4963
}
5064

5165
return nil

0 commit comments

Comments
 (0)