From 21ee25f07ad06c12150b2321d494eab641ef9ac2 Mon Sep 17 00:00:00 2001 From: Ghe Rivero Date: Thu, 30 May 2013 12:55:16 +0200 Subject: Add common code for fileutils. This code is present in nova, cinder and also needed by ironic package. * delete_if_exists * remove_path_on_error Also added some tests. openstack/common/fileutils.py => nova.common.utils <=> cinder.common.utils Change-Id: Id5001db161bb8e7dfb20d1b2cc2033e886cda32f Implements: blueprint image-tools --- openstack/common/fileutils.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) (limited to 'openstack') diff --git a/openstack/common/fileutils.py b/openstack/common/fileutils.py index bb2ef61..0c967da 100644 --- a/openstack/common/fileutils.py +++ b/openstack/common/fileutils.py @@ -16,9 +16,11 @@ # under the License. +import contextlib import errno import os +from openstack.common import excutils from openstack.common.gettextutils import _ from openstack.common import log as logging @@ -65,3 +67,32 @@ def read_cached_file(filename, force_reload=False): cache_info['mtime'] = mtime reloaded = True return (reloaded, cache_info['data']) + + +def delete_if_exists(path): + """Delete a file, but ignore file not found error. + + :param path: File to delete + """ + + try: + os.unlink(path) + except OSError as e: + if e.errno == errno.ENOENT: + return + else: + raise + + +@contextlib.contextmanager +def remove_path_on_error(path): + """Protect code that wants to operate on PATH atomically. + Any exception will cause PATH to be removed. + + :param path: File to work with + """ + try: + yield + except Exception: + with excutils.save_and_reraise_exception(): + delete_if_exists(path) -- cgit