summaryrefslogtreecommitdiffstats
path: root/openstack
diff options
context:
space:
mode:
authorGhe Rivero <ghe@debian.org>2013-05-30 12:55:16 +0200
committerGhe Rivero <ghe@debian.org>2013-06-06 08:51:42 +0200
commit21ee25f07ad06c12150b2321d494eab641ef9ac2 (patch)
treedb0e2601540a588c2fc2f6ded7e4728c1a1f1f34 /openstack
parent3f315db8dab8a859e7204e7ac184ea9796273a74 (diff)
downloadoslo-21ee25f07ad06c12150b2321d494eab641ef9ac2.tar.gz
oslo-21ee25f07ad06c12150b2321d494eab641ef9ac2.tar.xz
oslo-21ee25f07ad06c12150b2321d494eab641ef9ac2.zip
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
Diffstat (limited to 'openstack')
-rw-r--r--openstack/common/fileutils.py31
1 files changed, 31 insertions, 0 deletions
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)