|
4 | 4 | import gzip
|
5 | 5 | from http.server import BaseHTTPRequestHandler
|
6 | 6 | import os
|
| 7 | +import shutil |
7 | 8 | import socket
|
8 | 9 | from socketserver import ThreadingMixIn
|
9 | 10 | import ssl
|
@@ -446,21 +447,28 @@ def factory(cls, registry: CollectorRegistry) -> type:
|
446 | 447 | return MyMetricsHandler
|
447 | 448 |
|
448 | 449 |
|
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: |
450 | 451 | """Write metrics to the given path.
|
451 | 452 |
|
452 | 453 | This is intended for use with the Node exporter textfile collector.
|
453 | 454 | 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}' |
455 | 460 | try:
|
456 | 461 | with open(tmppath, 'wb') as f:
|
457 | 462 | f.write(generate_latest(registry, escaping))
|
458 | 463 |
|
459 | 464 | # 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) |
462 | 467 | else:
|
463 |
| - os.rename(tmppath, path) |
| 468 | + if os.name == 'nt': |
| 469 | + os.replace(tmppath, path) |
| 470 | + else: |
| 471 | + os.rename(tmppath, path) |
464 | 472 | except Exception:
|
465 | 473 | if os.path.exists(tmppath):
|
466 | 474 | os.remove(tmppath)
|
|
0 commit comments