-
Notifications
You must be signed in to change notification settings - Fork 580
feat(server): add GET /sandboxes/{id}/logs endpoint for log streaming #397
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -36,7 +36,7 @@ | |
| from dataclasses import dataclass | ||
| from datetime import datetime, timedelta, timezone | ||
| from threading import Lock, Timer | ||
| from typing import Any, Dict, Optional | ||
| from typing import Any, Dict, Iterator, Optional | ||
| from uuid import uuid4 | ||
|
|
||
| import docker | ||
|
|
@@ -1550,6 +1550,49 @@ def get_endpoint(self, sandbox_id: str, port: int, resolve_internal: bool = Fals | |
| }, | ||
| ) | ||
|
|
||
| def get_logs( | ||
| self, | ||
| sandbox_id: str, | ||
| follow: bool = False, | ||
| tail: Optional[int] = None, | ||
| timestamps: bool = False, | ||
| ) -> Iterator[bytes]: | ||
| """ | ||
| Stream stdout/stderr logs for a Docker sandbox container. | ||
|
|
||
| Args: | ||
| sandbox_id: Unique sandbox identifier | ||
| follow: If True, keep streaming until the container exits. | ||
| tail: Number of lines from the end to return. None means all lines. | ||
| timestamps: If True, prepend each log line with an RFC3339 timestamp. | ||
|
|
||
| Yields: | ||
| bytes: Raw log output chunks (Docker multiplexed-stream format). | ||
|
|
||
| Raises: | ||
| HTTPException: If the sandbox is not found or logs cannot be retrieved. | ||
| """ | ||
| container = self._get_container_by_sandbox_id(sandbox_id) | ||
| tail_arg: int | str = tail if tail is not None else "all" | ||
| try: | ||
| log_gen = container.logs( | ||
| stream=True, | ||
| follow=follow, | ||
| stdout=True, | ||
| stderr=True, | ||
| timestamps=timestamps, | ||
| tail=tail_arg, | ||
| ) | ||
| yield from log_gen | ||
|
Comment on lines
+1578
to
+1586
|
||
| except DockerException as exc: | ||
| raise HTTPException( | ||
| status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, | ||
| detail={ | ||
| "code": SandboxErrorCodes.CONTAINER_QUERY_FAILED, | ||
| "message": f"Failed to stream logs for sandbox {sandbox_id}: {str(exc)}", | ||
| }, | ||
| ) from exc | ||
|
|
||
| def _get_docker_host_ip(self) -> Optional[str]: | ||
| """When running inside a container, return [docker].host_ip for endpoint URLs (if set).""" | ||
| ip = (self.app_config.docker.host_ip or "").strip() | ||
|
|
||
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -22,7 +22,7 @@ | |||||||||||||||||||||||||||||||||||||||||||
| import logging | ||||||||||||||||||||||||||||||||||||||||||||
| import time | ||||||||||||||||||||||||||||||||||||||||||||
| from datetime import datetime, timedelta, timezone | ||||||||||||||||||||||||||||||||||||||||||||
| from typing import Optional, Dict, Any | ||||||||||||||||||||||||||||||||||||||||||||
| from typing import Iterator, Optional, Dict, Any | ||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||
| from fastapi import HTTPException, status | ||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||
|
|
@@ -679,6 +679,87 @@ def get_endpoint( | |||||||||||||||||||||||||||||||||||||||||||
| }, | ||||||||||||||||||||||||||||||||||||||||||||
| ) from e | ||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||
| def get_logs( | ||||||||||||||||||||||||||||||||||||||||||||
| self, | ||||||||||||||||||||||||||||||||||||||||||||
| sandbox_id: str, | ||||||||||||||||||||||||||||||||||||||||||||
| follow: bool = False, | ||||||||||||||||||||||||||||||||||||||||||||
| tail: Optional[int] = None, | ||||||||||||||||||||||||||||||||||||||||||||
| timestamps: bool = False, | ||||||||||||||||||||||||||||||||||||||||||||
| ) -> Iterator[bytes]: | ||||||||||||||||||||||||||||||||||||||||||||
| """ | ||||||||||||||||||||||||||||||||||||||||||||
| Stream logs from the Kubernetes Pod(s) that back a sandbox. | ||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||
| Finds pods labelled with the sandbox ID and streams their logs via | ||||||||||||||||||||||||||||||||||||||||||||
| the Kubernetes API. When *follow* is True the generator keeps | ||||||||||||||||||||||||||||||||||||||||||||
| streaming until the pod terminates. | ||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||
| Args: | ||||||||||||||||||||||||||||||||||||||||||||
| sandbox_id: Unique sandbox identifier | ||||||||||||||||||||||||||||||||||||||||||||
| follow: If True, keep streaming until the pod exits. | ||||||||||||||||||||||||||||||||||||||||||||
| tail: Number of lines from the end to return. None means all lines. | ||||||||||||||||||||||||||||||||||||||||||||
| timestamps: If True, prepend each log line with a timestamp. | ||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||
| Yields: | ||||||||||||||||||||||||||||||||||||||||||||
| bytes: Log output chunks. | ||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||
| Raises: | ||||||||||||||||||||||||||||||||||||||||||||
| HTTPException: If no pod is found for the sandbox or the API call | ||||||||||||||||||||||||||||||||||||||||||||
| fails. | ||||||||||||||||||||||||||||||||||||||||||||
| """ | ||||||||||||||||||||||||||||||||||||||||||||
| try: | ||||||||||||||||||||||||||||||||||||||||||||
| core_v1_api = self.k8s_client.get_core_v1_api() | ||||||||||||||||||||||||||||||||||||||||||||
| pods = core_v1_api.list_namespaced_pod( | ||||||||||||||||||||||||||||||||||||||||||||
| namespace=self.namespace, | ||||||||||||||||||||||||||||||||||||||||||||
| label_selector=f"{SANDBOX_ID_LABEL}={sandbox_id}", | ||||||||||||||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||
| if not pods.items: | ||||||||||||||||||||||||||||||||||||||||||||
| raise HTTPException( | ||||||||||||||||||||||||||||||||||||||||||||
| status_code=status.HTTP_404_NOT_FOUND, | ||||||||||||||||||||||||||||||||||||||||||||
| detail={ | ||||||||||||||||||||||||||||||||||||||||||||
| "code": SandboxErrorCodes.K8S_SANDBOX_NOT_FOUND, | ||||||||||||||||||||||||||||||||||||||||||||
| "message": f"No pods found for sandbox '{sandbox_id}'", | ||||||||||||||||||||||||||||||||||||||||||||
| }, | ||||||||||||||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||
| pod_name = pods.items[0].metadata.name | ||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||
| if follow: | ||||||||||||||||||||||||||||||||||||||||||||
| # Streaming mode: _preload_content=False gives a raw HTTP response. | ||||||||||||||||||||||||||||||||||||||||||||
| response = core_v1_api.read_namespaced_pod_log( | ||||||||||||||||||||||||||||||||||||||||||||
| name=pod_name, | ||||||||||||||||||||||||||||||||||||||||||||
| namespace=self.namespace, | ||||||||||||||||||||||||||||||||||||||||||||
| follow=True, | ||||||||||||||||||||||||||||||||||||||||||||
| tail_lines=tail, | ||||||||||||||||||||||||||||||||||||||||||||
| timestamps=timestamps, | ||||||||||||||||||||||||||||||||||||||||||||
| _preload_content=False, | ||||||||||||||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||||||||||||||
| for chunk in response.stream(amt=4096): | ||||||||||||||||||||||||||||||||||||||||||||
| if chunk: | ||||||||||||||||||||||||||||||||||||||||||||
| yield chunk | ||||||||||||||||||||||||||||||||||||||||||||
|
Comment on lines
+737
to
+739
|
||||||||||||||||||||||||||||||||||||||||||||
| for chunk in response.stream(amt=4096): | |
| if chunk: | |
| yield chunk | |
| try: | |
| for chunk in response.stream(amt=4096): | |
| if chunk: | |
| yield chunk | |
| finally: | |
| # Ensure the underlying HTTP response/connection is properly cleaned up. | |
| try: | |
| response.close() | |
| except Exception: | |
| # Best-effort close; avoid masking original exceptions. | |
| pass | |
| # Some response types (e.g., urllib3.HTTPResponse) expose release_conn(). | |
| release_conn = getattr(response, "release_conn", None) | |
| if callable(release_conn): | |
| try: | |
| release_conn() | |
| except Exception: | |
| pass |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Specify the target pod container when reading logs
This Kubernetes log call does not set container=..., but sandbox pods can contain an additional egress sidecar when network policy is enabled (via apply_egress_to_spec), making them multi-container pods. In that case the pod log API requires an explicit container selection, so this endpoint will fail for those sandboxes and return a 500 instead of streaming the sandbox container logs.
Useful? React with 👍 / 👎.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| # Copyright 2026 Alibaba Group Holding Ltd. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| """Tests for GET /sandboxes/{sandbox_id}/logs endpoint.""" | ||
|
|
||
| from fastapi.testclient import TestClient | ||
| from fastapi import HTTPException, status | ||
|
|
||
| from src.api import lifecycle | ||
|
|
||
|
|
||
| def _make_log_gen(*chunks: bytes): | ||
| """Return a generator that yields the given byte chunks.""" | ||
| def _gen(): | ||
| yield from chunks | ||
| return _gen() | ||
|
|
||
|
|
||
| def test_get_sandbox_logs_returns_plain_text(client: TestClient, auth_headers: dict, monkeypatch): | ||
| """Happy path: service returns log chunks and they are streamed as text/plain.""" | ||
| log_chunks = [b"line one\n", b"line two\n"] | ||
| monkeypatch.setattr( | ||
| lifecycle.sandbox_service, | ||
| "get_logs", | ||
| lambda sandbox_id, follow, tail, timestamps: _make_log_gen(*log_chunks), | ||
| ) | ||
|
|
||
| resp = client.get("/sandboxes/abc-123/logs", headers=auth_headers) | ||
|
|
||
| assert resp.status_code == 200 | ||
| assert "text/plain" in resp.headers["content-type"] | ||
| assert resp.content == b"line one\nline two\n" | ||
|
|
||
|
|
||
| def test_get_sandbox_logs_passes_query_params(client: TestClient, auth_headers: dict, monkeypatch): | ||
| """Query parameters (follow, tail, timestamps) are forwarded to the service.""" | ||
| captured = {} | ||
|
|
||
| def _fake_get_logs(sandbox_id, follow, tail, timestamps): | ||
| captured["sandbox_id"] = sandbox_id | ||
| captured["follow"] = follow | ||
| captured["tail"] = tail | ||
| captured["timestamps"] = timestamps | ||
| return _make_log_gen(b"log\n") | ||
|
|
||
| monkeypatch.setattr(lifecycle.sandbox_service, "get_logs", _fake_get_logs) | ||
|
|
||
| resp = client.get( | ||
| "/sandboxes/my-sandbox/logs", | ||
| params={"follow": "true", "tail": 50, "timestamps": "true"}, | ||
| headers=auth_headers, | ||
| ) | ||
|
|
||
| assert resp.status_code == 200 | ||
| assert captured["sandbox_id"] == "my-sandbox" | ||
| assert captured["follow"] is True | ||
| assert captured["tail"] == 50 | ||
| assert captured["timestamps"] is True | ||
|
|
||
|
|
||
| def test_get_sandbox_logs_empty_stream(client: TestClient, auth_headers: dict, monkeypatch): | ||
| """When the service returns an empty generator, a 200 with empty body is returned.""" | ||
| monkeypatch.setattr( | ||
| lifecycle.sandbox_service, | ||
| "get_logs", | ||
| lambda sandbox_id, follow, tail, timestamps: _make_log_gen(), | ||
| ) | ||
|
|
||
| resp = client.get("/sandboxes/empty-sandbox/logs", headers=auth_headers) | ||
|
|
||
| assert resp.status_code == 200 | ||
| assert resp.content == b"" | ||
|
|
||
|
|
||
| def test_get_sandbox_logs_not_found(client: TestClient, auth_headers: dict, monkeypatch): | ||
| """When the service raises 404, the endpoint propagates it.""" | ||
| def _raise_not_found(sandbox_id, follow, tail, timestamps): | ||
| raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Sandbox not found") | ||
|
|
||
| monkeypatch.setattr(lifecycle.sandbox_service, "get_logs", _raise_not_found) | ||
|
|
||
| resp = client.get("/sandboxes/missing/logs", headers=auth_headers) | ||
|
|
||
| assert resp.status_code == 404 | ||
|
|
||
|
|
||
| def test_get_sandbox_logs_requires_auth(client: TestClient): | ||
| """Requests without an API key are rejected with 401.""" | ||
| resp = client.get("/sandboxes/abc-123/logs") | ||
| assert resp.status_code == 401 | ||
|
|
||
|
|
||
| def test_get_sandbox_logs_tail_must_be_positive(client: TestClient, auth_headers: dict): | ||
| """tail=0 is invalid (minimum is 1); FastAPI should return 422.""" | ||
| resp = client.get("/sandboxes/abc-123/logs", params={"tail": 0}, headers=auth_headers) | ||
| assert resp.status_code == 422 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
get_logs(...)is passed directly intoStreamingResponse, but both runtime implementations are generator functions, so sandbox lookup/API errors are raised only when the response body is iterated. At that point the200status has already been sent, so missing sandboxes and backend failures no longer propagate as intended404/500API errors and instead appear as a broken/truncated successful stream.Useful? React with 👍 / 👎.