Instalog & Testlog tries to call tempfile.mkstemp directory to prevent dependency on file_utils, but that creates more potential leaks, or improper usage.
For example: (py/instalog/plugins/input_rpc.py)
fd, tmp_path = tempfile.mkstemp(dir=self._tmp_dir)
# If anything in the 'try' block raises an exception, make sure we
# close the file handle created by mkstemp.
try:
with open(tmp_path, 'w') as f:
f.write(zlib.decompress(base64.b64decode(att_data['value'])))
finally:
os.close(fd)
When fd is still open, we should open do another open(w). This may cause unexpected result on some platforms.
py/instalog/plugins/input_http.py:
fd, tmp_path = tempfile.mkstemp(prefix=data.name + '_', dir=self._tmp_dir)
with os.fdopen(fd, 'w') as f:
if data.file:
shutil.copyfileobj(data.file, f)
# cgi.MiniFieldStorage does not have attribute 'file', since it stores
# the binary data in-memory.
else:
f.write(data.value)
fd may keep open if fdopen raises exception (although for most of the case, this is unlikely to happen)
In fact, there are three styles of using mkstemp in Instalog:
1. fd, path = mkstemp(); os.close(fd) with open(path)....
2. fd, path = mkstemp(); try: with open(...) finally: os.close(fd)
3. fd, path = mkstemp(); with os.fdopen(...)
I think we should probably always use same style, with some simple way to check.
What about always using tempfile.NamedTemporaryFile(delete=True/False) ?
Comment 1 by bugdroid1@chromium.org
, Jun 1 2017