|
| 1 | +import logging |
| 2 | +import threading |
| 3 | +from typing import Callable, Any, List, Tuple, Optional |
| 4 | + |
| 5 | +from datarobot_drum.drum.enum import LOGGER_NAME_PREFIX |
| 6 | + |
| 7 | +logger = logging.getLogger(LOGGER_NAME_PREFIX + "." + __name__) |
| 8 | + |
| 9 | + |
| 10 | +class WorkerCtx: |
| 11 | + """ |
| 12 | + Context of a single gunicorn worker: |
| 13 | + - .start() — start background tasks |
| 14 | + - .stop() — stop background tasks (graceful) |
| 15 | + - .cleanup() — close resources (DB/clients) in the correct order |
| 16 | + - add_* methods for registering objects/callbacks for stopping/cleaning up |
| 17 | + """ |
| 18 | + |
| 19 | + def __init__(self, app): |
| 20 | + self.app = app |
| 21 | + self._running = False |
| 22 | + self._threads: List[threading.Thread] = [] |
| 23 | + self._greenlets: List[Any] = [] |
| 24 | + self._on_stop: List[Tuple[int, Callable[[], None], str]] = [] |
| 25 | + self._on_cleanup: List[Tuple[int, Callable[[], None], str]] = [] |
| 26 | + |
| 27 | + def add_thread( |
| 28 | + self, t: threading.Thread, *, join_timeout: float = 2.0, name: Optional[str] = None |
| 29 | + ): |
| 30 | + """ |
| 31 | + Adds a thread to the worker context and registers it for graceful stopping. |
| 32 | +
|
| 33 | + Args: |
| 34 | + t (threading.Thread): The thread to be added. |
| 35 | + join_timeout (float, optional): The timeout for joining the thread during stop. Defaults to 2.0 seconds. |
| 36 | + name (Optional[str], optional): A descriptive name for the thread. Defaults to None. |
| 37 | + """ |
| 38 | + t.daemon = True |
| 39 | + self._threads.append(t) |
| 40 | + |
| 41 | + def _join(): |
| 42 | + if t.is_alive(): |
| 43 | + t.join(join_timeout) |
| 44 | + |
| 45 | + self.defer_stop(_join, desc=name or f"thread:{id(t)}") |
| 46 | + |
| 47 | + def add_greenlet(self, g, *, kill_timeout: float = 2.0, name: Optional[str] = None): |
| 48 | + """ |
| 49 | + Adds a greenlet to the worker context and registers it for graceful stopping. |
| 50 | +
|
| 51 | + Args: |
| 52 | + g: The greenlet to be added. |
| 53 | + kill_timeout (float, optional): The timeout for killing the greenlet during stop. Defaults to 2.0 seconds. |
| 54 | + name (Optional[str], optional): A descriptive name for the greenlet. Defaults to None. |
| 55 | + """ |
| 56 | + self._greenlets.append(g) |
| 57 | + |
| 58 | + def _kill(): |
| 59 | + try: |
| 60 | + g.kill(block=True, timeout=kill_timeout) |
| 61 | + except Exception: |
| 62 | + pass |
| 63 | + |
| 64 | + self.defer_stop(_kill, desc=name or f"greenlet:{id(g)}") |
| 65 | + |
| 66 | + def add_closeable( |
| 67 | + self, obj: Any, method: str = "close", *, order: int = 0, desc: Optional[str] = None |
| 68 | + ): |
| 69 | + """ |
| 70 | + Registers an object to be closed using a specified method (e.g., close/quit/disconnect/shutdown) during cleanup (after stop). |
| 71 | +
|
| 72 | + Args: |
| 73 | + obj (Any): The object to be closed. |
| 74 | + method (str, optional): The method to call on the object for closing. Defaults to "close". |
| 75 | + order (int, optional): The priority order for cleanup. Lower values are executed later. Defaults to 0. |
| 76 | + desc (Optional[str], optional): A description for the cleanup action. Defaults to None. |
| 77 | + """ |
| 78 | + fn = getattr(obj, method, None) |
| 79 | + if callable(fn): |
| 80 | + self.defer_cleanup(fn, order=order, desc=desc or f"{obj}.{method}") |
| 81 | + |
| 82 | + def defer_stop(self, fn: Callable[[], None], *, order: int = 0, desc: str = "on_stop"): |
| 83 | + self._on_stop.append((order, fn, desc)) |
| 84 | + |
| 85 | + def defer_cleanup(self, fn: Callable[[], None], *, order: int = 0, desc: str = "on_cleanup"): |
| 86 | + self._on_cleanup.append((order, fn, desc)) |
| 87 | + |
| 88 | + def start(self): |
| 89 | + """ |
| 90 | + Starts background tasks for the worker context. |
| 91 | +
|
| 92 | + This method sets the running flag to True and initializes the main application logic. |
| 93 | + It imports and calls the `main` function from `datarobot_drum.drum.main`, passing |
| 94 | + the application instance and the worker context as arguments. |
| 95 | + """ |
| 96 | + self._running = True |
| 97 | + |
| 98 | + # fix RuntimeError: asyncio.run() cannot be called from a running event loop |
| 99 | + import asyncio |
| 100 | + import opentelemetry.instrumentation.openai.utils as otel_utils |
| 101 | + |
| 102 | + def fixed_run_async(method): |
| 103 | + try: |
| 104 | + loop = asyncio.get_running_loop() |
| 105 | + except RuntimeError: |
| 106 | + loop = None |
| 107 | + |
| 108 | + if loop and loop.is_running(): |
| 109 | + |
| 110 | + def handle_task_result(task): |
| 111 | + try: |
| 112 | + task.result() # retrieve exception if any |
| 113 | + except Exception as e: |
| 114 | + # Log or handle exceptions here if needed |
| 115 | + logger.error("OpenTelemetry async task error") |
| 116 | + |
| 117 | + # Schedule the coroutine safely and add done callback to handle errors |
| 118 | + task = loop.create_task(method) |
| 119 | + task.add_done_callback(handle_task_result) |
| 120 | + else: |
| 121 | + asyncio.run(method) |
| 122 | + |
| 123 | + # Apply monkey patch |
| 124 | + otel_utils.run_async = fixed_run_async |
| 125 | + |
| 126 | + from datarobot_drum.drum.main import main |
| 127 | + |
| 128 | + main(self.app, self) |
| 129 | + |
| 130 | + def stop(self): |
| 131 | + """ |
| 132 | + Gracefully stops the worker context. |
| 133 | +
|
| 134 | + This method sets the running flag to False and executes all registered |
| 135 | + stop callbacks in the order of their priority. Threads and greenlets |
| 136 | + are then joined or killed as part of the stopping process. |
| 137 | + """ |
| 138 | + self._running = False |
| 139 | + for _, fn, desc in sorted(self._on_stop, key=lambda x: x[0]): |
| 140 | + try: |
| 141 | + fn() |
| 142 | + except Exception: |
| 143 | + pass |
| 144 | + |
| 145 | + def cleanup(self): |
| 146 | + """ |
| 147 | + Cleans up resources in the worker context. |
| 148 | +
|
| 149 | + This method is called at the end of the worker's lifecycle to release resources. |
| 150 | + It executes all registered cleanup callbacks in reverse priority order, ensuring |
| 151 | + that resources are closed in the correct sequence. |
| 152 | +
|
| 153 | + Exceptions during cleanup are caught and ignored to prevent interruption. |
| 154 | + """ |
| 155 | + for _, fn, desc in sorted(self._on_cleanup, key=lambda x: x[0], reverse=True): |
| 156 | + try: |
| 157 | + logger.info("WorkerCtx cleanup: %s", desc) |
| 158 | + fn() |
| 159 | + except Exception as e: |
| 160 | + logger.error("Tracing shutdown failed: %s", e) |
| 161 | + |
| 162 | + def running(self) -> bool: |
| 163 | + return self._running |
| 164 | + |
| 165 | + |
| 166 | +def create_ctx(app): |
| 167 | + """ |
| 168 | + Factory method to create a WorkerCtx instance. |
| 169 | +
|
| 170 | + This method initializes the worker context for the application and allows |
| 171 | + registration of objects or callbacks for stopping and cleanup. It ensures |
| 172 | + that no long-running processes are started here; the actual startup occurs |
| 173 | + in `post_worker_init` via `ctx.start()`. |
| 174 | +
|
| 175 | + Args: |
| 176 | + app: The application instance. |
| 177 | +
|
| 178 | + Returns: |
| 179 | + WorkerCtx: The initialized worker context. |
| 180 | + """ |
| 181 | + ctx = WorkerCtx(app) |
| 182 | + return ctx |
0 commit comments