|
| 1 | +import http |
| 2 | +import json |
| 3 | +import urllib.error |
| 4 | +import urllib.parse |
| 5 | +import urllib.request |
| 6 | +from typing import Any, Optional, Tuple |
| 7 | + |
| 8 | +from ramalama.daemon.dto.model import ModelResponse, RunningModelResponse |
| 9 | +from ramalama.daemon.dto.serve import ServeRequest, ServeResponse, StopServeRequest |
| 10 | +from ramalama.logger import logger |
| 11 | + |
| 12 | + |
| 13 | +class DaemonAPIError(Exception): |
| 14 | + |
| 15 | + def __init__(self, reason: str, code: Optional[http.HTTPStatus] = None, *args): |
| 16 | + super().__init__(*args) |
| 17 | + |
| 18 | + self.reason = reason |
| 19 | + self.code = code |
| 20 | + |
| 21 | + def __str__(self): |
| 22 | + if self.code: |
| 23 | + return f"Call to daemon API failed ({self.code}): {self.reason}" |
| 24 | + return f"Call to daemon API failed: {self.reason}" |
| 25 | + |
| 26 | + |
| 27 | +class DaemonClient: |
| 28 | + |
| 29 | + def __init__(self, host: str, port: int): |
| 30 | + self.host = host |
| 31 | + self.port = port |
| 32 | + |
| 33 | + @property |
| 34 | + def base_url(self) -> str: |
| 35 | + return f"{self.host}:{self.port}" |
| 36 | + |
| 37 | + def list_available_models(self) -> list[ModelResponse]: |
| 38 | + url = f"http://{self.base_url}/api/tags" |
| 39 | + resp, _ = DaemonClient.call_api(url) |
| 40 | + if resp: |
| 41 | + return [ModelResponse(**model) for model in resp["models"]] |
| 42 | + |
| 43 | + def list_running_models(self) -> list[RunningModelResponse]: |
| 44 | + url = f"http://{self.base_url}/api/ps" |
| 45 | + resp, _ = DaemonClient.call_api(url) |
| 46 | + if resp: |
| 47 | + return [RunningModelResponse(**model) for model in resp["models"]] |
| 48 | + |
| 49 | + def start_model(self, model_name: str, runtime: str, exec_args: list[str]) -> Optional[str]: |
| 50 | + url = f"http://{self.base_url}/api/serve" |
| 51 | + request = ServeRequest(model_name, runtime, exec_args).to_dict() |
| 52 | + resp, _ = DaemonClient.call_api(url, method=http.HTTPMethod.POST, json_data=request) |
| 53 | + if resp: |
| 54 | + return f"http://{self.base_url}{ServeResponse(**resp).serve_path}" |
| 55 | + return None |
| 56 | + |
| 57 | + def stop_model(self, model_name: str) -> Optional[str]: |
| 58 | + url = f"http://{self.base_url}/api/stop" |
| 59 | + request = StopServeRequest(model_name).to_dict() |
| 60 | + DaemonClient.call_api(url, method=http.HTTPMethod.POST, json_data=request) |
| 61 | + |
| 62 | + def is_healthy(self) -> bool: |
| 63 | + url = f"http://{self.base_url}/api/health" |
| 64 | + try: |
| 65 | + _, code = DaemonClient.call_api(url) |
| 66 | + logger.debug(f"Health check success, code: {code}") |
| 67 | + return code == http.HTTPStatus.NO_CONTENT |
| 68 | + except DaemonAPIError as e: |
| 69 | + logger.debug(f"Health check failed: {e}") |
| 70 | + return False |
| 71 | + |
| 72 | + @staticmethod |
| 73 | + def call_api( |
| 74 | + url: str, method: http.HTTPMethod = http.HTTPMethod.GET, headers=None, params=None, json_data=None, timeout=10 |
| 75 | + ) -> Tuple[Any | None, http.HTTPStatus]: |
| 76 | + headers = headers or {} |
| 77 | + |
| 78 | + if params: |
| 79 | + query_string = urllib.parse.urlencode(params) |
| 80 | + separator = '&' if '?' in url else '?' |
| 81 | + url = f"{url}{separator}{query_string}" |
| 82 | + |
| 83 | + body = None |
| 84 | + if json_data is not None: |
| 85 | + body = json.dumps(json_data).encode('utf-8') |
| 86 | + headers['Content-Type'] = 'application/json' |
| 87 | + |
| 88 | + req = urllib.request.Request(url, data=body, headers=headers, method=method.value) |
| 89 | + try: |
| 90 | + with urllib.request.urlopen(req, timeout=timeout) as response: |
| 91 | + response_code = response.getcode() |
| 92 | + response_data = response.read().decode('utf-8') |
| 93 | + try: |
| 94 | + return json.loads(response_data), response_code |
| 95 | + except json.JSONDecodeError: |
| 96 | + return response_data, response_code |
| 97 | + except urllib.error.HTTPError as e: |
| 98 | + raise DaemonAPIError(e.reason, e.code) |
| 99 | + except urllib.error.URLError as e: |
| 100 | + raise DaemonAPIError(e.reason) |
| 101 | + except ConnectionResetError: |
| 102 | + raise DaemonAPIError("Connection reset") |
| 103 | + except Exception as e: |
| 104 | + raise DaemonAPIError(f"Unexpected error occurred: {e}") |
0 commit comments