8000 Fix `write_to_textfile` leaves back temp files on errors by ethanschen · Pull Request #1066 · prometheus/client_python · GitHub
[go: up one dir, main page]

Skip to content

Fix write_to_textfile leaves back temp files on errors #1066

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 25, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 12 additions & 7 deletions prometheus_client/exposition.py
Original file line number Diff line number Diff line change
Expand Up @@ -367,14 +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))
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)
# 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(
Expand Down
0