|
| 1 | +# SPDX-License-Identifier: BSD-3-Clause |
| 2 | +# Copyright (c) 2024 Scicatproject contributors (https://github.com/ScicatProject) |
| 3 | +""" |
| 4 | +This module contains the health check server for the online ingestor. |
| 5 | +It exposes an HTTP endpoint that checks the status of Kafka, Storage and SciCat. |
| 6 | +""" |
| 7 | + |
| 8 | +import json |
| 9 | +import logging |
| 10 | +import pathlib |
| 11 | +import threading |
| 12 | +from functools import partial |
| 13 | +from http.server import BaseHTTPRequestHandler, HTTPServer |
| 14 | +from time import sleep |
| 15 | +from typing import Any |
| 16 | + |
| 17 | +import requests |
| 18 | +from confluent_kafka import Consumer |
| 19 | + |
| 20 | +from scicat_configuration import OnlineIngestorConfig |
| 21 | + |
| 22 | + |
| 23 | +class HealthCheckHandler(BaseHTTPRequestHandler): |
| 24 | + """ |
| 25 | + HTTP Handler for the health check endpoint. |
| 26 | + It checks the status of Kafka, Storage and SciCat. |
| 27 | + """ |
| 28 | + |
| 29 | + def __init__( |
| 30 | + self, |
| 31 | + config: OnlineIngestorConfig, |
| 32 | + consumer: Consumer, |
| 33 | + logger: logging.Logger, |
| 34 | + *args: Any, |
| 35 | + **kwargs: Any, |
| 36 | + ): |
| 37 | + self.config: OnlineIngestorConfig = config |
| 38 | + self.consumer: Consumer = consumer |
| 39 | + self.logger: logging.Logger = logger |
| 40 | + super().__init__(*args, **kwargs) |
| 41 | + |
| 42 | + def do_GET(self) -> None: |
| 43 | + """Handle GET requests.""" |
| 44 | + if self.path == "/health": |
| 45 | + kafka_status = self._check_kafka() |
| 46 | + storage_status = self._check_storage() |
| 47 | + scicat_status = self._check_scicat() |
| 48 | + |
| 49 | + health_status = { |
| 50 | + "kafka": kafka_status, |
| 51 | + "storage": storage_status, |
| 52 | + "scicat": scicat_status, |
| 53 | + } |
| 54 | + |
| 55 | + if all(health_status.values()): |
| 56 | + self.send_response(200) |
| 57 | + else: |
| 58 | + self.send_response(503) |
| 59 | + |
| 60 | + self.send_header("Content-type", "application/json") |
| 61 | + self.end_headers() |
| 62 | + self.wfile.write(json.dumps(health_status).encode("utf-8")) |
| 63 | + else: |
| 64 | + self.send_response(404) |
| 65 | + self.end_headers() |
| 66 | + |
| 67 | + def _check_kafka(self) -> bool: |
| 68 | + """Check if Kafka is reachable.""" |
| 69 | + try: |
| 70 | + self.consumer.list_topics(timeout=5) |
| 71 | + return True |
| 72 | + except Exception as e: |
| 73 | + self.logger.error("Health check: Kafka connection failed: %s", e) |
| 74 | + return False |
| 75 | + |
| 76 | + def _check_storage(self) -> bool: |
| 77 | + """Check if the storage directory is accessible.""" |
| 78 | + try: |
| 79 | + file_handling = self.config.ingestion.file_handling |
| 80 | + directory = file_handling.data_directory |
| 81 | + if not directory: |
| 82 | + self.logger.warning("Health check: No data_directory configured.") |
| 83 | + return False |
| 84 | + path = pathlib.Path(directory) |
| 85 | + if not path.exists(): |
| 86 | + self.logger.error("Health check: Storage path does not exist: %s", path) |
| 87 | + return False |
| 88 | + |
| 89 | + # Attempt to list the directory to make sure the mount is accessible. |
| 90 | + next(path.iterdir(), None) |
| 91 | + return True |
| 92 | + except Exception as e: |
| 93 | + self.logger.error("Health check: Storage access failed: %s", e) |
| 94 | + return False |
| 95 | + |
| 96 | + def _check_scicat(self) -> bool: |
| 97 | + """Check if SciCat is reachable.""" |
| 98 | + try: |
| 99 | + scicat_config = self.config.scicat |
| 100 | + url = scicat_config.health_url |
| 101 | + response = requests.get(url, timeout=5) |
| 102 | + return response.status_code == 200 |
| 103 | + except Exception as e: |
| 104 | + self.logger.error("Health check: SciCat connection failed: %s", e) |
| 105 | + return False |
| 106 | + |
| 107 | + def log_message(self, format: str, *args: Any) -> None: |
| 108 | + pass # Disable default logging of BaseHTTPRequestHandler |
| 109 | + |
| 110 | + |
| 111 | +def _serve_health_server( |
| 112 | + server: HTTPServer, |
| 113 | + logger: logging.Logger, |
| 114 | + restart_delay: float = 5.0, |
| 115 | +) -> None: |
| 116 | + """Run the HTTP server forever, restarting if it crashes.""" |
| 117 | + |
| 118 | + while True: |
| 119 | + try: |
| 120 | + server.serve_forever() |
| 121 | + except Exception as exc: |
| 122 | + logger.error( |
| 123 | + "Health check server stopped unexpectedly: %s. Restarting in %s seconds.", |
| 124 | + exc, |
| 125 | + restart_delay, |
| 126 | + ) |
| 127 | + sleep(restart_delay) |
| 128 | + |
| 129 | + |
| 130 | +def start_health_server( |
| 131 | + config: OnlineIngestorConfig, consumer: Consumer, logger: logging.Logger |
| 132 | +) -> None: |
| 133 | + """Start the health check server in a daemon thread.""" |
| 134 | + handler = partial(HealthCheckHandler, config, consumer, logger) |
| 135 | + host = config.health_check.host |
| 136 | + port = config.health_check.port |
| 137 | + server = HTTPServer((host, port), handler) |
| 138 | + thread = threading.Thread(target=_serve_health_server, args=(server, logger)) |
| 139 | + thread.daemon = True |
| 140 | + thread.start() |
| 141 | + logger.info("Health check server started on %s:%s", host, port) |
0 commit comments