|
| 1 | +# Copyright Axis Communications AB. |
| 2 | +# |
| 3 | +# For a full list of individual contributors, please see the commit history. |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | +"""ETOS API log handler.""" |
| 17 | +import asyncio |
| 18 | +import logging |
| 19 | +from uuid import UUID |
| 20 | +from kubernetes import client, config |
| 21 | +from fastapi import APIRouter, HTTPException |
| 22 | + |
| 23 | +from sse_starlette.sse import EventSourceResponse |
| 24 | +from starlette.requests import Request |
| 25 | +import httpx |
| 26 | + |
| 27 | +LOGGER = logging.getLogger(__name__) |
| 28 | +ROUTER = APIRouter() |
| 29 | + |
| 30 | +try: |
| 31 | + config.load_incluster_config() |
| 32 | +except config.ConfigException: |
| 33 | + try: |
| 34 | + config.load_config() |
| 35 | + except config.ConfigException: |
| 36 | + LOGGER.warning("Could not load a Kubernetes config") |
| 37 | + |
| 38 | + |
| 39 | +@ROUTER.get("/logs/{uuid}", tags=["logs"]) |
| 40 | +async def get_logs(uuid: UUID, request: Request): |
| 41 | + """Get logs from an ETOS pod and stream them back as server sent events.""" |
| 42 | + corev1 = client.CoreV1Api() |
| 43 | + thread = corev1.list_namespaced_pod("etos-development", async_req=True) |
| 44 | + pod_list = thread.get() |
| 45 | + |
| 46 | + ip_addr = None |
| 47 | + for pod in pod_list.items: |
| 48 | + if pod.status.phase == "Running" and pod.metadata.name.startswith( |
| 49 | + f"suite-runner-{str(uuid)}" |
| 50 | + ): |
| 51 | + ip_addr = pod.status.pod_ip |
| 52 | + if ip_addr is None: |
| 53 | + raise HTTPException( |
| 54 | + status_code=404, detail=f"Suite runner with UUID={uuid} not found" |
| 55 | + ) |
| 56 | + |
| 57 | + async def sse(url): |
| 58 | + index = 0 |
| 59 | + while True: |
| 60 | + if await request.is_disconnected(): |
| 61 | + break |
| 62 | + try: |
| 63 | + response = httpx.get(url) |
| 64 | + lines = response.text.splitlines() |
| 65 | + for message in lines[index:]: |
| 66 | + yield {"id": index + 1, "event": "message", "data": message} |
| 67 | + index += 1 |
| 68 | + except httpx.RemoteProtocolError: |
| 69 | + LOGGER.exception("Failed to connect to pod %r", url) |
| 70 | + except IndexError: |
| 71 | + pass |
| 72 | + await asyncio.sleep(1) |
| 73 | + |
| 74 | + return EventSourceResponse( |
| 75 | + sse(f"http://{ip_addr}:8000/log"), |
| 76 | + ) |
0 commit comments