Skip to content

Commit

Permalink
Fix write_to_textfile leaves back temp files on errors (prometheus#1044)
Browse files Browse the repository at this point in the history
Signed-off-by: Ethan S. Chen <[email protected]>
  • Loading branch information
ethanschen committed Oct 16, 2024
1 parent 37cd873 commit d855887
Showing 1 changed file with 12 additions and 8 deletions.
20 changes: 12 additions & 8 deletions prometheus_client/exposition.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down

0 comments on commit d855887

Please sign in to comment.