Repository navigation
feat: add rp pod lifecycle commands #639
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
Open
+2,426
−38
Open
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
232e7cb
feat: add rp pod lifecycle commands
KAJdev 1173258
fix: wait for the pod container to start, not just its desired status
KAJdev 6ef070e
Merge remote-tracking branch 'origin/zeke/con-1118-rp-catalog' into z…
KAJdev 1bab5e8
Merge remote-tracking branch 'origin/zeke/con-1118-rp-catalog' into z…
KAJdev 574eb91
Merge remote-tracking branch 'origin/zeke/con-1118-rp-catalog' into z…
KAJdev c4489ab
refactor: simplify pod commands and share log streaming
KAJdev 5dbc295
Merge remote-tracking branch 'origin/zeke/con-1118-rp-catalog' into z…
KAJdev b9fec28
chore: integrate shared picker width fix
KAJdev 6d0518d
fix: read pod sync SSH keys through REST
KAJdev 31c8f8d
chore: stack pod commands on volume
KAJdev 01097e7
fix: harden pod readiness and log streaming
KAJdev 454d110
chore: sync catalog review fixes through volumes
KAJdev b416d94
chore: sync volume integration into pod commands
KAJdev 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,156 @@ | ||
| """shared pod and serverless log views backed by the sdk stream reader.""" | ||
|
|
||
| import asyncio | ||
| import json | ||
| from datetime import datetime, timezone | ||
|
|
||
| import aiohttp | ||
| import click | ||
|
|
||
| from runpod.api.ctl_commands import _path_segment | ||
| from runpod.api.rest import run_rest_request | ||
| from runpod.apps.logs import stream_pod_logs | ||
| from runpod.rp_cli import console as ui | ||
| from runpod.rp_cli.api import api_errors | ||
|
|
||
| SNAPSHOT_IDLE_SECONDS = 3 | ||
| WORKER_POLL_SECONDS = 5 | ||
| RECONNECT_SECONDS = 1 | ||
|
|
||
|
|
||
| async def _show_logs( | ||
| pod_id, endpoint_id, worker_ids, follow, source, tail, since, as_json | ||
| ): | ||
| started = datetime.now(timezone.utc) | ||
| records = [] | ||
| tasks = {} | ||
| width = 0 | ||
|
|
||
| def emit(worker, event): | ||
| if as_json: | ||
| click.echo( | ||
| json.dumps({"worker": worker, **event} if endpoint_id else event) | ||
| ) | ||
| else: | ||
| prefix = f"{worker:<{width}} " if endpoint_id else "" | ||
| click.echo(f"{prefix}[{event['source']}] {event['line']}") | ||
|
|
||
| async def consume(worker): | ||
| cursor = None | ||
|
|
||
| def remember(event_id): | ||
| nonlocal cursor | ||
| cursor = event_id | ||
|
|
||
| while True: | ||
| stream = stream_pod_logs( | ||
| worker, | ||
| endpoint_id=endpoint_id, | ||
| log_type=source, | ||
| tail=tail, | ||
| since=since, | ||
| last_event_id=cursor, | ||
| on_event_id=remember, | ||
| idle_timeout=None if follow else SNAPSHOT_IDLE_SECONDS, | ||
| ) | ||
| try: | ||
| async for event in stream: | ||
| if follow: | ||
| emit(worker, event) | ||
| elif ( | ||
| datetime.fromisoformat(event["ts"].replace("Z", "+00:00")) | ||
| >= started | ||
| ): | ||
| return | ||
| else: | ||
| records.append((worker, event)) | ||
| except aiohttp.ClientResponseError as exc: | ||
| if not endpoint_id or exc.status != 404: | ||
| raise | ||
| return | ||
| except (aiohttp.ClientConnectionError, asyncio.TimeoutError): | ||
| if not follow: | ||
| raise | ||
| finally: | ||
| await stream.aclose() | ||
| if not follow: | ||
| return | ||
| await asyncio.sleep(RECONNECT_SECONDS) | ||
|
|
||
| async def attach(): | ||
| nonlocal width | ||
| if pod_id: | ||
| ids = [pod_id] | ||
| else: | ||
| response = await asyncio.to_thread( | ||
| run_rest_request, | ||
| "GET", | ||
| f"/v2/serverless/{_path_segment(endpoint_id)}/workers", | ||
| ) | ||
| ids = [ | ||
| worker["id"] | ||
| for worker in response["workers"] | ||
| if not worker_ids or worker["id"] in worker_ids | ||
| ] | ||
| width = max([width, *(len(worker) for worker in ids)]) | ||
| for worker in ids: | ||
| if worker not in tasks: | ||
| tasks[worker] = asyncio.create_task(consume(worker)) | ||
|
|
||
| try: | ||
| await attach() | ||
| if not tasks and not as_json: | ||
| ui.console.print( | ||
| "[dim]waiting for workers ...[/dim]" | ||
| if follow | ||
| else "[dim]no workers[/dim]" | ||
| ) | ||
| if not follow: | ||
| await asyncio.gather(*tasks.values()) | ||
| else: | ||
| while True: | ||
| await asyncio.sleep(WORKER_POLL_SECONDS) | ||
| for task in tasks.values(): | ||
| if task.done(): | ||
| task.result() | ||
| tasks = { | ||
| worker: task for worker, task in tasks.items() if not task.done() | ||
| } | ||
| await attach() | ||
| finally: | ||
| for task in tasks.values(): | ||
| task.cancel() | ||
| await asyncio.gather(*tasks.values(), return_exceptions=True) | ||
| for worker, event in sorted(records, key=lambda row: row[1]["ts"]): | ||
| emit(worker, event) | ||
|
|
||
|
|
||
| def show_logs( | ||
| pod_id=None, | ||
| *, | ||
| endpoint_id=None, | ||
| worker_ids=(), | ||
| follow=False, | ||
| source=None, | ||
| tail=100, | ||
| since=None, | ||
| as_json=False, | ||
| ): | ||
| try: | ||
| with api_errors(): | ||
| asyncio.run( | ||
| _show_logs( | ||
| pod_id, | ||
| endpoint_id, | ||
| worker_ids, | ||
| follow, | ||
| source, | ||
| tail, | ||
| since, | ||
| as_json, | ||
| ) | ||
| ) | ||
| except KeyboardInterrupt: | ||
| return | ||
| except (aiohttp.ClientError, asyncio.TimeoutError) as exc: | ||
| raise click.ClickException(str(exc)) from exc |
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,64 @@ | ||
| """value parsing shared by resource command options.""" | ||
|
|
||
| import shlex | ||
| from collections.abc import Iterable | ||
|
|
||
| import click | ||
|
|
||
| from runpod.rp_cli.api import list_all | ||
| from runpod.rp_cli.compute import ResolutionError | ||
|
|
||
|
|
||
| def parse_env(values: Iterable[str]) -> dict[str, str]: | ||
| env = {} | ||
| for value in values: | ||
| key, separator, content = value.partition("=") | ||
| if not key or not separator: | ||
| raise click.UsageError("invalid --env value; use KEY=VALUE") | ||
| env[key] = content | ||
| return env | ||
|
|
||
|
|
||
| def container_fields( | ||
| options: dict, current: dict | None = None, unset_env: Iterable[str] = () | ||
| ) -> dict: | ||
| current = current or {} | ||
| body = { | ||
| field: options[option] | ||
| for option, field in ( | ||
| ("image", "image"), | ||
| ("template", "templateId"), | ||
| ("args", "args"), | ||
| ("disk", "disk"), | ||
| ("global_networking", "globalNetworking"), | ||
| ) | ||
| if options.get(option) is not None | ||
| } | ||
| for option in ("cmd", "entrypoint"): | ||
| if options.get(option) is not None: | ||
| try: | ||
| body[option] = shlex.split(options[option]) | ||
| except ValueError as exc: | ||
| raise click.BadParameter(str(exc), param_hint=f"--{option}") from exc | ||
| if options.get("ports"): | ||
| body["ports"] = list(options["ports"]) | ||
| if options.get("registry") is not None: | ||
| value = options["registry"] | ||
| body["registry"] = None | ||
| if value: | ||
| matches = [ | ||
| registry["id"] | ||
| for registry in list_all("/v2/registries", "registries") | ||
| if value in (registry["id"], registry["name"]) | ||
| ] | ||
| if not matches: | ||
| raise ResolutionError( | ||
| f"unknown registry credential '{value}'. list them with rp registry list" | ||
| ) | ||
| body["registry"] = matches[0] | ||
| if options.get("env") or unset_env: | ||
| env = {**(current.get("env") or {}), **parse_env(options.get("env") or ())} | ||
| for key in unset_env: | ||
| env.pop(key, None) | ||
| body["env"] = env | ||
| return body |
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.