Skip to content

Commit aad9be9

Browse files
Aaditya DhruvAaditya Dhruv
authored andcommitted
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]>
1 parent 6f19d31 commit aad9be9

File tree

1 file changed

+13
-5
lines changed

1 file changed

+13
-5
lines changed

prometheus_client/exposition.py

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import gzip
55
from http.server import BaseHTTPRequestHandler
66
import os
7+
import shutil
78
import socket
89
from socketserver import ThreadingMixIn
910
import ssl
@@ -446,21 +447,28 @@ def factory(cls, registry: CollectorRegistry) -> type:
446447
return MyMetricsHandler
447448

448449

449-
def write_to_textfile(path: str, registry: CollectorRegistry, escaping: str = openmetrics.ALLOWUTF8) -> None:
450+
def write_to_textfile(path: str, registry: CollectorRegistry, escaping: str = openmetrics.ALLOWUTF8, tmpdir: Optional[str] = None,) -> None:
450451
"""Write metrics to the given path.
451452
452453
This is intended for use with the Node exporter textfile collector.
453454
The path must end in .prom for the textfile collector to process it."""
454-
tmppath = f'{path}.{os.getpid()}.{threading.current_thread().ident}'
455+
if tmpdir is not None:
456+
filename = os.path.basename(path)
457+
tmppath = f'{os.path.join(tmpdir, filename)}.{os.getpid()}.{threading.current_thread().ident}'
458+
else:
459+
tmppath = f'{path}.{os.getpid()}.{threading.current_thread().ident}'
455460
try:
456461
with open(tmppath, 'wb') as f:
457462
f.write(generate_latest(registry, escaping))
458463

459464
# rename(2) is atomic but fails on Windows if the destination file exists
460-
if os.name == 'nt':
461-
os.replace(tmppath, path)
465+
if tmpdir is not None:
466+
shutil.move(tmppath, path)
462467
else:
463-
os.rename(tmppath, path)
468+
if os.name == 'nt':
469+
os.replace(tmppath, path)
470+
else:
471+
os.rename(tmppath, path)
464472
except Exception:
465473
if os.path.exists(tmppath):
466474
os.remove(tmppath)

0 commit comments

Comments
 (0)