From 5371649ab180660d8b0d25d0aa781f6b102f4c7f Mon Sep 17 00:00:00 2001 From: Bhoopesh Date: Sat, 26 Oct 2024 03:13:08 +0530 Subject: [PATCH] fix: use rand no for temp file Signed-off-by: Bhoopesh --- sztp-agent/pkg/secureagent/utils.go | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/sztp-agent/pkg/secureagent/utils.go b/sztp-agent/pkg/secureagent/utils.go index 23ad4f6..4993907 100644 --- a/sztp-agent/pkg/secureagent/utils.go +++ b/sztp-agent/pkg/secureagent/utils.go @@ -14,6 +14,7 @@ import ( "fmt" "io" "log" + "math/rand" "os" "path/filepath" "strings" @@ -90,8 +91,8 @@ func calculateSHA256File(filePath string) (string, error) { } func saveToFile(data interface{}, filePath string) error { - tempPath := filePath + ".tmp" - tempPath = filepath.Clean(tempPath) + filePath = filepath.Clean(filePath) + tempPath := fmt.Sprintf("%s.%d.tmp", filePath, rand.Intn(100000)) // rand number to avoid conflicts when multiple agents are running file, err := os.Create(tempPath) if err != nil { return err @@ -108,7 +109,11 @@ func saveToFile(data interface{}, filePath string) error { } // Atomic move of temp file to replace the original. - return os.Rename(tempPath, filePath) + if err := os.Rename(tempPath, filePath); err != nil { + return fmt.Errorf("failed to rename %s to %s: %v", tempPath, filePath, err) + } + + return nil } func ensureDirExists(dir string) error { @@ -127,11 +132,13 @@ func ensureFileExists(filePath string) error { return err } + fmt.Printf("Checking if file %s exists...\n", filePath) + if _, err := os.Stat(filePath); os.IsNotExist(err) { filePath = filepath.Clean(filePath) file, err := os.Create(filePath) if err != nil { - return fmt.Errorf("failed to create file %s: %v", filePath, err) + return fmt.Errorf("[ERROR] failed to create file %s: %v", filePath, err) } defer func() { if err := file.Close(); err != nil { @@ -157,7 +164,7 @@ func createSymlink(targetFile, linkFile string) error { // Check if linkFile exists and is a symlink to targetFile if existingTarget, err := os.Readlink(linkFile); err == nil { if existingTarget == targetFile { - return nil // Symlink already points to the target; skip creation + return nil // Symlink already points to the target -> skip creation } // Remove the existing file (even if it's a wrong symlink or regular file) if err := os.Remove(linkFile); err != nil {