|
| 1 | +import json |
| 2 | +import socket |
| 3 | +import threading |
| 4 | +from http.server import HTTPServer, SimpleHTTPRequestHandler |
| 5 | +from typing import Any, Optional |
| 6 | + |
| 7 | +from celery import bootsteps |
| 8 | +from celery.worker import WorkController |
| 9 | +from loguru import logger |
| 10 | + |
| 11 | +HEALTHCHECK_DEFAULT_PORT = 9000 |
| 12 | +HEALTHCHECK_DEFAULT_PING_TIMEOUT = 2.0 |
| 13 | +HEALTHCHECK_DEFAULT_HTTP_SERVER_SHUTDOWN_TIMEOUT = 2.0 |
| 14 | + |
| 15 | + |
| 16 | +class HealthcheckHandler(SimpleHTTPRequestHandler): |
| 17 | + """HTTP request handler with additional properties and functions""" |
| 18 | + |
| 19 | + def __init__( |
| 20 | + self, parent: WorkController, healthcheck_ping_timeout: float, *args: Any |
| 21 | + ): |
| 22 | + self.parent = parent |
| 23 | + self.healthcheck_ping_timeout = healthcheck_ping_timeout |
| 24 | + super().__init__(*args) |
| 25 | + |
| 26 | + def log_message(self, format: str, *args: Any) -> None: |
| 27 | + """ |
| 28 | + Override to suppress default HTTP server logging to stderr. |
| 29 | + The default implementation writes to stderr which can cause |
| 30 | + contention and deadlocks in test environments, especially with |
| 31 | + pytest's output capturing and parallel test execution. |
| 32 | + We use loguru for structured logging instead at the debug level. |
| 33 | + """ |
| 34 | + logger.debug(f"Healthcheck: {self.address_string()} - {format % args}") |
| 35 | + |
| 36 | + def do_GET(self) -> None: |
| 37 | + """Handle GET requests""" |
| 38 | + try: |
| 39 | + try: |
| 40 | + parent = self.parent |
| 41 | + insp = parent.app.control.inspect( |
| 42 | + destination=[parent.hostname], timeout=self.healthcheck_ping_timeout |
| 43 | + ) |
| 44 | + result = insp.ping() |
| 45 | + |
| 46 | + data = json.dumps({"status": "ok", "data": result}) |
| 47 | + logger.debug(f"Healthcheck ping result: {data}") |
| 48 | + |
| 49 | + self.send_response(200) |
| 50 | + self.send_header("Content-type", "application/json") |
| 51 | + self.end_headers() |
| 52 | + self.wfile.write(bytes(data, "utf-8")) |
| 53 | + except Exception as e: |
| 54 | + logger.warning(f"Healthcheck ping exception: {e}") |
| 55 | + response = {"status": "error", "data": str(e)} |
| 56 | + self.send_response(503) |
| 57 | + self.send_header("Content-type", "application/json") |
| 58 | + self.end_headers() |
| 59 | + self.wfile.write(bytes(json.dumps(response), "utf-8")) |
| 60 | + except Exception as ex: |
| 61 | + logger.exception("HealthcheckHandler exception", exc_info=ex) |
| 62 | + self.send_response(500) |
| 63 | + |
| 64 | + |
| 65 | +class HealthCheckServer(bootsteps.StartStopStep): |
| 66 | + # ignore kwargs type |
| 67 | + def __init__(self, parent: WorkController, **kwargs): # type: ignore [arg-type, no-untyped-def] |
| 68 | + self.thread: Optional[threading.Thread] = None |
| 69 | + self.http_server: Optional[HTTPServer] = None |
| 70 | + |
| 71 | + self.parent = parent |
| 72 | + |
| 73 | + # config |
| 74 | + self.healthcheck_port = int( |
| 75 | + getattr(parent.app.conf, "healthcheck_port", HEALTHCHECK_DEFAULT_PORT) |
| 76 | + ) |
| 77 | + self.healthcheck_ping_timeout = float( |
| 78 | + getattr( |
| 79 | + parent.app.conf, |
| 80 | + "healthcheck_ping_timeout", |
| 81 | + HEALTHCHECK_DEFAULT_PING_TIMEOUT, |
| 82 | + ) |
| 83 | + ) |
| 84 | + self.shutdown_timeout = float( |
| 85 | + getattr( |
| 86 | + parent.app.conf, |
| 87 | + "shutdown_timeout", |
| 88 | + HEALTHCHECK_DEFAULT_HTTP_SERVER_SHUTDOWN_TIMEOUT, |
| 89 | + ) |
| 90 | + ) |
| 91 | + |
| 92 | + super().__init__(parent, **kwargs) |
| 93 | + |
| 94 | + # The mypy hints for an HTTP handler are strange, so ignoring them here |
| 95 | + def http_handler(self, *args) -> None: # type: ignore [arg-type, no-untyped-def] |
| 96 | + HealthcheckHandler(self.parent, self.healthcheck_ping_timeout, *args) |
| 97 | + |
| 98 | + def start(self, parent: WorkController) -> None: |
| 99 | + # Ignore mypy hints here as the constructed object immediately handles the request |
| 100 | + # (if you look in the source code for SimpleHTTPRequestHandler, specifically the finalize request method) |
| 101 | + self.http_server = HTTPServer( |
| 102 | + ("0.0.0.0", self.healthcheck_port), |
| 103 | + self.http_handler, # type: ignore [arg-type] |
| 104 | + ) |
| 105 | + |
| 106 | + # Enable socket reuse to prevent port conflicts during rapid test cycling |
| 107 | + # This is especially important for session-scoped test workers |
| 108 | + self.http_server.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 109 | + |
| 110 | + # Set a socket timeout to prevent indefinite blocking on requests |
| 111 | + self.http_server.timeout = 5.0 |
| 112 | + |
| 113 | + self.thread = threading.Thread( |
| 114 | + target=self.http_server.serve_forever, daemon=True |
| 115 | + ) |
| 116 | + self.thread.start() |
| 117 | + logger.info(f"Health check server started on port {self.healthcheck_port}") |
| 118 | + |
| 119 | + def stop(self, parent: WorkController) -> None: |
| 120 | + if self.http_server is None: |
| 121 | + logger.warning( |
| 122 | + "Requested stop of HTTP healthcheck server, but no server was started" |
| 123 | + ) |
| 124 | + else: |
| 125 | + logger.info( |
| 126 | + f"Stopping health check server with a timeout of {self.shutdown_timeout} seconds" |
| 127 | + ) |
| 128 | + try: |
| 129 | + # Call shutdown - this should be safe from any thread |
| 130 | + # It will cause serve_forever() to return after handling any current request |
| 131 | + self.http_server.shutdown() |
| 132 | + except Exception as e: |
| 133 | + logger.warning(f"Error during HTTP server shutdown: {e}") |
| 134 | + |
| 135 | + # Wait for the thread to finish with a timeout |
| 136 | + if self.thread is None: |
| 137 | + logger.warning("No thread in HTTP healthcheck server to shutdown...") |
| 138 | + else: |
| 139 | + self.thread.join(self.shutdown_timeout) |
| 140 | + if self.thread.is_alive(): |
| 141 | + logger.warning( |
| 142 | + f"Healthcheck thread still alive after {self.shutdown_timeout}s timeout. " |
| 143 | + "It will continue running as a daemon thread." |
| 144 | + ) |
| 145 | + else: |
| 146 | + logger.info( |
| 147 | + f"Health check server stopped cleanly on port {self.healthcheck_port}" |
| 148 | + ) |
0 commit comments