From d8558871ce9297e420b4cf0925291baa53d81297 Mon Sep 17 00:00:00 2001 From: ethanschen Date: Wed, 16 Oct 2024 23:46:53 +0800 Subject: [PATCH] Fix write_to_textfile leaves back temp files on errors (#1044) Signed-off-by: Ethan S. Chen --- prometheus_client/exposition.py | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/prometheus_client/exposition.py b/prometheus_client/exposition.py index fab139df..82a2a8e7 100644 --- a/prometheus_client/exposition.py +++ b/prometheus_client/exposition.py @@ -367,15 +367,19 @@ def write_to_textfile(path: str, registry: CollectorRegistry) -> None: This is intended for use with the Node exporter textfile collector. The path must end in .prom for the textfile collector to process it.""" tmppath = f'{path}.{os.getpid()}.{threading.current_thread().ident}' - with open(tmppath, 'wb') as f: - f.write(generate_latest(registry)) - - # rename(2) is atomic but fails on Windows if the destination file exists - if os.name == 'nt': - os.replace(tmppath, path) - else: - os.rename(tmppath, path) + try: + with open(tmppath, 'wb') as f: + f.write(generate_latest(registry)) + # rename(2) is atomic but fails on Windows if the destination file exists + if os.name == 'nt': + os.replace(tmppath, path) + else: + os.rename(tmppath, path) + except Exception: + if os.path.exists(tmppath): + os.remove(tmppath) + raise def _make_handler( url: str,