Skip to content

Commit c89624f

Browse files
authored
Fix write_to_textfile leaves back temp files on errors (#1044) (#1066)
Signed-off-by: Ethan S. Chen <[email protected]>
1 parent 37cd873 commit c89624f

File tree

1 file changed

+12
-7
lines changed

1 file changed

+12
-7
lines changed

prometheus_client/exposition.py

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -367,14 +367,19 @@ def write_to_textfile(path: str, registry: CollectorRegistry) -> None:
367367
This is intended for use with the Node exporter textfile collector.
368368
The path must end in .prom for the textfile collector to process it."""
369369
tmppath = f'{path}.{os.getpid()}.{threading.current_thread().ident}'
370-
with open(tmppath, 'wb') as f:
371-
f.write(generate_latest(registry))
370+
try:
371+
with open(tmppath, 'wb') as f:
372+
f.write(generate_latest(registry))
372373

373-
# rename(2) is atomic but fails on Windows if the destination file exists
374-
if os.name == 'nt':
375-
os.replace(tmppath, path)
376-
else:
377-
os.rename(tmppath, path)
374+
# rename(2) is atomic but fails on Windows if the destination file exists
375+
if os.name == 'nt':
376+
os.replace(tmppath, path)
377+
else:
378+
os.rename(tmppath, path)
379+
except Exception:
380+
if os.path.exists(tmppath):
381+
os.remove(tmppath)
382+
raise
378383

379384

380385
def _make_handler(

0 commit comments

Comments
 (0)