|
| 1 | +import ipaddress |
| 2 | +import json |
| 3 | +import logging |
| 4 | +import os |
| 5 | +import socket |
| 6 | +import threading |
| 7 | +from dataclasses import dataclass |
| 8 | +from multiprocessing.pool import ThreadPool |
| 9 | +import time |
| 10 | +from typing import Any, Dict, List, Optional |
| 11 | + |
| 12 | +from pydantic import BaseModel, Field |
| 13 | + |
| 14 | +from taskiq.cli.info_server.models import WorkerState |
| 15 | + |
| 16 | +logger = logging.getLogger("taskiq.worker.info_server") |
| 17 | + |
| 18 | + |
| 19 | +class ServerState(BaseModel): |
| 20 | + """State of the taskiq server.""" |
| 21 | + |
| 22 | + workers_state: List[WorkerState] = Field(default_factory=list) |
| 23 | + workers_count: int |
| 24 | + active_tasks: Dict[str, List[Dict[str, Any]]] = Field(default_factory=dict) |
| 25 | + |
| 26 | + |
| 27 | +class TaskiqInfoServer(threading.Thread): |
| 28 | + def __init__( |
| 29 | + self, |
| 30 | + host: str, |
| 31 | + port: int, |
| 32 | + ready_event: Optional[threading.Event] = None, |
| 33 | + workers_count: int = 0, |
| 34 | + ) -> None: |
| 35 | + super().__init__() |
| 36 | + try: |
| 37 | + addr = ipaddress.ip_address(host) |
| 38 | + except ValueError: |
| 39 | + addr = host |
| 40 | + if isinstance(addr, ipaddress.IPv6Address): |
| 41 | + addr_family = socket.AF_INET6 |
| 42 | + else: |
| 43 | + addr_family = socket.AF_INET |
| 44 | + info = socket.getaddrinfo( |
| 45 | + host, |
| 46 | + port, |
| 47 | + family=addr_family, |
| 48 | + type=socket.SOCK_STREAM, |
| 49 | + ) |
| 50 | + self.addr_family, self.sock_kind, self.sock_proto, _, self.bind_info = info[0] |
| 51 | + self.stop_event = threading.Event() |
| 52 | + self.state = {} |
| 53 | + self.ready_event = ready_event |
| 54 | + self.state = ServerState(workers_count=workers_count) |
| 55 | + self.methods = { |
| 56 | + "update_state": self.update_state, |
| 57 | + } |
| 58 | + |
| 59 | + def wait_started(self) -> None: |
| 60 | + if self.ready_event is None: |
| 61 | + return |
| 62 | + while not self.ready_event.is_set(): |
| 63 | + time.sleep(0.1) |
| 64 | + if not self.is_alive(): |
| 65 | + raise RuntimeError("Failed to start server") |
| 66 | + |
| 67 | + def wait_workers(self, timeout: Optional[float] = None) -> None: |
| 68 | + start = time.monotonic() |
| 69 | + while True: |
| 70 | + for state in self.state.workers_state: |
| 71 | + if state == WorkerState.READY: |
| 72 | + break |
| 73 | + |
| 74 | + if self.state.workers_count == len(self.state.workers_state): |
| 75 | + break |
| 76 | + |
| 77 | + if timeout is not None and time.monotonic() - start > timeout: |
| 78 | + raise TimeoutError("Failed to start workers") |
| 79 | + print(self.state) |
| 80 | + time.sleep(0.1) |
| 81 | + |
| 82 | + def kill(self) -> None: |
| 83 | + self.stop_event.set() |
| 84 | + |
| 85 | + def run(self) -> None: |
| 86 | + server = socket.socket( |
| 87 | + self.addr_family, |
| 88 | + self.sock_kind, |
| 89 | + self.sock_proto, |
| 90 | + ) |
| 91 | + if os.name != "nt": |
| 92 | + server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 93 | + server.bind(self.bind_info) |
| 94 | + server.settimeout(1) |
| 95 | + server.listen() |
| 96 | + if self.ready_event is not None: |
| 97 | + self.ready_event.set() |
| 98 | + while True: |
| 99 | + try: |
| 100 | + client, addr = server.accept() |
| 101 | + logger.info(f"Accepted connection from {addr[0]}:{addr[1]}") |
| 102 | + threading.Thread(target=self._handle_client, args=(client,)).start() |
| 103 | + except TimeoutError: |
| 104 | + if self.stop_event.is_set(): |
| 105 | + break |
| 106 | + except Exception as exc: |
| 107 | + logger.warning( |
| 108 | + "Exception found when processing request %s", |
| 109 | + exc, |
| 110 | + exc_info=True, |
| 111 | + ) |
| 112 | + server.close() |
| 113 | + |
| 114 | + def _receive_request(self, client: socket.socket) -> Dict[str, Any]: |
| 115 | + body_len = client.recv(10) |
| 116 | + body_len = int.from_bytes(body_len, "big") |
| 117 | + buffer = b"" |
| 118 | + while len(buffer) < body_len: |
| 119 | + buffer += client.recv(1024) |
| 120 | + buffer = buffer[:body_len] |
| 121 | + return json.loads(buffer) |
| 122 | + |
| 123 | + def _send_response(self, client: socket.socket, data: Dict[str, Any]) -> None: |
| 124 | + encoded = json.dumps(data).encode("utf-8") |
| 125 | + body_len = len(encoded) |
| 126 | + client.sendall(body_len.to_bytes(10, "big") + encoded) |
| 127 | + |
| 128 | + def _handle_client(self, client: socket.socket) -> None: |
| 129 | + empty_response = {"status": "ok", "data": {}} |
| 130 | + try: |
| 131 | + request = self._receive_request(client) |
| 132 | + except ValueError as exc: |
| 133 | + self._send_response( |
| 134 | + client, |
| 135 | + {"status": "error", "description": str(exc)}, |
| 136 | + ) |
| 137 | + return |
| 138 | + if "method" not in request and "params" not in request: |
| 139 | + response = { |
| 140 | + "status": "error", |
| 141 | + "description": "Invalid request", |
| 142 | + } |
| 143 | + elif request["method"] not in self.methods: |
| 144 | + response = { |
| 145 | + "status": "error", |
| 146 | + "description": "Unknown method", |
| 147 | + } |
| 148 | + else: |
| 149 | + try: |
| 150 | + response = self.methods[request["method"]](request) or empty_response |
| 151 | + except Exception as exc: |
| 152 | + logger.warning( |
| 153 | + "Exception found when processing request %s", |
| 154 | + exc, |
| 155 | + exc_info=True, |
| 156 | + ) |
| 157 | + response = { |
| 158 | + "status": "error", |
| 159 | + "description": str(exc), |
| 160 | + } |
| 161 | + self._send_response(client, response) |
| 162 | + |
| 163 | + def update_state(self, request: Dict[str, Any]) -> None: |
| 164 | + worker_id = request["params"]["worker_id"] |
| 165 | + state = request["params"]["state"] |
| 166 | + self.state.workers_state[worker_id] = WorkerState(state) |
| 167 | + |
| 168 | + |
| 169 | +if __name__ == "__main__": |
| 170 | + logging.basicConfig(level=logging.INFO) |
| 171 | + ev = threading.Event() |
| 172 | + server = TaskiqInfoServer("127.0.0.1", 2332, ev) |
| 173 | + server.start() |
| 174 | + server.wait_started() |
| 175 | + server.join() |
0 commit comments