From f0d5df523b982ef1737dc0ee2e698b13041af64c Mon Sep 17 00:00:00 2001 From: Johannes Erdfelt Date: Tue, 28 Feb 2012 05:54:48 +0000 Subject: Add utils.tempdir() context manager for easy temp dirs Fixes bug 883323 (and others) Users of tempfile.mkdtemp() need to make sure the directory is cleaned up when it's done being used. Unfortunately, not all of the code does so at all, or safely (by using a try/finally block). Change-Id: I270109d83efec4f8b3dd954021493f4d96c6ab79 --- nova/utils.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) (limited to 'nova/utils.py') diff --git a/nova/utils.py b/nova/utils.py index 6bb0dd0f2..ef4932146 100644 --- a/nova/utils.py +++ b/nova/utils.py @@ -31,9 +31,11 @@ import pyclbr import random import re import shlex +import shutil import socket import struct import sys +import tempfile import time import types import uuid @@ -1543,3 +1545,15 @@ def temporary_chown(path, owner_uid=None): finally: if orig_uid != owner_uid: execute('chown', orig_uid, path, run_as_root=True) + + +@contextlib.contextmanager +def tempdir(**kwargs): + tmpdir = tempfile.mkdtemp(**kwargs) + try: + yield tmpdir + finally: + try: + shutil.rmtree(tmpdir) + except OSError, e: + LOG.debug(_('Could not remove tmpdir: %s'), str(e)) -- cgit