diff options
author | Tristan Van Berkom <tristan.vanberkom@codethink.co.uk> | 2019-01-18 14:25:16 -0500 |
---|---|---|
committer | Tristan Van Berkom <tristan.vanberkom@codethink.co.uk> | 2019-01-18 14:36:26 -0500 |
commit | 99699ffc1f50805b17cbc44635ce68a2668b7769 (patch) | |
tree | 82c289ea72ef290c5d08ccaf38de204adfeae1e1 | |
parent | c536ab6a859f551078c0ea07a3a20fdd9851276a (diff) | |
download | buildstream-99699ffc1f50805b17cbc44635ce68a2668b7769.tar.gz |
utils.py: Added _tempnamedfile()
When used in a child process in BuildStream, this should be
used instead of tempfile.NamedTemporaryFile() directly, otherwise
we fail to cleanup the file on SIGTERM.
-rw-r--r-- | buildstream/utils.py | 30 |
1 files changed, 30 insertions, 0 deletions
diff --git a/buildstream/utils.py b/buildstream/utils.py index 45b3c375f..e3ff88034 100644 --- a/buildstream/utils.py +++ b/buildstream/utils.py @@ -1032,6 +1032,36 @@ def _tempdir(suffix="", prefix="tmp", dir=None): # pylint: disable=redefined-bu cleanup_tempdir() +# _tempnamedfile() +# +# A context manager for doing work on an open temporary file +# which is guaranteed to be named and have an entry in the filesystem. +# +# Args: +# dir (str): A path to a parent directory for the temporary file +# suffix (str): A suffix for the temproary file name +# prefix (str): A prefix for the temporary file name +# +# Yields: +# (str): The temporary file handle +# +# Do not use tempfile.NamedTemporaryFile() directly, as this will +# leak files on the filesystem when BuildStream exits a process +# on SIGTERM. +# +@contextmanager +def _tempnamedfile(suffix="", prefix="tmp", dir=None): # pylint: disable=redefined-builtin + temp = None + + def close_tempfile(): + if temp is not None: + temp.close() + + with _signals.terminator(close_tempfile), \ + tempfile.NamedTemporaryFile(suffix=suffix, prefix=prefix, dir=dir) as temp: + yield temp + + # _kill_process_tree() # # Brutally murder a process and all of its children |