From 19254e978fbf132345fabcc3ed818af8f9575a07 Mon Sep 17 00:00:00 2001 From: Alex Cordeiro Date: Thu, 5 Mar 2020 17:46:26 -0800 Subject: [PATCH] services/ticker: update *.json files atomically (#2362) --- services/ticker/internal/utils/main.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/services/ticker/internal/utils/main.go b/services/ticker/internal/utils/main.go index f0d3ce4704..3286037855 100644 --- a/services/ticker/internal/utils/main.go +++ b/services/ticker/internal/utils/main.go @@ -16,9 +16,12 @@ func PanicIfError(e error) { } } -// WriteJSONToFile wrtites a json []byte dump to +// WriteJSONToFile atomically writes a json []byte dump to +// It ensures atomicity by first creating a tmp file (filename.tmp), writing +// the contents to it, then renaming it to the originally specified filename. func WriteJSONToFile(jsonBytes []byte, filename string) (numBytes int, err error) { - f, err := os.Create(filename) + tmp := fmt.Sprintf("%s.tmp", filename) + f, err := os.Create(tmp) PanicIfError(err) defer f.Close() @@ -32,6 +35,7 @@ func WriteJSONToFile(jsonBytes []byte, filename string) (numBytes int, err error return } + err = os.Rename(tmp, filename) return }