Skip to content

Commit 5129306

Browse files
committed
use atomicfile to create the file
1 parent c73b178 commit 5129306

1 file changed

Lines changed: 15 additions & 18 deletions

File tree

filestorage.go

Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -289,7 +289,7 @@ func fileLockIsStale(meta lockMeta) bool {
289289
// identified by filename. A successfully created
290290
// lockfile should be removed with removeLockfile.
291291
func createLockfile(filename string) error {
292-
err := atomicallyCreateFile(filename, true)
292+
err := atomicallyCreateFile(filename)
293293
if err != nil {
294294
return err
295295
}
@@ -376,29 +376,26 @@ func updateLockfileFreshness(filename string) (bool, error) {
376376

377377
// atomicallyCreateFile atomically creates the file
378378
// identified by filename if it doesn't already exist.
379-
func atomicallyCreateFile(filename string, writeLockInfo bool) error {
379+
func atomicallyCreateFile(filename string) error {
380380
// no need to check this error, we only really care about the file creation error
381381
_ = os.MkdirAll(filepath.Dir(filename), 0700)
382-
f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0644)
382+
fp, err := atomicfile.New(filename, 0o600)
383383
if err != nil {
384+
// cancel the write if file creation fails and error out
384385
return err
385386
}
386-
defer f.Close()
387-
if writeLockInfo {
388-
now := time.Now()
389-
meta := lockMeta{
390-
Created: now,
391-
Updated: now,
392-
}
393-
if err := json.NewEncoder(f).Encode(meta); err != nil {
394-
return err
395-
}
396-
// see https://github.com/caddyserver/caddy/issues/3954
397-
if err := f.Sync(); err != nil {
398-
return err
399-
}
387+
now := time.Now()
388+
meta := lockMeta{
389+
Created: now,
390+
Updated: now,
400391
}
401-
return nil
392+
if err := json.NewEncoder(fp).Encode(meta); err != nil {
393+
// cancel the write if json encoding fails and error out
394+
fp.Cancel()
395+
return err
396+
}
397+
// close, thereby flushing the write
398+
return fp.Close()
402399
}
403400

404401
// homeDir returns the best guess of the current user's home

0 commit comments

Comments
 (0)