|
| 1 | +# SPDX-License-Identifier: Apache-2.0 |
| 2 | + |
| 3 | +import asyncio |
| 4 | +from ssl import SSLContext |
| 5 | +from typing import Callable, Optional |
| 6 | + |
| 7 | +from watchfiles import Change, awatch |
| 8 | + |
| 9 | +from vllm.logger import init_logger |
| 10 | + |
| 11 | +logger = init_logger(__name__) |
| 12 | + |
| 13 | + |
| 14 | +class SSLCertRefresher: |
| 15 | + """A class that monitors SSL certificate files and |
| 16 | + reloads them when they change. |
| 17 | + """ |
| 18 | + |
| 19 | + def __init__(self, |
| 20 | + ssl_context: SSLContext, |
| 21 | + key_path: Optional[str] = None, |
| 22 | + cert_path: Optional[str] = None, |
| 23 | + ca_path: Optional[str] = None) -> None: |
| 24 | + self.ssl = ssl_context |
| 25 | + self.key_path = key_path |
| 26 | + self.cert_path = cert_path |
| 27 | + self.ca_path = ca_path |
| 28 | + |
| 29 | + # Setup certification chain watcher |
| 30 | + def update_ssl_cert_chain(change: Change, file_path: str) -> None: |
| 31 | + logger.info("Reloading SSL certificate chain") |
| 32 | + assert self.key_path and self.cert_path |
| 33 | + self.ssl.load_cert_chain(self.cert_path, self.key_path) |
| 34 | + |
| 35 | + self.watch_ssl_cert_task = None |
| 36 | + if self.key_path and self.cert_path: |
| 37 | + self.watch_ssl_cert_task = asyncio.create_task( |
| 38 | + self._watch_files([self.key_path, self.cert_path], |
| 39 | + update_ssl_cert_chain)) |
| 40 | + |
| 41 | + # Setup CA files watcher |
| 42 | + def update_ssl_ca(change: Change, file_path: str) -> None: |
| 43 | + logger.info("Reloading SSL CA certificates") |
| 44 | + assert self.ca_path |
| 45 | + self.ssl.load_verify_locations(self.ca_path) |
| 46 | + |
| 47 | + self.watch_ssl_ca_task = None |
| 48 | + if self.ca_path: |
| 49 | + self.watch_ssl_ca_task = asyncio.create_task( |
| 50 | + self._watch_files([self.ca_path], update_ssl_ca)) |
| 51 | + |
| 52 | + async def _watch_files(self, paths, fun: Callable[[Change, str], |
| 53 | + None]) -> None: |
| 54 | + """Watch multiple file paths asynchronously.""" |
| 55 | + logger.info("SSLCertRefresher monitors files: %s", paths) |
| 56 | + async for changes in awatch(*paths): |
| 57 | + try: |
| 58 | + for change, file_path in changes: |
| 59 | + logger.info("File change detected: %s - %s", change.name, |
| 60 | + file_path) |
| 61 | + fun(change, file_path) |
| 62 | + except Exception as e: |
| 63 | + logger.error( |
| 64 | + "SSLCertRefresher failed taking action on file change. " |
| 65 | + "Error: %s", e) |
| 66 | + |
| 67 | + def stop(self) -> None: |
| 68 | + """Stop watching files.""" |
| 69 | + if self.watch_ssl_cert_task: |
| 70 | + self.watch_ssl_cert_task.cancel() |
| 71 | + self.watch_ssl_cert_task = None |
| 72 | + if self.watch_ssl_ca_task: |
| 73 | + self.watch_ssl_ca_task.cancel() |
| 74 | + self.watch_ssl_ca_task = None |
0 commit comments