From afdea8f40517837b7e4b8884e3108d1a6e6a5075 Mon Sep 17 00:00:00 2001 From: Evan Lezar Date: Thu, 27 Jun 2024 11:57:28 +0200 Subject: [PATCH] Create driver-ready file atomically Signed-off-by: Evan Lezar --- validator/main.go | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/validator/main.go b/validator/main.go index eb94eac27..4b6ed3cf9 100644 --- a/validator/main.go +++ b/validator/main.go @@ -864,16 +864,23 @@ func createStatusFile(statusFile string) error { } func createStatusFileWithContent(statusFile string, content string) error { - f, err := os.Create(statusFile) + dir := filepath.Dir(statusFile) + tmpFile, err := os.CreateTemp(dir, filepath.Base(statusFile)+".*.tmp") if err != nil { - return fmt.Errorf("unable to create status file %s: %s", statusFile, err) + return fmt.Errorf("failed to create temporary status file: %w", err) } - - _, err = f.WriteString(content) + _, err = tmpFile.WriteString(content) + tmpFile.Close() if err != nil { - return fmt.Errorf("unable to write contents of status file %s: %s", statusFile, err) + return fmt.Errorf("failed to write temporary status file: %w", err) } + defer func() { + _ = os.Remove(tmpFile.Name()) + }() + if err := os.Rename(tmpFile.Name(), statusFile); err != nil { + return fmt.Errorf("error moving temporary file to '%v': %w", statusFile, err) + } return nil }