-
Notifications
You must be signed in to change notification settings - Fork 1
Adds live log streaming for remote pods #42
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
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
ed9c2bc
Streams live container logs to terminal during execution.
JyotinderSingh 82b9281
use ctx manager for streaming
JyotinderSingh ae0728e
remove redundant tests
JyotinderSingh 9379bae
move rich to main deps
JyotinderSingh d4adc23
adds pathways client test
JyotinderSingh 94a2279
ci fix
JyotinderSingh File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,137 @@ | ||
| """Live log streaming from Kubernetes pods. | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. the file doesnt really fit in backend. Maybe move it to utils? |
||
|
|
||
| Provides utilities to stream pod logs to stdout in real-time using a | ||
| background daemon thread. Used by both GKE and Pathways backends during | ||
| job execution. | ||
| """ | ||
|
|
||
| import sys | ||
| import threading | ||
| from collections import deque | ||
|
|
||
| import urllib3 | ||
| from absl import logging | ||
| from kubernetes.client.rest import ApiException | ||
| from rich.console import Console | ||
| from rich.live import Live | ||
| from rich.panel import Panel | ||
|
|
||
| _MAX_DISPLAY_LINES = 25 | ||
JyotinderSingh marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
|
|
||
| def _stream_pod_logs(core_v1, pod_name, namespace): | ||
| """Stream pod logs to stdout. Designed to run in a daemon thread. | ||
|
|
||
| Uses the Kubernetes follow API to tail logs in real-time. The stream | ||
| ends naturally when the container exits. | ||
|
|
||
| In interactive terminals, logs are displayed in a Rich Live panel. | ||
| In non-interactive contexts (piped output, CI), logs are streamed | ||
| as raw lines with Rich Rule delimiters. | ||
|
|
||
| Args: | ||
| core_v1: Kubernetes CoreV1Api client. | ||
| pod_name: Name of the pod to stream logs from. | ||
| namespace: Kubernetes namespace. | ||
| """ | ||
| console = Console() | ||
| resp = None | ||
| try: | ||
| resp = core_v1.read_namespaced_pod_log( | ||
| name=pod_name, | ||
| namespace=namespace, | ||
| follow=True, | ||
| _preload_content=False, | ||
| ) | ||
| if console.is_terminal: | ||
| _render_live_panel(resp, pod_name, console) | ||
| else: | ||
| _render_plain(resp, pod_name, console) | ||
| except ApiException: | ||
| pass # Pod deleted or not found | ||
| except urllib3.exceptions.ProtocolError: | ||
| pass # Connection broken mid-stream (pod terminated) | ||
JyotinderSingh marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| except Exception: | ||
| logging.warning( | ||
| "Log streaming from %s failed unexpectedly", pod_name, exc_info=True | ||
| ) | ||
| finally: | ||
| if resp is not None: | ||
| resp.release_conn() | ||
|
|
||
|
|
||
| def _render_live_panel(resp, pod_name, console): | ||
| """Render streaming logs inside a Rich Live panel.""" | ||
| lines = deque(maxlen=_MAX_DISPLAY_LINES) | ||
| title = f"Remote logs \u2022 {pod_name}" | ||
| buffer = "" | ||
|
|
||
| with Live( | ||
| _make_log_panel(lines, title), | ||
| console=console, | ||
| refresh_per_second=4, | ||
| ) as live: | ||
| for chunk in resp.stream(decode_content=True): | ||
| buffer += chunk.decode("utf-8", errors="replace") | ||
| while "\n" in buffer: | ||
| line, buffer = buffer.split("\n", 1) | ||
| lines.append(line) | ||
| live.update(_make_log_panel(lines, title)) | ||
|
|
||
| # Flush remaining partial line | ||
| if buffer.strip(): | ||
| lines.append(buffer) | ||
| live.update(_make_log_panel(lines, title)) | ||
|
|
||
|
|
||
| def _render_plain(resp, pod_name, console): | ||
| """Render streaming logs as raw lines with Rule delimiters.""" | ||
| console.rule(f"Remote logs ({pod_name})", style="blue") | ||
| for chunk in resp.stream(decode_content=True): | ||
| sys.stdout.write(chunk.decode("utf-8", errors="replace")) | ||
| sys.stdout.flush() | ||
| console.rule("End remote logs", style="blue") | ||
|
|
||
|
|
||
| def _make_log_panel(lines, title): | ||
| """Build a Panel renderable from accumulated log lines.""" | ||
| content = "\n".join(lines) if lines else "Waiting for output..." | ||
| return Panel(content, title=title, border_style="blue") | ||
|
|
||
|
|
||
| class LogStreamer: | ||
| """Context manager that owns the log-streaming thread lifecycle. | ||
|
|
||
| Usage:: | ||
|
|
||
| with LogStreamer(core_v1, namespace) as streamer: | ||
| while polling: | ||
| ... | ||
| if pod_is_running: | ||
| streamer.start(pod_name) # idempotent | ||
| """ | ||
|
|
||
| def __init__(self, core_v1, namespace): | ||
| self._core_v1 = core_v1 | ||
| self._namespace = namespace | ||
| self._thread = None | ||
|
|
||
| def __enter__(self): | ||
| return self | ||
|
|
||
| def __exit__(self, *exc): | ||
| if self._thread is not None: | ||
| self._thread.join(timeout=5) | ||
| return False | ||
|
|
||
| def start(self, pod_name): | ||
| """Start streaming if not already active (idempotent).""" | ||
| if self._thread is not None: | ||
| return | ||
| logging.info("Streaming logs from %s...", pod_name) | ||
| self._thread = threading.Thread( | ||
| target=_stream_pod_logs, | ||
| args=(self._core_v1, pod_name, self._namespace), | ||
| daemon=True, | ||
| ) | ||
| self._thread.start() | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.