From c938849cf82002f9a8945050b67e8762e4944269 Mon Sep 17 00:00:00 2001 From: subhamkrai Date: Thu, 30 Jul 2020 18:16:19 +0530 Subject: [PATCH] ceph: closing file which are open for writing using defer for closing file which are open for writing is not safe. so closing file again following below steps: 1. open files 2. defer file.close() 3. write 4.file.close() these will make sure files are closed. Signed-off-by: subhamkrai --- cmd/rook/rook/rook.go | 3 +++ pkg/daemon/ceph/agent/flexvolume/server.go | 6 +++++- pkg/daemon/util/copybins.go | 3 +++ pkg/util/exec/exec.go | 6 ++++++ 4 files changed, 17 insertions(+), 1 deletion(-) diff --git a/cmd/rook/rook/rook.go b/cmd/rook/rook/rook.go index db84c8d72..d7a31de29 100644 --- a/cmd/rook/rook/rook.go +++ b/cmd/rook/rook/rook.go @@ -215,6 +215,9 @@ func TerminateFatal(reason error) { if _, err = file.WriteString(reason.Error()); err != nil { fmt.Fprintln(os.Stderr, fmt.Errorf("failed to write message to termination log: %+v", err)) } + if err := file.Close(); err != nil { + logger.Errorf("failed to close file. %v", err) + } } os.Exit(1) diff --git a/pkg/daemon/ceph/agent/flexvolume/server.go b/pkg/daemon/ceph/agent/flexvolume/server.go index b2ca88513..69cb7a266 100644 --- a/pkg/daemon/ceph/agent/flexvolume/server.go +++ b/pkg/daemon/ceph/agent/flexvolume/server.go @@ -271,7 +271,11 @@ func copyFile(src, dest string) error { if err != nil { return errors.Wrapf(err, "error copying file from %s to %s", src, dest) } - return destFile.Sync() + err = destFile.Sync() + if err := destFile.Close(); err != nil { + return err + } + return err } // Gets the flex driver info (vendor, driver name) from a given path where the flex driver exists. diff --git a/pkg/daemon/util/copybins.go b/pkg/daemon/util/copybins.go index 91a89be1b..a4d15f70b 100644 --- a/pkg/daemon/util/copybins.go +++ b/pkg/daemon/util/copybins.go @@ -68,6 +68,9 @@ func copyBinary(sourceDir, targetDir, filename string) error { if _, err := io.Copy(destinationFile, sourceFile); err != nil { return err } + if err := destinationFile.Close(); err != nil { + return err + } // #nosec targetPath requires the permission to execute return os.Chmod(targetPath, 0700) } diff --git a/pkg/util/exec/exec.go b/pkg/util/exec/exec.go index 106813732..2fdef2c41 100644 --- a/pkg/util/exec/exec.go +++ b/pkg/util/exec/exec.go @@ -173,6 +173,9 @@ func (*CommandExecutor) ExecuteCommandWithOutputFileTimeout(timeout time.Duratio } fileOut, err := ioutil.ReadAll(outFile) + if err := outFile.Close(); err != nil { + return "", err + } return string(fileOut), err } @@ -206,6 +209,9 @@ func (*CommandExecutor) ExecuteCommandWithOutputFile(command, outfileArg string, // read the entire output file and return that to the caller fileOut, err := ioutil.ReadAll(outFile) + if err := outFile.Close(); err != nil { + return "", err + } return string(fileOut), err }