Fixes #1526 to make the persist_metadata function an atomic operation

Co-authored-by: Jussi Kukkonen <jkukkonen@vmware.com>
Signed-off-by: Suvaditya Mukherjee <suvadityamuk@gmail.com>
Signed-off-by: Jussi Kukkonen <jkukkonen@vmware.com>
This commit is contained in:
Suvaditya Mukherjee 2021-08-29 20:07:57 +05:30 committed by Jussi Kukkonen
parent ea9acf2bfd
commit ab81cfba7f

View file

@ -62,6 +62,7 @@
import logging
import os
import tempfile
from typing import List, Optional, Set, Tuple
from urllib import parse
@ -287,8 +288,17 @@ def _load_local_metadata(self, rolename: str) -> bytes:
return f.read()
def _persist_metadata(self, rolename: str, data: bytes) -> None:
with open(os.path.join(self._dir, f"{rolename}.json"), "wb") as f:
f.write(data)
"""Acts as an atomic write operation to make sure
that if the process of writing is halted, at least the
original data is left intact.
"""
original_filename = os.path.join(self._dir, f"{rolename}.json")
with tempfile.NamedTemporaryFile(
dir=self._dir, delete=False
) as temp_file:
temp_file.write(data)
os.replace(temp_file.name, original_filename)
def _load_root(self) -> None:
"""Load remote root metadata.