github.com/osdi23p228/fabric@v0.0.0-20221218062954-77808885f5db/common/ledger/blkstorage/file_util.go (about) 1 /* 2 Copyright IBM Corp. All Rights Reserved. 3 4 SPDX-License-Identifier: Apache-2.0 5 */ 6 7 package blkstorage 8 9 import ( 10 "os" 11 "path/filepath" 12 13 "github.com/pkg/errors" 14 ) 15 16 func createAndSyncFileAtomically(dir, tmpFile, finalFile string, content []byte) error { 17 tempFilePath := filepath.Join(dir, tmpFile) 18 finalFilePath := filepath.Join(dir, finalFile) 19 if err := createAndSyncFile(tempFilePath, content); err != nil { 20 return err 21 } 22 if err := os.Rename(tempFilePath, finalFilePath); err != nil { 23 return err 24 } 25 return syncDir(dir) 26 } 27 28 func createAndSyncFile(filePath string, content []byte) error { 29 file, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0644) 30 if err != nil { 31 return errors.Wrapf(err, "error while creating file:%s", filePath) 32 } 33 _, err = file.Write(content) 34 if err != nil { 35 file.Close() 36 return errors.Wrapf(err, "error while writing to file:%s", filePath) 37 } 38 if err = file.Sync(); err != nil { 39 file.Close() 40 return errors.Wrapf(err, "error while synching the file:%s", filePath) 41 } 42 if err := file.Close(); err != nil { 43 return errors.Wrapf(err, "error while closing the file:%s", filePath) 44 } 45 return nil 46 } 47 48 func syncDir(dirPath string) error { 49 dir, err := os.Open(dirPath) 50 if err != nil { 51 return errors.Wrapf(err, "error while opening dir:%s", dirPath) 52 } 53 if err := dir.Sync(); err != nil { 54 dir.Close() 55 return errors.Wrapf(err, "error while synching dir:%s", dirPath) 56 } 57 if err := dir.Close(); err != nil { 58 return errors.Wrapf(err, "error while closing dir:%s", dirPath) 59 } 60 return err 61 }