-
Notifications
You must be signed in to change notification settings - Fork 543
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 | ||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -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 |
| 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.
With Docker containers that are not running with a TTY,
container.logs(stdout=True, stderr=True)returns the Docker multiplexed stream format (binary framing), but the API advertisestext/plaincombined stdout/stderr. This will produce non-plain-text bytes for real containers. Consider demuxing/parsing the multiplexed stream (or using an option/approach that returns plain log bytes) before yielding, so the HTTP response body is actually plain-text.