Skip to content

Commit 7368028

Browse files
authored
Add support to write_to_textfile for custom tmpdir (#1115)
* Add support to write_to_textfile for custom tmpdir While the try/except block does prevent most of the temp files from persisting, if there is a non catchable exception, those temp files continue to pollute the directory. Optionally set the temp directory would let us write to something like /tmp, so the target directory isn't polluted Signed-off-by: Aaditya Dhruv <[email protected]> * Modify write_to_textfile to ensure tmpdir is on same filesystem The tmpdir must be on the same filesystem to ensure an atomic operation takes place. If this is not enforced, there could be partial writes which can lead to partial/incorrect metrics being exported Signed-off-by: Aaditya Dhruv <[email protected]> --------- Signed-off-by: Aaditya Dhruv <[email protected]>
1 parent 26da805 commit 7368028

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

prometheus_client/exposition.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -446,12 +446,21 @@ def factory(cls, registry: CollectorRegistry) -> type:
446446
return MyMetricsHandler
447447

448448

449-
def write_to_textfile(path: str, registry: CollectorRegistry, escaping: str = openmetrics.ALLOWUTF8) -> None:
449+
def write_to_textfile(path: str, registry: CollectorRegistry, escaping: str = openmetrics.ALLOWUTF8, tmpdir: Optional[str] = None) -> None:
450450
"""Write metrics to the given path.
451451
452452
This is intended for use with the Node exporter textfile collector.
453-
The path must end in .prom for the textfile collector to process it."""
454-
tmppath = f'{path}.{os.getpid()}.{threading.current_thread().ident}'
453+
The path must end in .prom for the textfile collector to process it.
454+
455+
An optional tmpdir parameter can be set to determine where the
456+
metrics will be temporarily written to. If not set, it will be in
457+
the same directory as the .prom file. If provided, the path MUST be
458+
on the same filesystem."""
459+
if tmpdir is not None:
460+
filename = os.path.basename(path)
461+
tmppath = f'{os.path.join(tmpdir, filename)}.{os.getpid()}.{threading.current_thread().ident}'
462+
else:
463+
tmppath = f'{path}.{os.getpid()}.{threading.current_thread().ident}'
455464
try:
456465
with open(tmppath, 'wb') as f:
457466
f.write(generate_latest(registry, escaping))

0 commit comments

Comments
 (0)