From bc92c20d67b95cb6aa554d6400b514b61c66fbb8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marek=20Marczykowski-G=C3=B3recki?= Date: Mon, 2 Dec 2013 03:32:33 +0100 Subject: [PATCH] core: do not truncate qubes.xml during save() Save the next one in temporary file, then move over to destination file. This way when writing the file to disk fails (e.g. out of disk space), user still have old file version intact. --- core/qubes.py | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/core/qubes.py b/core/qubes.py index df0653c9..8c0d8e46 100755 --- a/core/qubes.py +++ b/core/qubes.py @@ -28,6 +28,8 @@ import xml.parsers.expat import fcntl import time import warnings +import tempfile +import grp # Do not use XenAPI or create/read any VM files # This is for testing only! @@ -527,11 +529,16 @@ class QubesVmCollection(dict): try: - # We need to manually truncate the file, as we open the - # file as "r+" in the lock_db_for_writing() function - self.qubes_store_file.seek (0, os.SEEK_SET) - self.qubes_store_file.truncate() - tree.write(self.qubes_store_file, encoding="UTF-8", pretty_print=True) + new_store_file = tempfile.NamedTemporaryFile(prefix=self.qubes_store_filename, delete=False) + # XXX: do not get lock on the new file, as in all use cases + # unlock_db() is the next operation after save() + tree.write(new_store_file, encoding="UTF-8", pretty_print=True) + new_store_file.flush() + os.chmod(new_store_file.name, 0660) + os.chown(new_store_file.name, -1, grp.getgrnam('qubes').gr_gid) + os.rename(new_store_file.name, self.qubes_store_filename) + self.qubes_store_file.close() + self.qubes_store_file = new_store_file except EnvironmentError as err: print("{0}: export error: {1}".format( os.path.basename(sys.argv[0]), err))