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